From 4a19cc881fc0bb8b856764a46c5a0bd07faaedc2 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 6 Jul 2026 22:00:19 -0700 Subject: [PATCH 1/2] fix(terminal): send CSI-u Shift+Enter to kitty TUIs (droid) on Windows (#7620) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Windows, Shift+Enter was always sent as the Alt+Enter byte ESC+CR (added in #2418 for Codex, which reads win32-input-mode and ignores CSI-u). droid speaks the kitty keyboard protocol, parses CSI-u directly, and treats ESC+CR as a plain Enter — so Shift+Enter SUBMITTED the message instead of inserting a newline. droid works in other terminals (Windows Terminal, Warp) because those honor win32-input-mode / kitty; Orca (xterm.js) withholds kitty from local Windows ConPTY panes and emits neither. Make the Windows Shift+Enter byte pane-aware: latch whether a pane's program advertised the kitty keyboard protocol (query CSI ? u, push CSI > .. u, or set CSI = .. u) and send CSI-u (\x1b[13;2u) to those panes, keeping the Codex-compatible ESC+CR for win32-input-mode-only TUIs. Non-Windows is unchanged (always CSI-u). Verified end-to-end against the real droid and Codex CLIs through the actual production functions: droid now newlines, Codex still newlines. --- .../terminal-pane/keyboard-handlers.ts | 13 +- .../terminal-pane/pty-connection.ts | 9 ++ .../terminal-kitty-keyboard-awareness.test.ts | 113 ++++++++++++++++++ .../terminal-kitty-keyboard-awareness.ts | 56 +++++++++ .../terminal-shortcut-policy.test.ts | 50 +++++++- .../terminal-pane/terminal-shortcut-policy.ts | 18 ++- tests/e2e/terminal-shortcuts.spec.ts | 5 +- 7 files changed, 256 insertions(+), 8 deletions(-) create mode 100644 src/renderer/src/components/terminal-pane/terminal-kitty-keyboard-awareness.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-kitty-keyboard-awareness.ts diff --git a/src/renderer/src/components/terminal-pane/keyboard-handlers.ts b/src/renderer/src/components/terminal-pane/keyboard-handlers.ts index ed78a5d6500d..3ae87f267306 100644 --- a/src/renderer/src/components/terminal-pane/keyboard-handlers.ts +++ b/src/renderer/src/components/terminal-pane/keyboard-handlers.ts @@ -23,6 +23,7 @@ import { splitTerminalPaneWithInheritedCwd } from './terminal-pane-split-with-in import { useAppStore } from '@/store' import { recordTerminalUserInputForLeaf } from './terminal-input-activity' import { isLocalWindowsConptyPaneForCtrlArrow } from './terminal-ctrl-arrow-conpty' +import { isTerminalKittyKeyboardAware } from './terminal-kitty-keyboard-awareness' import { markTerminalFollowOutput, markTerminalPinnedViewport, @@ -293,6 +294,15 @@ export function useTerminalKeyboardShortcuts({ }) } + // Why: Windows Shift+Enter picks its byte from whether the active pane's + // program speaks the kitty keyboard protocol (droid) or only + // win32-input-mode (Codex). Resolved lazily so the per-pane lookup stays + // off other keystrokes. + const isActivePaneKittyKeyboardAware = (): boolean => { + const activePane = manager.getActivePane() ?? manager.getPanes()[0] + return isTerminalKittyKeyboardAware(activePane?.terminal) + } + const action = resolveTerminalShortcutAction( e, isMac, @@ -300,7 +310,8 @@ export function useTerminalKeyboardShortcuts({ optionKeyLocation, isWindows, keybindings, - isLocalWindowsConptyPane + isLocalWindowsConptyPane, + isActivePaneKittyKeyboardAware ) if (!action) { return diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index 9b1d2a3ae995..0b3953755e95 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -135,6 +135,7 @@ import { installTerminalCapabilityReplyHandlers, sendTerminalOscColorQueryReplies } from './terminal-capability-replies' +import { installKittyKeyboardAwarenessDetector } from './terminal-kitty-keyboard-awareness' import { cancelScheduledHiddenOutputRestore, scheduleHiddenOutputRestore @@ -2850,6 +2851,13 @@ export function connectPanePty( isReplaying: () => isPaneReplaying(deps.replayingPanesRef, pane.id), ...(isNativeWindowsConpty ? { da1Response: CONPTY_DA1_RESPONSE } : {}) }) + // Why: latch whether this pane's program speaks the kitty keyboard protocol so + // the shortcut policy can send CSI-u Shift+Enter to droid-style TUIs on Windows + // instead of the Codex-only Alt+Enter byte, which those TUIs submit. (#7620) + const kittyKeyboardAwarenessDisposable = installKittyKeyboardAwarenessDetector({ + terminal: pane.terminal, + parser: pane.terminal.parser + }) const respondToTerminalPixelSizeQueries = createTerminalPixelSizeQueryResponder( pane.terminal, (data) => transport.sendInput(data) @@ -6177,6 +6185,7 @@ export function connectPanePty( onDataDisposable.dispose() userInputActivityDisposable?.dispose() terminalCapabilityRepliesDisposable.dispose() + kittyKeyboardAwarenessDisposable.dispose() onResizeDisposable.dispose() onBufferChangeDisposable?.dispose() pane.container.removeEventListener(PANE_PTY_RESIZE_HOLD_FLUSH_EVENT, onHeldPtyResizeFlush) diff --git a/src/renderer/src/components/terminal-pane/terminal-kitty-keyboard-awareness.test.ts b/src/renderer/src/components/terminal-pane/terminal-kitty-keyboard-awareness.test.ts new file mode 100644 index 000000000000..5e5294c2b510 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-kitty-keyboard-awareness.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from 'vitest' +import { Terminal } from '@xterm/headless' +import { + installKittyKeyboardAwarenessDetector, + isTerminalKittyKeyboardAware, + markTerminalKittyKeyboardAware +} from './terminal-kitty-keyboard-awareness' + +function writeTerminal(term: Terminal, data: string): Promise { + return new Promise((resolve) => term.write(data, resolve)) +} + +function createDetectedTerminal(options?: { kittyKeyboard?: boolean }): { + term: Terminal + dispose: () => void +} { + const term = new Terminal({ + cols: 80, + rows: 24, + allowProposedApi: true, + ...(options?.kittyKeyboard === undefined + ? {} + : { vtExtensions: { kittyKeyboard: options.kittyKeyboard } }) + }) + const disposable = installKittyKeyboardAwarenessDetector({ + terminal: term as never, + parser: term.parser + }) + return { + term, + dispose: () => { + disposable.dispose() + term.dispose() + } + } +} + +describe('terminal kitty keyboard awareness', () => { + it('treats null/undefined terminals as not aware', () => { + expect(isTerminalKittyKeyboardAware(null)).toBe(false) + expect(isTerminalKittyKeyboardAware(undefined)).toBe(false) + }) + + it('marks a terminal aware after a kitty query (CSI ? u), the sequence droid emits', async () => { + const { term, dispose } = createDetectedTerminal() + try { + expect(isTerminalKittyKeyboardAware(term as never)).toBe(false) + await writeTerminal(term, '\x1b[?u') + expect(isTerminalKittyKeyboardAware(term as never)).toBe(true) + } finally { + dispose() + } + }) + + it('marks a terminal aware on push (CSI > N u) and set (CSI = N ; M u) controls', async () => { + for (const control of ['\x1b[>1u', '\x1b[=1;1u']) { + const { term, dispose } = createDetectedTerminal() + try { + await writeTerminal(term, control) + expect(isTerminalKittyKeyboardAware(term as never)).toBe(true) + } finally { + dispose() + } + } + }) + + it('does not mark a terminal aware for unrelated CSI sequences (e.g. Codex has none)', async () => { + const { term, dispose } = createDetectedTerminal() + try { + // win32-input-mode enable + DA1 query + SGR reset: nothing kitty here. + await writeTerminal(term, '\x1b[?9001h\x1b[c\x1b[0mhello') + expect(isTerminalKittyKeyboardAware(term as never)).toBe(false) + } finally { + dispose() + } + }) + + it('still detects the query when xterm has the kitty encoder enabled', async () => { + const { term, dispose } = createDetectedTerminal({ kittyKeyboard: true }) + try { + await writeTerminal(term, '\x1b[?u') + expect(isTerminalKittyKeyboardAware(term as never)).toBe(true) + } finally { + dispose() + } + }) + + it('stops latching after dispose', async () => { + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + const disposable = installKittyKeyboardAwarenessDetector({ + terminal: term as never, + parser: term.parser + }) + disposable.dispose() + try { + await writeTerminal(term, '\x1b[?u') + expect(isTerminalKittyKeyboardAware(term as never)).toBe(false) + } finally { + term.dispose() + } + }) + + it('exposes an imperative mark for callers that observe kitty out-of-band', () => { + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + try { + expect(isTerminalKittyKeyboardAware(term as never)).toBe(false) + markTerminalKittyKeyboardAware(term as never) + expect(isTerminalKittyKeyboardAware(term as never)).toBe(true) + } finally { + term.dispose() + } + }) +}) diff --git a/src/renderer/src/components/terminal-pane/terminal-kitty-keyboard-awareness.ts b/src/renderer/src/components/terminal-pane/terminal-kitty-keyboard-awareness.ts new file mode 100644 index 000000000000..8978d42c5b56 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-kitty-keyboard-awareness.ts @@ -0,0 +1,56 @@ +import type { IDisposable, IParser, Terminal } from '@xterm/xterm' + +// Why: Orca advertises the kitty keyboard protocol but withholds it from local +// Windows ConPTY panes (see terminal-keyboard-protocol.ts), and xterm never +// exposes the live kitty state to us. To pick the right Shift+Enter encoding on +// Windows we need to know whether the pane's *program* speaks CSI-u: kitty TUIs +// (e.g. droid) parse `\x1b[13;2u` and treat the Alt+Enter byte `\x1b\r` as a +// plain Enter that SUBMITS, while win32-input-mode-only TUIs (e.g. Codex) only +// newline on `\x1b\r` and ignore CSI-u. A program announces CSI-u support by +// emitting a kitty keyboard control (query `CSI ? u`, push `CSI > … u`, or set +// `CSI = … u`); we latch that per-terminal so the shortcut policy can prefer +// CSI-u for those panes. (#7620; the win32-only fallback comes from #2418.) + +const kittyKeyboardAwareTerminals = new WeakSet() + +export function markTerminalKittyKeyboardAware(terminal: Terminal): void { + kittyKeyboardAwareTerminals.add(terminal) +} + +export function isTerminalKittyKeyboardAware(terminal: Terminal | null | undefined): boolean { + return terminal != null && kittyKeyboardAwareTerminals.has(terminal) +} + +// Private-marker bytes that introduce an app→terminal kitty keyboard control: +// `?` = query flags, `>` = push flags, `=` = set flags. Pop (`<`) is omitted — +// disabling the protocol does not prove the program parses CSI-u input. +const KITTY_KEYBOARD_CONTROL_PREFIXES = ['?', '>', '='] as const + +type KittyKeyboardAwarenessDeps = { + terminal: Terminal + parser: Pick +} + +/** + * Latches a pane as kitty-keyboard-aware the first time its program emits a + * kitty keyboard control. Registered on the pane parser next to the capability + * reply handlers; returns false from every handler so xterm's own kitty logic + * (enabled on non-Windows panes) still answers the query / applies the flags. + */ +export function installKittyKeyboardAwarenessDetector( + deps: KittyKeyboardAwarenessDeps +): IDisposable { + const disposables = KITTY_KEYBOARD_CONTROL_PREFIXES.map((prefix) => + deps.parser.registerCsiHandler({ prefix, final: 'u' }, () => { + markTerminalKittyKeyboardAware(deps.terminal) + return false + }) + ) + return { + dispose: () => { + for (const disposable of disposables) { + disposable.dispose() + } + } + } +} diff --git a/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts b/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts index 0f0c4cec3d14..2c08b654c976 100644 --- a/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts @@ -89,7 +89,9 @@ describe('resolveTerminalShortcutAction', () => { }) }) - it('uses the Codex-compatible Shift+Enter sequence on Windows', () => { + it('uses the Codex-compatible Shift+Enter sequence on Windows win32-input-mode panes', () => { + // Default (no kitty-awareness getter) and an explicit non-kitty pane both + // fall back to Alt+Enter so Codex-on-PowerShell newlines instead of ignoring. expect( resolveTerminalShortcutAction( event({ key: 'Enter', code: 'Enter', shiftKey: true }), @@ -102,6 +104,52 @@ describe('resolveTerminalShortcutAction', () => { type: 'sendInput', data: '\x1b\r' }) + expect( + resolveTerminalShortcutAction( + event({ key: 'Enter', code: 'Enter', shiftKey: true }), + false, + 'false', + 0, + true, + undefined, + undefined, + () => false + ) + ).toEqual({ type: 'sendInput', data: '\x1b\r' }) + }) + + it('sends CSI-u Shift+Enter to Windows panes that speak the kitty keyboard protocol (#7620)', () => { + // Why: droid parses CSI-u directly and treats the Alt+Enter byte as a plain + // Enter that submits, so kitty-aware Windows panes must get `\x1b[13;2u`. + expect( + resolveTerminalShortcutAction( + event({ key: 'Enter', code: 'Enter', shiftKey: true }), + false, + 'false', + 0, + true, + undefined, + undefined, + () => true + ) + ).toEqual({ type: 'sendInput', data: '\x1b[13;2u' }) + }) + + it('always uses CSI-u Shift+Enter off Windows regardless of kitty awareness', () => { + for (const kittyAware of [() => true, () => false, undefined]) { + expect( + resolveTerminalShortcutAction( + event({ key: 'Enter', code: 'Enter', shiftKey: true }), + false, + 'false', + 0, + false, + undefined, + undefined, + kittyAware + ) + ).toEqual({ type: 'sendInput', data: '\x1b[13;2u' }) + } }) it('forwards Ctrl+Enter as the kitty CSI-u chord so TUIs can cue instead of send', () => { diff --git a/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.ts b/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.ts index 35cc6c00ffef..f6e1573f1743 100644 --- a/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.ts +++ b/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.ts @@ -58,7 +58,11 @@ export function resolveTerminalShortcutAction( // ConPTY (PowerShell/cmd via PSReadLine). Only consulted for the Ctrl+Arrow // word-nav rule below, so the execution-host lookup it performs stays off the // hot path for every other keystroke. - isLocalWindowsConptyPane?: () => boolean + isLocalWindowsConptyPane?: () => boolean, + // Why: lazily reports whether the active pane's program advertised the kitty + // keyboard protocol. Only consulted for the Windows Shift+Enter rule below, so + // the per-pane lookup stays off the hot path for every other keystroke. + isActivePaneKittyKeyboardAware?: () => boolean ): TerminalShortcutAction | null { const platform: NodeJS.Platform = isMac ? 'darwin' : isWindows ? 'win32' : 'linux' if (!event.repeat) { @@ -118,9 +122,15 @@ export function resolveTerminalShortcutAction( event.shiftKey && event.key === 'Enter' ) { - // Why: Codex on Windows PowerShell treats CSI-u Shift+Enter as inert, - // while the Alt+Enter byte path inserts a composer newline. - return { type: 'sendInput', data: isWindows ? '\x1b\r' : '\x1b[13;2u' } + // Why: Shift+Enter must insert a composer newline, but Windows TUIs split on + // encoding. Codex (crossterm/win32-input-mode, no CSI-u) only newlines on the + // Alt+Enter byte `\x1b\r`; kitty-protocol TUIs like droid parse CSI-u directly + // and treat `\x1b\r` as a plain Enter that SUBMITS the message. So on Windows, + // send CSI-u only to panes whose program advertised the kitty keyboard + // protocol, and keep the Codex-compatible Alt+Enter otherwise. Non-Windows + // always uses CSI-u. (#7620 for droid; #2418 for the Codex fallback.) + const preferCsiU = !isWindows || isActivePaneKittyKeyboardAware?.() === true + return { type: 'sendInput', data: preferCsiU ? '\x1b[13;2u' : '\x1b\r' } } if ( diff --git a/tests/e2e/terminal-shortcuts.spec.ts b/tests/e2e/terminal-shortcuts.spec.ts index d0243f5cc039..d75fc555477f 100644 --- a/tests/e2e/terminal-shortcuts.spec.ts +++ b/tests/e2e/terminal-shortcuts.spec.ts @@ -723,8 +723,9 @@ test.describe('Terminal Shortcuts', () => { // Ctrl+Backspace → \x17 (unix-word-rubout). await pressAndExpectWrite(orcaPage, electronApp, 'Control+Backspace', '\x17') - // Shift+Enter → a modified Enter byte path so agents can distinguish it - // from plain Enter. Windows uses Esc+CR because Codex ignores CSI-u there. + // Shift+Enter → a modified Enter byte path so agents can distinguish it from + // plain Enter. On Windows a plain (non-kitty) pane uses Esc+CR because Codex + // ignores CSI-u there; kitty-protocol panes (e.g. droid) get CSI-u (#7620). await pressAndExpectWrite( orcaPage, electronApp, From 62ead1b2f666d609f6ea5cbead514ac350d3dbef Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 10 Jul 2026 20:41:34 -0700 Subject: [PATCH 2/2] fix(terminal): route Windows Shift+Enter safely for Droid --- .github/workflows/computer-e2e.yml | 19 + .github/workflows/daemon-relocation-spike.yml | 97 + .github/workflows/pr.yml | 29 +- .github/workflows/release-cut.yml | 354 +- .github/workflows/release-mac-build.yml | 5 +- .github/workflows/win-update-e2e.yml | 145 + .github/workflows/win-update-survival-e2e.yml | 116 + .../workflows/windows-signing-rehearsal.yml | 360 ++ .gitignore | 6 + .npmrc | 5 +- AGENTS.md | 12 + README.md | 7 +- build-plugins/plain-node-entry-guard.ts | 130 + config/electron-builder.config.cjs | 73 +- config/nsis/daemon-host-uninstall.nsh | 23 + ...erm__addon-serialize@0.15.0-beta.287.patch | 55 + .../@xterm__addon-webgl@0.20.0-beta.286.patch | 89 +- config/reliability-gates.jsonc | 939 +++- .../scripts/audit-localization-coverage.mjs | 3 +- config/scripts/build-native-for-platform.mjs | 6 +- .../build-notification-status-macos.mjs | 97 + config/scripts/build-relay.mjs | 27 + .../check-terminal-perf-report-budgets.mjs | 15 + ...heck-terminal-perf-report-budgets.test.mjs | 28 + config/scripts/computer-e2e-workflow.test.mjs | 51 + config/scripts/daemon-boot-smoke.mjs | 217 + .../scripts/electron-builder-config.test.mjs | 33 + config/scripts/ensure-native-runtime.mjs | 10 +- config/scripts/ensure-native-runtime.test.mjs | 43 +- .../generate-terminal-perf-html-report.mjs | 483 ++ ...enerate-terminal-perf-html-report.test.mjs | 272 ++ ...git-binary-compatibility-workflow.test.mjs | 20 + config/scripts/localize-renderer-strings.mjs | 3 +- ...package-electron-runtime-contract.test.mjs | 34 +- config/scripts/rebuild-native-deps.mjs | 10 +- config/scripts/rebuild-native-deps.test.mjs | 4 +- config/scripts/release-rc-history.mjs | 6 +- config/scripts/run-electron-vite-dev.mjs | 69 +- .../run-multi-workspace-typing-bench.mjs | 63 + .../run-terminal-scale-perf-report-gate.mjs | 16 +- ...n-terminal-scale-perf-report-gate.test.mjs | 31 +- .../serve-headless-fresh-profile-pairing.mjs | 326 ++ .../styled-scrollbar-jsx-check.mjs | 3 +- .../summarize-terminal-perf-report.mjs | 1 + config/scripts/terminal-perf-report-rows.mjs | 199 + .../scripts/verify-localization-catalog.mjs | 3 +- .../scripts/verify-packaged-daemon-entry.cjs | 58 + .../verify-packaged-daemon-entry.test.mjs | 57 + .../windows-daemon-workspace-close-repro.mjs | 271 ++ config/tsconfig.cli.json | 9 +- config/tsconfig.node.json | 1 + config/tsconfig.tc.web.json | 1 - docs/STYLEGUIDE.md | 2 +- docs/agent-status-over-wsl.md | 374 ++ docs/assets/readme-downloads.svg | 8 +- docs/assets/wechat-qr-backup.jpg | Bin 0 -> 211009 bytes docs/editor-find-layout-aware-shortcut.md | 92 + docs/issue-7649-vscode-wsl-launch.md | 95 + ...all-sessions-also-kills-empty-terminals.md | 203 + docs/readme/README.es.md | 4 +- docs/readme/README.ja.md | 4 +- docs/readme/README.ko.md | 4 +- docs/readme/README.pt.md | 8 +- docs/readme/README.zh-CN.md | 9 +- docs/reference/git-compatibility.md | 62 + .../reference/terminal-hidden-view-parking.md | 115 + .../reference/terminal-model-view-contract.md | 218 + docs/reference/terminal-query-authority.md | 326 ++ .../terminal-side-effect-authority.md | 252 + ...source-control-push-failure-ai-recovery.md | 368 ++ docs/terminal-main-owned-state.md | 11 + docs/wrapped-terminal-file-link-fragments.md | 115 + electron.vite.config.ts | 6 +- mobile/app.json | 4 +- mobile/app/_layout.tsx | 9 + mobile/app/connection-log.tsx | 221 + .../h/[hostId]/agent-history/[worktreeId].tsx | 18 + .../app/h/[hostId]/history/[worktreeId].tsx | 219 +- mobile/app/h/[hostId]/index.tsx | 89 +- mobile/app/h/[hostId]/pr/[worktreeId].tsx | 49 +- .../app/h/[hostId]/session/[worktreeId].tsx | 222 +- .../mobile-session-command-input-styles.ts | 29 + .../session/mobile-session-route-types.ts | 2 +- .../[hostId]/source-control/[worktreeId].tsx | 3 + mobile/app/h/[hostId]/tasks.tsx | 112 +- mobile/app/h/_layout.tsx | 4 + mobile/app/index.tsx | 7 +- mobile/app/troubleshoot.tsx | 88 +- mobile/package.json | 9 +- mobile/pnpm-lock.yaml | 1074 +++-- .../MobileAgentSessionHistoryIcon.tsx | 48 + .../MobileAgentSessionHistoryList.tsx | 177 + .../MobileAgentSessionHistoryPanel.tsx | 421 ++ .../agent-history/agent-history-capability.ts | 4 + .../agent-history-current-worktree-badge.ts | 7 + .../agent-history-resume-target.test.ts | 372 ++ .../agent-history-resume-target.ts | 304 ++ .../agent-history-scope-paths.test.ts | 60 + .../agent-history-scope-paths.ts | 60 + .../agent-history/agent-history-sections.ts | 59 + .../agent-history-session-card.test.ts | 221 + .../agent-history-session-card.ts | 68 + .../agent-history-session-worktree.test.ts | 86 + .../agent-history-session-worktree.ts | 103 + .../src/agent-history/agent-history-styles.ts | 242 + .../use-mobile-agent-history-state.ts | 192 + .../worktree-navigation-actions.ts | 50 + mobile/src/components/AccountUsage.tsx | 22 +- mobile/src/components/MobileMarkdown.tsx | 2 +- mobile/src/components/MobilePRSidebar.tsx | 58 +- .../src/components/MobilePrComposeSheet.tsx | 5 +- mobile/src/components/MobileSearchField.tsx | 201 + .../pr-sidebar/MobilePrViewPanel.tsx | 145 +- .../pr-sidebar/PRActionsSection.tsx | 124 +- .../pr-sidebar/PRCommentsSection.tsx | 16 +- .../pr-sidebar/PRReviewersSection.tsx | 46 +- .../src/components/pr-sidebar/PRSection.tsx | 20 +- .../components/pr-sidebar/PRSidebarHeader.tsx | 127 +- .../pr-sidebar/ReviewerPickerDrawer.tsx | 48 +- .../pr-sidebar/mobile-pr-sidebar-styles.ts | 44 +- .../pr-sidebar/pr-actions-styles.ts | 13 + .../pr-sidebar/pr-comment-composer-styles.ts | 3 +- .../connection-diagnostics-report.test.ts | 55 + .../connection-diagnostics-report.ts | 58 + .../src/diagnostics/host-reachability.test.ts | 24 +- mobile/src/diagnostics/host-reachability.ts | 12 + .../troubleshoot-common-issues.tsx | 73 + .../mobile-notifications.test.ts | 49 +- .../src/notifications/mobile-notifications.ts | 33 + .../session/MobileSessionHeaderIconButton.tsx | 39 + .../MobileSessionHeaderMoreActionsSheet.tsx | 57 + mobile/src/session/SessionDockColumn.tsx | 60 +- mobile/src/session/TerminalPaneView.tsx | 14 +- .../session/ai-vault-resume-launch.test.ts | 300 ++ mobile/src/session/ai-vault-resume-launch.ts | 269 ++ mobile/src/session/github-pr-rpc.test.ts | 17 + mobile/src/session/github-pr-value-readers.ts | 13 +- mobile/src/session/mobile-pr-sidebar-state.ts | 56 + .../session/mobile-session-route-helpers.ts | 2 +- .../mobile-session-startup-source.test.ts | 2 + .../session/mobile-terminal-records.test.ts | 12 + mobile/src/session/mobile-terminal-records.ts | 23 +- mobile/src/session/pr-actions-engine.test.ts | 45 + mobile/src/session/pr-actions-engine.ts | 21 +- mobile/src/session/session-panel-host.test.ts | 46 +- mobile/src/session/session-panel-host.ts | 20 +- .../session/use-mobile-pr-branch-context.ts | 19 +- ...mobile-pr-sidebar-controller-probe.test.ts | 100 + .../use-mobile-pr-sidebar-controller.test.ts | 87 + .../use-mobile-pr-sidebar-controller.ts | 271 +- .../src/session/use-mobile-terminal-paste.ts | 2 +- .../source-control/MobileGitHistoryList.tsx | 271 ++ .../MobileSourceControlBranchCard.tsx | 78 + .../MobileSourceControlContent.tsx | 56 +- .../MobileSourceControlHeader.tsx | 25 +- .../MobileSourceControlPanel.tsx | 337 +- .../MobileSourceControlPrChip.tsx | 121 + .../MobileSourceControlSegments.tsx | 45 + .../mobile-history-screen-state.test.ts | 47 + .../mobile-history-screen-state.ts | 30 + .../mobile-pr-chip-summary.test.ts | 138 + .../source-control/mobile-pr-chip-summary.ts | 104 + .../mobile-source-control-actions.test.ts | 4 +- .../mobile-source-control-actions.ts | 2 +- ...bile-source-control-conflict-abort.test.ts | 28 + .../mobile-source-control-conflict-abort.ts | 18 + .../mobile-source-control-hub-styles.ts | 126 + .../mobile-source-control-hub-tab.test.ts | 22 + .../mobile-source-control-hub-tab.ts | 29 + .../mobile-source-control-styles.ts | 18 + .../use-mobile-source-control-runners.ts | 27 +- .../use-mobile-source-control-state.ts | 9 +- mobile/src/terminal/TerminalWebView.tsx | 100 +- .../terminal-foreground-recovery.test.ts | 6 + .../terminal-ios-dictation-write-back.test.ts | 25 + .../terminal-keyboard-dismiss.test.ts | 82 + .../src/terminal/terminal-keyboard-dismiss.ts | 17 + .../terminal-text-input-normalization.test.ts | 6 - .../terminal-text-input-normalization.ts | 19 +- .../terminal/terminal-viewport-refit.test.ts | 30 + .../src/terminal/terminal-viewport-refit.ts | 51 +- .../src/terminal/terminal-webview-contract.ts | 14 + .../terminal-webview-engine-error.test.ts | 108 +- .../terminal/terminal-webview-engine.test.ts | 135 +- mobile/src/terminal/terminal-webview-html.ts | 39 +- .../src/terminal/terminal-webview-messages.ts | 1 + .../terminal-webview-text-zoom.test.ts | 8 +- .../terminal-webview-theme-injected.ts | 27 + ...erminal-webview-webgl-recovery-injected.ts | 62 + .../use-terminal-live-input-commit.test.ts | 26 + .../use-terminal-live-input-commit.ts | 8 +- mobile/src/transport/client-context.test.ts | 159 + mobile/src/transport/client-context.tsx | 19 +- .../src/transport/connection-health.test.ts | 80 + mobile/src/transport/connection-health.ts | 40 +- .../transport/connection-log-buffer.test.ts | 56 + mobile/src/transport/connection-log-buffer.ts | 84 + mobile/src/transport/rpc-client.test.ts | 32 +- mobile/src/transport/rpc-client.ts | 76 +- .../src/transport/rpc-response-shape.test.ts | 19 + .../worktree/mobile-workspace-lineage.test.ts | 36 +- .../src/worktree/mobile-workspace-lineage.ts | 25 +- .../src/worktree/workspace-list-ordering.ts | 124 + .../worktree/workspace-list-sections.test.ts | 313 +- .../src/worktree/workspace-list-sections.ts | 107 +- mobile/src/worktree/workspace-list-types.ts | 8 + .../worktree-activation-result.test.ts | 13 + .../worktree/worktree-activation-result.ts | 8 + .../worktree/worktree-list-snapshot.test.ts | 44 + mobile/src/worktree/worktree-list-snapshot.ts | 7 + mobile/tsconfig.json | 4 +- mobile/vitest.config.ts | 21 +- native/notification-status-macos/main.swift | 35 + notes/garble-fuzz-divergences.md | 296 ++ notes/orca-performance-branch-guide.md | 532 +++ notes/terminal-performance-initiative.md | 583 +++ package.json | 33 +- pnpm-lock.yaml | 417 +- previews/mobile-driver-overlay-preview.html | 523 --- src/cli/agent-context.test.ts | 93 + src/cli/agent-context.ts | 60 + src/cli/args.test.ts | 190 + src/cli/args.ts | 120 +- src/cli/command-suggestion.test.ts | 85 + src/cli/command-suggestion.ts | 101 + src/cli/dispatch.ts | 6 + src/cli/format-recovery.test.ts | 60 + src/cli/format.ts | 47 +- src/cli/handlers/agent-hooks.test.ts | 14 +- src/cli/handlers/agent-hooks.ts | 16 +- src/cli/handlers/introspection.ts | 16 + src/cli/handlers/terminal.ts | 4 +- src/cli/help.ts | 18 +- src/cli/index.test.ts | 219 +- src/cli/index.ts | 48 +- src/cli/registry-parity.test.ts | 46 + src/cli/registry-parity.ts | 21 + src/cli/runtime/envelope-schema.test.ts | 56 + src/cli/runtime/types.ts | 9 +- src/cli/specs/core.ts | 17 +- src/cli/specs/index.ts | 2 + src/cli/specs/introspection.ts | 15 + src/cli/vocabulary-policy.test.ts | 53 + src/cli/vocabulary-policy.ts | 73 + .../first-work-branch-rename.test.ts | 34 + .../agent-hooks/first-work-branch-rename.ts | 24 +- .../remote-hook-service-installers.test.ts | 201 +- .../remote-managed-hook-installers.ts | 49 +- .../agent-hooks/server-grok-discovery.test.ts | 119 + src/main/agent-hooks/server.test.ts | 2 + src/main/agent-hooks/server.ts | 70 +- src/main/agent-hooks/wsl-hook-fs-adapter.ts | 136 + src/main/agent-hooks/wsl-hook-relay-deps.ts | 90 + src/main/agent-hooks/wsl-hook-relay-launch.ts | 330 ++ src/main/agent-hooks/wsl-hook-relay-link.ts | 58 + .../wsl-hook-relay-live.integration.test.ts | 203 + .../wsl-hook-relay-manager.test.ts | 389 ++ .../agent-hooks/wsl-hook-relay-manager.ts | 328 ++ .../wsl-hook-relay-recovery.test.ts | 155 + .../agent-hooks/wsl-hook-relay-recovery.ts | 81 + .../wsl-hook-relay-sentinel.test.ts | 152 + .../agent-hooks/wsl-hook-relay-sentinel.ts | 159 + src/main/ai-vault/cached-session-list.ts | 101 + .../remote-session-scanner-sources.ts | 28 +- .../ai-vault/remote-session-scanner-types.ts | 4 + .../ai-vault/remote-session-scanner.test.ts | 119 + src/main/ai-vault/remote-session-scanner.ts | 23 +- .../ai-vault/runtime-session-scanner.test.ts | 147 + src/main/ai-vault/runtime-session-scanner.ts | 195 + src/main/ai-vault/session-list-results.ts | 71 + .../ai-vault/session-scanner-accumulator.ts | 7 +- .../ai-vault/session-scanner-agent-parser.ts | 3 +- ...sion-scanner-claude-subagent-prune.test.ts | 61 + .../session-scanner-claude-subagents.test.ts | 396 ++ .../session-scanner-claude-subagents.ts | 281 ++ .../session-scanner-codex-parser.test.ts | 51 + .../ai-vault/session-scanner-discovery.ts | 2 + .../session-scanner-gemini-parsers.ts | 156 + .../session-scanner-injected-title.test.ts | 56 + .../ai-vault/session-scanner-parse-cache.ts | 17 +- .../session-scanner-primary-parsers.ts | 181 +- .../session-scanner-recoverable-empty.test.ts | 261 ++ .../session-scanner-source-discovery.ts | 32 +- .../session-scanner-subagent-transcripts.ts | 85 + src/main/ai-vault/session-scanner-types.ts | 3 + src/main/automations/service.test.ts | 56 + src/main/automations/service.ts | 32 +- .../browser-cookie-import-test-database.ts | 82 + .../browser/browser-cookie-import.test.ts | 211 +- src/main/browser/browser-cookie-import.ts | 143 +- src/main/browser/browser-manager.test.ts | 287 +- src/main/browser/browser-manager.ts | 108 +- .../browser-session-permission-policy.ts | 5 +- ...owser-session-registry.persistence.test.ts | 48 + .../browser/browser-session-registry.test.ts | 43 + src/main/browser/browser-session-registry.ts | 119 +- .../browser/browser-session-startup.test.ts | 29 + src/main/browser/browser-session-startup.ts | 9 +- src/main/browser/cdp-ws-proxy.test.ts | 142 + src/main/browser/cdp-ws-proxy.ts | 88 +- src/main/browser/chromium-cookie-path.ts | 13 + .../browser/chromium-cookie-snapshot.test.ts | 170 + src/main/browser/chromium-cookie-snapshot.ts | 140 + src/main/claude-usage/scanner-scan.test.ts | 313 ++ src/main/claude-usage/scanner.ts | 154 +- src/main/claude-usage/store.ts | 5 +- src/main/claude-usage/types.ts | 8 + .../runtime-home-service.test.ts | 164 +- .../codex-accounts/runtime-home-service.ts | 83 +- src/main/codex-accounts/service.test.ts | 41 +- src/main/codex-accounts/service.ts | 31 +- .../codex-accounts/wsl-codex-command.test.ts | 23 + src/main/codex-accounts/wsl-codex-command.ts | 43 + src/main/codex-usage/scanner-paths.test.ts | 220 +- src/main/codex-usage/scanner.test.ts | 5 + src/main/codex-usage/scanner.ts | 122 +- src/main/codex-usage/store.test.ts | 6 +- src/main/codex-usage/store.ts | 5 +- src/main/codex-usage/types.ts | 12 + src/main/codex/codex-config-mirror.test.ts | 245 + src/main/codex/codex-config-mirror.ts | 106 +- src/main/codex/codex-hook-identity.ts | 72 + src/main/codex/codex-session-bridge.test.ts | 45 + src/main/codex/codex-session-bridge.ts | 17 +- .../codex/codex-session-source-home.test.ts | 72 + src/main/codex/codex-session-source-home.ts | 43 + .../codex/codex-wsl-hook-install-plan.test.ts | 200 + src/main/codex/codex-wsl-hook-install-plan.ts | 197 + .../codex/config-settings-promotion.test.ts | 442 ++ src/main/codex/config-settings-promotion.ts | 341 ++ src/main/codex/config-toml-trust.test.ts | 82 + src/main/codex/config-toml-trust.ts | 120 +- .../codex/hook-service-wsl-runtime.test.ts | 384 ++ src/main/codex/hook-service.ts | 605 ++- src/main/codex/hook-trust-promotion.test.ts | 399 ++ src/main/codex/hook-trust-promotion.ts | 257 ++ .../daemon-background-transient-facts.test.ts | 76 + .../daemon-background-transient-facts.ts | 106 + src/main/daemon/daemon-entry.test.ts | 25 + src/main/daemon/daemon-entry.ts | 75 +- src/main/daemon/daemon-errors.ts | 22 + src/main/daemon/daemon-file-log.test.ts | 100 + src/main/daemon/daemon-file-log.ts | 137 + ...n-foreground-confirmation-protocol.test.ts | 9 + .../daemon-foreground-process-protocol.ts | 11 + src/main/daemon/daemon-health.test.ts | 60 +- src/main/daemon/daemon-health.ts | 91 +- .../daemon/daemon-host-relocation.test.ts | 270 ++ src/main/daemon/daemon-host-relocation.ts | 398 ++ src/main/daemon/daemon-init.test.ts | 394 +- src/main/daemon/daemon-init.ts | 207 +- src/main/daemon/daemon-main.ts | 5 +- src/main/daemon/daemon-pty-adapter.test.ts | 353 +- src/main/daemon/daemon-pty-adapter.ts | 429 +- src/main/daemon/daemon-pty-router.test.ts | 112 +- src/main/daemon/daemon-pty-router.ts | 46 +- src/main/daemon/daemon-server.test.ts | 111 + src/main/daemon/daemon-server.ts | 224 +- .../daemon/daemon-stream-backlog-probe.ts | 55 + .../daemon/daemon-stream-data-batcher.test.ts | 478 +- src/main/daemon/daemon-stream-data-batcher.ts | 360 +- src/main/daemon/daemon-stream-data-split.ts | 114 + src/main/daemon/daemon-stream-events.ts | 78 + .../daemon/daemon-stream-keep-tail-drop.ts | 182 + .../degraded-daemon-fallback-shutdown.ts | 25 + .../degraded-daemon-pty-provider.test.ts | 79 +- .../daemon/degraded-daemon-pty-provider.ts | 72 +- .../headless-emulator-fidelity.fuzz.test.ts | 430 ++ src/main/daemon/headless-emulator.test.ts | 153 + src/main/daemon/headless-emulator.ts | 384 +- .../hibernation-cold-restore-repro.test.ts | 2 +- src/main/daemon/history-manager.ts | 25 + src/main/daemon/history-reader.ts | 16 +- ...subprocess-foreground-scan-cadence.test.ts | 188 + src/main/daemon/pty-subprocess.test.ts | 138 +- src/main/daemon/pty-subprocess.ts | 107 +- src/main/daemon/reattach-snapshot.test.ts | 20 +- ...ro-7329-remote-snapshot-corruption.test.ts | 182 + .../session-ingest-throughput.bench.test.ts | 130 + src/main/daemon/session.test.ts | 142 +- src/main/daemon/session.ts | 102 +- ...rminal-history-incremental-restore.test.ts | 7 +- .../daemon/terminal-host-create-contract.ts | 33 + src/main/daemon/terminal-host.ts | 82 +- .../terminal-mode-rehydrate-sequences.ts | 47 + src/main/daemon/terminal-mouse-mode-mirror.ts | 119 + .../daemon/terminal-osc-cwd-title-scanner.ts | 53 + .../daemon/terminal-snapshot-ansi-buffers.ts | 21 + ...minal-snapshot-serialize-roundtrip.test.ts | 254 + .../terminal-view-attribute-responder.ts | 191 + src/main/daemon/types.ts | 143 +- src/main/droid/hook-service.ts | 126 +- .../emulator/serve-sim-state-watcher.test.ts | 17 +- src/main/external-editor-launch.test.ts | 135 +- src/main/external-editor-launch.ts | 22 +- src/main/git/branch-rename.test.ts | 52 +- src/main/git/branch-rename.ts | 31 +- src/main/git/check-ignored-paths.test.ts | 37 +- src/main/git/check-ignored-paths.ts | 38 +- src/main/git/git-capability-state.test.ts | 37 + src/main/git/git-capability-state.ts | 44 + src/main/git/remote.test.ts | 29 + src/main/git/remove-worktree.test.ts | 50 +- src/main/git/repo-search-ref-compat.test.ts | 6 +- src/main/git/repo.ts | 56 +- src/main/git/runner-wsl-gh-fallback.test.ts | 23 + src/main/git/runner.test.ts | 25 +- src/main/git/runner.ts | 39 +- src/main/git/status-wsl-pathspecs.test.ts | 87 + src/main/git/status.ts | 58 +- .../git/worktree-git-capabilities.test.ts | 138 + src/main/git/worktree-list-paths.test.ts | 46 + src/main/git/worktree.test.ts | 47 + src/main/git/worktree.ts | 136 +- src/main/github/client.test.ts | 16 +- src/main/github/client.ts | 71 +- src/main/github/conflict-summary-cache.ts | 150 + src/main/github/conflict-summary.test.ts | 348 ++ src/main/github/conflict-summary.ts | 211 +- .../github/pr-refresh-coordinator.test.ts | 67 +- src/main/github/pr-refresh-coordinator.ts | 19 +- src/main/github/rate-limit.test.ts | 138 + src/main/github/rate-limit.ts | 11 + src/main/gitlab/client-mr.test.ts | 3 + src/main/gitlab/client.ts | 5 +- src/main/grok-accounts/status.test.ts | 69 + src/main/grok-accounts/status.ts | 32 + src/main/grok/hook-service.test.ts | 52 +- src/main/grok/hook-service.ts | 85 +- src/main/index.ts | 110 +- src/main/ipc/ai-vault.test.ts | 172 +- src/main/ipc/ai-vault.ts | 262 +- src/main/ipc/app.test.ts | 153 +- src/main/ipc/app.ts | 87 +- ...list-files-git-directory-expansion.test.ts | 103 + .../ipc/filesystem-list-files-git-fallback.ts | 85 +- src/main/ipc/filesystem-list-files.test.ts | 57 + src/main/ipc/filesystem-list-files.ts | 5 +- .../ipc/filesystem-watcher-ignore.test.ts | 38 +- src/main/ipc/filesystem-watcher-ignore.ts | 49 +- src/main/ipc/filesystem-watcher.ts | 27 +- src/main/ipc/filesystem.test.ts | 35 + src/main/ipc/filesystem.ts | 55 +- src/main/ipc/grok-accounts.ts | 6 + src/main/ipc/jira.ts | 11 + src/main/ipc/linear.test.ts | 38 +- src/main/ipc/linear.ts | 18 +- .../ipc/notification-authorization-status.ts | 92 + src/main/ipc/notifications.test.ts | 471 +- src/main/ipc/notifications.ts | 403 +- .../ipc/orca-profile-auth-handlers.test.ts | 171 + .../orca-profile-org-members-handlers.test.ts | 116 + .../ipc/orca-profile-org-members-handlers.ts | 128 + src/main/ipc/orca-profiles.test.ts | 321 ++ src/main/ipc/orca-profiles.ts | 291 ++ .../ipc/parcel-watcher-entry-path.test.ts | 40 + src/main/ipc/parcel-watcher-entry-path.ts | 37 + .../ipc/parcel-watcher-process-entry.test.ts | 218 + src/main/ipc/parcel-watcher-process-entry.ts | 254 + src/main/ipc/parcel-watcher-process.test.ts | 286 ++ src/main/ipc/parcel-watcher-process.ts | 329 ++ src/main/ipc/preflight-command-exec.test.ts | 56 + src/main/ipc/preflight-command-exec.ts | 23 +- .../ipc/preflight-wsl-agent-detection.test.ts | 16 + src/main/ipc/preflight-wsl-agent-detection.ts | 13 +- src/main/ipc/preflight.test.ts | 74 + src/main/ipc/preflight.ts | 43 +- src/main/ipc/pty-hidden-delivery-gate.test.ts | 118 + src/main/ipc/pty-hidden-delivery-gate.ts | 154 + .../ipc/pty-producer-flow-control.test.ts | 137 + src/main/ipc/pty-producer-flow-control.ts | 105 + src/main/ipc/pty.test.ts | 3889 +++++++++++++--- src/main/ipc/pty.ts | 1510 +++++- src/main/ipc/rate-limits.test.ts | 20 +- src/main/ipc/rate-limits.ts | 1 + src/main/ipc/register-core-handlers.test.ts | 95 +- src/main/ipc/register-core-handlers.ts | 17 +- src/main/ipc/repos-remote.test.ts | 14 +- src/main/ipc/repos.ts | 69 +- src/main/ipc/settings.test.ts | 39 +- src/main/ipc/settings.ts | 13 + src/main/ipc/shell.test.ts | 17 + src/main/ipc/ssh.test.ts | 112 +- src/main/ipc/ssh.ts | 103 +- .../ipc/tui-agent-detection-commands.test.ts | 49 + src/main/ipc/tui-agent-detection-commands.ts | 77 + .../ipc/workspace-cleanup-activity.test.ts | 163 + src/main/ipc/workspace-cleanup-activity.ts | 126 + src/main/ipc/workspace-cleanup-scan.ts | 97 +- src/main/ipc/workspace-cleanup.test.ts | 232 +- src/main/ipc/worktree-remote.ts | 6 +- src/main/ipc/worktrees.test.ts | 450 +- src/main/ipc/worktrees.ts | 274 +- src/main/jira/issues.test.ts | 96 + src/main/jira/issues.ts | 82 + src/main/linear/issue-list-filter.test.ts | 80 + src/main/linear/issue-list-filter.ts | 117 + src/main/linear/issues.test.ts | 46 +- src/main/linear/issues.ts | 72 +- ...cal-worktree-removal-recovery-live.test.ts | 128 + .../local-worktree-removal-recovery.test.ts | 257 +- src/main/local-worktree-removal-recovery.ts | 141 +- .../memory/hydrate-local-pty-registry.test.ts | 175 +- src/main/memory/hydrate-local-pty-registry.ts | 80 +- .../native-chat/session-file-resolver.test.ts | 74 +- src/main/native-chat/session-file-resolver.ts | 23 + .../transcript-fallback-id.test.ts | 22 + .../native-chat/transcript-fallback-id.ts | 10 + .../transcript-line-decoders-claude.ts | 66 + .../transcript-line-decoders-codex.ts | 139 + .../transcript-line-decoders-grok.ts | 247 + .../transcript-line-decoders.grok.test.ts | 198 + .../native-chat/transcript-line-decoders.ts | 183 +- .../native-chat/transcript-reader.test.ts | 68 + src/main/native-chat/transcript-reader.ts | 32 +- .../transcript-stream-lines.test.ts | 49 + .../native-chat/transcript-stream-lines.ts | 47 + src/main/native-chat/transcript-watch.ts | 59 +- src/main/observability/bundle.test.ts | 47 + src/main/observability/bundle.ts | 30 +- src/main/observability/index.ts | 37 +- src/main/observability/logs-directory.ts | 41 + src/main/opencode-usage/scanner.test.ts | 241 +- src/main/opencode-usage/scanner.ts | 141 +- src/main/opencode-usage/store.test.ts | 10 +- src/main/opencode-usage/store.ts | 4 +- src/main/opencode-usage/types.ts | 7 + .../profile-cloud-auth-config.test.ts | 122 + .../profile-cloud-auth-config.ts | 115 + .../profile-cloud-auth-status.ts | 56 + .../profile-cloud-client.test.ts | 249 + .../orca-profiles/profile-cloud-client.ts | 263 ++ .../orca-profiles/profile-cloud-dev-auth.ts | 67 + .../profile-cloud-dev-org-members.ts | 130 + .../profile-cloud-dev-service.test.ts | 142 + .../profile-cloud-dev-service.ts | 92 + src/main/orca-profiles/profile-cloud-index.ts | 143 + .../profile-cloud-org-members-client.test.ts | 150 + .../profile-cloud-org-members-client.ts | 209 + .../profile-cloud-org-members-service.test.ts | 259 ++ .../profile-cloud-org-members-service.ts | 212 + .../orca-profiles/profile-cloud-pkce.test.ts | 127 + src/main/orca-profiles/profile-cloud-pkce.ts | 142 + .../profile-cloud-service-auth-retry.test.ts | 247 + .../profile-cloud-service-refresh.test.ts | 254 + .../profile-cloud-service.test.ts | 285 ++ .../orca-profiles/profile-cloud-service.ts | 300 ++ .../profile-cloud-session-exchange.ts | 14 + .../profile-cloud-session-refresh.ts | 178 + .../profile-cloud-session-store.test.ts | 172 + .../profile-cloud-session-store.ts | 209 + .../orca-profiles/profile-index-store.test.ts | 198 + src/main/orca-profiles/profile-index-store.ts | 327 ++ .../profile-project-presence.test.ts | 145 + .../orca-profiles/profile-project-presence.ts | 51 + .../profile-project-session-state.ts | 155 + .../profile-project-session-transfer.ts | 215 + .../profile-project-source-removal.ts | 66 + .../profile-project-state-file.ts | 139 + .../profile-project-transfer-payload.ts | 294 ++ .../profile-project-transfer.test.ts | 301 ++ .../orca-profiles/profile-project-transfer.ts | 77 + .../profile-project-worktree-identity.ts | 77 + .../orca-profiles/profile-storage-paths.ts | 72 + .../orca-profiles/profile-ui-scope.test.ts | 14 + src/main/orca-profiles/profile-ui-scope.ts | 6 + src/main/persistence.test.ts | 525 ++- src/main/persistence.ts | 366 +- .../pi/agent-status-extension-source.test.ts | 317 ++ src/main/pi/agent-status-extension-source.ts | 82 + src/main/pi/legacy-omp-overlay-migration.ts | 242 + .../pi/titlebar-extension-service.test.ts | 247 + src/main/pi/titlebar-extension-service.ts | 11 + .../agent-foreground-process.test.ts | 250 +- .../providers/agent-foreground-process.ts | 65 +- src/main/providers/local-pty-provider.test.ts | 60 +- src/main/providers/local-pty-provider.ts | 59 +- .../providers/local-pty-shell-ready.test.ts | 137 +- src/main/providers/local-pty-shell-ready.ts | 26 +- src/main/providers/provider-dispatch.test.ts | 3 + .../providers/ssh-filesystem-provider.test.ts | 35 +- src/main/providers/ssh-filesystem-provider.ts | 12 +- src/main/providers/ssh-git-provider.test.ts | 26 +- src/main/providers/ssh-git-provider.ts | 17 +- src/main/providers/ssh-pty-provider.test.ts | 33 +- src/main/providers/ssh-pty-provider.ts | 36 +- src/main/providers/types.ts | 80 +- .../windows-agent-foreground-process.ts | 83 +- .../windows-conpty-process-membership.test.ts | 64 + .../windows-conpty-process-membership.ts | 74 + .../windows-foreground-process-rows.ts | 16 +- src/main/providers/windows-shell-args.test.ts | 44 +- src/main/providers/windows-shell-args.ts | 2 + src/main/pty/codex-home-wsl-env.ts | 16 + src/main/pty/terminal-cwd-realpath.test.ts | 43 - src/main/pty/terminal-cwd-realpath.ts | 30 - src/main/pty/wsl-orca-env.test.ts | 23 + src/main/pty/wsl-orca-env.ts | 12 +- .../auth-filesystem-operation.test.ts | 119 + .../rate-limits/auth-filesystem-operation.ts | 175 + .../rate-limits/codex-auth-presence.test.ts | 134 +- src/main/rate-limits/codex-auth-presence.ts | 71 +- .../codex-fetcher-auth-errors.test.ts | 2 +- .../rate-limits/codex-fetcher-backend.test.ts | 196 + .../codex-fetcher-pty-settle.test.ts | 2 +- src/main/rate-limits/codex-fetcher.test.ts | 155 +- src/main/rate-limits/codex-fetcher.ts | 242 +- src/main/rate-limits/grok-auth.test.ts | 48 + src/main/rate-limits/grok-auth.ts | 116 + src/main/rate-limits/grok-fetcher.test.ts | 164 + src/main/rate-limits/grok-fetcher.ts | 173 + src/main/rate-limits/service.test.ts | 146 +- src/main/rate-limits/service.ts | 205 +- src/main/repo-worktrees.test.ts | 22 +- src/main/repo-worktrees.ts | 8 +- src/main/runtime/fetch-remote-cache.test.ts | 71 +- src/main/runtime/file-watcher-host.ts | 6 +- src/main/runtime/file-watcher-worker.ts | 5 +- src/main/runtime/mobile-presence-lock.test.ts | 263 +- ...bile-session-tabs-notify-coalescer.test.ts | 120 + .../mobile-session-tabs-notify-coalescer.ts | 109 + .../mobile-subscribe-integration.test.ts | 106 + .../runtime/orca-runtime-terminal-cwd.test.ts | 12 +- src/main/runtime/orca-runtime.test.ts | 3389 +++++++++++++- src/main/runtime/orca-runtime.ts | 2258 +++++++-- .../runtime/orchestration/coordinator.test.ts | 10 +- src/main/runtime/orchestration/coordinator.ts | 7 +- ...ned-tail-redraw-window.equivalence.test.ts | 90 + src/main/runtime/rpc/dispatcher.ts | 2 +- .../e2ee-channel-text-backpressure.test.ts | 98 + src/main/runtime/rpc/e2ee-channel.ts | 29 +- src/main/runtime/rpc/methods/ai-vault.test.ts | 228 + src/main/runtime/rpc/methods/ai-vault.ts | 65 + .../runtime/rpc/methods/client-ui.test.ts | 8 +- src/main/runtime/rpc/methods/client-ui.ts | 4 + src/main/runtime/rpc/methods/index.ts | 2 + src/main/runtime/rpc/methods/jira.test.ts | 9 +- src/main/runtime/rpc/methods/jira.ts | 11 + .../linear-issue-attribute-filter-schema.ts | 35 + src/main/runtime/rpc/methods/linear.test.ts | 4 +- src/main/runtime/rpc/methods/linear.ts | 9 +- .../runtime/rpc/methods/orchestration.test.ts | 36 +- src/main/runtime/rpc/methods/orchestration.ts | 2 +- src/main/runtime/rpc/methods/session-tabs.ts | 7 +- src/main/runtime/rpc/methods/ssh.test.ts | 37 +- src/main/runtime/rpc/methods/ssh.ts | 17 +- src/main/runtime/rpc/methods/terminal.ts | 420 +- src/main/runtime/rpc/methods/worktree.test.ts | 46 +- src/main/runtime/rpc/methods/worktree.ts | 7 +- src/main/runtime/rpc/streaming.test.ts | 3 + .../terminal-geometry-stale-handle.test.ts | 222 + .../terminal-multiplex-escape-tail.test.ts | 131 + .../runtime/rpc/terminal-multiplex.test.ts | 1281 +++++- .../rpc/terminal-output-batching.test.ts | 36 +- src/main/runtime/rpc/terminal-send.test.ts | 41 +- .../rpc/terminal-subscribe-buffer.test.ts | 330 +- .../rpc/ws-fallback-port-store.test.ts | 35 + .../runtime/rpc/ws-fallback-port-store.ts | 45 + src/main/runtime/rpc/ws-transport.test.ts | 122 + src/main/runtime/rpc/ws-transport.ts | 56 +- src/main/runtime/runtime-rpc.test.ts | 209 + src/main/runtime/runtime-rpc.ts | 17 +- .../terminal-model-query-authority.test.ts | 140 + .../runtime/terminal-model-query-authority.ts | 111 + .../runtime/terminal-query-responder.test.ts | 827 ++++ .../runtime/terminal-view-attribute-store.ts | 57 + src/main/shell-templates.ts | 17 +- .../speech/stt-offline-audio-chunker.test.ts | 100 + src/main/speech/stt-offline-audio-chunker.ts | 92 + src/main/speech/stt-service.test.ts | 172 +- src/main/speech/stt-service.ts | 215 +- src/main/speech/stt-worker-model-config.ts | 81 + src/main/speech/stt-worker.ts | 161 +- src/main/ssh/relay-protocol.test.ts | 17 + src/main/ssh/relay-protocol.ts | 39 + src/main/ssh/ssh-channel-multiplexer.test.ts | 75 + src/main/ssh/ssh-channel-multiplexer.ts | 58 + src/main/ssh/ssh-connection-store.test.ts | 158 +- src/main/ssh/ssh-connection-store.ts | 36 + .../ssh/ssh-git-response-stream-reader.ts | 311 ++ src/main/ssh/ssh-port-forward.test.ts | 21 + src/main/ssh/ssh-port-scanner.test.ts | 261 ++ src/main/ssh/ssh-port-scanner.ts | 76 +- src/main/ssh/ssh-relay-deploy.ts | 11 +- .../ssh/ssh-relay-session-test-fixtures.ts | 48 + src/main/ssh/ssh-relay-session.test.ts | 189 +- src/main/ssh/ssh-relay-session.ts | 109 +- .../ssh-remote-cli-host-passthrough.test.ts | 250 + .../ssh/ssh-remote-cli-host-passthrough.ts | 270 ++ src/main/ssh/ssh-remote-orca-cli.test.ts | 182 +- src/main/ssh/ssh-remote-orca-cli.ts | 90 +- src/main/ssh/ssh-target-id-migration.test.ts | 139 + src/main/ssh/ssh-target-id-migration.ts | 116 + src/main/ssh/ssh-target-readoption.test.ts | 198 + src/main/ssh/ssh-target-readoption.ts | 99 + .../ssh/system-ssh-port-forward-provider.ts | 8 + .../synthetic-title-frame-routing.test.ts | 24 + src/main/synthetic-title-frame-routing.ts | 14 + src/main/system-resume-broadcast.test.ts | 64 + src/main/system-resume-broadcast.ts | 39 + src/main/terminal-scrollback-snapshots.ts | 85 +- src/main/tray/system-tray.test.ts | 82 +- src/main/tray/system-tray.ts | 43 +- src/main/tray/tray-attention-icon.test.ts | 88 + src/main/tray/tray-attention-icon.ts | 52 + src/main/updater-events.ts | 34 +- src/main/updater-lifecycle-diagnostics.ts | 12 + src/main/updater-mac-install.ts | 21 +- src/main/updater.mac-install.test.ts | 4 +- src/main/updater.test.ts | 160 +- src/main/updater.ts | 158 +- src/main/win32-utils.test.ts | 21 + .../window/attach-main-window-services.ts | 1 + src/main/window/createMainWindow.test.ts | 104 + src/main/window/createMainWindow.ts | 17 + .../window/main-window-visibility.test.ts | 28 + src/main/window/main-window-visibility.ts | 38 + src/preload/api-types.ts | 207 +- src/preload/e2e-config.ts | 5 +- src/preload/index.ts | 188 +- src/relay/agent-hook-server.test.ts | 157 + src/relay/agent-hook-server.ts | 156 +- src/relay/dispatcher.test.ts | 67 + src/relay/dispatcher.ts | 12 +- src/relay/fs-handler-git-fallback.ts | 71 +- .../fs-handler-list-files-cancel.test.ts | 127 + .../fs-handler-list-files-ignored.test.ts | 94 +- src/relay/fs-handler-list-files.ts | 29 +- src/relay/fs-handler-readdir-fallback.ts | 6 +- src/relay/fs-handler.ts | 46 +- .../fs-list-files-cancel.integration.test.ts | 209 + .../fs-list-files-scan-coordinator.test.ts | 222 + src/relay/fs-list-files-scan-coordinator.ts | 104 + src/relay/git-handler-branch-cleanup.test.ts | 24 +- src/relay/git-handler-branch-cleanup.ts | 8 +- src/relay/git-handler-check-ignore.test.ts | 44 + src/relay/git-handler-check-ignore.ts | 35 + .../git-handler-local-base-ref-refresh.ts | 6 +- src/relay/git-handler-ops.ts | 2 +- src/relay/git-handler-status-ops.ts | 31 - src/relay/git-handler-utils.test.ts | 45 +- src/relay/git-handler-utils.ts | 40 +- ...-handler-worktree-git-capabilities.test.ts | 115 + src/relay/git-handler-worktree-list.ts | 43 + src/relay/git-handler-worktree-ops.test.ts | 80 +- src/relay/git-handler-worktree-ops.ts | 36 +- src/relay/git-handler-worktree-paths.test.ts | 12 +- src/relay/git-handler-worktree-remove.ts | 53 +- src/relay/git-handler.test.ts | 40 +- src/relay/git-handler.ts | 225 +- ...-pty-echo-backpressure.integration.test.ts | 309 ++ .../git-response-stream-ownership.test.ts | 68 + src/relay/git-response-stream.ts | 211 + src/relay/preflight-handler.test.ts | 123 +- src/relay/preflight-handler.ts | 53 +- src/relay/protocol.ts | 21 + src/relay/pty-handler.test.ts | 305 +- src/relay/pty-handler.ts | 111 +- src/relay/pty-shell-utils.test.ts | 35 + src/relay/pty-shell-utils.ts | 13 + src/relay/relay-command-env.test.ts | 19 +- src/relay/relay-command-env.ts | 14 + src/relay/relay-diagnostic-log.test.ts | 21 + src/relay/relay-diagnostic-log.ts | 7 + src/relay/relay-handshake.ts | 13 +- src/relay/relay.ts | 72 +- src/relay/remote-cli-env.test.ts | 4 + src/relay/remote-cli-env.ts | 2 + src/relay/remote-cli-stdin.test.ts | 12 + src/relay/remote-cli-stdin.ts | 6 + src/relay/remote-cli-timeout.test.ts | 60 +- src/relay/remote-cli-timeout.ts | 65 +- src/relay/rotating-log-writer.test.ts | 161 + src/relay/rotating-log-writer.ts | 174 + src/relay/wsl-agent-hook-relay.test.ts | 195 + src/relay/wsl-agent-hook-relay.ts | 114 + src/relay/wsl-hook-fs-bridge.test.ts | 143 + src/relay/wsl-hook-fs-bridge.ts | 153 + src/renderer/src/App.tsx | 76 +- src/renderer/src/app-startup-routing.test.ts | 4 +- src/renderer/src/assets/main.css | 96 +- .../src/assets/rich-markdown-editor.css | 5 +- .../assets/terminal-scrollbar-style.test.ts | 17 + src/renderer/src/assets/terminal.css | 4 +- src/renderer/src/components/AgentStateDot.tsx | 7 +- .../src/components/GitHubItemDialog.tsx | 138 +- .../src/components/LinearItemDrawer.tsx | 4 + .../src/components/PullRequestPage.tsx | 49 +- src/renderer/src/components/TaskPage.tsx | 674 ++- src/renderer/src/components/Terminal.tsx | 403 +- .../BrowserAnnotationSendMenuContent.test.tsx | 105 + .../BrowserAnnotationSendMenuContent.tsx | 29 + .../components/browser-pane/BrowserPane.tsx | 32 +- .../components/editor/CombinedDiffViewer.tsx | 85 +- .../src/components/editor/DiffSectionItem.tsx | 11 +- .../src/components/editor/DiffViewer.tsx | 10 +- .../editor/EditorAutosaveController.tsx | 10 +- .../components/editor/EditorContent.test.tsx | 143 +- .../src/components/editor/EditorContent.tsx | 67 +- .../src/components/editor/EditorPanel.tsx | 25 +- .../components/editor/EditorPanelHeader.tsx | 50 +- .../components/editor/EditorPanelShell.tsx | 6 +- .../editor/ExternalFileChangeBanner.test.tsx | 231 + .../editor/ExternalFileChangeBanner.tsx | 185 + .../ExternalFileChangeCompareDialog.test.tsx | 142 + .../ExternalFileChangeCompareDialog.tsx | 191 + .../src/components/editor/IpynbViewer.tsx | 12 +- .../src/components/editor/MonacoEditor.tsx | 17 +- .../components/editor/RichMarkdownEditor.tsx | 5 + .../editor/RichMarkdownEditorSurface.tsx | 6 + .../editor/RichMarkdownLinkBubble.tsx | 178 +- .../combined-diff-section-connection.test.ts | 128 + .../combined-diff-section-connection.ts | 17 + .../editor/diff-content-signature.ts | 16 + .../editor-autosave-conflict-flow.test.ts | 191 + ...editor-autosave-controller-test-fixture.ts | 52 + .../editor/editor-autosave-controller.ts | 84 +- .../src/components/editor/editor-autosave.ts | 13 + .../editor/editor-changed-on-disk-mark.ts | 26 + .../editor-external-change-telemetry.ts | 62 + .../editor-panel-git-entry-selector.test.ts | 74 + .../editor/editor-panel-git-entry-selector.ts | 17 + .../editor/editor-panel-render-model.test.ts | 72 +- .../editor/editor-panel-render-model.ts | 30 +- .../editor-restored-tab-conflict-scan.test.ts | 361 ++ .../editor-restored-tab-conflict-scan.ts | 228 + .../editor/editor-self-write-registry.test.ts | 14 +- .../editor/editor-self-write-registry.ts | 10 +- .../editor/editor-shortcuts.test.ts | 198 + .../src/components/editor/editor-shortcuts.ts | 28 + .../useEditorPanelContentState.test.tsx | 189 +- .../editor/useEditorPanelContentState.ts | 64 +- .../useEditorPanelExternalContentEvents.ts | 6 + .../useEditorPanelFileLoadRetry.test.tsx | 2 +- .../agents-orchestration/UsagePage.tsx | 28 +- .../FloatingTerminalToggleButton.test.tsx | 62 + .../FloatingTerminalToggleButton.tsx | 35 +- .../github-item-dialog-merge-routing.test.ts | 71 - ...github-item-dialog-source-boundary.test.ts | 15 +- .../github/GitHubMarkdownComposer.tsx | 5 + .../src/components/jira-issue-sorter.ts | 80 + ...-issue-attribute-filter-dropdowns.test.tsx | 40 + ...inear-issue-attribute-filter-dropdowns.tsx | 298 ++ ...ssue-attribute-filter-primary-team.test.ts | 38 + ...ear-issue-attribute-filter-primary-team.ts | 30 + ...linear-issue-attribute-filter-sections.tsx | 377 ++ .../components/mobile/mobile-platform-copy.ts | 2 +- .../native-chat/NativeChatComposer.tsx | 21 +- .../native-chat/NativeChatView.test.tsx | 2 +- .../native-chat-attachment-upload.test.ts | 171 + .../native-chat-attachment-upload.ts | 105 + .../native-chat-availability.test.ts | 50 +- .../native-chat/native-chat-availability.ts | 9 +- .../native-chat-image-paste.test.ts | 8 + .../native-chat/native-chat-image-paste.ts | 6 +- .../native-chat/native-chat-noise.test.ts | 1 + .../native-chat/native-chat-noise.ts | 10 +- .../native-chat-pane-resolution.test.ts | 54 +- .../native-chat/native-chat-pending.test.ts | 39 + .../native-chat/native-chat-pending.ts | 12 +- ...-native-chat-composer-attachments.test.tsx | 6 +- .../use-native-chat-composer-attachments.ts | 9 +- .../use-native-chat-composer-paste.test.tsx | 220 + .../use-native-chat-composer-paste.ts | 92 +- ...-native-chat-external-attachments.test.tsx | 158 + .../use-native-chat-external-attachments.ts | 69 + .../use-native-chat-toggle-shortcut.ts | 7 +- .../new-workspace/SmartWorkspaceNameField.tsx | 7 +- .../mac-notification-permission-card.tsx | 228 + .../onboarding/NotificationStep.test.tsx | 39 + .../onboarding/NotificationStep.tsx | 89 +- .../onboarding/OnboardingFlow.test.tsx | 12 +- .../components/onboarding/OnboardingFlow.tsx | 15 +- .../use-onboarding-flow-persistence.ts | 16 +- .../onboarding/use-onboarding-flow.ts | 28 +- .../orca-profiles/OrcaProfileAvatar.tsx | 22 + .../OrcaProfileCloudMenuItems.tsx | 126 + .../orca-profiles/OrcaProfileCreateDialog.tsx | 66 + .../OrcaProfileManagementDialog.tsx | 272 ++ .../orca-profiles/OrcaProfileOrgMemberRow.tsx | 135 + .../OrcaProfileOrgMembersDialog.test.tsx | 151 + .../OrcaProfileOrgMembersDialog.tsx | 300 ++ ...rcaProfileProjectTransferConfirmDialog.tsx | 162 + .../OrcaProfileSignOutConfirmDialog.tsx | 60 + .../OrcaProfileSwitchConfirmDialog.tsx | 129 + .../OrcaProfileSwitcher.test.tsx | 172 + .../orca-profiles/OrcaProfileSwitcher.tsx | 403 ++ .../orca-profile-org-members-labels.ts | 79 + .../orca-profile-switch-liveness.test.ts | 194 + .../orca-profile-switch-liveness.ts | 180 + .../ports/WorkspacePortScanner.test.tsx | 363 +- .../components/ports/WorkspacePortScanner.tsx | 167 +- .../pull-request-page-host-boundary.test.ts | 9 +- .../quick-open-file-list.react.test.tsx | 35 +- .../src/components/quick-open-file-list.ts | 36 +- .../components/right-sidebar/AiVaultPanel.tsx | 77 +- .../right-sidebar/AiVaultPanelControls.tsx | 26 +- .../right-sidebar/AiVaultPanelHeader.tsx | 7 +- .../AiVaultSessionActionMenuItems.tsx | 20 +- .../right-sidebar/AiVaultSessionDetails.tsx | 203 +- .../right-sidebar/AiVaultSessionRow.tsx | 6 +- .../AiVaultSessionSubagents.test.tsx | 99 + .../right-sidebar/AiVaultSessionSubagents.tsx | 165 + .../AiVaultSessionUnsavedNotice.tsx | 91 + .../AiVaultSessionVirtualList.tsx | 22 +- .../CommitArea.chevron-spinner.test.tsx | 3 + .../CommitArea.generate.test.tsx | 3 + .../CommitArea.primary-icons.test.tsx | 3 + .../right-sidebar/CommitArea.test.tsx | 54 + .../SessionRowTrailingActions.tsx | 2 +- ...rceControl.commit-failure-recovery.test.ts | 4 +- ...ourceControl.push-failure-recovery.test.ts | 46 + ...SourceControl.remote-action-errors.test.ts | 36 +- .../right-sidebar/SourceControl.tsx | 609 +-- .../SourceControl.virtual-file-list.test.tsx | 430 ++ .../SourceControlAgentActionDialog.test.tsx | 19 + .../right-sidebar/ai-vault-host-scope.test.ts | 80 +- .../right-sidebar/ai-vault-host-scope.ts | 74 +- .../ai-vault-original-pane-actions.ts | 28 +- .../ai-vault-original-pane-index.test.ts | 254 + .../ai-vault-original-pane-index.ts | 189 + .../ai-vault-original-pane.test.ts | 60 +- .../right-sidebar/ai-vault-original-pane.ts | 35 +- .../ai-vault-session-display.test.ts | 11 +- .../right-sidebar/ai-vault-session-display.ts | 117 +- .../ai-vault-session-filters.test.ts | 59 +- .../right-sidebar/ai-vault-session-filters.ts | 283 +- .../ai-vault-session-launch-actions.ts | 45 +- .../ai-vault-session-projects.test.ts | 5 +- .../ai-vault-session-projects.ts | 12 +- .../ai-vault-session-resume.test.ts | 106 +- .../right-sidebar/ai-vault-session-resume.ts | 20 +- .../ai-vault-session-row-display.tsx | 53 +- .../ai-vault-session-worktree.test.ts | 5 +- .../ai-vault-view-defaults.test.ts | 72 + .../right-sidebar/ai-vault-view-defaults.ts | 29 + .../coalesced-poll-runner.test.ts | 185 +- .../right-sidebar/coalesced-poll-runner.ts | 97 +- ...le-explorer-runtime-owner-boundary.test.ts | 2 +- .../pr-comments-list-selection.test.tsx | 12 + .../right-sidebar/push-failure-summary.ts | 6 + .../runSourceControlAgentActionStart.test.ts | 171 + .../runSourceControlAgentActionStart.ts | 23 +- .../source-control-action-error.ts | 34 + ...e-control-ai-commit-failure-launch.test.ts | 117 +- ...source-control-ai-commit-failure-launch.ts | 136 +- .../source-control-ai-controller-types.ts | 1 + .../source-control-ai-prompts.ts | 5 + .../source-control-ai-push-failure-launch.ts | 47 + .../source-control-ai-recovery-launch.ts | 178 + .../source-control-dropdown-items.test.ts | 82 +- .../source-control-dropdown-items.ts | 118 +- .../source-control-manual-review-url.ts | 4 +- .../source-control-push-recovery.test.ts | 128 + .../source-control-push-recovery.ts | 85 + .../source-control-recovery-notice.tsx | 348 ++ .../source-control-virtual-file-list.test.tsx | 465 ++ .../source-control-virtual-file-list.tsx | 170 + .../use-file-explorer-ignored-paths.ts | 114 + .../right-sidebar/use-source-control-ai.ts | 81 +- .../use-source-control-recovery-ai.ts | 139 + ...orerVisibleRowProjection.debounce.test.tsx | 98 + ...seFileExplorerVisibleRowProjection.test.ts | 7 +- .../useFileExplorerVisibleRowProjection.ts | 89 +- .../right-sidebar/useGitStatusPolling.ts | 53 +- .../components/settings/AccountsPane.test.tsx | 35 + .../src/components/settings/AccountsPane.tsx | 537 ++- .../src/components/settings/AgentsPane.tsx | 210 +- .../settings/AppearancePane.test.tsx | 25 + .../AppearanceWindowSidebarSection.tsx | 4 +- .../settings/CommitMessageAiPane.test.tsx | 1 + .../src/components/settings/DevToolsPane.tsx | 129 +- .../EphemeralVmsExperimentalSetting.tsx | 2 +- .../settings/GrokAccountsSection.tsx | 186 + .../settings/MobileSettingsPane.tsx | 2 +- .../NativeChatExperimentalSetting.tsx | 6 +- .../components/settings/NotificationsPane.tsx | 29 +- .../RepositorySourceControlAiSection.test.ts | 1 + .../src/components/settings/Settings.tsx | 3 +- .../SourceControlActionRepoOverrideNote.tsx | 3 + .../src/components/settings/SshPane.tsx | 50 +- .../settings/TerminalInteractionSection.tsx | 5 +- ...TerminalSettingsPreview.lifecycle.test.tsx | 6 + .../settings/TerminalSettingsPreview.tsx | 8 +- .../settings/VoiceSpeechModelSection.test.tsx | 30 +- .../settings/VoiceSpeechModelSection.tsx | 4 +- .../components/settings/accounts-search.ts | 24 +- ...nt-skill-installed-command-callers.test.ts | 4 +- ...ce-status-bar-antigravity-toggle-search.ts | 43 + ...ppearance-status-bar-grok-toggle-search.ts | 37 + .../appearance-status-bar-search.test.ts | 13 + .../settings/appearance-status-bar-search.ts | 4 + ...codex-session-source-home-control.test.tsx | 108 + .../codex-session-source-home-control.tsx | 169 + .../linear-agent-skill-install-cta.test.tsx | 185 + .../linear-agent-skill-install-cta.tsx | 186 + .../native-chat-experimental-search-entry.ts | 6 +- .../settings/notification-settings-copy.ts | 33 +- .../provider-account-visibility.test.ts | 227 + .../settings/provider-account-visibility.ts | 101 + .../source-control-action-recipe-options.ts | 4 + .../task-tracker-integration-cards.test.tsx | 21 +- .../task-tracker-integration-cards.tsx | 2 + .../shared/kill-all-terminal-surfaces.test.ts | 365 ++ .../shared/kill-all-terminal-surfaces.ts | 215 + .../shared/useDaemonActions.test.tsx | 152 + .../components/shared/useDaemonActions.tsx | 150 +- .../sidebar/DeleteWorktreeDialog.test.tsx | 41 +- .../sidebar/DeleteWorktreeDialog.tsx | 20 +- .../sidebar/ForgetSshWorkspaceDialog.tsx | 195 + .../components/sidebar/HostRemoveDialog.tsx | 226 +- .../sidebar/LinearAgentSkillSetupPrompt.tsx | 28 +- .../components/sidebar/RemoveFolderDialog.tsx | 30 +- .../sidebar/SidebarToolbar.test.tsx | 16 + .../src/components/sidebar/SidebarToolbar.tsx | 6 +- .../src/components/sidebar/WorktreeCard.tsx | 20 +- .../src/components/sidebar/WorktreeList.tsx | 7 +- .../delete-worktree-dirty-change-counts.ts | 32 + .../delete-worktree-failure-toast.test.tsx | 43 + .../sidebar/delete-worktree-failure-toast.tsx | 28 +- .../sidebar/delete-worktree-flow.test.ts | 41 +- .../sidebar/delete-worktree-flow.ts | 51 +- .../sidebar/delete-worktree-toast.test.ts | 33 +- .../sidebar/delete-worktree-toast.ts | 38 +- src/renderer/src/components/sidebar/index.tsx | 2 + .../ssh-host-remove-resolution.test.ts | 90 + .../sidebar/ssh-host-remove-resolution.ts | 55 + .../sidebar/ssh-host-remove-workspaces.ts | 70 + .../ssh-workspace-forget-resolution.test.ts | 70 + .../ssh-workspace-forget-resolution.ts | 50 + .../sidebar/worktree-card-agent-summary.ts | 2 + .../components/stats/GrokUsagePane.test.tsx | 106 + .../src/components/stats/GrokUsagePane.tsx | 137 + .../src/components/stats/StatsPane.tsx | 13 +- .../src/components/stats/stats-search.ts | 9 +- .../src/components/status-bar/StatusBar.tsx | 300 +- .../status-bar/WorkspaceSpaceManagerPanel.tsx | 2 + .../status-bar/inline-usage-bars.test.tsx | 7 +- .../status-bar-agent-gating.test.ts | 6 + .../status-bar/status-bar-agent-gating.ts | 11 +- .../status-bar-provider-menu-focus.test.tsx | 3 +- .../status-bar-provider-visibility.test.ts | 150 +- .../status-bar-provider-visibility.ts | 39 +- .../status-bar-runtime-groups.test.ts | 97 +- .../src/components/status-bar/tooltip.test.ts | 78 +- .../src/components/status-bar/tooltip.tsx | 34 +- .../status-bar/usage-error-copy.test.ts | 5 + .../components/status-bar/usage-error-copy.ts | 6 + .../components/tab-bar/BrowserTab.test.tsx | 15 + .../src/components/tab-bar/BrowserTab.tsx | 23 +- .../components/tab-bar/EditorFileTab.test.tsx | 18 + .../src/components/tab-bar/EditorFileTab.tsx | 11 +- .../tab-bar/EditorFileTabContextMenu.test.tsx | 24 + .../tab-bar/EditorFileTabContextMenu.tsx | 32 +- .../SortableTab.rename-shortcut.test.tsx | 24 + .../tab-bar/SortableTabContextMenu.test.tsx | 16 +- .../tab-bar/SortableTabContextMenu.tsx | 61 +- .../src/components/tab-bar/TabBar.tsx | 6 + .../tab-bar/TabWorkspaceLayoutMenuSection.tsx | 24 +- .../tab-bar/TerminalTabSplitMenuSection.tsx | 73 + .../tab-group/AiVaultSessionDropLayer.tsx | 42 +- .../components/tab-group/TabGroupPanel.tsx | 16 +- .../tab-group/TabGroupSplitLayout.tsx | 32 +- .../task-page-jira-grouping.test.ts | 202 + .../components/task-page-jira-issue-list.tsx | 353 ++ .../task-page-jira-sort-controls.test.tsx | 56 + .../task-page-jira-sort-controls.tsx | 137 + .../components/task-page-jira-sorting.test.ts | 269 ++ .../components/task-page-jira-status-order.ts | 63 + ...task-page-linear-issue-empty-state.test.ts | 82 + .../task-page-linear-issue-empty-state.ts | 46 + .../task-page-linear-issue-request.test.ts | 77 + .../task-page-linear-issue-request.ts | 80 + .../task-page-new-issue-draft.test.ts | 165 + .../components/task-page-new-issue-draft.ts | 93 + .../components/terminal-pane/TerminalPane.tsx | 62 +- .../TerminalPaneOverlayLayer.tsx | 92 +- .../TerminalSshReconnectOverlay.test.tsx | 161 +- .../TerminalSshReconnectOverlay.tsx | 127 +- .../agent-completion-coordinator-types.ts | 13 + .../agent-completion-coordinator.test.ts | 95 +- .../agent-completion-coordinator.ts | 165 +- ...ent-completion-no-evidence-cadence.test.ts | 212 + .../agent-hook-terminal-lifecycle.test.ts | 50 + .../agent-hook-terminal-lifecycle.ts | 26 + .../agent-task-complete-policy.ts | 66 + .../hard-wrapped-terminal-path-fragments.ts | 68 + .../hidden-reveal-reconciliation.fuzz.test.ts | 558 +++ .../terminal-pane/keyboard-handlers.ts | 59 +- .../layout-serialization.test.ts | 39 +- .../terminal-pane/layout-serialization.ts | 60 +- .../pane-foreground-agent-tracker.test.ts | 250 +- .../pane-foreground-agent-tracker.ts | 147 +- .../parked-terminal-byte-watcher.test.ts | 813 ++++ .../parked-terminal-byte-watcher.ts | 347 ++ .../parked-terminal-mode2031-responder.ts | 50 + .../terminal-pane/pty-connection-types.ts | 11 + .../terminal-pane/pty-connection.test.ts | 4087 +++++++++++++++-- .../terminal-pane/pty-connection.ts | 2030 ++++++-- .../pty-data-sidecar-subscriptions.ts | 6 + .../terminal-pane/pty-delivery-interest.ts | 42 + .../pty-dispatcher-delivery-interest.test.ts | 107 + .../pty-dispatcher-delivery-resync.test.ts | 92 + .../pty-dispatcher-pi-routing.test.ts | 18 +- .../pty-dispatcher-push-reattach.test.ts | 111 + .../terminal-pane/pty-dispatcher.ts | 222 +- .../pty-model-restore-channel.test.ts | 86 + .../pty-model-restore-channel.ts | 66 + .../terminal-pane/pty-pre-handler-buffer.ts | 15 + .../pty-renderer-delivery-claims.test.ts | 62 + .../pty-renderer-delivery-claims.ts | 122 + .../terminal-pane/pty-transport-types.ts | 40 +- .../terminal-pane/pty-transport.test.ts | 291 ++ .../components/terminal-pane/pty-transport.ts | 150 +- .../remote-runtime-pty-batching.test.ts | 44 +- .../remote-runtime-pty-batching.ts | 8 + ...-runtime-pty-query-reply-immediate.test.ts | 142 + ...e-runtime-pty-snapshot-escape-tail.test.ts | 116 + .../remote-runtime-pty-transport.test.ts | 115 +- .../remote-runtime-pty-transport.ts | 106 +- .../terminal-pane/replay-guard.test.ts | 342 +- .../components/terminal-pane/replay-guard.ts | 146 +- .../ssh-pane-connect-gate.test.ts | 87 + .../terminal-pane/ssh-pane-connect-gate.ts | 51 + .../stale-document-visibility.test.ts | 157 + .../stale-document-visibility.ts | 109 + .../terminal-pane/terminal-appearance.test.ts | 136 +- .../terminal-pane/terminal-appearance.ts | 152 +- .../terminal-capability-replies.ts | 70 +- .../terminal-command-lifecycle.ts | 92 +- .../terminal-delivery-watchdog.test.ts | 201 + .../terminal-delivery-watchdog.ts | 278 ++ .../terminal-pane/terminal-fit-restore.ts | 12 +- .../terminal-freeze-breadcrumbs.ts | 34 + .../terminal-freeze-report.test.ts | 79 + .../terminal-pane/terminal-freeze-report.ts | 59 + .../terminal-hidden-delivery-gate.ts | 45 + ...terminal-hidden-restore-scrollback.test.ts | 14 + .../terminal-hidden-restore-scrollback.ts | 13 + .../terminal-hidden-view-parking.test.ts | 529 +++ .../terminal-hidden-view-parking.ts | 285 ++ ...al-ime-candidate-key-release-guard.test.ts | 183 + ...erminal-ime-candidate-key-release-guard.ts | 94 + .../terminal-ime-composition-tracker.test.ts | 170 + .../terminal-ime-composition-tracker.ts | 75 +- ...minal-keyboard-protocol-pane-agent.test.ts | 45 + .../terminal-keyboard-protocol-pane-agent.ts | 16 + .../terminal-kitty-keyboard-awareness.test.ts | 113 - .../terminal-kitty-keyboard-awareness.ts | 56 - .../terminal-link-handlers.test.ts | 78 + .../terminal-pane-tab-detach.test.ts | 44 +- .../terminal-pane/terminal-pane-tab-detach.ts | 7 +- .../terminal-parked-tab-watchers.test.ts | 564 +++ .../terminal-parked-tab-watchers.ts | 278 ++ .../terminal-parked-watcher-registry.ts | 107 + .../terminal-parking-e2e-overrides.test.ts | 82 + .../terminal-parking-e2e-overrides.ts | 34 + .../terminal-parser-handler-guard.test.ts | 108 + .../terminal-parser-handler-guard.ts | 44 + .../terminal-pty-ack-gate.test.ts | 123 + .../terminal-pane/terminal-pty-ack-gate.ts | 89 +- .../terminal-shortcut-policy.test.ts | 279 +- .../terminal-pane/terminal-shortcut-policy.ts | 151 +- .../terminal-shutdown-layout-capture.test.ts | 56 +- .../terminal-shutdown-layout-capture.ts | 12 +- ...terminal-side-effect-facts-handler.test.ts | 509 ++ .../terminal-side-effect-facts-handler.ts | 242 + .../terminal-title-tracker-parity.test.ts | 378 ++ ...terminal-view-attributes-publisher.test.ts | 249 + .../terminal-view-attributes-publisher.ts | 251 + .../terminal-visibility-resume.test.ts | 47 +- .../terminal-visibility-resume.ts | 19 +- ...inal-webgl-diagnostics-breadcrumbs.test.ts | 30 + .../terminal-windows-shift-enter.test.ts | 88 + .../terminal-windows-shift-enter.ts | 43 + .../use-notification-dispatch.test.ts | 129 +- .../use-notification-dispatch.ts | 52 +- .../use-terminal-pane-global-effects.test.ts | 201 +- .../use-terminal-pane-global-effects.ts | 34 +- .../use-terminal-pane-lifecycle.ts | 204 +- .../use-terminal-tab-cold-parking.ts | 243 + .../use-terminal-window-wake-recovery.test.ts | 114 + .../use-terminal-window-wake-recovery.ts | 52 +- .../wrapped-terminal-link-ranges.test.ts | 241 +- .../wrapped-terminal-link-ranges.ts | 151 +- .../xterm-bypass-event-fixture.ts | 17 + .../xterm-bypass-policy-non-mac.test.ts | 258 +- .../terminal-pane/xterm-bypass-policy.test.ts | 50 +- .../terminal-pane/xterm-bypass-policy.ts | 60 +- .../xterm-write-buffer-stall.repro.test.ts | 79 + .../terminal/active-terminal-repair.test.ts | 51 +- .../terminal/active-terminal-repair.ts | 16 + ...background-terminal-worktree-mount.test.ts | 120 +- .../background-terminal-worktree-mount.ts | 148 + .../terminal-tab-actions-kill-all.test.ts | 131 + .../WorkspaceCleanupDialog.tsx | 911 ++-- ...background-removal-late-settlement.test.ts | 92 + ...rkspace-cleanup-background-removal.test.ts | 596 +++ .../workspace-cleanup-background-removal.ts | 262 ++ .../workspace-cleanup-candidate-labels.ts | 176 + .../workspace-cleanup-candidate-list.test.tsx | 88 + .../workspace-cleanup-candidate-list.tsx | 72 + ...rkspace-cleanup-candidate-row-data.test.ts | 59 + .../workspace-cleanup-candidate-row-data.ts | 204 + ...orkspace-cleanup-candidate-row-details.tsx | 107 + .../workspace-cleanup-candidate-row.test.tsx | 65 + .../workspace-cleanup-candidate-row.tsx | 347 ++ ...rkspace-cleanup-removal-candidates.test.ts | 16 + .../workspace-cleanup-removal-candidates.ts | 13 + .../workspace-cleanup-removal-settlement.ts | 137 + .../workspace-cleanup-status-pill.tsx | 26 + src/renderer/src/constants/terminal.ts | 22 + src/renderer/src/env.d.ts | 4 + ...gent-hook-completion-notifications.test.ts | 81 +- .../agent-hook-completion-notifications.ts | 66 +- .../src/hooks/metadata-request-cache.test.ts | 75 +- .../src/hooks/metadata-request-cache.ts | 55 + .../hooks/programmatic-scroll-marks.test.ts | 75 + .../src/hooks/programmatic-scroll-marks.ts | 72 + .../hooks/runtime-client-events-sync.test.ts | 211 +- .../src/hooks/runtime-client-events-sync.ts | 37 +- .../hooks/ssh-reconnect-pane-retry.test.ts | 46 + .../src/hooks/ssh-reconnect-pane-retry.ts | 22 + .../src/hooks/useEditorExternalWatch.test.ts | 173 + .../src/hooks/useEditorExternalWatch.ts | 125 +- .../src/hooks/useGitHubSlugMetadata.test.tsx | 52 + .../src/hooks/useGitHubSlugMetadata.ts | 18 +- src/renderer/src/hooks/useIpcEvents.test.ts | 229 +- src/renderer/src/hooks/useIpcEvents.ts | 241 +- .../src/hooks/useIssueMetadata.test.tsx | 153 + src/renderer/src/hooks/useIssueMetadata.ts | 41 +- .../hooks/useSettingsNavigationMetadata.ts | 4 +- ...tualizedScrollAnchor.listener-deps.test.ts | 7 +- ...dScrollAnchor.marks-restore-signal.test.ts | 432 ++ .../src/hooks/useVirtualizedScrollAnchor.ts | 223 +- .../virtualized-scroll-anchor-listener.ts | 140 + .../virtualized-scroll-anchor-recording.ts | 6 +- .../virtualized-scroll-anchor-restore.ts | 148 + src/renderer/src/i18n/locales/en.json | 584 ++- src/renderer/src/i18n/locales/es.json | 678 ++- src/renderer/src/i18n/locales/ja.json | 658 ++- src/renderer/src/i18n/locales/ko.json | 654 ++- src/renderer/src/i18n/locales/zh.json | 616 ++- .../src/i18n/native-chat-locales.test.ts | 30 + .../src/i18n/no-top-level-translate.test.ts | 3 +- .../src/lib/agent-followup-delivery.test.ts | 110 + .../src/lib/agent-followup-delivery.ts | 22 +- .../lib/agent-launch-prompt-delivery.test.ts | 4 +- .../src/lib/agent-row-primary-text.test.ts | 253 +- .../src/lib/agent-row-primary-text.ts | 126 +- ...gent-startup-delayed-delivery-perf.test.ts | 164 + .../src/lib/agent-startup-delayed-delivery.ts | 28 +- src/renderer/src/lib/agent-status.test.ts | 33 + .../src/lib/ai-vault-resume-command.test.ts | 21 + .../src/lib/ai-vault-resume-command.ts | 2 + .../src/lib/ai-vault-resume-target.test.ts | 32 +- .../src/lib/ai-vault-resume-target.ts | 18 +- .../lib/automation-session-observer.test.ts | 129 + .../src/lib/automation-session-observer.ts | 16 +- .../src/lib/blocked-notification-fallback.ts | 39 + .../src/lib/connection-context.test.ts | 40 + .../src/lib/crash-breadcrumb-recorder.ts | 25 + src/renderer/src/lib/crash-diagnostics.ts | 21 +- .../src/lib/ensure-hooks-confirmed.test.ts | 22 + .../src/lib/ensure-hooks-confirmed.ts | 42 +- src/renderer/src/lib/github-links.ts | 112 +- .../lib/github-source-runtime-context.test.ts | 91 + .../src/lib/github-source-runtime-context.ts | 21 + ...hook-command-delayed-delivery-perf.test.ts | 40 + .../src/lib/hook-command-delayed-delivery.ts | 26 +- .../layout-base-character.test.ts | 45 + .../keyboard-layout/layout-base-character.ts | 78 + .../launch-agent-background-session.test.ts | 116 +- .../lib/launch-agent-background-session.ts | 270 +- .../src/lib/launch-agent-in-new-tab.test.ts | 170 +- .../src/lib/launch-agent-in-new-tab.ts | 116 +- .../src/lib/launch-agent-web-host-tab.ts | 75 + .../src/lib/launch-ai-vault-session.test.ts | 58 + .../src/lib/launch-ai-vault-session.ts | 35 +- .../lib/linear-agent-skill-update-command.ts | 28 + .../lib/monaco-peek-preview-options.test.ts | 98 + .../src/lib/monaco-peek-preview-options.ts | 67 + src/renderer/src/lib/monaco-setup.ts | 2 + .../lib/native-chat-initial-view-mode.test.ts | 37 +- .../src/lib/native-chat-initial-view-mode.ts | 8 +- .../src/lib/native-chat-supported-agent.ts | 6 +- ...native-chat-transcript-readability.test.ts | 11 + .../lib/native-chat-transcript-readability.ts | 8 + src/renderer/src/lib/new-workspace.test.ts | 77 +- src/renderer/src/lib/new-workspace.ts | 12 +- .../src/lib/pane-manager/pane-dom-creation.ts | 1 + .../lib/pane-manager/pane-lifecycle.test.ts | 128 +- .../src/lib/pane-manager/pane-lifecycle.ts | 26 +- .../lib/pane-manager/pane-manager-registry.ts | 28 + .../lib/pane-manager/pane-manager-types.ts | 3 + .../src/lib/pane-manager/pane-manager.ts | 12 +- .../pane-manager/pane-reveal-repaint.test.ts | 30 +- .../lib/pane-manager/pane-reveal-repaint.ts | 44 +- .../pane-terminal-foreground-render-settle.ts | 60 +- .../pane-terminal-output-ack-credit.ts | 45 + ...-output-scheduler-throughput.bench.test.ts | 127 + .../pane-terminal-output-scheduler.test.ts | 420 +- .../pane-terminal-output-scheduler.ts | 421 +- .../lib/pane-manager/pane-webgl-renderer.ts | 5 + .../terminal-arabic-shaping-joiner.test.ts | 324 ++ .../terminal-arabic-shaping-joiner.ts | 289 ++ .../terminal-keyboard-protocol.test.ts | 60 +- .../terminal-keyboard-protocol.ts | 24 + .../terminal-ligatures-addon.test.ts | 154 + .../pane-manager/terminal-ligatures-addon.ts | 120 + .../windows-pty-compatibility.test.ts | 36 +- .../pane-manager/windows-pty-compatibility.ts | 11 + .../xterm-write-callback-guard.test.ts | 110 + .../xterm-write-callback-guard.ts | 40 + .../src/lib/repo-runtime-owner.test.ts | 95 + src/renderer/src/lib/repo-runtime-owner.ts | 19 + ...-agent-session-suppress-navigation.test.ts | 140 + .../src/lib/resume-sleeping-agent-session.ts | 122 +- .../src/lib/sleeping-agent-session-launch.ts | 128 + .../lib/source-control-remote-error.test.ts | 70 + .../src/lib/source-control-remote-error.ts | 37 + .../src/lib/tui-agent-startup.test.ts | 6 +- .../src/lib/use-tab-agent-pi-identity.test.ts | 305 ++ .../use-tab-agent-sleeping-session.test.ts | 184 + src/renderer/src/lib/use-tab-agent.test.ts | 4 + src/renderer/src/lib/use-tab-agent.ts | 174 +- ...wake-sleeping-agents-in-background.test.ts | 320 ++ .../lib/wake-sleeping-agents-in-background.ts | 212 + .../lib/window-visibility-interval.test.ts | 45 + .../src/lib/window-visibility-interval.ts | 6 +- .../lib/workspace-port-scan-debounce.test.ts | 150 + .../src/lib/workspace-port-scan-debounce.ts | 44 + .../workspace-session-editor-drafts.test.ts | 45 + src/renderer/src/lib/workspace-session.ts | 8 +- src/renderer/src/lib/worktree-activation.ts | 12 +- src/renderer/src/lib/worktree-status.test.ts | 63 + src/renderer/src/lib/worktree-status.ts | 15 +- ...runtime-terminal-frame-drop-resync.test.ts | 236 + .../remote-runtime-terminal-multiplexer.ts | 258 +- .../src/runtime/runtime-client-events.test.ts | 43 + .../src/runtime/runtime-client-events.ts | 17 +- .../runtime-environment-ssh-state.test.ts | 255 + .../runtime/runtime-environment-ssh-state.ts | 165 + .../src/runtime/runtime-file-client.test.ts | 236 +- .../src/runtime/runtime-file-client.ts | 126 +- .../src/runtime/runtime-hooks-client.ts | 6 +- .../src/runtime/runtime-jira-client.ts | 15 + .../src/runtime/runtime-linear-client.test.ts | 69 + .../src/runtime/runtime-linear-client.ts | 67 +- .../runtime-provider-accounts-client.test.ts | 389 ++ .../runtime-provider-accounts-client.ts | 276 ++ .../src/runtime/runtime-rpc-client.test.ts | 321 ++ .../src/runtime/runtime-rpc-client.ts | 135 +- .../runtime/runtime-terminal-stream.test.ts | 238 +- .../src/runtime/web-session-tabs-sync.test.ts | 41 + .../src/runtime/web-session-tabs-sync.ts | 41 +- src/renderer/src/store/index.ts | 8 +- src/renderer/src/store/selectors.test.ts | 70 +- src/renderer/src/store/selectors.ts | 43 + .../slices/agent-generated-tab-title.test.ts | 209 + .../slices/agent-status-drop-ipc.test.ts | 19 + .../slices/agent-status-quit-capture.test.ts | 95 + src/renderer/src/store/slices/agent-status.ts | 240 +- .../src/store/slices/diffComments.test.ts | 8 +- src/renderer/src/store/slices/editor.test.ts | 61 + src/renderer/src/store/slices/editor.ts | 75 +- src/renderer/src/store/slices/github.test.ts | 177 +- src/renderer/src/store/slices/github.ts | 64 +- .../store/slices/linear-invalidation.test.ts | 13 +- src/renderer/src/store/slices/linear.test.ts | 193 +- src/renderer/src/store/slices/linear.ts | 121 +- .../src/store/slices/new-issue-draft.test.ts | 81 + .../src/store/slices/new-issue-draft.ts | 41 + .../slices/orca-profiles-auth-actions.test.ts | 219 + .../slices/orca-profiles-auth-actions.ts | 211 + .../src/store/slices/orca-profiles.test.ts | 265 ++ .../src/store/slices/orca-profiles.ts | 153 + .../src/store/slices/pane-foreground-agent.ts | 3 + .../src/store/slices/rate-limits.test.ts | 19 + src/renderer/src/store/slices/rate-limits.ts | 13 + .../repos-host-identity-routing.test.ts | 82 +- .../slices/repos-runtime-routing-fixture.ts | 117 + src/renderer/src/store/slices/repos.test.ts | 164 +- src/renderer/src/store/slices/repos.ts | 106 +- .../slices/runtime-environment-ssh.test.ts | 198 + .../store/slices/runtime-environment-ssh.ts | 263 ++ .../src/store/slices/runtime-status.test.ts | 123 + .../src/store/slices/runtime-status.ts | 20 +- src/renderer/src/store/slices/ssh.test.ts | 14 +- src/renderer/src/store/slices/ssh.ts | 21 +- .../src/store/slices/store-cascades.test.ts | 150 +- .../src/store/slices/store-test-helpers.ts | 8 +- .../slices/superseded-ssh-repo-rows.test.ts | 56 + .../store/slices/superseded-ssh-repo-rows.ts | 50 + .../src/store/slices/tabs-hydration.test.ts | 31 + .../src/store/slices/tabs-hydration.ts | 13 +- src/renderer/src/store/slices/tabs.test.ts | 53 + src/renderer/src/store/slices/tabs.ts | 12 +- ...erminal-pane-detach-agent-identity.test.ts | 91 + .../store/slices/terminals-hydration.test.ts | 43 +- src/renderer/src/store/slices/terminals.ts | 149 +- src/renderer/src/store/slices/ui.test.ts | 22 +- src/renderer/src/store/slices/ui.ts | 68 +- ...rkspace-cleanup-removal-preflight.test.ts} | 490 +- .../workspace-cleanup-scan-progress.test.ts | 598 +++ .../workspace-cleanup-slice-test-harness.ts | 110 + .../src/store/slices/workspace-cleanup.ts | 229 +- .../src/store/slices/worktree-helpers.ts | 16 +- .../src/store/slices/worktrees.test.ts | 132 + src/renderer/src/store/slices/worktrees.ts | 325 +- src/renderer/src/store/types.ts | 8 +- src/renderer/src/web/web-preload-api.test.ts | 152 + src/renderer/src/web/web-preload-api.ts | 255 +- src/shared/agent-detection.test.ts | 30 +- src/shared/agent-detection.ts | 510 +- src/shared/agent-hook-listener.test.ts | 328 +- src/shared/agent-hook-listener.ts | 259 +- src/shared/agent-process-recognition.test.ts | 7 + src/shared/agent-prompt-injection.test.ts | 44 + src/shared/agent-prompt-injection.ts | 43 + src/shared/agent-status-identity.ts | 3 +- src/shared/agent-status-types.test.ts | 65 + src/shared/agent-status-types.ts | 30 +- src/shared/agent-title-core.ts | 110 + src/shared/agent-title-identity.ts | 111 + src/shared/agent-title-owner.ts | 44 +- src/shared/agent-title-status.ts | 203 + src/shared/agent-tui-ansi-fuzz-stream.ts | 279 ++ src/shared/ai-vault-session-display.ts | 112 + src/shared/ai-vault-session-filters.test.ts | 116 + src/shared/ai-vault-session-filters.ts | 298 ++ src/shared/ai-vault-types.test.ts | 88 + src/shared/ai-vault-types.ts | 81 +- src/shared/automation-run-retention.test.ts | 173 + src/shared/automation-run-retention.ts | 65 + src/shared/automations-types.ts | 15 + .../command-code-output-status.test.ts | 0 .../command-code-output-status.ts | 8 + .../command-code-prompt-text.ts | 0 src/shared/constants.ts | 8 + src/shared/e2e-config.ts | 13 +- src/shared/file-listing-cancellation.ts | 38 + src/shared/git-binary-compatibility.test.ts | 145 + src/shared/git-branch-cleanup.test.ts | 64 +- src/shared/git-branch-cleanup.ts | 43 +- src/shared/git-capability-cache.test.ts | 133 + src/shared/git-capability-cache.ts | 115 + src/shared/git-check-ignore-stdio.test.ts | 38 + src/shared/git-check-ignore-stdio.ts | 42 + src/shared/git-clone-failure-message.test.ts | 12 + src/shared/git-clone-failure-message.ts | 10 +- src/shared/git-cquoted-path.test.ts | 12 + src/shared/git-cquoted-path.ts | 31 +- src/shared/git-fetch-auto-maintenance.ts | 10 + src/shared/git-merge-tree-capability.test.ts | 32 + src/shared/git-merge-tree-capability.ts | 27 + src/shared/git-output-locale.ts | 16 + src/shared/git-ref-command-capabilities.ts | 14 + src/shared/git-remote-error.test.ts | 37 + src/shared/git-remote-error.ts | 8 + src/shared/git-uncommitted-line-stats.test.ts | 17 + src/shared/git-uncommitted-line-stats.ts | 17 +- .../git-worktree-command-capabilities.ts | 34 + src/shared/github-links.ts | 102 + src/shared/grok-session-path-lookup-queue.ts | 158 + src/shared/grok-session-paths.test.ts | 387 ++ src/shared/grok-session-paths.ts | 294 ++ .../harness-injected-user-turns.test.ts | 80 +- src/shared/harness-injected-user-turns.ts | 77 +- src/shared/jira-types.ts | 4 + .../linear-issue-attribute-filter.test.ts | 137 + src/shared/linear-issue-attribute-filter.ts | 244 + src/shared/map-with-concurrency.test.ts | 50 + src/shared/map-with-concurrency.ts | 24 + src/shared/orca-dispatch-status-prompt.ts | 135 + src/shared/orca-profiles.ts | 346 ++ src/shared/osc-title-scan-tail.test.ts | 17 + src/shared/osc-title-scan-tail.ts | 13 +- src/shared/pane-agent-owner.test.ts | 44 + src/shared/pane-agent-owner.ts | 58 + src/shared/pi-compatible-synthetic-title.ts | 10 +- src/shared/posix-command-path-lookup.test.ts | 312 ++ src/shared/posix-command-path-lookup.ts | 65 + src/shared/process-table-snapshot.test.ts | 52 + src/shared/process-table-snapshot.ts | 78 +- src/shared/protocol-version.ts | 11 +- src/shared/pty-delivery-diagnostics.test.ts | 77 + src/shared/pty-delivery-diagnostics.ts | 107 + src/shared/pty-model-restore-marker.ts | 19 + src/shared/pty-renderer-delivery-health.ts | 45 + src/shared/quick-open-directory-validation.ts | 7 + src/shared/quick-open-expansion-paths.test.ts | 26 + src/shared/quick-open-expansion-paths.ts | 37 + src/shared/quick-open-filter.test.ts | 31 +- src/shared/quick-open-filter.ts | 18 +- .../quick-open-git-directory-collapse.test.ts | 58 + src/shared/quick-open-readdir-walk.test.ts | 295 +- src/shared/quick-open-readdir-walk.ts | 205 +- src/shared/rate-limit-types.test.ts | 6 +- src/shared/rate-limit-types.ts | 22 +- src/shared/remote-runtime-client.test.ts | 36 +- src/shared/remote-runtime-client.ts | 81 +- .../remote-runtime-request-websocket.ts | 10 + ...te-runtime-shared-control-boundary.test.ts | 3 +- ...-runtime-shared-control-connection.test.ts | 122 +- ...emote-runtime-shared-control-connection.ts | 50 +- ...e-shared-control-keepalive-refresh.test.ts | 98 + .../remote-runtime-shared-control-open.ts | 68 +- .../remote-runtime-shared-control-requests.ts | 22 +- ...remote-runtime-shared-control-stability.ts | 32 + .../remote-runtime-shared-control-state.ts | 22 +- ...ntime-shared-control-subscriptions.test.ts | 150 + ...te-runtime-shared-control-subscriptions.ts | 19 +- .../remote-runtime-shared-control-types.ts | 15 + src/shared/remote-runtime-socket-liveness.ts | 75 + src/shared/runtime-client-events.ts | 5 + src/shared/runtime-rpc-envelope.ts | 57 +- src/shared/runtime-subscription-replay.ts | 25 + src/shared/runtime-types.ts | 8 + src/shared/source-control-ai-actions.test.ts | 26 + src/shared/source-control-ai-actions.ts | 5 + ...ce-control-commit-failure-agent-command.ts | 18 +- ...urce-control-push-failure-agent-command.ts | 18 + .../source-control-push-failure.test.ts | 136 + src/shared/source-control-push-failure.ts | 272 ++ ...rce-control-recovery-agent-command.test.ts | 53 + .../source-control-recovery-agent-command.ts | 25 + src/shared/ssh-pty-id.test.ts | 38 + src/shared/ssh-pty-id.ts | 19 +- src/shared/ssh-types.ts | 17 + src/shared/status-bar-defaults.ts | 2 + src/shared/subprocess-stdin-write.test.ts | 30 + src/shared/subprocess-stdin-write.ts | 10 + src/shared/telemetry-events.ts | 31 + .../terminal-bell-detector.test.ts} | 2 +- .../terminal-bell-detector.ts} | 13 +- .../terminal-github-pr-link-detector.test.ts | 0 .../terminal-github-pr-link-detector.ts | 9 + ...rminal-kitty-keyboard-mode-tracker.test.ts | 147 + .../terminal-kitty-keyboard-mode-tracker.ts | 186 + .../terminal-line-height-settings.test.ts | 20 + src/shared/terminal-line-height-settings.ts | 11 + .../terminal-osc133-command-finished.ts | 108 + .../terminal-output-side-effects.test.ts | 222 + src/shared/terminal-output-side-effects.ts | 326 ++ .../terminal-partial-escape-tail.test.ts | 86 + src/shared/terminal-partial-escape-tail.ts | 149 + src/shared/terminal-query-reply.test.ts | 99 + src/shared/terminal-query-reply.ts | 69 + src/shared/terminal-reply-query-extraction.ts | 160 + src/shared/terminal-restore-parity-fixture.ts | 284 ++ src/shared/terminal-scrollback-policy.test.ts | 16 +- src/shared/terminal-scrollback-policy.ts | 17 + .../terminal-serialize-absolute-cursor.ts | 95 + src/shared/terminal-side-effect-facts.ts | 56 + src/shared/terminal-startup-cwd.test.ts | 174 +- src/shared/terminal-startup-cwd.ts | 64 +- src/shared/terminal-stream-protocol.test.ts | 15 + src/shared/terminal-stream-protocol.ts | 8 +- src/shared/terminal-title-agent-type.test.ts | 33 +- src/shared/terminal-title-agent-type.ts | 217 +- src/shared/terminal-title-display.ts | 108 + src/shared/terminal-title-status.ts | 230 + src/shared/terminal-view-attributes.test.ts | 119 + src/shared/terminal-view-attributes.ts | 188 + src/shared/terminal-webgl-diagnostics.ts | 26 + src/shared/tui-agent-config.ts | 34 +- src/shared/tui-agent-startup.test.ts | 57 + src/shared/tui-agent-startup.ts | 3 +- src/shared/types.ts | 70 +- src/shared/workspace-session-schema.ts | 3 +- src/shared/worktree-removal.ts | 75 + .../ws-outbound-backpressure-queue.test.ts | 128 + src/shared/ws-outbound-backpressure-queue.ts | 147 + src/shared/wsl-hook-relay-contract.ts | 88 + src/shared/wsl-login-shell-command.test.ts | 66 + src/shared/wsl-login-shell-command.ts | 17 + ...icial-opencode-hidden-pressure-scenario.ts | 139 +- ...ificial-opencode-hidden-pressure-script.ts | 52 + ...ificial-opencode-main-pressure-scenario.ts | 9 +- .../artificial-opencode-pane-interactions.ts | 119 + ...cial-opencode-revisit-pressure-scenario.ts | 311 ++ .../artificial-opencode-terminal-load.spec.ts | 279 +- .../e2e/chinese-ime-chat-input-repro.spec.ts | 196 + tests/e2e/global-setup.ts | 12 +- tests/e2e/global-teardown.ts | 2 +- tests/e2e/helpers/orca-app.ts | 90 +- tests/e2e/helpers/seeded-test-repo.ts | 67 + tests/e2e/helpers/terminal-input-probes.ts | 290 ++ tests/e2e/large-file-count-fixtures.ts | 133 + tests/e2e/onboarding.spec.ts | 47 +- tests/e2e/orca-profiles.spec.ts | 74 + ...erer-crash-recovery-terminal-input.spec.ts | 172 + .../restart-restore-terminal-input.spec.ts | 259 ++ ...rich-markdown-link-bubble-stacking.spec.ts | 157 + .../source-control-large-file-count.spec.ts | 446 ++ tests/e2e/ssh-docker-relay-perf.spec.ts | 133 + .../sustained-agent-typing-load-scripts.ts | 135 + ...minal-foreground-confirmation.unit.test.ts | 130 + .../terminal-foreground-redraw-freeze.spec.ts | 144 +- ...terminal-hidden-tui-visual-restore.spec.ts | 205 +- .../e2e/terminal-hidden-view-parking.spec.ts | 552 +++ ...terminal-long-table-scroll-restore.spec.ts | 26 - ...nal-multi-workspace-typing-latency.spec.ts | 602 +++ ...inal-pane-close-layout-consistency.spec.ts | 360 ++ tests/e2e/terminal-parked-memory.spec.ts | 358 ++ ...rminal-push-delivery-loss-recovery.spec.ts | 106 + ...nal-raw-emoji-table-scroll-restore.spec.ts | 8 +- .../terminal-reattach-mouse-mode-leak.spec.ts | 260 ++ tests/e2e/terminal-shortcuts.spec.ts | 105 +- tests/e2e/terminal-sleep-wake-restore.spec.ts | 220 + .../terminal-stuck-occlusion-recovery.spec.ts | 147 + tools/benchmarks/cpu-pressure-worker.mjs | 21 + .../terminal-headless-parse-bench.mjs | 70 + tools/benchmarks/terminal-pipeline-bench.mjs | 569 +++ tools/daemon-relocation-spike/README.md | 160 + .../daemon-relocation-spike/app-inventory.mjs | 146 + tools/daemon-relocation-spike/cli.mjs | 88 + .../daemon-relocation-spike/daemon-launch.mjs | 99 + tools/daemon-relocation-spike/host-copy.mjs | 62 + .../loaded-module-probe.mjs | 85 + .../loaded-modules.ps1 | 44 + .../daemon-relocation-spike/ndjson-client.mjs | 262 ++ tools/daemon-relocation-spike/selftest.mjs | 166 + tools/daemon-relocation-spike/spike.mjs | 313 ++ .../daemon-relocation-spike/tier-file-set.mjs | 135 + tools/repro-orchestration-long-prompt.mjs | 504 ++ tools/repro-watcher-crash-7547/.gitignore | 1 + tools/repro-watcher-crash-7547/README.md | 50 + tools/repro-watcher-crash-7547/child.cjs | 470 ++ .../repro-watcher-crash-7547/fixed-child.cjs | 334 ++ tools/repro-watcher-crash-7547/run.cjs | 74 + tools/win-update-e2e/README.md | 215 + tools/win-update-e2e/app-driver.mjs | 357 ++ tools/win-update-e2e/assertions.mjs | 186 + tools/win-update-e2e/cli-args.mjs | 201 + tools/win-update-e2e/daemon-processes.mjs | 173 + tools/win-update-e2e/installer-steps.mjs | 227 + tools/win-update-e2e/interactivity-probes.mjs | 99 + tools/win-update-e2e/onboarding-profile.mjs | 77 + tools/win-update-e2e/platform-guard.mjs | 38 + tools/win-update-e2e/powershell-runner.mjs | 87 + tools/win-update-e2e/preflight.mjs | 161 + .../registry-shortcut-backup.mjs | 312 ++ tools/win-update-e2e/run.mjs | 628 +++ tools/win-update-e2e/window-enum.ps1 | 122 + tools/win-update-e2e/window-watch.mjs | 174 + tools/win-update-e2e/window-watch.ps1 | 91 + 1648 files changed, 173422 insertions(+), 16353 deletions(-) create mode 100644 .github/workflows/daemon-relocation-spike.yml create mode 100644 .github/workflows/win-update-e2e.yml create mode 100644 .github/workflows/win-update-survival-e2e.yml create mode 100644 .github/workflows/windows-signing-rehearsal.yml create mode 100644 build-plugins/plain-node-entry-guard.ts create mode 100644 config/nsis/daemon-host-uninstall.nsh create mode 100644 config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch create mode 100644 config/scripts/build-notification-status-macos.mjs create mode 100644 config/scripts/daemon-boot-smoke.mjs create mode 100644 config/scripts/generate-terminal-perf-html-report.mjs create mode 100644 config/scripts/generate-terminal-perf-html-report.test.mjs create mode 100644 config/scripts/git-binary-compatibility-workflow.test.mjs create mode 100644 config/scripts/run-multi-workspace-typing-bench.mjs create mode 100755 config/scripts/serve-headless-fresh-profile-pairing.mjs create mode 100644 config/scripts/terminal-perf-report-rows.mjs create mode 100644 config/scripts/verify-packaged-daemon-entry.cjs create mode 100644 config/scripts/verify-packaged-daemon-entry.test.mjs create mode 100644 config/scripts/windows-daemon-workspace-close-repro.mjs create mode 100644 docs/agent-status-over-wsl.md create mode 100644 docs/assets/wechat-qr-backup.jpg create mode 100644 docs/editor-find-layout-aware-shortcut.md create mode 100644 docs/issue-7649-vscode-wsl-launch.md create mode 100644 docs/kill-all-sessions-also-kills-empty-terminals.md create mode 100644 docs/reference/git-compatibility.md create mode 100644 docs/reference/terminal-hidden-view-parking.md create mode 100644 docs/reference/terminal-model-view-contract.md create mode 100644 docs/reference/terminal-query-authority.md create mode 100644 docs/reference/terminal-side-effect-authority.md create mode 100644 docs/source-control-push-failure-ai-recovery.md create mode 100644 docs/wrapped-terminal-file-link-fragments.md create mode 100644 mobile/app/connection-log.tsx create mode 100644 mobile/app/h/[hostId]/agent-history/[worktreeId].tsx create mode 100644 mobile/src/agent-history/MobileAgentSessionHistoryIcon.tsx create mode 100644 mobile/src/agent-history/MobileAgentSessionHistoryList.tsx create mode 100644 mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx create mode 100644 mobile/src/agent-history/agent-history-capability.ts create mode 100644 mobile/src/agent-history/agent-history-current-worktree-badge.ts create mode 100644 mobile/src/agent-history/agent-history-resume-target.test.ts create mode 100644 mobile/src/agent-history/agent-history-resume-target.ts create mode 100644 mobile/src/agent-history/agent-history-scope-paths.test.ts create mode 100644 mobile/src/agent-history/agent-history-scope-paths.ts create mode 100644 mobile/src/agent-history/agent-history-sections.ts create mode 100644 mobile/src/agent-history/agent-history-session-card.test.ts create mode 100644 mobile/src/agent-history/agent-history-session-card.ts create mode 100644 mobile/src/agent-history/agent-history-session-worktree.test.ts create mode 100644 mobile/src/agent-history/agent-history-session-worktree.ts create mode 100644 mobile/src/agent-history/agent-history-styles.ts create mode 100644 mobile/src/agent-history/use-mobile-agent-history-state.ts create mode 100644 mobile/src/agent-history/worktree-navigation-actions.ts create mode 100644 mobile/src/components/MobileSearchField.tsx create mode 100644 mobile/src/diagnostics/connection-diagnostics-report.test.ts create mode 100644 mobile/src/diagnostics/connection-diagnostics-report.ts create mode 100644 mobile/src/diagnostics/troubleshoot-common-issues.tsx create mode 100644 mobile/src/session/MobileSessionHeaderIconButton.tsx create mode 100644 mobile/src/session/MobileSessionHeaderMoreActionsSheet.tsx create mode 100644 mobile/src/session/ai-vault-resume-launch.test.ts create mode 100644 mobile/src/session/ai-vault-resume-launch.ts create mode 100644 mobile/src/session/use-mobile-pr-sidebar-controller-probe.test.ts create mode 100644 mobile/src/source-control/MobileGitHistoryList.tsx create mode 100644 mobile/src/source-control/MobileSourceControlBranchCard.tsx create mode 100644 mobile/src/source-control/MobileSourceControlPrChip.tsx create mode 100644 mobile/src/source-control/MobileSourceControlSegments.tsx create mode 100644 mobile/src/source-control/mobile-history-screen-state.test.ts create mode 100644 mobile/src/source-control/mobile-history-screen-state.ts create mode 100644 mobile/src/source-control/mobile-pr-chip-summary.test.ts create mode 100644 mobile/src/source-control/mobile-pr-chip-summary.ts create mode 100644 mobile/src/source-control/mobile-source-control-conflict-abort.test.ts create mode 100644 mobile/src/source-control/mobile-source-control-conflict-abort.ts create mode 100644 mobile/src/source-control/mobile-source-control-hub-styles.ts create mode 100644 mobile/src/source-control/mobile-source-control-hub-tab.test.ts create mode 100644 mobile/src/source-control/mobile-source-control-hub-tab.ts create mode 100644 mobile/src/terminal/terminal-ios-dictation-write-back.test.ts create mode 100644 mobile/src/terminal/terminal-keyboard-dismiss.test.ts create mode 100644 mobile/src/terminal/terminal-keyboard-dismiss.ts create mode 100644 mobile/src/terminal/terminal-webview-theme-injected.ts create mode 100644 mobile/src/terminal/terminal-webview-webgl-recovery-injected.ts create mode 100644 mobile/src/transport/client-context.test.ts create mode 100644 mobile/src/transport/connection-health.test.ts create mode 100644 mobile/src/transport/connection-log-buffer.test.ts create mode 100644 mobile/src/transport/connection-log-buffer.ts create mode 100644 mobile/src/worktree/workspace-list-ordering.ts create mode 100644 mobile/src/worktree/worktree-activation-result.test.ts create mode 100644 mobile/src/worktree/worktree-activation-result.ts create mode 100644 native/notification-status-macos/main.swift create mode 100644 notes/garble-fuzz-divergences.md create mode 100644 notes/orca-performance-branch-guide.md create mode 100644 notes/terminal-performance-initiative.md delete mode 100644 previews/mobile-driver-overlay-preview.html create mode 100644 src/cli/agent-context.test.ts create mode 100644 src/cli/agent-context.ts create mode 100644 src/cli/command-suggestion.test.ts create mode 100644 src/cli/command-suggestion.ts create mode 100644 src/cli/format-recovery.test.ts create mode 100644 src/cli/handlers/introspection.ts create mode 100644 src/cli/registry-parity.test.ts create mode 100644 src/cli/registry-parity.ts create mode 100644 src/cli/specs/introspection.ts create mode 100644 src/cli/vocabulary-policy.test.ts create mode 100644 src/cli/vocabulary-policy.ts create mode 100644 src/main/agent-hooks/server-grok-discovery.test.ts create mode 100644 src/main/agent-hooks/wsl-hook-fs-adapter.ts create mode 100644 src/main/agent-hooks/wsl-hook-relay-deps.ts create mode 100644 src/main/agent-hooks/wsl-hook-relay-launch.ts create mode 100644 src/main/agent-hooks/wsl-hook-relay-link.ts create mode 100644 src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts create mode 100644 src/main/agent-hooks/wsl-hook-relay-manager.test.ts create mode 100644 src/main/agent-hooks/wsl-hook-relay-manager.ts create mode 100644 src/main/agent-hooks/wsl-hook-relay-recovery.test.ts create mode 100644 src/main/agent-hooks/wsl-hook-relay-recovery.ts create mode 100644 src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts create mode 100644 src/main/agent-hooks/wsl-hook-relay-sentinel.ts create mode 100644 src/main/ai-vault/cached-session-list.ts create mode 100644 src/main/ai-vault/runtime-session-scanner.test.ts create mode 100644 src/main/ai-vault/runtime-session-scanner.ts create mode 100644 src/main/ai-vault/session-list-results.ts create mode 100644 src/main/ai-vault/session-scanner-claude-subagent-prune.test.ts create mode 100644 src/main/ai-vault/session-scanner-claude-subagents.test.ts create mode 100644 src/main/ai-vault/session-scanner-claude-subagents.ts create mode 100644 src/main/ai-vault/session-scanner-gemini-parsers.ts create mode 100644 src/main/ai-vault/session-scanner-injected-title.test.ts create mode 100644 src/main/ai-vault/session-scanner-recoverable-empty.test.ts create mode 100644 src/main/ai-vault/session-scanner-subagent-transcripts.ts create mode 100644 src/main/browser/browser-cookie-import-test-database.ts create mode 100644 src/main/browser/chromium-cookie-path.ts create mode 100644 src/main/browser/chromium-cookie-snapshot.test.ts create mode 100644 src/main/browser/chromium-cookie-snapshot.ts create mode 100644 src/main/codex-accounts/wsl-codex-command.test.ts create mode 100644 src/main/codex-accounts/wsl-codex-command.ts create mode 100644 src/main/codex/codex-hook-identity.ts create mode 100644 src/main/codex/codex-session-source-home.test.ts create mode 100644 src/main/codex/codex-session-source-home.ts create mode 100644 src/main/codex/codex-wsl-hook-install-plan.test.ts create mode 100644 src/main/codex/codex-wsl-hook-install-plan.ts create mode 100644 src/main/codex/config-settings-promotion.test.ts create mode 100644 src/main/codex/config-settings-promotion.ts create mode 100644 src/main/codex/hook-service-wsl-runtime.test.ts create mode 100644 src/main/codex/hook-trust-promotion.test.ts create mode 100644 src/main/codex/hook-trust-promotion.ts create mode 100644 src/main/daemon/daemon-background-transient-facts.test.ts create mode 100644 src/main/daemon/daemon-background-transient-facts.ts create mode 100644 src/main/daemon/daemon-errors.ts create mode 100644 src/main/daemon/daemon-file-log.test.ts create mode 100644 src/main/daemon/daemon-file-log.ts create mode 100644 src/main/daemon/daemon-foreground-confirmation-protocol.test.ts create mode 100644 src/main/daemon/daemon-foreground-process-protocol.ts create mode 100644 src/main/daemon/daemon-host-relocation.test.ts create mode 100644 src/main/daemon/daemon-host-relocation.ts create mode 100644 src/main/daemon/daemon-stream-backlog-probe.ts create mode 100644 src/main/daemon/daemon-stream-data-split.ts create mode 100644 src/main/daemon/daemon-stream-events.ts create mode 100644 src/main/daemon/daemon-stream-keep-tail-drop.ts create mode 100644 src/main/daemon/degraded-daemon-fallback-shutdown.ts create mode 100644 src/main/daemon/headless-emulator-fidelity.fuzz.test.ts create mode 100644 src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts create mode 100644 src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts create mode 100644 src/main/daemon/session-ingest-throughput.bench.test.ts create mode 100644 src/main/daemon/terminal-host-create-contract.ts create mode 100644 src/main/daemon/terminal-mode-rehydrate-sequences.ts create mode 100644 src/main/daemon/terminal-mouse-mode-mirror.ts create mode 100644 src/main/daemon/terminal-osc-cwd-title-scanner.ts create mode 100644 src/main/daemon/terminal-snapshot-ansi-buffers.ts create mode 100644 src/main/daemon/terminal-snapshot-serialize-roundtrip.test.ts create mode 100644 src/main/daemon/terminal-view-attribute-responder.ts create mode 100644 src/main/git/git-capability-state.test.ts create mode 100644 src/main/git/git-capability-state.ts create mode 100644 src/main/git/status-wsl-pathspecs.test.ts create mode 100644 src/main/git/worktree-git-capabilities.test.ts create mode 100644 src/main/github/conflict-summary-cache.ts create mode 100644 src/main/github/conflict-summary.test.ts create mode 100644 src/main/github/rate-limit.test.ts create mode 100644 src/main/grok-accounts/status.test.ts create mode 100644 src/main/grok-accounts/status.ts create mode 100644 src/main/ipc/filesystem-list-files-git-directory-expansion.test.ts create mode 100644 src/main/ipc/grok-accounts.ts create mode 100644 src/main/ipc/notification-authorization-status.ts create mode 100644 src/main/ipc/orca-profile-auth-handlers.test.ts create mode 100644 src/main/ipc/orca-profile-org-members-handlers.test.ts create mode 100644 src/main/ipc/orca-profile-org-members-handlers.ts create mode 100644 src/main/ipc/orca-profiles.test.ts create mode 100644 src/main/ipc/orca-profiles.ts create mode 100644 src/main/ipc/parcel-watcher-entry-path.test.ts create mode 100644 src/main/ipc/parcel-watcher-entry-path.ts create mode 100644 src/main/ipc/parcel-watcher-process-entry.test.ts create mode 100644 src/main/ipc/parcel-watcher-process-entry.ts create mode 100644 src/main/ipc/parcel-watcher-process.test.ts create mode 100644 src/main/ipc/parcel-watcher-process.ts create mode 100644 src/main/ipc/preflight-command-exec.test.ts create mode 100644 src/main/ipc/pty-hidden-delivery-gate.test.ts create mode 100644 src/main/ipc/pty-hidden-delivery-gate.ts create mode 100644 src/main/ipc/pty-producer-flow-control.test.ts create mode 100644 src/main/ipc/pty-producer-flow-control.ts create mode 100644 src/main/ipc/tui-agent-detection-commands.test.ts create mode 100644 src/main/ipc/tui-agent-detection-commands.ts create mode 100644 src/main/ipc/workspace-cleanup-activity.test.ts create mode 100644 src/main/ipc/workspace-cleanup-activity.ts create mode 100644 src/main/linear/issue-list-filter.test.ts create mode 100644 src/main/linear/issue-list-filter.ts create mode 100644 src/main/local-worktree-removal-recovery-live.test.ts create mode 100644 src/main/native-chat/transcript-fallback-id.test.ts create mode 100644 src/main/native-chat/transcript-fallback-id.ts create mode 100644 src/main/native-chat/transcript-line-decoders-claude.ts create mode 100644 src/main/native-chat/transcript-line-decoders-codex.ts create mode 100644 src/main/native-chat/transcript-line-decoders-grok.ts create mode 100644 src/main/native-chat/transcript-line-decoders.grok.test.ts create mode 100644 src/main/native-chat/transcript-stream-lines.test.ts create mode 100644 src/main/native-chat/transcript-stream-lines.ts create mode 100644 src/main/observability/logs-directory.ts create mode 100644 src/main/orca-profiles/profile-cloud-auth-config.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-auth-config.ts create mode 100644 src/main/orca-profiles/profile-cloud-auth-status.ts create mode 100644 src/main/orca-profiles/profile-cloud-client.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-client.ts create mode 100644 src/main/orca-profiles/profile-cloud-dev-auth.ts create mode 100644 src/main/orca-profiles/profile-cloud-dev-org-members.ts create mode 100644 src/main/orca-profiles/profile-cloud-dev-service.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-dev-service.ts create mode 100644 src/main/orca-profiles/profile-cloud-index.ts create mode 100644 src/main/orca-profiles/profile-cloud-org-members-client.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-org-members-client.ts create mode 100644 src/main/orca-profiles/profile-cloud-org-members-service.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-org-members-service.ts create mode 100644 src/main/orca-profiles/profile-cloud-pkce.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-pkce.ts create mode 100644 src/main/orca-profiles/profile-cloud-service-auth-retry.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-service-refresh.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-service.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-service.ts create mode 100644 src/main/orca-profiles/profile-cloud-session-exchange.ts create mode 100644 src/main/orca-profiles/profile-cloud-session-refresh.ts create mode 100644 src/main/orca-profiles/profile-cloud-session-store.test.ts create mode 100644 src/main/orca-profiles/profile-cloud-session-store.ts create mode 100644 src/main/orca-profiles/profile-index-store.test.ts create mode 100644 src/main/orca-profiles/profile-index-store.ts create mode 100644 src/main/orca-profiles/profile-project-presence.test.ts create mode 100644 src/main/orca-profiles/profile-project-presence.ts create mode 100644 src/main/orca-profiles/profile-project-session-state.ts create mode 100644 src/main/orca-profiles/profile-project-session-transfer.ts create mode 100644 src/main/orca-profiles/profile-project-source-removal.ts create mode 100644 src/main/orca-profiles/profile-project-state-file.ts create mode 100644 src/main/orca-profiles/profile-project-transfer-payload.ts create mode 100644 src/main/orca-profiles/profile-project-transfer.test.ts create mode 100644 src/main/orca-profiles/profile-project-transfer.ts create mode 100644 src/main/orca-profiles/profile-project-worktree-identity.ts create mode 100644 src/main/orca-profiles/profile-storage-paths.ts create mode 100644 src/main/orca-profiles/profile-ui-scope.test.ts create mode 100644 src/main/orca-profiles/profile-ui-scope.ts create mode 100644 src/main/pi/agent-status-extension-source.test.ts create mode 100644 src/main/pi/legacy-omp-overlay-migration.ts create mode 100644 src/main/providers/windows-conpty-process-membership.test.ts create mode 100644 src/main/providers/windows-conpty-process-membership.ts delete mode 100644 src/main/pty/terminal-cwd-realpath.test.ts delete mode 100644 src/main/pty/terminal-cwd-realpath.ts create mode 100644 src/main/rate-limits/auth-filesystem-operation.test.ts create mode 100644 src/main/rate-limits/auth-filesystem-operation.ts create mode 100644 src/main/rate-limits/codex-fetcher-backend.test.ts create mode 100644 src/main/rate-limits/grok-auth.test.ts create mode 100644 src/main/rate-limits/grok-auth.ts create mode 100644 src/main/rate-limits/grok-fetcher.test.ts create mode 100644 src/main/rate-limits/grok-fetcher.ts create mode 100644 src/main/runtime/mobile-session-tabs-notify-coalescer.test.ts create mode 100644 src/main/runtime/mobile-session-tabs-notify-coalescer.ts create mode 100644 src/main/runtime/retained-tail-redraw-window.equivalence.test.ts create mode 100644 src/main/runtime/rpc/e2ee-channel-text-backpressure.test.ts create mode 100644 src/main/runtime/rpc/methods/ai-vault.test.ts create mode 100644 src/main/runtime/rpc/methods/ai-vault.ts create mode 100644 src/main/runtime/rpc/methods/linear-issue-attribute-filter-schema.ts create mode 100644 src/main/runtime/rpc/terminal-geometry-stale-handle.test.ts create mode 100644 src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts create mode 100644 src/main/runtime/rpc/ws-fallback-port-store.test.ts create mode 100644 src/main/runtime/rpc/ws-fallback-port-store.ts create mode 100644 src/main/runtime/terminal-model-query-authority.test.ts create mode 100644 src/main/runtime/terminal-model-query-authority.ts create mode 100644 src/main/runtime/terminal-query-responder.test.ts create mode 100644 src/main/runtime/terminal-view-attribute-store.ts create mode 100644 src/main/speech/stt-offline-audio-chunker.test.ts create mode 100644 src/main/speech/stt-offline-audio-chunker.ts create mode 100644 src/main/speech/stt-worker-model-config.ts create mode 100644 src/main/ssh/ssh-git-response-stream-reader.ts create mode 100644 src/main/ssh/ssh-port-scanner.test.ts create mode 100644 src/main/ssh/ssh-relay-session-test-fixtures.ts create mode 100644 src/main/ssh/ssh-remote-cli-host-passthrough.test.ts create mode 100644 src/main/ssh/ssh-remote-cli-host-passthrough.ts create mode 100644 src/main/ssh/ssh-target-id-migration.test.ts create mode 100644 src/main/ssh/ssh-target-id-migration.ts create mode 100644 src/main/ssh/ssh-target-readoption.test.ts create mode 100644 src/main/ssh/ssh-target-readoption.ts create mode 100644 src/main/synthetic-title-frame-routing.test.ts create mode 100644 src/main/synthetic-title-frame-routing.ts create mode 100644 src/main/system-resume-broadcast.test.ts create mode 100644 src/main/system-resume-broadcast.ts create mode 100644 src/main/tray/tray-attention-icon.test.ts create mode 100644 src/main/tray/tray-attention-icon.ts create mode 100644 src/main/updater-lifecycle-diagnostics.ts create mode 100644 src/main/window/main-window-visibility.test.ts create mode 100644 src/main/window/main-window-visibility.ts create mode 100644 src/relay/fs-handler-list-files-cancel.test.ts create mode 100644 src/relay/fs-list-files-cancel.integration.test.ts create mode 100644 src/relay/fs-list-files-scan-coordinator.test.ts create mode 100644 src/relay/fs-list-files-scan-coordinator.ts create mode 100644 src/relay/git-handler-check-ignore.test.ts create mode 100644 src/relay/git-handler-check-ignore.ts create mode 100644 src/relay/git-handler-worktree-git-capabilities.test.ts create mode 100644 src/relay/git-handler-worktree-list.ts create mode 100644 src/relay/git-response-pty-echo-backpressure.integration.test.ts create mode 100644 src/relay/git-response-stream-ownership.test.ts create mode 100644 src/relay/git-response-stream.ts create mode 100644 src/relay/relay-diagnostic-log.test.ts create mode 100644 src/relay/relay-diagnostic-log.ts create mode 100644 src/relay/rotating-log-writer.test.ts create mode 100644 src/relay/rotating-log-writer.ts create mode 100644 src/relay/wsl-agent-hook-relay.test.ts create mode 100644 src/relay/wsl-agent-hook-relay.ts create mode 100644 src/relay/wsl-hook-fs-bridge.test.ts create mode 100644 src/relay/wsl-hook-fs-bridge.ts create mode 100644 src/renderer/src/assets/terminal-scrollbar-style.test.ts create mode 100644 src/renderer/src/components/browser-pane/BrowserAnnotationSendMenuContent.test.tsx create mode 100644 src/renderer/src/components/browser-pane/BrowserAnnotationSendMenuContent.tsx create mode 100644 src/renderer/src/components/editor/ExternalFileChangeBanner.test.tsx create mode 100644 src/renderer/src/components/editor/ExternalFileChangeBanner.tsx create mode 100644 src/renderer/src/components/editor/ExternalFileChangeCompareDialog.test.tsx create mode 100644 src/renderer/src/components/editor/ExternalFileChangeCompareDialog.tsx create mode 100644 src/renderer/src/components/editor/combined-diff-section-connection.test.ts create mode 100644 src/renderer/src/components/editor/combined-diff-section-connection.ts create mode 100644 src/renderer/src/components/editor/editor-autosave-conflict-flow.test.ts create mode 100644 src/renderer/src/components/editor/editor-autosave-controller-test-fixture.ts create mode 100644 src/renderer/src/components/editor/editor-changed-on-disk-mark.ts create mode 100644 src/renderer/src/components/editor/editor-external-change-telemetry.ts create mode 100644 src/renderer/src/components/editor/editor-panel-git-entry-selector.test.ts create mode 100644 src/renderer/src/components/editor/editor-panel-git-entry-selector.ts create mode 100644 src/renderer/src/components/editor/editor-restored-tab-conflict-scan.test.ts create mode 100644 src/renderer/src/components/editor/editor-restored-tab-conflict-scan.ts create mode 100644 src/renderer/src/components/editor/editor-shortcuts.test.ts delete mode 100644 src/renderer/src/components/github-item-dialog-merge-routing.test.ts create mode 100644 src/renderer/src/components/jira-issue-sorter.ts create mode 100644 src/renderer/src/components/linear-issue-attribute-filter-dropdowns.test.tsx create mode 100644 src/renderer/src/components/linear-issue-attribute-filter-dropdowns.tsx create mode 100644 src/renderer/src/components/linear-issue-attribute-filter-primary-team.test.ts create mode 100644 src/renderer/src/components/linear-issue-attribute-filter-primary-team.ts create mode 100644 src/renderer/src/components/linear-issue-attribute-filter-sections.tsx create mode 100644 src/renderer/src/components/native-chat/native-chat-attachment-upload.test.ts create mode 100644 src/renderer/src/components/native-chat/native-chat-attachment-upload.ts create mode 100644 src/renderer/src/components/native-chat/use-native-chat-composer-paste.test.tsx create mode 100644 src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx create mode 100644 src/renderer/src/components/native-chat/use-native-chat-external-attachments.ts create mode 100644 src/renderer/src/components/notifications/mac-notification-permission-card.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileAvatar.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileCloudMenuItems.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileCreateDialog.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileManagementDialog.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileOrgMemberRow.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileOrgMembersDialog.test.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileOrgMembersDialog.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileProjectTransferConfirmDialog.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileSignOutConfirmDialog.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileSwitchConfirmDialog.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileSwitcher.test.tsx create mode 100644 src/renderer/src/components/orca-profiles/OrcaProfileSwitcher.tsx create mode 100644 src/renderer/src/components/orca-profiles/orca-profile-org-members-labels.ts create mode 100644 src/renderer/src/components/orca-profiles/orca-profile-switch-liveness.test.ts create mode 100644 src/renderer/src/components/orca-profiles/orca-profile-switch-liveness.ts create mode 100644 src/renderer/src/components/right-sidebar/AiVaultSessionSubagents.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/AiVaultSessionSubagents.tsx create mode 100644 src/renderer/src/components/right-sidebar/AiVaultSessionUnsavedNotice.tsx create mode 100644 src/renderer/src/components/right-sidebar/SourceControl.push-failure-recovery.test.ts create mode 100644 src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/ai-vault-original-pane-index.test.ts create mode 100644 src/renderer/src/components/right-sidebar/ai-vault-original-pane-index.ts create mode 100644 src/renderer/src/components/right-sidebar/ai-vault-view-defaults.test.ts create mode 100644 src/renderer/src/components/right-sidebar/ai-vault-view-defaults.ts create mode 100644 src/renderer/src/components/right-sidebar/push-failure-summary.ts create mode 100644 src/renderer/src/components/right-sidebar/runSourceControlAgentActionStart.test.ts create mode 100644 src/renderer/src/components/right-sidebar/source-control-action-error.ts create mode 100644 src/renderer/src/components/right-sidebar/source-control-ai-push-failure-launch.ts create mode 100644 src/renderer/src/components/right-sidebar/source-control-ai-recovery-launch.ts create mode 100644 src/renderer/src/components/right-sidebar/source-control-push-recovery.test.ts create mode 100644 src/renderer/src/components/right-sidebar/source-control-push-recovery.ts create mode 100644 src/renderer/src/components/right-sidebar/source-control-recovery-notice.tsx create mode 100644 src/renderer/src/components/right-sidebar/source-control-virtual-file-list.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/source-control-virtual-file-list.tsx create mode 100644 src/renderer/src/components/right-sidebar/use-file-explorer-ignored-paths.ts create mode 100644 src/renderer/src/components/right-sidebar/use-source-control-recovery-ai.ts create mode 100644 src/renderer/src/components/right-sidebar/useFileExplorerVisibleRowProjection.debounce.test.tsx create mode 100644 src/renderer/src/components/settings/GrokAccountsSection.tsx create mode 100644 src/renderer/src/components/settings/appearance-status-bar-antigravity-toggle-search.ts create mode 100644 src/renderer/src/components/settings/appearance-status-bar-grok-toggle-search.ts create mode 100644 src/renderer/src/components/settings/codex-session-source-home-control.test.tsx create mode 100644 src/renderer/src/components/settings/codex-session-source-home-control.tsx create mode 100644 src/renderer/src/components/settings/linear-agent-skill-install-cta.test.tsx create mode 100644 src/renderer/src/components/settings/linear-agent-skill-install-cta.tsx create mode 100644 src/renderer/src/components/settings/provider-account-visibility.test.ts create mode 100644 src/renderer/src/components/settings/provider-account-visibility.ts create mode 100644 src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts create mode 100644 src/renderer/src/components/shared/kill-all-terminal-surfaces.ts create mode 100644 src/renderer/src/components/shared/useDaemonActions.test.tsx create mode 100644 src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.tsx create mode 100644 src/renderer/src/components/sidebar/delete-worktree-dirty-change-counts.ts create mode 100644 src/renderer/src/components/sidebar/ssh-host-remove-resolution.test.ts create mode 100644 src/renderer/src/components/sidebar/ssh-host-remove-resolution.ts create mode 100644 src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts create mode 100644 src/renderer/src/components/sidebar/ssh-workspace-forget-resolution.test.ts create mode 100644 src/renderer/src/components/sidebar/ssh-workspace-forget-resolution.ts create mode 100644 src/renderer/src/components/stats/GrokUsagePane.test.tsx create mode 100644 src/renderer/src/components/stats/GrokUsagePane.tsx create mode 100644 src/renderer/src/components/tab-bar/TerminalTabSplitMenuSection.tsx create mode 100644 src/renderer/src/components/task-page-jira-grouping.test.ts create mode 100644 src/renderer/src/components/task-page-jira-issue-list.tsx create mode 100644 src/renderer/src/components/task-page-jira-sort-controls.test.tsx create mode 100644 src/renderer/src/components/task-page-jira-sort-controls.tsx create mode 100644 src/renderer/src/components/task-page-jira-sorting.test.ts create mode 100644 src/renderer/src/components/task-page-jira-status-order.ts create mode 100644 src/renderer/src/components/task-page-linear-issue-empty-state.test.ts create mode 100644 src/renderer/src/components/task-page-linear-issue-empty-state.ts create mode 100644 src/renderer/src/components/task-page-linear-issue-request.test.ts create mode 100644 src/renderer/src/components/task-page-linear-issue-request.ts create mode 100644 src/renderer/src/components/task-page-new-issue-draft.test.ts create mode 100644 src/renderer/src/components/task-page-new-issue-draft.ts create mode 100644 src/renderer/src/components/terminal-pane/agent-completion-no-evidence-cadence.test.ts create mode 100644 src/renderer/src/components/terminal-pane/agent-hook-terminal-lifecycle.test.ts create mode 100644 src/renderer/src/components/terminal-pane/agent-hook-terminal-lifecycle.ts create mode 100644 src/renderer/src/components/terminal-pane/agent-task-complete-policy.ts create mode 100644 src/renderer/src/components/terminal-pane/hard-wrapped-terminal-path-fragments.ts create mode 100644 src/renderer/src/components/terminal-pane/hidden-reveal-reconciliation.fuzz.test.ts create mode 100644 src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts create mode 100644 src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts create mode 100644 src/renderer/src/components/terminal-pane/parked-terminal-mode2031-responder.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-delivery-interest.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-dispatcher-delivery-interest.test.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-dispatcher-delivery-resync.test.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-dispatcher-push-reattach.test.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-model-restore-channel.test.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-model-restore-channel.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-renderer-delivery-claims.test.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-renderer-delivery-claims.ts create mode 100644 src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts create mode 100644 src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts create mode 100644 src/renderer/src/components/terminal-pane/ssh-pane-connect-gate.test.ts create mode 100644 src/renderer/src/components/terminal-pane/ssh-pane-connect-gate.ts create mode 100644 src/renderer/src/components/terminal-pane/stale-document-visibility.test.ts create mode 100644 src/renderer/src/components/terminal-pane/stale-document-visibility.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-delivery-watchdog.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-delivery-watchdog.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-freeze-breadcrumbs.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-freeze-report.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-freeze-report.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-hidden-delivery-gate.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-hidden-restore-scrollback.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-hidden-restore-scrollback.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-keyboard-protocol-pane-agent.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-keyboard-protocol-pane-agent.ts delete mode 100644 src/renderer/src/components/terminal-pane/terminal-kitty-keyboard-awareness.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/terminal-kitty-keyboard-awareness.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-parked-watcher-registry.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-parser-handler-guard.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-parser-handler-guard.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-title-tracker-parity.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-view-attributes-publisher.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-view-attributes-publisher.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-webgl-diagnostics-breadcrumbs.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.ts create mode 100644 src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts create mode 100644 src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts create mode 100644 src/renderer/src/components/terminal-pane/xterm-bypass-event-fixture.ts create mode 100644 src/renderer/src/components/terminal-pane/xterm-write-buffer-stall.repro.test.ts create mode 100644 src/renderer/src/components/terminal/terminal-tab-actions-kill-all.test.ts create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-background-removal-late-settlement.test.ts create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-background-removal.test.ts create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-background-removal.ts create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-labels.ts create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-list.test.tsx create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-list.tsx create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row-data.test.ts create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row-data.ts create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row-details.tsx create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row.test.tsx create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row.tsx create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-removal-candidates.test.ts create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-removal-candidates.ts create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-removal-settlement.ts create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-status-pill.tsx create mode 100644 src/renderer/src/hooks/programmatic-scroll-marks.test.ts create mode 100644 src/renderer/src/hooks/programmatic-scroll-marks.ts create mode 100644 src/renderer/src/hooks/ssh-reconnect-pane-retry.test.ts create mode 100644 src/renderer/src/hooks/ssh-reconnect-pane-retry.ts create mode 100644 src/renderer/src/hooks/useIssueMetadata.test.tsx create mode 100644 src/renderer/src/hooks/useVirtualizedScrollAnchor.marks-restore-signal.test.ts create mode 100644 src/renderer/src/hooks/virtualized-scroll-anchor-listener.ts create mode 100644 src/renderer/src/hooks/virtualized-scroll-anchor-restore.ts create mode 100644 src/renderer/src/i18n/native-chat-locales.test.ts create mode 100644 src/renderer/src/lib/agent-followup-delivery.test.ts create mode 100644 src/renderer/src/lib/agent-startup-delayed-delivery-perf.test.ts create mode 100644 src/renderer/src/lib/automation-session-observer.test.ts create mode 100644 src/renderer/src/lib/blocked-notification-fallback.ts create mode 100644 src/renderer/src/lib/crash-breadcrumb-recorder.ts create mode 100644 src/renderer/src/lib/hook-command-delayed-delivery-perf.test.ts create mode 100644 src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts create mode 100644 src/renderer/src/lib/keyboard-layout/layout-base-character.ts create mode 100644 src/renderer/src/lib/launch-agent-web-host-tab.ts create mode 100644 src/renderer/src/lib/linear-agent-skill-update-command.ts create mode 100644 src/renderer/src/lib/monaco-peek-preview-options.test.ts create mode 100644 src/renderer/src/lib/monaco-peek-preview-options.ts create mode 100644 src/renderer/src/lib/native-chat-transcript-readability.test.ts create mode 100644 src/renderer/src/lib/native-chat-transcript-readability.ts create mode 100644 src/renderer/src/lib/pane-manager/pane-terminal-output-ack-credit.ts create mode 100644 src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-throughput.bench.test.ts create mode 100644 src/renderer/src/lib/pane-manager/terminal-arabic-shaping-joiner.test.ts create mode 100644 src/renderer/src/lib/pane-manager/terminal-arabic-shaping-joiner.ts create mode 100644 src/renderer/src/lib/pane-manager/terminal-ligatures-addon.test.ts create mode 100644 src/renderer/src/lib/pane-manager/terminal-ligatures-addon.ts create mode 100644 src/renderer/src/lib/pane-manager/xterm-write-callback-guard.test.ts create mode 100644 src/renderer/src/lib/pane-manager/xterm-write-callback-guard.ts create mode 100644 src/renderer/src/lib/resume-sleeping-agent-session-suppress-navigation.test.ts create mode 100644 src/renderer/src/lib/sleeping-agent-session-launch.ts create mode 100644 src/renderer/src/lib/use-tab-agent-pi-identity.test.ts create mode 100644 src/renderer/src/lib/use-tab-agent-sleeping-session.test.ts create mode 100644 src/renderer/src/lib/wake-sleeping-agents-in-background.test.ts create mode 100644 src/renderer/src/lib/wake-sleeping-agents-in-background.ts create mode 100644 src/renderer/src/lib/workspace-port-scan-debounce.test.ts create mode 100644 src/renderer/src/lib/workspace-port-scan-debounce.ts create mode 100644 src/renderer/src/runtime/remote-runtime-terminal-frame-drop-resync.test.ts create mode 100644 src/renderer/src/runtime/runtime-environment-ssh-state.test.ts create mode 100644 src/renderer/src/runtime/runtime-environment-ssh-state.ts create mode 100644 src/renderer/src/runtime/runtime-provider-accounts-client.test.ts create mode 100644 src/renderer/src/runtime/runtime-provider-accounts-client.ts create mode 100644 src/renderer/src/store/slices/new-issue-draft.test.ts create mode 100644 src/renderer/src/store/slices/new-issue-draft.ts create mode 100644 src/renderer/src/store/slices/orca-profiles-auth-actions.test.ts create mode 100644 src/renderer/src/store/slices/orca-profiles-auth-actions.ts create mode 100644 src/renderer/src/store/slices/orca-profiles.test.ts create mode 100644 src/renderer/src/store/slices/orca-profiles.ts create mode 100644 src/renderer/src/store/slices/rate-limits.test.ts create mode 100644 src/renderer/src/store/slices/repos-runtime-routing-fixture.ts create mode 100644 src/renderer/src/store/slices/runtime-environment-ssh.test.ts create mode 100644 src/renderer/src/store/slices/runtime-environment-ssh.ts create mode 100644 src/renderer/src/store/slices/superseded-ssh-repo-rows.test.ts create mode 100644 src/renderer/src/store/slices/superseded-ssh-repo-rows.ts create mode 100644 src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts rename src/renderer/src/store/slices/{workspace-cleanup.test.ts => workspace-cleanup-removal-preflight.test.ts} (50%) create mode 100644 src/renderer/src/store/slices/workspace-cleanup-scan-progress.test.ts create mode 100644 src/renderer/src/store/slices/workspace-cleanup-slice-test-harness.ts create mode 100644 src/shared/agent-prompt-injection.test.ts create mode 100644 src/shared/agent-prompt-injection.ts create mode 100644 src/shared/agent-title-core.ts create mode 100644 src/shared/agent-title-identity.ts create mode 100644 src/shared/agent-title-status.ts create mode 100644 src/shared/agent-tui-ansi-fuzz-stream.ts create mode 100644 src/shared/ai-vault-session-display.ts create mode 100644 src/shared/ai-vault-session-filters.test.ts create mode 100644 src/shared/ai-vault-session-filters.ts create mode 100644 src/shared/ai-vault-types.test.ts create mode 100644 src/shared/automation-run-retention.test.ts create mode 100644 src/shared/automation-run-retention.ts rename src/{renderer/src/components/terminal-pane => shared}/command-code-output-status.test.ts (100%) rename src/{renderer/src/components/terminal-pane => shared}/command-code-output-status.ts (95%) rename src/{renderer/src/components/terminal-pane => shared}/command-code-prompt-text.ts (100%) create mode 100644 src/shared/file-listing-cancellation.ts create mode 100644 src/shared/git-binary-compatibility.test.ts create mode 100644 src/shared/git-capability-cache.test.ts create mode 100644 src/shared/git-capability-cache.ts create mode 100644 src/shared/git-check-ignore-stdio.test.ts create mode 100644 src/shared/git-check-ignore-stdio.ts create mode 100644 src/shared/git-cquoted-path.test.ts create mode 100644 src/shared/git-fetch-auto-maintenance.ts create mode 100644 src/shared/git-merge-tree-capability.test.ts create mode 100644 src/shared/git-merge-tree-capability.ts create mode 100644 src/shared/git-output-locale.ts create mode 100644 src/shared/git-ref-command-capabilities.ts create mode 100644 src/shared/git-worktree-command-capabilities.ts create mode 100644 src/shared/github-links.ts create mode 100644 src/shared/grok-session-path-lookup-queue.ts create mode 100644 src/shared/grok-session-paths.test.ts create mode 100644 src/shared/grok-session-paths.ts create mode 100644 src/shared/linear-issue-attribute-filter.test.ts create mode 100644 src/shared/linear-issue-attribute-filter.ts create mode 100644 src/shared/map-with-concurrency.test.ts create mode 100644 src/shared/map-with-concurrency.ts create mode 100644 src/shared/orca-dispatch-status-prompt.ts create mode 100644 src/shared/orca-profiles.ts create mode 100644 src/shared/osc-title-scan-tail.test.ts create mode 100644 src/shared/pane-agent-owner.test.ts create mode 100644 src/shared/pane-agent-owner.ts create mode 100644 src/shared/posix-command-path-lookup.test.ts create mode 100644 src/shared/posix-command-path-lookup.ts create mode 100644 src/shared/pty-delivery-diagnostics.test.ts create mode 100644 src/shared/pty-delivery-diagnostics.ts create mode 100644 src/shared/pty-model-restore-marker.ts create mode 100644 src/shared/pty-renderer-delivery-health.ts create mode 100644 src/shared/quick-open-directory-validation.ts create mode 100644 src/shared/quick-open-expansion-paths.test.ts create mode 100644 src/shared/quick-open-expansion-paths.ts create mode 100644 src/shared/quick-open-git-directory-collapse.test.ts create mode 100644 src/shared/remote-runtime-shared-control-keepalive-refresh.test.ts create mode 100644 src/shared/remote-runtime-shared-control-subscriptions.test.ts create mode 100644 src/shared/remote-runtime-socket-liveness.ts create mode 100644 src/shared/runtime-subscription-replay.ts create mode 100644 src/shared/source-control-push-failure-agent-command.ts create mode 100644 src/shared/source-control-push-failure.test.ts create mode 100644 src/shared/source-control-push-failure.ts create mode 100644 src/shared/source-control-recovery-agent-command.test.ts create mode 100644 src/shared/source-control-recovery-agent-command.ts create mode 100644 src/shared/ssh-pty-id.test.ts create mode 100644 src/shared/subprocess-stdin-write.test.ts create mode 100644 src/shared/subprocess-stdin-write.ts rename src/{renderer/src/components/terminal-pane/bell-detector.test.ts => shared/terminal-bell-detector.test.ts} (93%) rename src/{renderer/src/components/terminal-pane/bell-detector.ts => shared/terminal-bell-detector.ts} (82%) rename src/{renderer/src/lib => shared}/terminal-github-pr-link-detector.test.ts (100%) rename src/{renderer/src/lib => shared}/terminal-github-pr-link-detector.ts (91%) create mode 100644 src/shared/terminal-kitty-keyboard-mode-tracker.test.ts create mode 100644 src/shared/terminal-kitty-keyboard-mode-tracker.ts create mode 100644 src/shared/terminal-line-height-settings.test.ts create mode 100644 src/shared/terminal-line-height-settings.ts create mode 100644 src/shared/terminal-osc133-command-finished.ts create mode 100644 src/shared/terminal-output-side-effects.test.ts create mode 100644 src/shared/terminal-output-side-effects.ts create mode 100644 src/shared/terminal-partial-escape-tail.test.ts create mode 100644 src/shared/terminal-partial-escape-tail.ts create mode 100644 src/shared/terminal-query-reply.test.ts create mode 100644 src/shared/terminal-query-reply.ts create mode 100644 src/shared/terminal-reply-query-extraction.ts create mode 100644 src/shared/terminal-restore-parity-fixture.ts create mode 100644 src/shared/terminal-serialize-absolute-cursor.ts create mode 100644 src/shared/terminal-side-effect-facts.ts create mode 100644 src/shared/terminal-title-display.ts create mode 100644 src/shared/terminal-title-status.ts create mode 100644 src/shared/terminal-view-attributes.test.ts create mode 100644 src/shared/terminal-view-attributes.ts create mode 100644 src/shared/terminal-webgl-diagnostics.ts create mode 100644 src/shared/worktree-removal.ts create mode 100644 src/shared/ws-outbound-backpressure-queue.test.ts create mode 100644 src/shared/ws-outbound-backpressure-queue.ts create mode 100644 src/shared/wsl-hook-relay-contract.ts create mode 100644 tests/e2e/artificial-opencode-hidden-pressure-script.ts create mode 100644 tests/e2e/artificial-opencode-pane-interactions.ts create mode 100644 tests/e2e/artificial-opencode-revisit-pressure-scenario.ts create mode 100644 tests/e2e/helpers/seeded-test-repo.ts create mode 100644 tests/e2e/helpers/terminal-input-probes.ts create mode 100644 tests/e2e/large-file-count-fixtures.ts create mode 100644 tests/e2e/orca-profiles.spec.ts create mode 100644 tests/e2e/renderer-crash-recovery-terminal-input.spec.ts create mode 100644 tests/e2e/restart-restore-terminal-input.spec.ts create mode 100644 tests/e2e/rich-markdown-link-bubble-stacking.spec.ts create mode 100644 tests/e2e/source-control-large-file-count.spec.ts create mode 100644 tests/e2e/sustained-agent-typing-load-scripts.ts create mode 100644 tests/e2e/terminal-foreground-confirmation.unit.test.ts create mode 100644 tests/e2e/terminal-hidden-view-parking.spec.ts create mode 100644 tests/e2e/terminal-multi-workspace-typing-latency.spec.ts create mode 100644 tests/e2e/terminal-pane-close-layout-consistency.spec.ts create mode 100644 tests/e2e/terminal-parked-memory.spec.ts create mode 100644 tests/e2e/terminal-push-delivery-loss-recovery.spec.ts create mode 100644 tests/e2e/terminal-reattach-mouse-mode-leak.spec.ts create mode 100644 tests/e2e/terminal-sleep-wake-restore.spec.ts create mode 100644 tests/e2e/terminal-stuck-occlusion-recovery.spec.ts create mode 100644 tools/benchmarks/cpu-pressure-worker.mjs create mode 100644 tools/benchmarks/terminal-headless-parse-bench.mjs create mode 100644 tools/benchmarks/terminal-pipeline-bench.mjs create mode 100644 tools/daemon-relocation-spike/README.md create mode 100644 tools/daemon-relocation-spike/app-inventory.mjs create mode 100644 tools/daemon-relocation-spike/cli.mjs create mode 100644 tools/daemon-relocation-spike/daemon-launch.mjs create mode 100644 tools/daemon-relocation-spike/host-copy.mjs create mode 100644 tools/daemon-relocation-spike/loaded-module-probe.mjs create mode 100644 tools/daemon-relocation-spike/loaded-modules.ps1 create mode 100644 tools/daemon-relocation-spike/ndjson-client.mjs create mode 100644 tools/daemon-relocation-spike/selftest.mjs create mode 100644 tools/daemon-relocation-spike/spike.mjs create mode 100644 tools/daemon-relocation-spike/tier-file-set.mjs create mode 100644 tools/repro-orchestration-long-prompt.mjs create mode 100644 tools/repro-watcher-crash-7547/.gitignore create mode 100644 tools/repro-watcher-crash-7547/README.md create mode 100644 tools/repro-watcher-crash-7547/child.cjs create mode 100644 tools/repro-watcher-crash-7547/fixed-child.cjs create mode 100644 tools/repro-watcher-crash-7547/run.cjs create mode 100644 tools/win-update-e2e/README.md create mode 100644 tools/win-update-e2e/app-driver.mjs create mode 100644 tools/win-update-e2e/assertions.mjs create mode 100644 tools/win-update-e2e/cli-args.mjs create mode 100644 tools/win-update-e2e/daemon-processes.mjs create mode 100644 tools/win-update-e2e/installer-steps.mjs create mode 100644 tools/win-update-e2e/interactivity-probes.mjs create mode 100644 tools/win-update-e2e/onboarding-profile.mjs create mode 100644 tools/win-update-e2e/platform-guard.mjs create mode 100644 tools/win-update-e2e/powershell-runner.mjs create mode 100644 tools/win-update-e2e/preflight.mjs create mode 100644 tools/win-update-e2e/registry-shortcut-backup.mjs create mode 100644 tools/win-update-e2e/run.mjs create mode 100644 tools/win-update-e2e/window-enum.ps1 create mode 100644 tools/win-update-e2e/window-watch.mjs create mode 100644 tools/win-update-e2e/window-watch.ps1 diff --git a/.github/workflows/computer-e2e.yml b/.github/workflows/computer-e2e.yml index 8024d4989188..58cdbb36d1cd 100644 --- a/.github/workflows/computer-e2e.yml +++ b/.github/workflows/computer-e2e.yml @@ -10,7 +10,15 @@ on: - 'config/scripts/computer-use-skill-guidance.test.mjs' - 'config/scripts/computer-use-smoke.mjs' - 'config/scripts/computer-use-smoke.test.mjs' + - 'config/scripts/daemon-boot-smoke.mjs' + - 'config/scripts/windows-daemon-workspace-close-repro.mjs' - 'config/scripts/verify-computer-native.mjs' + # Why: the native-smoke job boots the built terminal daemon under plain + # Node, so any change to the daemon bundle graph or the main build must + # re-run it (the v1.4.129-rc.1 daemon outage shipped with green CI). + - 'electron.vite.config.ts' + - 'build-plugins/**' + - 'src/main/daemon/**' - 'native/computer-use-macos/**' - 'native/computer-use-linux/**' - 'native/computer-use-windows/**' @@ -98,6 +106,17 @@ jobs: - run: pnpm verify:computer-native - run: pnpm build:cli - run: pnpm build:electron-vite + # Why: boot the BUILT daemon-entry under plain Node the way production + # forks it. v1.4.129-rc.1 shipped a daemon that exited at module load + # (leaked electron require) while every other check passed; this fails + # the PR when the built daemon cannot start on ubuntu-22.04 / windows. + - name: Daemon boot smoke + run: node config/scripts/daemon-boot-smoke.mjs + # Why: workspace removal overlaps graceful renderer teardown with the + # forced main-process sweep; exercise that exact pair against real ConPTY. + - name: Windows daemon workspace-close repro + if: runner.os == 'Windows' + run: node config/scripts/windows-daemon-workspace-close-repro.mjs - if: runner.os == 'Linux' env: ORCA_COMPUTER_E2E: '1' diff --git a/.github/workflows/daemon-relocation-spike.yml b/.github/workflows/daemon-relocation-spike.yml new file mode 100644 index 000000000000..319580dc264c --- /dev/null +++ b/.github/workflows/daemon-relocation-spike.yml @@ -0,0 +1,97 @@ +name: Daemon Relocation Spike + +# Why: Phase 1 of the Windows update-survival work relocates the terminal +# daemon's file closure out of the install dir so it survives an update. Before +# implementing it in the app, this spike finds the MINIMAL set of packaged files +# that a copied Orca.exe (run as node) needs to start the daemon and drive a +# ConPTY session from a relocated directory, holding no install-dir file locks. +# Runs from the feature branch via push (workflow_dispatch only works on the +# default branch); main is never touched. + +on: + push: + branches: + - Jinwoo-H/windows-update-survival + paths: + - 'tools/daemon-relocation-spike/**' + - '.github/workflows/daemon-relocation-spike.yml' + workflow_dispatch: {} + +permissions: + contents: read + +concurrency: + group: daemon-relocation-spike-${{ github.ref }} + cancel-in-progress: true + +jobs: + spike: + name: relocation file-set spike + runs-on: windows-2022 + timeout-minutes: 40 + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + # This job only reads the repo to build/run the spike; it never pushes. + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + run_install: false + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # Why: cache the unpacked build keyed on the inputs that affect it, so + # spike-script-only edits skip the ~15 min electron-builder build. + - name: Cache unpacked build + id: cache-unpacked + uses: actions/cache@v4 + with: + path: dist/win-unpacked + key: win-unpacked-${{ hashFiles('src/**', 'config/**', 'package.json', 'pnpm-lock.yaml') }} + + - name: Build unpacked app + if: steps.cache-unpacked.outputs.cache-hit != 'true' + run: pnpm run build:unpack + + - name: Run relocation spike (all tiers) + shell: pwsh + run: | + New-Item -ItemType Directory -Force artifacts | Out-Null + $log = "artifacts/spike-output.log" + $tiers = @('full', 'no-gpu', 'minimal') + $any = $false + foreach ($tier in $tiers) { + "===== TIER: $tier =====" | Tee-Object -FilePath $log -Append + $work = Join-Path $env:RUNNER_TEMP "spike-$tier" + # --keep-work-dir so the per-tier daemon stdout/stderr logs survive + # for the artifact upload (the spike otherwise removes work-dir), + # which is what diagnoses a tier that fails to reach ready. + node tools/daemon-relocation-spike/spike.mjs ` + --app-dir dist/win-unpacked ` + --work-dir "$work" ` + --tier $tier ` + --keep-work-dir 2>&1 | Tee-Object -FilePath $log -Append + if ($LASTEXITCODE -eq 0) { $any = $true } + } + if (-not $any) { throw "No tier passed the relocation spike" } + + - name: Upload spike output + if: always() + uses: actions/upload-artifact@v7 + with: + name: daemon-relocation-spike-output + path: | + artifacts/spike-output.log + ${{ runner.temp }}/spike-*/**/*.log + retention-days: 7 + if-no-files-found: warn diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 2f91c946bc72..0a4169c6b7d3 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -17,7 +17,7 @@ jobs: uses: actions/checkout@v6 - name: Install native build tools - run: sudo apt-get update && sudo apt-get install -y build-essential python3 zsh + run: sudo apt-get update && sudo apt-get install -y build-essential python3 zlib1g-dev zsh - name: Setup Node.js uses: actions/setup-node@v6 @@ -103,6 +103,33 @@ jobs: - name: Typecheck run: pnpm typecheck + # Why: real old Git diagnostics differ from mocked errors. Keep the + # fallback predicates executable across the baseline, transition, and + # current command shapes so a newly added flag cannot silently regress. + - name: Verify Git binary compatibility matrix + run: | + archive="$RUNNER_TEMP/git-2.25.5.tar.gz" + source="$RUNNER_TEMP/git-2.25.5" + curl -fsSL https://www.kernel.org/pub/software/scm/git/git-2.25.5.tar.gz -o "$archive" + echo "41662c52fc16fec4963bfc41075e71f8ead6b5e386797eb6f9a1111ff95a8ddf $archive" \ + | sha256sum --check + mkdir -p "$source" + tar -xzf "$archive" -C "$source" --strip-components=1 + make -C "$source" -j2 NO_GETTEXT=YesPlease NO_TCLTK=YesPlease NO_PYTHON=YesPlease git + ORCA_GIT_COMPAT_BINARY="$source/git" ORCA_GIT_COMPAT_VERSION="2.25.5" \ + pnpm exec vitest run --config config/vitest.config.ts \ + src/shared/git-binary-compatibility.test.ts + + for spec in \ + "alpine/git:edge-2.38.1|2.38.1" \ + "alpine/git:v2.49.1|2.49.1"; do + image="${spec%%|*}" + version="${spec#*|}" + ORCA_GIT_COMPAT_IMAGE="$image" ORCA_GIT_COMPAT_VERSION="$version" \ + pnpm exec vitest run --config config/vitest.config.ts \ + src/shared/git-binary-compatibility.test.ts + done + # Why: postinstall rebuilds better-sqlite3 for Electron's ABI via # @electron/rebuild, but vitest runs under system Node.js. Rebuild # it for Node so orchestration tests can load the native module. diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml index 96af9bd0cd1e..397772bfb7ec 100644 --- a/.github/workflows/release-cut.yml +++ b/.github/workflows/release-cut.yml @@ -41,6 +41,11 @@ on: required: false default: false type: boolean + version_suffix: + description: Extra prerelease identifier appended to an rc version (e.g. "perf" -> 1.2.3-rc.4.perf). rc kind only. + required: false + type: string + default: '' permissions: contents: write @@ -192,6 +197,7 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} KIND: ${{ github.event_name == 'schedule' && 'rc' || inputs.kind }} + VERSION_SUFFIX: ${{ github.event_name == 'schedule' && '' || inputs.version_suffix }} run: | set -euo pipefail @@ -366,6 +372,18 @@ jobs: fi new="${base}-rc.$((highest_rc + 1))" fi + if [[ -n "${VERSION_SUFFIX:-}" ]]; then + # Why a dot-appended identifier (rc.N.perf): it sorts just + # above its own base rc.N but BELOW rc.N+1, so suffixed side- + # branch builds never outrank the main RC series and cannot + # hijack the update channel; clients find them by matching the + # identifier ("perf") in the prerelease components. + if [[ ! "$VERSION_SUFFIX" =~ ^[0-9A-Za-z]+$ ]]; then + echo "::error::version_suffix must be alphanumeric, got: $VERSION_SUFFIX" >&2 + exit 1 + fi + new="${new}.${VERSION_SUFFIX}" + fi ;; patch|minor|major) new="$(bump "$latest_stable" "$KIND")" @@ -719,6 +737,10 @@ jobs: ~/.cache/electron-builder runs-on: ${{ matrix.os }} + # Why: hosted runners hard-cap jobs at 6h; the Windows SignPath waits + # (1h inner + 4h installer) are budgeted to fit under this with the + # build itself, so a slow approval can't kill the job mid-flow. + timeout-minutes: 360 permissions: actions: read @@ -804,7 +826,10 @@ jobs: TAG: ${{ needs.cut.outputs.tag }} run: | set -euo pipefail - if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+-rc\.[0-9]+$ ]]; then + # Why the optional trailing identifier: suffixed side-branch RCs + # (vX.Y.Z-rc.N.perf) are rc-channel prerelease builds — same telemetry + # identity as plain RCs. + if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+-rc\.[0-9]+(\.[0-9A-Za-z]+)?$ ]]; then identity=rc elif [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then identity=stable @@ -958,6 +983,244 @@ jobs: } } + # ── Windows inner-binary signing (issue #7785) ───────────────────── + # Why: SignPath cannot deep-sign inside NSIS installers, so inner PE + # files (Orca.exe, node-pty *.node, DLLs) are signed via a separate zip + # request, then the installer is rebuilt from the signed tree before the + # existing installer signing request below. Every step in this chain is + # fail-open (continue-on-error + outcome gating): any failure ships the + # original installer with unsigned inner binaries, exactly like releases + # did before this chain existed. Rehearsed end to end in run 28988432001 + # (.github/workflows/windows-signing-rehearsal.yml). + + # Why: only unsigned PE files go to SignPath. Files that already carry a + # valid signature (Microsoft's OpenConsole.exe) must keep their signer. + - name: Stage unsigned inner PE files for signing + id: stage-inner + if: matrix.platform == 'win' + continue-on-error: true + shell: pwsh + run: | + $root = Resolve-Path 'dist/win-unpacked' + $stage = New-Item -ItemType Directory -Force -Path 'signing-stage' + $list = New-Object System.Collections.Generic.List[string] + $skipped = New-Object System.Collections.Generic.List[string] + + Get-ChildItem -Path $root -Recurse -File | + Where-Object { $_.Extension -in '.exe', '.dll', '.node' } | + ForEach-Object { + $relative = [System.IO.Path]::GetRelativePath($root, $_.FullName) + $signature = Get-AuthenticodeSignature -FilePath $_.FullName + if ($signature.Status -eq 'Valid') { + $skipped.Add("$relative ") + return + } + $destination = Join-Path $stage.FullName $relative + New-Item -ItemType Directory -Force -Path (Split-Path $destination) | Out-Null + Copy-Item -Path $_.FullName -Destination $destination -Force + $list.Add($relative) + } + + if (-not ($list -contains 'Orca.exe')) { + throw 'Orca.exe was not staged for signing; unpacked layout changed?' + } + if (-not ($list | Where-Object { $_ -like '*conpty_console_list.node' })) { + throw 'node-pty conpty_console_list.node was not staged; this is the file from issue #7785.' + } + + Set-Content -Path 'inner-signing-list.txt' -Value ($list -join "`n") + Write-Host "Staged $($list.Count) unsigned PE files for signing:" + $list | ForEach-Object { Write-Host " $_" } + Write-Host "Skipped $($skipped.Count) already-signed files:" + $skipped | ForEach-Object { Write-Host " $_" } + + - name: Upload unsigned inner binaries for SignPath + id: upload-unsigned-inner + if: matrix.platform == 'win' && steps.stage-inner.outcome == 'success' + continue-on-error: true + uses: actions/upload-artifact@v7 + with: + name: orca-windows-inner-unsigned-${{ needs.cut.outputs.tag }} + path: signing-stage/** + if-no-files-found: error + + - name: Submit inner binaries signing request + id: submit-inner-signing + if: matrix.platform == 'win' && steps.upload-unsigned-inner.outcome == 'success' + continue-on-error: true + uses: signpath/github-action-submit-signing-request@v2 + with: + api-token: ${{ secrets.SIGNPATH_API_TOKEN }} + organization-id: c37aa192-a27a-4377-9c90-5d6c95912dc0 + project-slug: orca + signing-policy-slug: release-signing + artifact-configuration-slug: windows-inner-binaries-zip + github-artifact-id: ${{ steps.upload-unsigned-inner.outputs.artifact-id }} + wait-for-completion: false + + - name: Notify Slack that inner-binary signing is waiting for approval + id: notify-inner-signing + if: matrix.platform == 'win' && steps.submit-inner-signing.outcome == 'success' + continue-on-error: true + shell: pwsh + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} + SIGNPATH_ORGANIZATION_ID: c37aa192-a27a-4377-9c90-5d6c95912dc0 + SIGNPATH_REQUEST_ID: ${{ steps.submit-inner-signing.outputs.signing-request-id }} + SIGNPATH_REQUEST_URL: ${{ steps.submit-inner-signing.outputs.signing-request-web-url }} + TAG: ${{ needs.cut.outputs.tag }} + GITHUB_RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + if ([string]::IsNullOrWhiteSpace($env:SLACK_WEBHOOK_URL)) { + throw 'SLACK_WEBHOOK_URL secret is required so release approvers know when SignPath is waiting.' + } + + $requestUrl = $env:SIGNPATH_REQUEST_URL + if ([string]::IsNullOrWhiteSpace($requestUrl)) { + $requestUrl = "https://app.signpath.io/Web/$env:SIGNPATH_ORGANIZATION_ID/SigningRequests/$env:SIGNPATH_REQUEST_ID" + } + + $message = "Orca Windows release $env:TAG inner-binaries signing request (1 of 2) is ready for SignPath approval.`n<$requestUrl|Open SignPath signing request>`n<$env:GITHUB_RUN_URL|Open GitHub Actions run>" + $payload = @{ + text = $message + blocks = @( + @{ + type = 'section' + text = @{ + type = 'mrkdwn' + text = $message + } + } + ) + } | ConvertTo-Json -Depth 5 + + Invoke-RestMethod -Method Post -Uri $env:SLACK_WEBHOOK_URL -ContentType 'application/json' -Body $payload + + # Why gate on the notify outcome too: if nobody was told to approve, + # don't hold the release for the approval window — fall through and + # ship like today instead. The 1h wait (vs the installer's 4h) keeps + # both waits plus the build inside the 360-minute job cap; missing it + # falls through to today's unsigned-inner flow rather than blocking. + - name: Download signed inner binaries from SignPath + id: download-signed-inner + if: matrix.platform == 'win' && steps.submit-inner-signing.outcome == 'success' && steps.notify-inner-signing.outcome == 'success' + continue-on-error: true + shell: pwsh + env: + SIGNPATH_API_TOKEN: ${{ secrets.SIGNPATH_API_TOKEN }} + SIGNPATH_REQUEST_ID: ${{ steps.submit-inner-signing.outputs.signing-request-id }} + run: | + Get-SignedArtifact ` + -OrganizationId c37aa192-a27a-4377-9c90-5d6c95912dc0 ` + -ApiToken $env:SIGNPATH_API_TOKEN ` + -SigningRequestId $env:SIGNPATH_REQUEST_ID ` + -OutputArtifactPath signed-inner.zip ` + -Force ` + -WaitForCompletionTimeoutInSeconds 3600 + + New-Item -ItemType Directory -Path signed-inner -Force + Expand-Archive -Path signed-inner.zip -DestinationPath signed-inner -Force + + # Why: copy back strictly by the staged list so a layout mismatch in the + # returned artifact fails loudly (into fail-open) instead of silently + # shipping a mix of signed and unsigned binaries. + - name: Restore signed inner binaries into unpacked app + id: restore-signed-inner + if: matrix.platform == 'win' && steps.download-signed-inner.outcome == 'success' + continue-on-error: true + shell: pwsh + run: | + $root = Resolve-Path 'dist/win-unpacked' + $failures = New-Object System.Collections.Generic.List[string] + foreach ($relative in Get-Content 'inner-signing-list.txt') { + $signed = Get-ChildItem -Path signed-inner -Recurse -File | + Where-Object { [System.IO.Path]::GetRelativePath((Resolve-Path 'signed-inner'), $_.FullName).TrimStart('\', '/') -like "*$relative" } | + Select-Object -First 1 + if ($null -eq $signed) { + $failures.Add("missing from signed artifact: $relative") + continue + } + $signature = Get-AuthenticodeSignature -FilePath $signed.FullName + if ($null -eq $signature.SignerCertificate) { + $failures.Add("returned without a signature: $relative") + continue + } + Copy-Item -Path $signed.FullName -Destination (Join-Path $root $relative) -Force + Write-Host ("{0,-14} {1} <{2}>" -f $signature.Status, $relative, $signature.SignerCertificate.Subject) + } + if ($failures.Count -gt 0) { + $failures | ForEach-Object { Write-Host "::error::$_" } + throw "Signed inner artifact did not round-trip cleanly ($($failures.Count) failures)." + } + + # Why this step exists: electron-builder's CopyElevateHelper re-copies a + # pristine elevate.exe from its download cache over resources\elevate.exe + # on EVERY nsis pack — including the --prepackaged rebuild below — which + # clobbered the SignPath signature in v1.4.129-rc.4. There is no supported + # way to disable just the copy, so we overwrite the cache's copy with our + # signed one (identical bytes plus signature) so the clobber becomes a + # no-op. Known quirk: the cache persists across releases via actions/cache, + # so later runs may see elevate.exe as already signed and skip staging it — + # that is fine (the signature is timestamped) and the evidence gate checks + # elevate.exe in the shipped installer unconditionally. If this ever causes + # trouble, delete this step; the only effect is elevate.exe shipping + # unsigned again, which the evidence gate will flag. + - name: Replace cached elevate.exe with the signed copy + id: sign-elevate-cache + if: matrix.platform == 'win' && steps.restore-signed-inner.outcome == 'success' + continue-on-error: true + shell: pwsh + run: | + $signed = 'dist/win-unpacked/resources/elevate.exe' + if (-not (Test-Path $signed)) { + Write-Host '::warning::No elevate.exe in win-unpacked resources; nothing to protect from the rebuild clobber.' + exit 0 + } + $signature = Get-AuthenticodeSignature -FilePath $signed + $subject = if ($null -eq $signature.SignerCertificate) { '' } else { $signature.SignerCertificate.Subject } + if ($signature.Status -ne 'Valid' -or $subject -notlike '*CN=SignPath Foundation*') { + Write-Host "::warning::win-unpacked elevate.exe is not SignPath-signed ($($signature.Status), $subject); skipping cache swap." + exit 0 + } + $cached = @(Get-ChildItem "$env:LOCALAPPDATA\electron-builder\Cache\nsis" -Recurse -Filter elevate.exe -ErrorAction SilentlyContinue) + if ($cached.Count -eq 0) { + Write-Host '::warning::No cached elevate.exe found (electron-builder cache layout changed?); the rebuild will pack the unsigned copy and the evidence gate will flag it.' + exit 0 + } + foreach ($file in $cached) { + Copy-Item -Path $signed -Destination $file.FullName -Force + Write-Host "Replaced $($file.FullName) with the SignPath-signed copy." + } + + - name: Rebuild NSIS installer from signed unpacked app + id: rebuild-nsis-signed + if: matrix.platform == 'win' && steps.restore-signed-inner.outcome == 'success' + continue-on-error: true + shell: pwsh + run: | + # Why: keep the pre-rebuild artifacts so a failed rebuild can fall + # back to shipping them unchanged (fail-open). + New-Item -ItemType Directory -Path prepack-backup -Force | Out-Null + Copy-Item 'dist/orca-windows-setup.exe' 'prepack-backup/orca-windows-setup.exe' -Force + Copy-Item 'dist/latest.yml' 'prepack-backup/latest.yml' -Force + + pnpm exec electron-builder --config config/electron-builder.config.cjs --win --publish never --prepackaged "$env:GITHUB_WORKSPACE\dist\win-unpacked" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if (-not (Test-Path 'dist/orca-windows-setup.exe')) { + throw 'electron-builder --prepackaged did not produce dist/orca-windows-setup.exe' + } + + - name: Roll back to original installer after failed rebuild + if: matrix.platform == 'win' && steps.rebuild-nsis-signed.outcome == 'failure' + shell: pwsh + run: | + if (Test-Path 'prepack-backup/orca-windows-setup.exe') { + Copy-Item 'prepack-backup/orca-windows-setup.exe' 'dist/orca-windows-setup.exe' -Force + Copy-Item 'prepack-backup/latest.yml' 'dist/latest.yml' -Force + Write-Warning 'Restored pre-rebuild installer; this release ships with unsigned inner binaries.' + } + # ── End Windows inner-binary signing ─────────────────────────────── + - name: Upload unsigned Windows installer for SignPath if: matrix.platform == 'win' id: upload-unsigned-windows-installer @@ -992,6 +1255,7 @@ jobs: SIGNPATH_REQUEST_URL: ${{ steps.submit-signing-request.outputs.signing-request-web-url }} TAG: ${{ needs.cut.outputs.tag }} GITHUB_RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} + INNER_SIGNING_SUBMITTED: ${{ steps.submit-inner-signing.outcome == 'success' }} run: | if ([string]::IsNullOrWhiteSpace($env:SLACK_WEBHOOK_URL)) { throw 'SLACK_WEBHOOK_URL secret is required so release approvers know when SignPath is waiting.' @@ -1002,7 +1266,9 @@ jobs: $requestUrl = "https://app.signpath.io/Web/$env:SIGNPATH_ORGANIZATION_ID/SigningRequests/$env:SIGNPATH_REQUEST_ID" } - $message = "Orca Windows release $env:TAG is ready for SignPath approval.`n<$requestUrl|Open SignPath signing request>`n<$env:GITHUB_RUN_URL|Open GitHub Actions run>" + # Why: releases where inner signing fell through have only this one request. + $stage = if ($env:INNER_SIGNING_SUBMITTED -eq 'true') { 'installer signing request (2 of 2)' } else { 'signing request' } + $message = "Orca Windows release $env:TAG $stage is ready for SignPath approval.`n<$requestUrl|Open SignPath signing request>`n<$env:GITHUB_RUN_URL|Open GitHub Actions run>" $payload = @{ text = $message blocks = @( @@ -1085,6 +1351,90 @@ jobs: } $signature.SignerCertificate | Format-List Subject,Issuer,NotBefore,NotAfter,Thumbprint + # Why: evidence gate for inner-binary signing (issue #7785, supersedes + # PR #7170's Orca.exe-only gate — this covers every staged .exe/.dll/.node + # by extracting the shipped installer). Warn-only until the flow has been + # proven on a real release, then flip ORCA_WINDOWS_INNER_SIGNATURE_REQUIRED + # to 'true' so unsigned inner binaries block the release. + - name: Verify Windows inner binary signatures + if: matrix.platform == 'win' + shell: pwsh + env: + ORCA_WINDOWS_INNER_SIGNATURE_REQUIRED: 'false' + INNER_SIGNING_COMPLETED: ${{ steps.rebuild-nsis-signed.outcome == 'success' }} + run: | + $required = $env:ORCA_WINDOWS_INNER_SIGNATURE_REQUIRED -eq 'true' + if ($env:INNER_SIGNING_COMPLETED -ne 'true') { + $message = 'Windows inner-binary signing did not complete; this release ships unsigned inner binaries (fail-open, issue #7785).' + if ($required) { throw $message } + Write-Host "::warning::$message" + exit 0 + } + + # Why try/catch: while the gate is warn-only, even an unexpected + # script error (extraction hiccup, missing file) must not block + # the release — only the flip to required makes failures fatal. + try { + $report = New-Object System.Collections.Generic.List[string] + $failures = New-Object System.Collections.Generic.List[string] + + # Why: verify the files a user actually gets on disk, not the build + # tree — 7z parses the NSIS exe directly as its embedded payload. + $7za = 'node_modules/7zip-bin/win/x64/7za.exe' + New-Item -ItemType Directory -Path inner-evidence-extract -Force | Out-Null + & $7za x 'dist/orca-windows-setup.exe' '-oinner-evidence-extract' -y | Out-Null + + $root = Resolve-Path 'inner-evidence-extract' + # Why elevate.exe is always appended: staging skips already-signed + # files, and the persisted electron-builder cache can carry a + # previously signed elevate.exe — so it may be absent from the list + # in some runs, yet it is the file most at risk of losing its + # signature in the NSIS rebuild. Verify it in every release. + $targets = @(Get-Content 'inner-signing-list.txt') + if ($targets -notcontains 'resources\elevate.exe') { + $targets += 'resources\elevate.exe' + } + foreach ($relative in $targets) { + $path = Join-Path $root $relative + if (-not (Test-Path $path)) { + $failures.Add("missing from installer payload: $relative") + continue + } + $signature = Get-AuthenticodeSignature -FilePath $path + $subject = if ($null -eq $signature.SignerCertificate) { '' } else { $signature.SignerCertificate.Subject } + $line = "{0,-14} {1} <{2}>" -f $signature.Status, $relative, $subject + $report.Add($line) + Write-Host $line + if ($signature.Status -ne 'Valid' -or $subject -notlike '*CN=SignPath Foundation*') { + $failures.Add("not signed by SignPath Foundation: $relative ($($signature.Status), $subject)") + } + } + + Set-Content -Path 'inner-signing-evidence.txt' -Value ($report -join "`n") + if ($failures.Count -gt 0) { + $failures | ForEach-Object { Write-Host "::warning::$_" } + $message = "Windows inner-binary evidence gate found $($failures.Count) problems." + if ($required) { throw $message } + Write-Host "::warning::$message Fail-open until ORCA_WINDOWS_INNER_SIGNATURE_REQUIRED is 'true'." + } else { + Write-Host "All $($targets.Count) inner binaries in the shipped installer are signed by SignPath Foundation." + } + } catch { + if ($required) { throw } + Write-Host "::warning::Windows inner-binary evidence gate errored: $_ (fail-open, issue #7785)." + } + + - name: Upload Windows inner signing evidence + if: always() && matrix.platform == 'win' + uses: actions/upload-artifact@v7 + with: + name: orca-windows-inner-signing-evidence-${{ needs.cut.outputs.tag }} + path: | + inner-signing-evidence.txt + inner-signing-list.txt + if-no-files-found: ignore + retention-days: 30 + - name: Publish signed Windows release artifacts if: matrix.platform == 'win' uses: nick-fields/retry@v4 diff --git a/.github/workflows/release-mac-build.yml b/.github/workflows/release-mac-build.yml index e82502baa475..3638d40f00c1 100644 --- a/.github/workflows/release-mac-build.yml +++ b/.github/workflows/release-mac-build.yml @@ -96,7 +96,10 @@ jobs: TAG: ${{ inputs.tag }} run: | set -euo pipefail - if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+-rc\.[0-9]+$ ]]; then + # Why the optional trailing identifier: suffixed side-branch RCs + # (vX.Y.Z-rc.N.perf) are rc-channel prerelease builds — same telemetry + # identity as plain RCs. + if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+-rc\.[0-9]+(\.[0-9A-Za-z]+)?$ ]]; then identity=rc elif [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then identity=stable diff --git a/.github/workflows/win-update-e2e.yml b/.github/workflows/win-update-e2e.yml new file mode 100644 index 000000000000..21c788256b23 --- /dev/null +++ b/.github/workflows/win-update-e2e.yml @@ -0,0 +1,145 @@ +name: Windows Update-Survival E2E + +# Why: proves what happens to terminal sessions across a real Windows app update +# by installing one released version, updating to another, and asserting on the +# packaged artifacts (daemon survival, terminal interactivity, zero console +# flashes). This MUST run on a disposable CI Windows: electron-builder's oneClick +# installer uninstalls the registry-registered copy of the app before every +# install, so running the harness on a machine with a real Orca install would +# delete it. A fresh runner has no Orca registered, so it is the only safe home +# for install-based testing. Manual dispatch only. + +# Why: workflow_dispatch only works once a workflow is on the default branch. +# To exercise this from the unmerged feature branch WITHOUT touching main, a +# push trigger scoped to that exact branch runs the workflow from the branch's +# own tree. The paths filter keeps it to harness/workflow edits so ordinary +# commits don't spend 30 min of Windows runner time. Push runs have no inputs, +# so every parameter falls back to a default below. +on: + push: + branches: + - Jinwoo-H/windows-update-survival + paths: + - 'tools/win-update-e2e/**' + - '.github/workflows/win-update-e2e.yml' + workflow_dispatch: + inputs: + from_tag: + description: Release tag to install first (e.g. v1.4.124-rc.8) + required: true + type: string + to_tag: + description: Release tag to update to (e.g. v1.4.124-rc.9) + required: true + type: string + expect: + description: Expected outcome profile + required: true + type: choice + default: cold-restore + options: + - cold-restore + - survival + asset_pattern: + description: Installer asset glob + required: false + type: string + default: '*windows-setup.exe' + soak_seconds: + description: Post-relaunch console-window watch duration + required: false + type: string + default: '60' + +permissions: + contents: read + +# Why: cancel a superseded run when iterating — a new push to the branch makes +# the in-flight Windows job obsolete, so free the runner immediately. +concurrency: + group: win-update-e2e-${{ github.ref }} + cancel-in-progress: true + +jobs: + update-e2e: + name: update ${{ inputs.from_tag || 'v1.4.124-rc.8' }} -> ${{ inputs.to_tag || 'v1.4.124-rc.9' }} (${{ inputs.expect || 'cold-restore' }}) + runs-on: windows-2022 + timeout-minutes: 30 + env: + FROM_TAG: ${{ inputs.from_tag || 'v1.4.124-rc.8' }} + TO_TAG: ${{ inputs.to_tag || 'v1.4.124-rc.9' }} + EXPECT: ${{ inputs.expect || 'cold-restore' }} + ASSET_PATTERN: ${{ inputs.asset_pattern || '*windows-setup.exe' }} + SOAK_SECONDS: ${{ inputs.soak_seconds || '60' }} + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + # This job only reads the repo and downloads a release; it never pushes. + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + run_install: false + + # Why: the harness only needs its runtime deps (the Playwright Electron + # driver); it drives already-built installer artifacts, so no app build. + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # Why: fail fast with a readable message if a tag has no matching Windows + # installer, rather than deep inside the harness. + - name: Download installers + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: pwsh + run: | + New-Item -ItemType Directory -Force artifacts/from | Out-Null + New-Item -ItemType Directory -Force artifacts/to | Out-Null + gh release download "$env:FROM_TAG" --repo "${{ github.repository }}" --pattern "$env:ASSET_PATTERN" --dir artifacts/from + gh release download "$env:TO_TAG" --repo "${{ github.repository }}" --pattern "$env:ASSET_PATTERN" --dir artifacts/to + $from = Get-ChildItem artifacts/from -Filter *.exe | Select-Object -First 1 + $to = Get-ChildItem artifacts/to -Filter *.exe | Select-Object -First 1 + if (-not $from) { throw "No installer matching '$env:ASSET_PATTERN' in $env:FROM_TAG" } + if (-not $to) { throw "No installer matching '$env:ASSET_PATTERN' in $env:TO_TAG" } + "FROM_EXE=$($from.FullName)" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + "TO_EXE=$($to.FullName)" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + + # Why: no --install-dir here. A CI runner has no real Orca registered, so + # the harness installs to the default per-user location and owns it — the + # isolated-install machinery exists only to (imperfectly) protect a real + # developer install, which does not apply on a throwaway runner. + - name: Run update-survival harness + id: harness + shell: pwsh + env: + # Why: on a driving failure the harness dumps a screenshot + DOM state + # here so the actual post-onboarding UI is visible in the artifacts. + ORCA_E2E_DIAG_DIR: artifacts/diag + run: | + $log = "artifacts/harness-output.log" + node tools/win-update-e2e/run.mjs ` + --from "$env:FROM_EXE" ` + --to "$env:TO_EXE" ` + --expect "$env:EXPECT" ` + --soak-seconds "$env:SOAK_SECONDS" 2>&1 | Tee-Object -FilePath $log + exit $LASTEXITCODE + + - name: Upload harness output + if: always() + uses: actions/upload-artifact@v7 + with: + name: win-update-e2e-output + # Why: log + diagnostics only, never the multi-hundred-MB installers. + path: | + artifacts/harness-output.log + artifacts/diag/** + retention-days: 7 + if-no-files-found: warn diff --git a/.github/workflows/win-update-survival-e2e.yml b/.github/workflows/win-update-survival-e2e.yml new file mode 100644 index 000000000000..f5e7cb093090 --- /dev/null +++ b/.github/workflows/win-update-survival-e2e.yml @@ -0,0 +1,116 @@ +name: Windows Update-Survival E2E (branch build) + +# Why: proves the Phase 1 daemon-host relocation actually makes terminal +# sessions SURVIVE a Windows update. Builds an (unsigned) installer FROM THIS +# BRANCH, then runs the win-update-e2e harness with --expect survival: install, +# open a terminal, silently update over it, relaunch, and assert the daemon PID +# is unchanged and the pre-update terminal is still interactive with no console +# flashing. Runs from the feature branch via push (workflow_dispatch only works +# on the default branch); main is never touched. A CI runner is the only safe +# place to install/update — see the relocation post-mortem. + +on: + push: + branches: + - Jinwoo-H/windows-update-survival + paths: + - 'src/main/daemon/**' + - 'src/main/pty/**' + - 'tools/win-update-e2e/**' + - 'config/electron-builder.config.cjs' + - '.github/workflows/win-update-survival-e2e.yml' + workflow_dispatch: + inputs: + expect: + description: Expected outcome profile + required: true + type: choice + default: survival + options: + - survival + - cold-restore + +permissions: + contents: read + +concurrency: + group: win-update-survival-e2e-${{ github.ref }} + cancel-in-progress: true + +jobs: + survival: + name: survival (branch build over itself) + runs-on: windows-2022 + timeout-minutes: 50 + env: + EXPECT: ${{ inputs.expect || 'survival' }} + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + # This job only builds and runs the harness locally; it never pushes. + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version-file: package.json + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + run_install: false + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # Why: cache the built installer keyed on the inputs that affect it, so a + # harness-only edit skips the ~20 min electron-builder build. The daemon + # relocation code lives under src/, so changing it correctly rebuilds. + - name: Cache branch installer + id: cache-installer + uses: actions/cache@v4 + with: + path: dist/orca-windows-setup.exe + key: branch-installer-${{ hashFiles('src/**', 'config/**', 'package.json', 'pnpm-lock.yaml') }} + + - name: Build Windows installer (unsigned) + if: steps.cache-installer.outputs.cache-hit != 'true' + run: | + node config/scripts/ensure-native-runtime.mjs --runtime=electron + pnpm run build:desktop + pnpm exec electron-builder --config config/electron-builder.config.cjs --win --publish never + + # Why: install the branch build, open a terminal, update the SAME build + # over it, and assert the relocated daemon survives. Same build on both + # sides isolates the survival mechanism (NSIS kill sweep + userData daemon + # + adoption) from cross-version staleness policy. No --install-dir: a CI + # runner has no real Orca to protect. + - name: Run survival harness + id: harness + shell: pwsh + env: + ORCA_E2E_DIAG_DIR: artifacts/diag + run: | + New-Item -ItemType Directory -Force artifacts | Out-Null + $exe = "dist/orca-windows-setup.exe" + if (-not (Test-Path $exe)) { throw "Installer not found at $exe" } + $log = "artifacts/survival-output.log" + node tools/win-update-e2e/run.mjs ` + --from "$exe" ` + --to "$exe" ` + --expect "$env:EXPECT" ` + --soak-seconds 60 2>&1 | Tee-Object -FilePath $log + exit $LASTEXITCODE + + - name: Upload survival output + if: always() + uses: actions/upload-artifact@v7 + with: + name: win-update-survival-output + path: | + artifacts/survival-output.log + artifacts/diag/** + retention-days: 7 + if-no-files-found: warn diff --git a/.github/workflows/windows-signing-rehearsal.yml b/.github/workflows/windows-signing-rehearsal.yml new file mode 100644 index 000000000000..24b4307a83bd --- /dev/null +++ b/.github/workflows/windows-signing-rehearsal.yml @@ -0,0 +1,360 @@ +# Windows inner-binary signing rehearsal. +# +# Why: SignPath cannot deep-sign inside NSIS installers, so shipping signed +# inner binaries (Orca.exe, node-pty *.node, DLLs — see issue #7785) requires +# a two-request flow: sign the unpacked PE files first, then build the NSIS +# installer from the signed tree, then sign the installer. This workflow +# rehearses that entire flow from a branch, end to end, without publishing +# anything — so the release pipeline on main is never at risk while we verify. +# +# Runs only via manual dispatch. Use the test-signing policy for iteration +# (auto-approved test certificate) and release-signing to rehearse the +# production flow (requires manual SignPath approvals). Rehearsed successfully +# with test-signing (run 28987534795) and release-signing (run 28988432001). +name: Windows signing rehearsal + +on: + workflow_dispatch: + inputs: + signing-policy-slug: + description: SignPath signing policy + type: choice + default: test-signing + options: + - test-signing + - release-signing + inner-artifact-configuration-slug: + description: SignPath artifact configuration for the inner-binaries zip + type: string + default: windows-inner-binaries-zip + +jobs: + rehearse: + # Why: SignPath origin verification requires GitHub-hosted runners, and + # windows-2022 matches the real release job's build environment. + runs-on: windows-2022 + timeout-minutes: 360 + permissions: + actions: read + contents: read + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + # Why: nothing here pushes; keep the token out of .git/config. + persist-credentials: false + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + run_install: false + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version-file: package.json + cache: pnpm + + - name: Cache electron-builder downloads + uses: actions/cache@v5 + with: + path: | + ~\AppData\Local\electron\Cache + ~\AppData\Local\electron-builder\Cache + key: electron-builder-win-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + electron-builder-win- + + - name: Install dependencies + uses: nick-fields/retry@v4 + with: + timeout_minutes: 10 + max_attempts: 3 + retry_wait_seconds: 30 + command: pnpm install --frozen-lockfile + + # Why: rehearsal builds are never published, so the official-build + # secrets (telemetry key, diagnostics URL) are intentionally omitted. + - name: Build app + run: pnpm build:release + env: + NODE_OPTIONS: --max-old-space-size=4096 + + - name: Package unpacked Windows app + shell: pwsh + run: | + node config/scripts/ensure-native-runtime.mjs --runtime=electron + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + pnpm exec electron-builder --config config/electron-builder.config.cjs --win --dir --publish never + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if (-not (Test-Path 'dist/win-unpacked/Orca.exe')) { + throw 'electron-builder --dir did not produce dist/win-unpacked/Orca.exe' + } + + # Why: only unsigned PE files go to SignPath. Files that already carry a + # valid signature (Microsoft's OpenConsole.exe, signed vendor DLLs) must + # keep their original signer, so they are excluded from the request. + - name: Stage unsigned PE files for inner signing + id: stage-inner + shell: pwsh + run: | + $root = Resolve-Path 'dist/win-unpacked' + $stage = New-Item -ItemType Directory -Force -Path 'signing-stage' + $list = New-Object System.Collections.Generic.List[string] + $skipped = New-Object System.Collections.Generic.List[string] + + Get-ChildItem -Path $root -Recurse -File | + Where-Object { $_.Extension -in '.exe', '.dll', '.node' } | + ForEach-Object { + $relative = [System.IO.Path]::GetRelativePath($root, $_.FullName) + $signature = Get-AuthenticodeSignature -FilePath $_.FullName + if ($signature.Status -eq 'Valid') { + $skipped.Add("$relative ") + return + } + $destination = Join-Path $stage.FullName $relative + New-Item -ItemType Directory -Force -Path (Split-Path $destination) | Out-Null + Copy-Item -Path $_.FullName -Destination $destination -Force + $list.Add($relative) + } + + if (-not ($list -contains 'Orca.exe')) { + throw 'Orca.exe was not staged for signing; unpacked layout changed?' + } + if (-not ($list | Where-Object { $_ -like '*conpty_console_list.node' })) { + throw 'node-pty conpty_console_list.node was not staged; this is the file from issue #7785.' + } + + Set-Content -Path 'inner-signing-list.txt' -Value ($list -join "`n") + Write-Host "Staged $($list.Count) unsigned PE files for signing:" + $list | ForEach-Object { Write-Host " $_" } + Write-Host "Skipped $($skipped.Count) already-signed files:" + $skipped | ForEach-Object { Write-Host " $_" } + + - name: Upload unsigned inner binaries for SignPath + id: upload-unsigned-inner + uses: actions/upload-artifact@v7 + with: + name: orca-windows-inner-unsigned-${{ github.run_id }} + path: signing-stage/** + if-no-files-found: error + + - name: Install SignPath PowerShell module + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 + $useResourceGet = $null -ne (Get-Command -Name Install-PSResource -ErrorAction SilentlyContinue) + if ($useResourceGet) { + if ($null -eq (Get-PSResourceRepository -Name PSGallery -ErrorAction SilentlyContinue)) { + Register-PSResourceRepository -PSGallery -Trusted + } else { + Set-PSResourceRepository -Name PSGallery -Trusted + } + Install-PSResource -Name SignPath -Version '[4.0.0,5.0.0)' -Repository PSGallery -Scope CurrentUser -TrustRepository -Reinstall -ErrorAction Stop + } else { + Install-Module -Name SignPath -Repository PSGallery -MinimumVersion 4.0.0 -MaximumVersion 4.999.999 -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop + } + Import-Module SignPath -ErrorAction Stop + Get-Command -Name Get-SignedArtifact -Module SignPath -ErrorAction Stop + + - name: Submit inner binaries signing request + id: submit-inner-signing + uses: signpath/github-action-submit-signing-request@v2 + with: + api-token: ${{ secrets.SIGNPATH_API_TOKEN }} + organization-id: c37aa192-a27a-4377-9c90-5d6c95912dc0 + project-slug: orca + signing-policy-slug: ${{ inputs.signing-policy-slug || 'test-signing' }} + artifact-configuration-slug: ${{ inputs.inner-artifact-configuration-slug || 'windows-inner-binaries-zip' }} + github-artifact-id: ${{ steps.upload-unsigned-inner.outputs.artifact-id }} + wait-for-completion: false + + - name: Download signed inner binaries from SignPath + shell: pwsh + env: + SIGNPATH_API_TOKEN: ${{ secrets.SIGNPATH_API_TOKEN }} + SIGNPATH_REQUEST_ID: ${{ steps.submit-inner-signing.outputs.signing-request-id }} + run: | + Get-SignedArtifact ` + -ApiToken $env:SIGNPATH_API_TOKEN ` + -OrganizationId 'c37aa192-a27a-4377-9c90-5d6c95912dc0' ` + -SigningRequestId $env:SIGNPATH_REQUEST_ID ` + -OutputArtifactPath signed-inner.zip ` + -Force ` + -WaitForCompletionTimeoutInSeconds 3600 + New-Item -ItemType Directory -Path signed-inner -Force + Expand-Archive -Path signed-inner.zip -DestinationPath signed-inner -Force + + # Why: copy back strictly by the staged list so a layout mismatch in the + # returned artifact fails loudly instead of silently shipping a mix of + # signed and unsigned binaries. + - name: Restore signed inner binaries into unpacked app + shell: pwsh + run: | + $root = Resolve-Path 'dist/win-unpacked' + $failures = New-Object System.Collections.Generic.List[string] + foreach ($relative in Get-Content 'inner-signing-list.txt') { + $signed = Get-ChildItem -Path signed-inner -Recurse -File | + Where-Object { [System.IO.Path]::GetRelativePath((Resolve-Path 'signed-inner'), $_.FullName).TrimStart('\', '/') -like "*$relative" } | + Select-Object -First 1 + if ($null -eq $signed) { + $failures.Add("missing from signed artifact: $relative") + continue + } + $signature = Get-AuthenticodeSignature -FilePath $signed.FullName + if ($null -eq $signature.SignerCertificate) { + $failures.Add("returned without a signature: $relative") + continue + } + Copy-Item -Path $signed.FullName -Destination (Join-Path $root $relative) -Force + Write-Host ("{0,-14} {1} <{2}>" -f $signature.Status, $relative, $signature.SignerCertificate.Subject) + } + if ($failures.Count -gt 0) { + $failures | ForEach-Object { Write-Host "::error::$_" } + throw "Signed inner artifact did not round-trip cleanly ($($failures.Count) failures)." + } + + - name: Build NSIS installer from signed unpacked app + shell: pwsh + run: | + pnpm exec electron-builder --config config/electron-builder.config.cjs --win --publish never --prepackaged "$env:GITHUB_WORKSPACE\dist\win-unpacked" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if (-not (Test-Path 'dist/orca-windows-setup.exe')) { + throw 'electron-builder --prepackaged did not produce dist/orca-windows-setup.exe' + } + + - name: Upload unsigned Windows installer for SignPath + id: upload-unsigned-installer + uses: actions/upload-artifact@v7 + with: + name: orca-windows-installer-unsigned-${{ github.run_id }} + path: dist/orca-windows-setup.exe + if-no-files-found: error + + - name: Submit Windows installer signing request + id: submit-installer-signing + uses: signpath/github-action-submit-signing-request@v2 + with: + api-token: ${{ secrets.SIGNPATH_API_TOKEN }} + organization-id: c37aa192-a27a-4377-9c90-5d6c95912dc0 + project-slug: orca + signing-policy-slug: ${{ inputs.signing-policy-slug || 'test-signing' }} + artifact-configuration-slug: github-actions-windows-installer + github-artifact-id: ${{ steps.upload-unsigned-installer.outputs.artifact-id }} + wait-for-completion: false + + - name: Download signed Windows installer from SignPath + shell: pwsh + env: + SIGNPATH_API_TOKEN: ${{ secrets.SIGNPATH_API_TOKEN }} + SIGNPATH_REQUEST_ID: ${{ steps.submit-installer-signing.outputs.signing-request-id }} + run: | + Get-SignedArtifact ` + -ApiToken $env:SIGNPATH_API_TOKEN ` + -OrganizationId 'c37aa192-a27a-4377-9c90-5d6c95912dc0' ` + -SigningRequestId $env:SIGNPATH_REQUEST_ID ` + -OutputArtifactPath signed-windows.zip ` + -Force ` + -WaitForCompletionTimeoutInSeconds 14400 + New-Item -ItemType Directory -Path signed-windows -Force + Expand-Archive -Path signed-windows.zip -DestinationPath signed-windows -Force + + # Why: signing changes installer bytes, so the updater metadata must be + # regenerated exactly like the release job's staging step does. + - name: Stage signed Windows installer and regenerate updater metadata + shell: pwsh + run: | + $signedInstaller = Get-ChildItem -Path signed-windows -Recurse -File -Filter 'orca-windows-setup.exe' | Select-Object -First 1 + if ($null -eq $signedInstaller) { + throw 'Signed Windows installer was not returned by SignPath.' + } + Copy-Item -Path $signedInstaller.FullName -Destination 'dist/orca-windows-setup.exe' -Force + & 'node_modules/app-builder-bin/win/x64/app-builder.exe' blockmap --input 'dist/orca-windows-setup.exe' --output 'dist/orca-windows-setup.exe.blockmap' + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + $installer = Get-Item 'dist/orca-windows-setup.exe' + $blockmap = Get-Item 'dist/orca-windows-setup.exe.blockmap' + $stream = [System.IO.File]::OpenRead($installer.FullName) + try { + $sha512 = [System.Security.Cryptography.SHA512]::Create() + $hash = [Convert]::ToBase64String($sha512.ComputeHash($stream)) + } finally { + if ($null -ne $sha512) { $sha512.Dispose() } + $stream.Dispose() + } + $latestYml = Get-Content -Path 'dist/latest.yml' -Raw + $latestYml = [regex]::Replace($latestYml, '(?m)^(\s*)sha512: .+$', { + param($match) + "$($match.Groups[1].Value)sha512: $hash" + }) + $latestYml = $latestYml -replace '(?m)^ size: \d+$', " size: $($installer.Length)" + $latestYml = $latestYml -replace '(?m)^ blockMapSize: \d+$', " blockMapSize: $($blockmap.Length)" + Set-Content -Path 'dist/latest.yml' -Value $latestYml -NoNewline + + # Why: this is the pass/fail heart of the rehearsal — the same evidence + # check that will later gate releases (see PR #7170). Test certificates + # do not chain to a trusted root, so Status=Valid is only required for + # release-signing runs; test-signing runs require a present signature. + - name: Verify signatures end to end + shell: pwsh + env: + SIGNING_POLICY: ${{ inputs.signing-policy-slug || 'test-signing' }} + run: | + $report = New-Object System.Collections.Generic.List[string] + $failures = New-Object System.Collections.Generic.List[string] + $requireValid = $env:SIGNING_POLICY -eq 'release-signing' + + function Test-Signature([string]$label, [string]$path) { + $signature = Get-AuthenticodeSignature -FilePath $path + $subject = if ($null -eq $signature.SignerCertificate) { '' } else { $signature.SignerCertificate.Subject } + $line = "{0,-14} {1} <{2}>" -f $signature.Status, $label, $subject + $script:report.Add($line) + Write-Host $line + if ($null -eq $signature.SignerCertificate -or $signature.Status -eq 'NotSigned') { + $script:failures.Add("unsigned: $label") + } elseif ($script:requireValid -and $signature.Status -ne 'Valid') { + $script:failures.Add("not Valid under release-signing: $label ($($signature.Status))") + } elseif ($script:requireValid -and $subject -notlike '*CN=SignPath Foundation*') { + $script:failures.Add("unexpected signer: $label ($subject)") + } + } + + Test-Signature 'installer: orca-windows-setup.exe' 'dist/orca-windows-setup.exe' + + # Extract the signed installer and verify the files a user actually + # gets on disk — including the exact file from issue #7785. + $7za = 'node_modules/7zip-bin/win/x64/7za.exe' + New-Item -ItemType Directory -Path extracted-app -Force | Out-Null + & $7za x 'dist/orca-windows-setup.exe' '-oextracted-app' -y | Out-Null + + $root = Resolve-Path 'extracted-app' + foreach ($relative in Get-Content 'inner-signing-list.txt') { + $path = Join-Path $root $relative + if (-not (Test-Path $path)) { + $failures.Add("missing from installer payload: $relative") + continue + } + Test-Signature "installed: $relative" $path + } + + Set-Content -Path 'signing-evidence.txt' -Value ($report -join "`n") + if ($failures.Count -gt 0) { + $failures | ForEach-Object { Write-Host "::error::$_" } + throw "Signing rehearsal failed with $($failures.Count) problems." + } + Write-Host "All $((Get-Content 'inner-signing-list.txt').Count) inner binaries plus the installer are signed." + + - name: Upload rehearsal evidence and installer + if: always() + uses: actions/upload-artifact@v7 + with: + name: windows-signing-rehearsal-${{ inputs.signing-policy-slug || 'test-signing' }}-${{ github.run_id }} + path: | + signing-evidence.txt + inner-signing-list.txt + dist/orca-windows-setup.exe + dist/orca-windows-setup.exe.blockmap + dist/latest.yml + retention-days: 7 diff --git a/.gitignore b/.gitignore index 24595e4c7087..ed81a687a694 100644 --- a/.gitignore +++ b/.gitignore @@ -60,6 +60,9 @@ pnpm-debug.log* # Coverage coverage/ +# Prod release scan output (accidental adds) +prod-release-scan-*.md + # Benchmark run output /tools/benchmarks/results/*.json /.bench-fixtures/ @@ -119,3 +122,6 @@ src/renderer/src/i18n/locales/.zh-catalog-cache.json src/renderer/src/i18n/locales/.ko-catalog-cache.json src/renderer/src/i18n/locales/.ja-catalog-cache.json src/renderer/src/i18n/locales/.es-catalog-cache.json + +# Bench result JSONs are working artifacts; headline numbers live in notes/terminal-performance-initiative.md +tools/benchmarks/results/terminal-pipeline-*.json diff --git a/.npmrc b/.npmrc index 9e4363a8cd18..196b4fee4cf0 100644 --- a/.npmrc +++ b/.npmrc @@ -1,6 +1,9 @@ shamefully-hoist=true minimum-release-age=4320 -minimum-release-age-exclude[]=electron@42.3.3 +minimum-release-age-exclude[]=electron@43.1.0 +minimum-release-age-exclude[]=node-abi@4.33.0 +minimum-release-age-exclude[]=typescript@7.0.2 +minimum-release-age-exclude[]=@typescript/typescript-* minimum-release-age-exclude[]=mermaid@11.15.0 minimum-release-age-exclude[]=@mermaid-js/parser@1.1.1 minimum-release-age-exclude[]=serve-sim@0.1.40 diff --git a/AGENTS.md b/AGENTS.md index b10035e9b17c..989fa611226d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,6 +36,18 @@ Orca targets macOS, Linux, and Windows. Keep all platform-dependent behavior beh All changes must consider the SSH use case. Don't assume local-only execution. +## Git Binary Compatibility + +Orca runs the user's Git binary on native, WSL, and SSH hosts, which may all have different versions. Treat Git 2.25 as the core-workflow baseline and follow [`docs/reference/git-compatibility.md`](./docs/reference/git-compatibility.md). + +When adding or changing a Git command: + +- Check when every subcommand and option was introduced. For newer behavior, keep a baseline-compatible fallback or degrade safely. +- Use `GitCapabilityCache` with a narrow unsupported-error predicate so recurring operations do not retry a known-invalid command. Do not rely only on `git --version`; wrappers such as `simple-git` do not remove host-version differences. +- Scope capability state to the host that executes Git: native, WSL distro, SSH provider, or relay connection. Cover the first fallback, later cached calls, concurrent probes, and relevant host isolation in tests. +- Keep the real-binary compatibility contract in PR CI current. When adopting a newer Git feature, add its version boundary so the preferred command and fallback both run against representative Git releases. +- Preserve commands that begin with global Git options such as `-c` before the subcommand, including auto-maintenance suppression used by worktree-create fetches. + ## Git Provider Compatibility Source-control and review changes must consider GitLab and other supported git providers, not only GitHub. Keep provider-specific behavior behind explicit checks, and avoid GitHub-only naming for generic review concepts. diff --git a/README.md b/README.md index 8e9bc05d3f3a..ee5cf6a0a780 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Monitor and steer your agents from your phone — get notified when an agent finishes and send follow-ups from anywhere. -[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [Android APK 0.0.24](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) +[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [Android APK 0.0.25](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) @@ -230,7 +230,7 @@ yay -S stably-orca-bin Pair with your desktop app to monitor and steer your agents from your phone. - **iOS:** [Download on the App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) or [join TestFlight](https://testflight.apple.com/join/YjeGMQBA) -- **Android:** [Download APK 0.0.24](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) +- **Android:** [Download APK 0.0.25](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) --- @@ -238,9 +238,10 @@ Pair with your desktop app to monitor and steer your agents from your phone. - **Discord:** Join the community on **[Discord](https://discord.gg/fzjDKHxv8Q)**. - **Twitter / X:** Follow **[@orca_build](https://x.com/orca_build)** for updates and announcements. -- **WeChat:** Scan the QR code to join the community. +- **WeChat:** Scan the QR code to join the community. If the first group is full, use the backup group. WeChat QR code for the Orca community + Backup WeChat QR code for the Orca community - **Feedback & Ideas:** We ship fast. Missing something? [Request a new feature](https://github.com/stablyai/orca/issues). - **Privacy:** See the [privacy & telemetry docs](https://www.onorca.dev/docs/telemetry) for what anonymous usage data Orca collects and how to opt out. diff --git a/build-plugins/plain-node-entry-guard.ts b/build-plugins/plain-node-entry-guard.ts new file mode 100644 index 000000000000..1fddb5f6a121 --- /dev/null +++ b/build-plugins/plain-node-entry-guard.ts @@ -0,0 +1,130 @@ +import { spawnSync } from 'node:child_process' +import { join } from 'node:path' +import type { NormalizedOutputOptions, OutputBundle, OutputChunk, Plugin } from 'rollup' + +// Why: v1.4.129-rc.1 shipped a dead terminal daemon because a shared main +// chunk gained `require("electron")` (an import edge added in #7642), and the +// daemon is forked as a plain-Node process where electron cannot be required. +// Nothing in CI executes the built daemon-entry under plain Node, so the leak +// stayed invisible until an adopted old daemon died. This guard fails the +// build when any chunk reachable from a plain-Node fork entry requires +// electron, and smoke-loads daemon-entry under plain Node to prove its module +// graph still resolves. + +// Entries executed as plain Node (ELECTRON_RUN_AS_NODE / no electron runtime): +// forked daemon, parcel-watcher and computer sidecars, and the CLI-run +// agent-hooks entry. require("electron") throws MODULE_NOT_FOUND in all of them. +const PLAIN_NODE_ENTRY_NAMES = [ + 'daemon-entry', + 'parcel-watcher-process-entry', + 'computer-sidecar', + 'agent-hooks/managed-agent-hook-controls' +] as const + +const ELECTRON_REQUIRE_RE = /require\(\s*["']electron["']\s*\)/ + +function collectReachableChunks( + entry: OutputChunk, + byFileName: Map +): OutputChunk[] { + const seen = new Set() + const reachable: OutputChunk[] = [] + const stack = [entry.fileName] + while (stack.length > 0) { + const fileName = stack.pop() as string + if (seen.has(fileName)) { + continue + } + seen.add(fileName) + const chunk = byFileName.get(fileName) + if (!chunk) { + continue + } + reachable.push(chunk) + for (const imported of [...chunk.imports, ...chunk.dynamicImports]) { + stack.push(imported) + } + } + return reachable +} + +function assertNoElectronRequire( + entryName: string, + entry: OutputChunk, + byFileName: Map +): void { + for (const chunk of collectReachableChunks(entry, byFileName)) { + if (ELECTRON_REQUIRE_RE.test(chunk.code)) { + throw new Error( + `[plain-node-entry-guard] "${entryName}" reaches chunk "${chunk.fileName}" that ` + + `requires electron. "${entryName}" runs as a plain-Node process, where ` + + `require("electron") throws MODULE_NOT_FOUND and kills it at startup (the ` + + `v1.4.129-rc.1 daemon outage). Keep electron imports out of its module graph.` + ) + } + } +} + +// Why: proves the whole daemon-entry graph resolves under plain Node (no +// unresolved requires). require("electron") does not throw in a dev tree with +// node_modules present, so the static scan above — not this smoke — is the +// electron regression guard; this only catches gross load failures. +function smokeLoadDaemonEntry(outputDir: string): void { + const entryPath = join(outputDir, 'daemon-entry.js') + const result = spawnSync(process.execPath, [entryPath], { + encoding: 'utf8', + timeout: 15_000 + }) + if (result.error) { + throw new Error( + `[plain-node-entry-guard] could not smoke-load daemon-entry.js under plain Node: ` + + `${result.error.message}` + ) + } + const stderr = result.stderr ?? '' + if (/Cannot find module|MODULE_NOT_FOUND/.test(stderr)) { + throw new Error( + `[plain-node-entry-guard] daemon-entry.js failed to load under plain Node:\n${stderr}` + ) + } + if (!stderr.includes('Usage: daemon-entry')) { + throw new Error( + `[plain-node-entry-guard] daemon-entry.js did not reach argv parsing under plain Node ` + + `(expected the "Usage: daemon-entry" error). stderr:\n${stderr}` + ) + } +} + +export function createPlainNodeEntryGuardPlugin(): Plugin { + return { + name: 'orca-plain-node-entry-guard', + writeBundle(options: NormalizedOutputOptions, bundle: OutputBundle) { + // Why: skip in `electron-vite dev` watch mode — the smoke would respawn on + // every rebuild, and the guard only needs to gate produced builds. + if (this.meta.watchMode) { + return + } + const chunks = Object.values(bundle).filter( + (item): item is OutputChunk => item.type === 'chunk' + ) + const byFileName = new Map(chunks.map((chunk) => [chunk.fileName, chunk])) + const entryByName = new Map() + for (const chunk of chunks) { + if (chunk.isEntry && chunk.name) { + entryByName.set(chunk.name, chunk) + } + } + + for (const entryName of PLAIN_NODE_ENTRY_NAMES) { + const entry = entryByName.get(entryName) + if (entry) { + assertNoElectronRequire(entryName, entry, byFileName) + } + } + + if (entryByName.has('daemon-entry') && options.dir) { + smokeLoadDaemonEntry(options.dir) + } + } + } +} diff --git a/config/electron-builder.config.cjs b/config/electron-builder.config.cjs index 9e482825a733..61f38c081c4a 100644 --- a/config/electron-builder.config.cjs +++ b/config/electron-builder.config.cjs @@ -2,6 +2,10 @@ const { chmodSync, existsSync, readdirSync } = require('node:fs') const { execFileSync } = require('node:child_process') const { join, resolve } = require('node:path') const electronBuilderNativeRebuild = require('./scripts/electron-builder-native-rebuild.cjs') +const { + assertPackagedDaemonEntryExists, + verifyPackagedDaemonEntryBoots +} = require('./scripts/verify-packaged-daemon-entry.cjs') const { createPackagedRuntimeNodeModuleResources, prunePackagedRuntimeNodeModules, @@ -106,6 +110,7 @@ module.exports = { 'out/main/win32-utils.js', 'out/main/daemon-entry.js', 'out/main/computer-sidecar.js', + 'out/main/parcel-watcher-process-entry.js', 'out/main/chunks/**', 'resources/**', 'node_modules/ws/**', @@ -129,6 +134,24 @@ module.exports = { } prunePackagedRuntimeNodeModules(resourcesDir, context.electronPlatformName, context.arch) verifyPackagedMainRuntimeDeps(resourcesDir) + // Why: boot the packaged daemon-entry under plain Node, but only for the + // slice matching the packaging host's arch — daemon-entry.js is JS, yet it + // require()s the native (N-API) node-pty for the TARGET arch, which the host + // Node cannot load cross-arch. `Arch` enum: ia32=0, x64=1, armv7l=2, + // arm64=3, universal=4 (universal contains the host slice, so run it). + const archEnumByNodeArch = { ia32: 0, x64: 1, armv7l: 2, arm64: 3 } + const hostArchEnum = archEnumByNodeArch[process.arch] + if (context.arch === hostArchEnum || context.arch === 4) { + verifyPackagedDaemonEntryBoots(resourcesDir) + } else { + // Why: a cross-arch slice can't be booted by the host Node, but the + // unpacked entry must still exist — its absence is a layout regression + // regardless of arch, so only the boot is skipped, not the check. + assertPackagedDaemonEntryExists(resourcesDir) + console.log( + `[verify-packaged-daemon-entry] skipped boot on cross-arch slice (target ${context.arch}, host ${process.arch})` + ) + } chmodUnixCliLaunchers(resourcesDir, context.electronPlatformName) chmodMacServeSimHelpers(resourcesDir, context.electronPlatformName) for (const filename of readdirSync(resourcesDir)) { @@ -142,6 +165,10 @@ module.exports = { } if (context.electronPlatformName === 'darwin') { await signMacComputerUseHelper(join(resourcesDir, 'Orca Computer Use.app'), context.packager) + await signMacNotificationStatusHelper( + join(resourcesDir, '..', 'MacOS', 'orca-notification-status'), + context.packager + ) } }, win: { @@ -173,7 +200,11 @@ module.exports = { artifactName: 'orca-windows-setup.${ext}', shortcutName: '${productName}', uninstallDisplayName: '${productName}', - createDesktopShortcut: 'always' + createDesktopShortcut: 'always', + // Why: on a real uninstall, stop and remove the relocated terminal daemon + // (which lives outside the install dir under LOCALAPPDATA by design). Guarded + // by ${isUpdated} inside so it never runs during an update's uninstallOldVersion. + include: resolve(__dirname, 'nsis', 'daemon-host-uninstall.nsh') }, mac: { icon: 'resources/build/icon.icns', @@ -229,6 +260,15 @@ module.exports = { }, featureWallResources ], + // Why: the notification-status helper must execute from Contents/MacOS — + // on macOS 26 UNUserNotificationCenter aborts (bundleProxyForCurrentProcess + // is nil) for executables launched out of Contents/Resources (#7929). + extraFiles: [ + { + from: 'native/notification-status-macos/.build/release/orca-notification-status', + to: 'MacOS/orca-notification-status' + } + ], target: [ { target: 'dmg', @@ -398,6 +438,37 @@ async function signMacComputerUseHelper(helperAppPath, packager) { }) } +async function signMacNotificationStatusHelper(helperPath, packager) { + if (!existsSync(helperPath)) { + if (isMacRelease) { + throw new Error(`Missing orca-notification-status helper at ${helperPath}`) + } + return + } + const codeSigningInfo = + isMacRelease && process.env.CSC_LINK && packager?.codeSigningInfo?.value + ? await packager.codeSigningInfo.value + : null + const identity = + process.env.CSC_NAME ?? + findInstalledMacSigningIdentity(codeSigningInfo?.keychainFile) ?? + (isMacRelease ? null : '-') + if (!identity) { + throw new Error('Missing signing identity for orca-notification-status helper') + } + // Why: macOS keys notification records to the code-signing identifier; the + // binary embeds the app's CFBundleIdentifier in __TEXT,__info_plist so this + // (and any later) `codesign --force` derives the correct identifier. Sign + // before the outer Orca.app is sealed, like the computer-use helper. + const args = ['--force', '--sign', identity] + if (isMacRelease) { + args.push('--options', 'runtime', '--timestamp') + } + args.push(helperPath) + execFileSync('codesign', args, { stdio: 'inherit' }) + execFileSync('codesign', ['--verify', '--strict', helperPath], { stdio: 'inherit' }) +} + function codesignArgs(identity, targetPath) { const args = ['--force', '--deep', '--sign', identity] if (isMacRelease) { diff --git a/config/nsis/daemon-host-uninstall.nsh b/config/nsis/daemon-host-uninstall.nsh new file mode 100644 index 000000000000..dc3a497ce679 --- /dev/null +++ b/config/nsis/daemon-host-uninstall.nsh @@ -0,0 +1,23 @@ +; Clean up the relocated terminal daemon on a REAL uninstall. +; +; Why: the daemon host is deliberately copied to a distinct image name +; (orca-terminal-daemon.exe) under %LOCALAPPDATA%\Orca\daemon-host so that app +; UPDATES cannot kill it — that relocation is what keeps terminals alive across +; updates. The same design means a normal uninstall's process sweep and file +; removal both miss it, leaving an orphaned daemon plus its runtime copy behind. +; +; The ${isUpdated} guard is essential: electron-builder runs this uninstaller as +; part of uninstallOldVersion on EVERY update, and killing the daemon there would +; defeat the whole feature. Only clean up on a genuine uninstall. +; +; The image name and the LOCALAPPDATA folder name must stay in sync with +; DAEMON_HOST_EXE_NAME and LOCAL_HOST_ROOT_NAME in +; src/main/daemon/daemon-host-relocation.ts. +!macro customUnInstall + ${ifNot} ${isUpdated} + nsExec::Exec 'taskkill /F /IM orca-terminal-daemon.exe' + ; Give the OS a moment to release the image lock before removing the tree. + Sleep 500 + RMDir /r "$LOCALAPPDATA\Orca\daemon-host" + ${endIf} +!macroend diff --git a/config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch b/config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch new file mode 100644 index 000000000000..eab0cd584522 --- /dev/null +++ b/config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch @@ -0,0 +1,55 @@ +diff --git a/lib/addon-serialize.js b/lib/addon-serialize.js +index d669293d06d801ef472d5c2454ce86876e5c321f..96bb66cdc05289b6a7ce5ed64fc833624c885c57 100644 +--- a/lib/addon-serialize.js ++++ b/lib/addon-serialize.js +@@ -1,2 +1,2 @@ +-!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SerializeAddon=e():t.SerializeAddon=e()}(globalThis,()=>(()=>{"use strict";var t={992(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_ANSI_COLORS=void 0;const s=r(993);e.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const t=[s.css.toColor("#2e3436"),s.css.toColor("#cc0000"),s.css.toColor("#4e9a06"),s.css.toColor("#c4a000"),s.css.toColor("#3465a4"),s.css.toColor("#75507b"),s.css.toColor("#06989a"),s.css.toColor("#d3d7cf"),s.css.toColor("#555753"),s.css.toColor("#ef2929"),s.css.toColor("#8ae234"),s.css.toColor("#fce94f"),s.css.toColor("#729fcf"),s.css.toColor("#ad7fa8"),s.css.toColor("#34e2e2"),s.css.toColor("#eeeeec")],e=[0,95,135,175,215,255];for(let r=0;r<216;r++){const i=e[r/36%6|0],n=e[r/6%6|0],o=e[r%6];t.push({css:s.channels.toCss(i,n,o),rgba:s.channels.toRgba(i,n,o)})}for(let e=0;e<24;e++){const r=8+10*e;t.push({css:s.channels.toCss(r,r,r),rgba:s.channels.toRgba(r,r,r)})}return t})())},993(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.rgba=e.rgb=e.css=e.color=e.channels=e.NULL_COLOR=void 0,e.toPaddedHex=c,e.contrastRatio=f;let r=0,s=0,i=0,n=0;var o,l,a,u,h;function c(t){const e=t.toString(16);return e.length<2?"0"+e:e}function f(t,e){return t>>0},t.toColor=function(e,r,s,i){return{css:t.toCss(e,r,s,i),rgba:t.toRgba(e,r,s,i)}}}(o||(e.channels=o={})),function(t){function e(t,e){return n=Math.round(255*e),[r,s,i]=h.toChannels(t.rgba),{css:o.toCss(r,s,i,n),rgba:o.toRgba(r,s,i,n)}}t.blend=function(t,e){if(n=(255&e.rgba)/255,1===n)return{css:e.css,rgba:e.rgba};const l=e.rgba>>24&255,a=e.rgba>>16&255,u=e.rgba>>8&255,h=t.rgba>>24&255,c=t.rgba>>16&255,f=t.rgba>>8&255;return r=h+Math.round((l-h)*n),s=c+Math.round((a-c)*n),i=f+Math.round((u-f)*n),{css:o.toCss(r,s,i),rgba:o.toRgba(r,s,i)}},t.isOpaque=function(t){return!(255&~t.rgba)},t.ensureContrastRatio=function(t,e,r){const s=h.ensureContrastRatio(t.rgba,e.rgba,r);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},t.opaque=function(t){const e=(255|t.rgba)>>>0;return[r,s,i]=h.toChannels(e),{css:o.toCss(r,s,i),rgba:e}},t.opacity=e,t.multiplyOpacity=function(t,r){return n=255&t.rgba,e(t,n*r/255)},t.toColorRGB=function(t){return[t.rgba>>24&255,t.rgba>>16&255,t.rgba>>8&255]}}(l||(e.color=l={})),function(t){let e,l;try{const t=document.createElement("canvas");t.width=1,t.height=1;const r=t.getContext("2d",{willReadFrequently:!0});r&&(e=r,e.globalCompositeOperation="copy",l=e.createLinearGradient(0,0,1,1))}catch{}t.toColor=function(t){if(t.match(/#[\da-f]{3,8}/i))switch(t.length){case 4:return r=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),i=parseInt(t.slice(3,4).repeat(2),16),o.toColor(r,s,i);case 5:return r=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),i=parseInt(t.slice(3,4).repeat(2),16),n=parseInt(t.slice(4,5).repeat(2),16),o.toColor(r,s,i,n);case 7:return{css:t,rgba:(parseInt(t.slice(1),16)<<8|255)>>>0};case 9:return{css:t,rgba:parseInt(t.slice(1),16)>>>0}}const a=t.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(a)return r=parseInt(a[1],10),s=parseInt(a[2],10),i=parseInt(a[3],10),n=Math.round(255*(void 0===a[5]?1:parseFloat(a[5]))),o.toColor(r,s,i,n);if("transparent"===t)return{css:"transparent",rgba:0};if(!e||!l)throw new Error("css.toColor: Unsupported css format");if(e.fillStyle=l,e.fillStyle=t,"string"!=typeof e.fillStyle)throw new Error("css.toColor: Unsupported css format");if(e.fillRect(0,0,1,1),[r,s,i,n]=e.getImageData(0,0,1,1).data,255!==n)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(r,s,i,n),css:t}}}(a||(e.css=a={})),function(t){function e(t,e,r){const s=t/255,i=e/255,n=r/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}t.relativeLuminance=function(t){return e(t>>16&255,t>>8&255,255&t)},t.relativeLuminance2=e}(u||(e.rgb=u={})),function(t){function e(t,e,r){const s=t>>24&255,i=t>>16&255,n=t>>8&255;let o=e>>24&255,l=e>>16&255,a=e>>8&255,h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));for(;h0||l>0||a>0);)o-=Math.max(0,Math.ceil(.1*o)),l-=Math.max(0,Math.ceil(.1*l)),a-=Math.max(0,Math.ceil(.1*a)),h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));return(o<<24|l<<16|a<<8|255)>>>0}function l(t,e,r){const s=t>>24&255,i=t>>16&255,n=t>>8&255;let o=e>>24&255,l=e>>16&255,a=e>>8&255,h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));for(;h>>0}t.blend=function(t,e){if(n=(255&e)/255,1===n)return e;const l=e>>24&255,a=e>>16&255,u=e>>8&255,h=t>>24&255,c=t>>16&255,f=t>>8&255;return r=h+Math.round((l-h)*n),s=c+Math.round((a-c)*n),i=f+Math.round((u-f)*n),o.toRgba(r,s,i)},t.ensureContrastRatio=function(t,r,s){const i=u.relativeLuminance(t>>8),n=u.relativeLuminance(r>>8);if(f(i,n)>8));if(of(i,u.relativeLuminance(e>>8))?n:e}return n}const o=l(t,r,s),a=f(i,u.relativeLuminance(o>>8));if(af(i,u.relativeLuminance(n>>8))?o:n}return o}},t.reduceLuminance=e,t.increaseLuminance=l,t.toChannels=function(t){return[t>>24&255,t>>16&255,t>>8&255,255&t]}}(h||(e.rgba=h={}))}},e={};function r(s){var i=e[s];if(void 0!==i)return i.exports;var n=e[s]={exports:{}};return t[s](n,n.exports,r),n.exports}var s={};return(()=>{var t=s;Object.defineProperty(t,"__esModule",{value:!0}),t.HTMLSerializeHandler=t.SerializeAddon=void 0;const e=r(992);function i(t,e,r){return Math.max(e,Math.min(t,r))}class n{constructor(t){this._buffer=t}serialize(t,e){const r=this._buffer.getNullCell(),s=this._buffer.getNullCell();let i=r;const n=t.start.y,o=t.end.y,l=t.start.x,a=t.end.x;this._beforeSerialize(o-n,n,o);for(let e=n;e<=o;e++){const n=this._buffer.getLine(e);if(n){const o=e===t.start.y?l:0,u=e===t.end.y?a:n.length;for(let t=o;t0&&!l(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`[${this._nullCellCount}X`);let r="";if(!e){t-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);const e=this._buffer.getLine(t),s=this._buffer.getLine(t+1);if(s.isWrapped){r="";const i=e.getCell(e.length-1,this._thisRowLastChar),n=e.getCell(e.length-2,this._thisRowLastSecondChar),o=s.getCell(0,this._nextRowFirstChar),a=o.getWidth()>1;let u=!1;(o.getChars()&&a?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||0===i.getWidth())&&l(i,o)&&(u=!0),a&&(n.getChars()||0===n.getWidth())&&l(i,o)&&l(n,o)&&(u=!0)),u||(r="-".repeat(this._nullCellCount+1),r+="",this._nullCellCount>0&&(r+="",r+=`[${e.length-this._nullCellCount}C`,r+=`[${this._nullCellCount}X`,r+=`[${e.length-this._nullCellCount}D`,r+=""),this._lastContentCursorRow=t+1,this._lastContentCursorCol=0,this._lastCursorRow=t+1,this._lastCursorCol=0)}else r="\r\n",this._lastCursorRow=t+1,this._lastCursorCol=0}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=r,this._currentRow="",this._nullCellCount=0}_diffStyle(t,e){const r=[];if(h(t,e))return r;const s=!o(t,e),i=!l(t,e),n=!u(t,e);if(s||i||n)if(t.isAttributeDefault())e.isAttributeDefault()||r.push(0);else{if(s){const e=t.getFgColor();t.isFgRGB()?r.push(38,2,e>>>16&255,e>>>8&255,255&e):t.isFgPalette()?e>=16?r.push(38,5,e):r.push(8&e?90+(7&e):30+(7&e)):r.push(39)}if(i){const e=t.getBgColor();t.isBgRGB()?r.push(48,2,e>>>16&255,e>>>8&255,255&e):t.isBgPalette()?e>=16?r.push(48,5,e):r.push(8&e?100+(7&e):40+(7&e)):r.push(49)}if(n){if(t.isInverse()!==e.isInverse()&&r.push(t.isInverse()?7:27),t.isBold()!==e.isBold()&&r.push(t.isBold()?1:22),a(t,e))t.isUnderline()!==e.isUnderline()&&r.push(t.isUnderline()?4:24);else{const e=t.getUnderlineStyle();if(0===e)r.push(24);else if(1===e&&t.isUnderlineColorDefault())r.push(4);else if(r.push("4:"+e),!t.isUnderlineColorDefault()){const e=t.getUnderlineColor();t.isUnderlineColorRGB()?r.push("58:2::"+(e>>>16&255)+":"+(e>>>8&255)+":"+(255&e)):r.push("58:5:"+e)}}t.isOverline()!==e.isOverline()&&r.push(t.isOverline()?53:55),t.isBlink()!==e.isBlink()&&r.push(t.isBlink()?5:25),t.isInvisible()!==e.isInvisible()&&r.push(t.isInvisible()?8:28),t.isItalic()!==e.isItalic()&&r.push(t.isItalic()?3:23),t.isDim()!==e.isDim()&&r.push(t.isDim()?2:22),t.isStrikethrough()!==e.isStrikethrough()&&r.push(t.isStrikethrough()?9:29)}}return r}_nextCell(t,e,r,s){if(0===t.getWidth())return;const i=""===t.getChars(),n=this._diffStyle(t,this._cursorStyle);if(i?!l(this._cursorStyle,t):n.length>0){this._nullCellCount>0&&(l(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`[${n.join(";")}m`;const t=this._buffer.getLine(r);void 0!==t&&(t.getCell(s,this._cursorStyle),this._cursorStyleRow=r,this._cursorStyleCol=s)}i?this._nullCellCount+=t.getWidth():(this._nullCellCount>0&&(l(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._currentRow+=t.getChars(),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=s+t.getWidth())}_serializeString(t){let e=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(e=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let r="";for(let t=0;t{t>0?r+=`[${t}C`:t<0&&(r+=`[${-t}D`)};(t!==this._lastCursorRow||e!==this._lastCursorCol)&&((s=t-this._lastCursorRow)>0?r+=`[${s}B`:s<0&&(r+=`[${-s}A`),i(e-this._lastCursorCol))}var s;const i=this._terminal._core._inputHandler._curAttrData,n=this._diffStyle(i,this._cursorStyle);return n.length>0&&(r+=`[${n.join(";")}m`),r}}t.SerializeAddon=class{activate(t){this._terminal=t}_serializeBufferByScrollback(t,e,r){const s=e.length,n=void 0===r?s:i(r+t.rows,0,s);return this._serializeBufferByRange(t,e,{start:s-n,end:s-1},!1)}_serializeBufferByRange(t,e,r,s){return new c(e,t).serialize({start:{x:0,y:"number"==typeof r.start?r.start:r.start.line},end:{x:t.cols,y:"number"==typeof r.end?r.end:r.end.line}},s)}_serializeBufferAsHTML(t,e){const r=t.buffer.active,s=new f(r,t,e),n=e.onlySelection??!1,o=e.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:t.cols,y:(o.endLine,o.endLine)}});if(!n){const n=r.length,o=e.scrollback,l=void 0===o?n:i(o+t.rows,0,n);return s.serialize({start:{x:0,y:n-l},end:{x:t.cols,y:n-1}})}const l=this._terminal?.getSelectionPosition();return void 0!==l?s.serialize({start:{x:l.start.x,y:l.start.y},end:{x:l.end.x,y:l.end.y}}):""}_serializeScrollRegion(t){const e=t._core.buffer,r=e.scrollTop,s=e.scrollBottom;return 0!==r||s!==t.rows-1?`[${r+1};${s+1}r`:""}_serializeModes(t){let e="";const r=t.modes;if(r.applicationCursorKeysMode&&(e+="[?1h"),r.applicationKeypadMode&&(e+="[?66h"),r.bracketedPasteMode&&(e+="[?2004h"),r.insertMode&&(e+=""),r.originMode&&(e+="[?6h"),r.reverseWraparoundMode&&(e+="[?45h"),r.sendFocusMode&&(e+="[?1004h"),!1===r.wraparoundMode&&(e+="[?7l"),"none"!==r.mouseTrackingMode)switch(r.mouseTrackingMode){case"x10":e+="[?9h";break;case"vt200":e+="[?1000h";break;case"drag":e+="[?1002h";break;case"any":e+="[?1003h"}return r.showCursor||(e+="[?25l"),e}serialize(t){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let e=t?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,t.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,t?.scrollback);return t?.excludeAltBuffer||"alternate"!==this._terminal.buffer.active.type||(e+=`[?1049h${this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0)}`),t?.excludeModes||(e+=this._serializeModes(this._terminal),e+=this._serializeScrollRegion(this._terminal)),e}serializeAsHTML(t){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,t??{})}dispose(){}};class f extends n{constructor(t,r,s){super(t),this._terminal=r,this._options=s,this._currentRow="",this._htmlContent="",r._core._themeService?this._ansiColors=r._core._themeService.colors.ansi:this._ansiColors=e.DEFAULT_ANSI_COLORS}_beforeSerialize(t,e,r){this._htmlContent+="\x3c!--StartFragment--\x3e
";let s="#000000",i="#ffffff";this._options.includeGlobalBackground&&(s=this._terminal.options.theme?.foreground??"#ffffff",i=this._terminal.options.theme?.background??"#000000");const n=[];n.push("color: "+s+";"),n.push("background-color: "+i+";"),n.push("font-family: "+this._terminal.options.fontFamily+";"),n.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
\x3c!--EndFragment--\x3e"}_rowEnd(t,e){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(t,e){const r=e?t.getFgColor():t.getBgColor();return(e?t.isFgRGB():t.isBgRGB())?"#"+[r>>16&255,r>>8&255,255&r].map(t=>t.toString(16).padStart(2,"0")).join(""):(e?t.isFgPalette():t.isBgPalette())?this._ansiColors[r].css:void 0}_getUnderlineColor(t){if(t.isUnderlineColorDefault())return;const e=t.getUnderlineColor();return t.isUnderlineColorRGB()?"#"+[e>>16&255,e>>8&255,255&e].map(t=>t.toString(16).padStart(2,"0")).join(""):this._ansiColors[e].css}_getUnderlineStyle(t){switch(t.getUnderlineStyle()){case 1:default:return"underline";case 2:return"underline double";case 3:return"underline wavy";case 4:return"underline dotted";case 5:return"underline dashed"}}_diffStyle(t,e){const r=[];if(h(t,e))return;const s=!o(t,e),i=!l(t,e),n=!u(t,e);if(s||i||n){const e=this._getHexColor(t,!0);e&&r.push("color: "+e+";");const s=this._getHexColor(t,!1);s&&r.push("background-color: "+s+";"),t.isInverse()&&r.push("color: #000000; background-color: #BFBFBF;"),t.isBold()&&r.push("font-weight: bold;");const i=[];if(t.isUnderline()&&i.push(this._getUnderlineStyle(t)),t.isOverline()&&i.push("overline"),t.isStrikethrough()&&i.push("line-through"),t.isBlink()&&i.push("blink"),i.length>0&&r.push("text-decoration: "+i.join(" ")+";"),t.isUnderline()){const e=this._getUnderlineColor(t);e&&r.push("text-decoration-color: "+e+";")}return t.isInvisible()&&r.push("visibility: hidden;"),t.isItalic()&&r.push("font-style: italic;"),t.isDim()&&r.push("opacity: 0.5;"),r}}_nextCell(t,e,r,s){if(0===t.getWidth())return;const i=""===t.getChars(),n=this._diffStyle(t,e);n&&(this._currentRow+=0===n.length?"":""),this._currentRow+=i?" ":function(t){switch(t){case"&":return"&";case"<":return"<"}return t}(t.getChars())}_serializeString(){return this._htmlContent}}t.HTMLSerializeHandler=f})(),s})()); ++!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SerializeAddon=e():t.SerializeAddon=e()}(globalThis,()=>(()=>{"use strict";var t={992(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_ANSI_COLORS=void 0;const s=r(993);e.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const t=[s.css.toColor("#2e3436"),s.css.toColor("#cc0000"),s.css.toColor("#4e9a06"),s.css.toColor("#c4a000"),s.css.toColor("#3465a4"),s.css.toColor("#75507b"),s.css.toColor("#06989a"),s.css.toColor("#d3d7cf"),s.css.toColor("#555753"),s.css.toColor("#ef2929"),s.css.toColor("#8ae234"),s.css.toColor("#fce94f"),s.css.toColor("#729fcf"),s.css.toColor("#ad7fa8"),s.css.toColor("#34e2e2"),s.css.toColor("#eeeeec")],e=[0,95,135,175,215,255];for(let r=0;r<216;r++){const i=e[r/36%6|0],n=e[r/6%6|0],o=e[r%6];t.push({css:s.channels.toCss(i,n,o),rgba:s.channels.toRgba(i,n,o)})}for(let e=0;e<24;e++){const r=8+10*e;t.push({css:s.channels.toCss(r,r,r),rgba:s.channels.toRgba(r,r,r)})}return t})())},993(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.rgba=e.rgb=e.css=e.color=e.channels=e.NULL_COLOR=void 0,e.toPaddedHex=c,e.contrastRatio=f;let r=0,s=0,i=0,n=0;var o,l,a,u,h;function c(t){const e=t.toString(16);return e.length<2?"0"+e:e}function f(t,e){return t>>0},t.toColor=function(e,r,s,i){return{css:t.toCss(e,r,s,i),rgba:t.toRgba(e,r,s,i)}}}(o||(e.channels=o={})),function(t){function e(t,e){return n=Math.round(255*e),[r,s,i]=h.toChannels(t.rgba),{css:o.toCss(r,s,i,n),rgba:o.toRgba(r,s,i,n)}}t.blend=function(t,e){if(n=(255&e.rgba)/255,1===n)return{css:e.css,rgba:e.rgba};const l=e.rgba>>24&255,a=e.rgba>>16&255,u=e.rgba>>8&255,h=t.rgba>>24&255,c=t.rgba>>16&255,f=t.rgba>>8&255;return r=h+Math.round((l-h)*n),s=c+Math.round((a-c)*n),i=f+Math.round((u-f)*n),{css:o.toCss(r,s,i),rgba:o.toRgba(r,s,i)}},t.isOpaque=function(t){return!(255&~t.rgba)},t.ensureContrastRatio=function(t,e,r){const s=h.ensureContrastRatio(t.rgba,e.rgba,r);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},t.opaque=function(t){const e=(255|t.rgba)>>>0;return[r,s,i]=h.toChannels(e),{css:o.toCss(r,s,i),rgba:e}},t.opacity=e,t.multiplyOpacity=function(t,r){return n=255&t.rgba,e(t,n*r/255)},t.toColorRGB=function(t){return[t.rgba>>24&255,t.rgba>>16&255,t.rgba>>8&255]}}(l||(e.color=l={})),function(t){let e,l;try{const t=document.createElement("canvas");t.width=1,t.height=1;const r=t.getContext("2d",{willReadFrequently:!0});r&&(e=r,e.globalCompositeOperation="copy",l=e.createLinearGradient(0,0,1,1))}catch{}t.toColor=function(t){if(t.match(/#[\da-f]{3,8}/i))switch(t.length){case 4:return r=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),i=parseInt(t.slice(3,4).repeat(2),16),o.toColor(r,s,i);case 5:return r=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),i=parseInt(t.slice(3,4).repeat(2),16),n=parseInt(t.slice(4,5).repeat(2),16),o.toColor(r,s,i,n);case 7:return{css:t,rgba:(parseInt(t.slice(1),16)<<8|255)>>>0};case 9:return{css:t,rgba:parseInt(t.slice(1),16)>>>0}}const a=t.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(a)return r=parseInt(a[1],10),s=parseInt(a[2],10),i=parseInt(a[3],10),n=Math.round(255*(void 0===a[5]?1:parseFloat(a[5]))),o.toColor(r,s,i,n);if("transparent"===t)return{css:"transparent",rgba:0};if(!e||!l)throw new Error("css.toColor: Unsupported css format");if(e.fillStyle=l,e.fillStyle=t,"string"!=typeof e.fillStyle)throw new Error("css.toColor: Unsupported css format");if(e.fillRect(0,0,1,1),[r,s,i,n]=e.getImageData(0,0,1,1).data,255!==n)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(r,s,i,n),css:t}}}(a||(e.css=a={})),function(t){function e(t,e,r){const s=t/255,i=e/255,n=r/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}t.relativeLuminance=function(t){return e(t>>16&255,t>>8&255,255&t)},t.relativeLuminance2=e}(u||(e.rgb=u={})),function(t){function e(t,e,r){const s=t>>24&255,i=t>>16&255,n=t>>8&255;let o=e>>24&255,l=e>>16&255,a=e>>8&255,h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));for(;h0||l>0||a>0);)o-=Math.max(0,Math.ceil(.1*o)),l-=Math.max(0,Math.ceil(.1*l)),a-=Math.max(0,Math.ceil(.1*a)),h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));return(o<<24|l<<16|a<<8|255)>>>0}function l(t,e,r){const s=t>>24&255,i=t>>16&255,n=t>>8&255;let o=e>>24&255,l=e>>16&255,a=e>>8&255,h=f(u.relativeLuminance2(o,l,a),u.relativeLuminance2(s,i,n));for(;h>>0}t.blend=function(t,e){if(n=(255&e)/255,1===n)return e;const l=e>>24&255,a=e>>16&255,u=e>>8&255,h=t>>24&255,c=t>>16&255,f=t>>8&255;return r=h+Math.round((l-h)*n),s=c+Math.round((a-c)*n),i=f+Math.round((u-f)*n),o.toRgba(r,s,i)},t.ensureContrastRatio=function(t,r,s){const i=u.relativeLuminance(t>>8),n=u.relativeLuminance(r>>8);if(f(i,n)>8));if(of(i,u.relativeLuminance(e>>8))?n:e}return n}const o=l(t,r,s),a=f(i,u.relativeLuminance(o>>8));if(af(i,u.relativeLuminance(n>>8))?o:n}return o}},t.reduceLuminance=e,t.increaseLuminance=l,t.toChannels=function(t){return[t>>24&255,t>>16&255,t>>8&255,255&t]}}(h||(e.rgba=h={}))}},e={};function r(s){var i=e[s];if(void 0!==i)return i.exports;var n=e[s]={exports:{}};return t[s](n,n.exports,r),n.exports}var s={};return(()=>{var t=s;Object.defineProperty(t,"__esModule",{value:!0}),t.HTMLSerializeHandler=t.SerializeAddon=void 0;const e=r(992);function i(t,e,r){return Math.max(e,Math.min(t,r))}class n{constructor(t){this._buffer=t}serialize(t,e){const r=this._buffer.getNullCell(),s=this._buffer.getNullCell();let i=r;const n=t.start.y,o=t.end.y,l=t.start.x,a=t.end.x;this._beforeSerialize(o-n,n,o);for(let e=n;e<=o;e++){const n=this._buffer.getLine(e);if(n){const o=e===t.start.y?l:0,u=e===t.end.y?a:n.length;for(let t=o;t0&&!l(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`[${this._nullCellCount}X`);let r="";if(!e){t-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);const e=this._buffer.getLine(t),s=this._buffer.getLine(t+1);if(s.isWrapped){r="";const i=e.getCell(e.length-1,this._thisRowLastChar),n=e.getCell(e.length-2,this._thisRowLastSecondChar),o=s.getCell(0,this._nextRowFirstChar),a=o.getWidth()>1;let u=!1;(o.getChars()&&a?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||0===i.getWidth())&&l(i,o)&&(u=!0),a&&(n.getChars()||0===n.getWidth())&&l(i,o)&&l(n,o)&&(u=!0)),u||(r="-".repeat(this._nullCellCount+1),r+="",this._nullCellCount>0&&(r+="",r+=`[${e.length-this._nullCellCount}C`,r+=`[${this._nullCellCount}X`,r+=`[${e.length-this._nullCellCount}D`,r+=""),this._lastContentCursorRow=t+1,this._lastContentCursorCol=0,this._lastCursorRow=t+1,this._lastCursorCol=0)}else r="\r\n",this._lastCursorRow=t+1,this._lastCursorCol=0}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=r,this._currentRow="",this._nullCellCount=0}_diffStyle(t,e){const r=[];if(h(t,e))return r;const s=!o(t,e),i=!l(t,e),n=!u(t,e);if(s||i||n)if(t.isAttributeDefault())e.isAttributeDefault()||r.push(0);else{if(s){const e=t.getFgColor();t.isFgRGB()?r.push(38,2,e>>>16&255,e>>>8&255,255&e):t.isFgPalette()?e>=16?r.push(38,5,e):r.push(8&e?90+(7&e):30+(7&e)):r.push(39)}if(i){const e=t.getBgColor();t.isBgRGB()?r.push(48,2,e>>>16&255,e>>>8&255,255&e):t.isBgPalette()?e>=16?r.push(48,5,e):r.push(8&e?100+(7&e):40+(7&e)):r.push(49)}if(n){if(t.isInverse()!==e.isInverse()&&r.push(t.isInverse()?7:27),/* PATCH(orca): bold(1)/dim(2) share reset 22 - clear before re-set, as one group */((b,d)=>{if(b||d){const c=b&&!t.isBold()||d&&!t.isDim();c&&r.push(22),t.isBold()&&(b||c)&&r.push(1),t.isDim()&&(d||c)&&r.push(2)}})(t.isBold()!==e.isBold(),t.isDim()!==e.isDim()),a(t,e))t.isUnderline()!==e.isUnderline()&&r.push(t.isUnderline()?4:24);else{const e=t.getUnderlineStyle();if(0===e)r.push(24);else if(1===e&&t.isUnderlineColorDefault())r.push(4);else if(r.push("4:"+e),!t.isUnderlineColorDefault()){const e=t.getUnderlineColor();t.isUnderlineColorRGB()?r.push("58:2::"+(e>>>16&255)+":"+(e>>>8&255)+":"+(255&e)):r.push("58:5:"+e)}}t.isOverline()!==e.isOverline()&&r.push(t.isOverline()?53:55),t.isBlink()!==e.isBlink()&&r.push(t.isBlink()?5:25),t.isInvisible()!==e.isInvisible()&&r.push(t.isInvisible()?8:28),t.isItalic()!==e.isItalic()&&r.push(t.isItalic()?3:23),t.isStrikethrough()!==e.isStrikethrough()&&r.push(t.isStrikethrough()?9:29)}}return r}_nextCell(t,e,r,s){if(0===t.getWidth())return;const i=""===t.getChars(),n=this._diffStyle(t,this._cursorStyle);if(i?!l(this._cursorStyle,t):n.length>0){this._nullCellCount>0&&(l(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`[${n.join(";")}m`;const t=this._buffer.getLine(r);void 0!==t&&(t.getCell(s,this._cursorStyle),this._cursorStyleRow=r,this._cursorStyleCol=s)}i?this._nullCellCount+=t.getWidth():(this._nullCellCount>0&&(l(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._currentRow+=t.getChars(),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=s+t.getWidth())}_serializeString(t){let e=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(e=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let r="";for(let t=0;t{t>0?r+=`[${t}C`:t<0&&(r+=`[${-t}D`)};(t!==this._lastCursorRow||e!==this._lastCursorCol)&&((s=t-this._lastCursorRow)>0?r+=`[${s}B`:s<0&&(r+=`[${-s}A`),i(e-this._lastCursorCol))}var s;const i=this._terminal._core._inputHandler._curAttrData,n=this._diffStyle(i,this._cursorStyle);return n.length>0&&(r+=`[${n.join(";")}m`),r}}t.SerializeAddon=class{activate(t){this._terminal=t}_serializeBufferByScrollback(t,e,r){const s=e.length,n=void 0===r?s:i(r+t.rows,0,s);return this._serializeBufferByRange(t,e,{start:s-n,end:s-1},!1)}_serializeBufferByRange(t,e,r,s){return new c(e,t).serialize({start:{x:0,y:"number"==typeof r.start?r.start:r.start.line},end:{x:t.cols,y:"number"==typeof r.end?r.end:r.end.line}},s)}_serializeBufferAsHTML(t,e){const r=t.buffer.active,s=new f(r,t,e),n=e.onlySelection??!1,o=e.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:t.cols,y:(o.endLine,o.endLine)}});if(!n){const n=r.length,o=e.scrollback,l=void 0===o?n:i(o+t.rows,0,n);return s.serialize({start:{x:0,y:n-l},end:{x:t.cols,y:n-1}})}const l=this._terminal?.getSelectionPosition();return void 0!==l?s.serialize({start:{x:l.start.x,y:l.start.y},end:{x:l.end.x,y:l.end.y}}):""}_serializeScrollRegion(t){const e=t._core.buffer,r=e.scrollTop,s=e.scrollBottom;return 0!==r||s!==t.rows-1?`[${r+1};${s+1}r`:""}_serializeModes(t){let e="";const r=t.modes;if(r.applicationCursorKeysMode&&(e+="[?1h"),r.applicationKeypadMode&&(e+="[?66h"),r.bracketedPasteMode&&(e+="[?2004h"),r.insertMode&&(e+=""),r.originMode&&(e+="[?6h"),r.reverseWraparoundMode&&(e+="[?45h"),r.sendFocusMode&&(e+="[?1004h"),!1===r.wraparoundMode&&(e+="[?7l"),"none"!==r.mouseTrackingMode)switch(r.mouseTrackingMode){case"x10":e+="[?9h";break;case"vt200":e+="[?1000h";break;case"drag":e+="[?1002h";break;case"any":e+="[?1003h"}return r.showCursor||(e+="[?25l"),e}serialize(t){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let e=t?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,t.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,t?.scrollback);return t?.excludeAltBuffer||"alternate"!==this._terminal.buffer.active.type||(e+=`[?1049h${this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0)}`),t?.excludeModes||(e+=this._serializeModes(this._terminal),e+=this._serializeScrollRegion(this._terminal)),e}serializeAsHTML(t){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,t??{})}dispose(){}};class f extends n{constructor(t,r,s){super(t),this._terminal=r,this._options=s,this._currentRow="",this._htmlContent="",r._core._themeService?this._ansiColors=r._core._themeService.colors.ansi:this._ansiColors=e.DEFAULT_ANSI_COLORS}_beforeSerialize(t,e,r){this._htmlContent+="\x3c!--StartFragment--\x3e
";let s="#000000",i="#ffffff";this._options.includeGlobalBackground&&(s=this._terminal.options.theme?.foreground??"#ffffff",i=this._terminal.options.theme?.background??"#000000");const n=[];n.push("color: "+s+";"),n.push("background-color: "+i+";"),n.push("font-family: "+this._terminal.options.fontFamily+";"),n.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
\x3c!--EndFragment--\x3e"}_rowEnd(t,e){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(t,e){const r=e?t.getFgColor():t.getBgColor();return(e?t.isFgRGB():t.isBgRGB())?"#"+[r>>16&255,r>>8&255,255&r].map(t=>t.toString(16).padStart(2,"0")).join(""):(e?t.isFgPalette():t.isBgPalette())?this._ansiColors[r].css:void 0}_getUnderlineColor(t){if(t.isUnderlineColorDefault())return;const e=t.getUnderlineColor();return t.isUnderlineColorRGB()?"#"+[e>>16&255,e>>8&255,255&e].map(t=>t.toString(16).padStart(2,"0")).join(""):this._ansiColors[e].css}_getUnderlineStyle(t){switch(t.getUnderlineStyle()){case 1:default:return"underline";case 2:return"underline double";case 3:return"underline wavy";case 4:return"underline dotted";case 5:return"underline dashed"}}_diffStyle(t,e){const r=[];if(h(t,e))return;const s=!o(t,e),i=!l(t,e),n=!u(t,e);if(s||i||n){const e=this._getHexColor(t,!0);e&&r.push("color: "+e+";");const s=this._getHexColor(t,!1);s&&r.push("background-color: "+s+";"),t.isInverse()&&r.push("color: #000000; background-color: #BFBFBF;"),t.isBold()&&r.push("font-weight: bold;");const i=[];if(t.isUnderline()&&i.push(this._getUnderlineStyle(t)),t.isOverline()&&i.push("overline"),t.isStrikethrough()&&i.push("line-through"),t.isBlink()&&i.push("blink"),i.length>0&&r.push("text-decoration: "+i.join(" ")+";"),t.isUnderline()){const e=this._getUnderlineColor(t);e&&r.push("text-decoration-color: "+e+";")}return t.isInvisible()&&r.push("visibility: hidden;"),t.isItalic()&&r.push("font-style: italic;"),t.isDim()&&r.push("opacity: 0.5;"),r}}_nextCell(t,e,r,s){if(0===t.getWidth())return;const i=""===t.getChars(),n=this._diffStyle(t,e);n&&(this._currentRow+=0===n.length?"
":""),this._currentRow+=i?" ":function(t){switch(t){case"&":return"&";case"<":return"<"}return t}(t.getChars())}_serializeString(){return this._htmlContent}}t.HTMLSerializeHandler=f})(),s})()); + //# sourceMappingURL=addon-serialize.js.map +\ No newline at end of file +diff --git a/lib/addon-serialize.mjs b/lib/addon-serialize.mjs +index a5c4c4dd05b7efcc23d0e45661ffd4e42da80f21..475e45b3ed228027531deea5530bd03859f4a4e0 100644 +--- a/lib/addon-serialize.mjs ++++ b/lib/addon-serialize.mjs +@@ -15,5 +15,5 @@ + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + var m=0,b=0,_=0,p=0;var g;(t=>{function a(r,l,s,i){return i!==void 0?`#${w(r)}${w(l)}${w(s)}${w(i)}`:`#${w(r)}${w(l)}${w(s)}`}t.toCss=a;function n(r,l,s,i=255){return(r<<24|l<<16|s<<8|i)>>>0}t.toRgba=n;function e(r,l,s,i){return{css:t.toCss(r,l,s,i),rgba:t.toRgba(r,l,s,i)}}t.toColor=e})(g||={});var N;(i=>{function a(o,u){if(p=(u.rgba&255)/255,p===1)return{css:u.css,rgba:u.rgba};let f=u.rgba>>24&255,C=u.rgba>>16&255,c=u.rgba>>8&255,h=o.rgba>>24&255,d=o.rgba>>16&255,I=o.rgba>>8&255;m=h+Math.round((f-h)*p),b=d+Math.round((C-d)*p),_=I+Math.round((c-I)*p);let L=g.toCss(m,b,_),E=g.toRgba(m,b,_);return{css:L,rgba:E}}i.blend=a;function n(o){return(o.rgba&255)===255}i.isOpaque=n;function e(o,u,f){let C=B.ensureContrastRatio(o.rgba,u.rgba,f);if(C)return g.toColor(C>>24&255,C>>16&255,C>>8&255)}i.ensureContrastRatio=e;function t(o){let u=(o.rgba|255)>>>0;return[m,b,_]=B.toChannels(u),{css:g.toCss(m,b,_),rgba:u}}i.opaque=t;function r(o,u){return p=Math.round(u*255),[m,b,_]=B.toChannels(o.rgba),{css:g.toCss(m,b,_,p),rgba:g.toRgba(m,b,_,p)}}i.opacity=r;function l(o,u){return p=o.rgba&255,r(o,p*u/255)}i.multiplyOpacity=l;function s(o){return[o.rgba>>24&255,o.rgba>>16&255,o.rgba>>8&255]}i.toColorRGB=s})(N||={});var x;(t=>{let a,n;try{let r=document.createElement("canvas");r.width=1,r.height=1;let l=r.getContext("2d",{willReadFrequently:!0});l&&(a=l,a.globalCompositeOperation="copy",n=a.createLinearGradient(0,0,1,1))}catch{}function e(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return m=parseInt(r.slice(1,2).repeat(2),16),b=parseInt(r.slice(2,3).repeat(2),16),_=parseInt(r.slice(3,4).repeat(2),16),g.toColor(m,b,_);case 5:return m=parseInt(r.slice(1,2).repeat(2),16),b=parseInt(r.slice(2,3).repeat(2),16),_=parseInt(r.slice(3,4).repeat(2),16),p=parseInt(r.slice(4,5).repeat(2),16),g.toColor(m,b,_,p);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let l=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(l)return m=parseInt(l[1],10),b=parseInt(l[2],10),_=parseInt(l[3],10),p=Math.round((l[5]===void 0?1:parseFloat(l[5]))*255),g.toColor(m,b,_,p);if(r==="transparent")return{css:"transparent",rgba:0};if(!a||!n)throw new Error("css.toColor: Unsupported css format");if(a.fillStyle=n,a.fillStyle=r,typeof a.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(a.fillRect(0,0,1,1),[m,b,_,p]=a.getImageData(0,0,1,1).data,p!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:g.toRgba(m,b,_,p),css:r}}t.toColor=e})(x||={});var v;(e=>{function a(t){return n(t>>16&255,t>>8&255,t&255)}e.relativeLuminance=a;function n(t,r,l){let s=t/255,i=r/255,o=l/255,u=s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4),f=i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4),C=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4);return u*.2126+f*.7152+C*.0722}e.relativeLuminance2=n})(v||={});var B;(l=>{function a(s,i){if(p=(i&255)/255,p===1)return i;let o=i>>24&255,u=i>>16&255,f=i>>8&255,C=s>>24&255,c=s>>16&255,h=s>>8&255;return m=C+Math.round((o-C)*p),b=c+Math.round((u-c)*p),_=h+Math.round((f-h)*p),g.toRgba(m,b,_)}l.blend=a;function n(s,i,o){let u=v.relativeLuminance(s>>8),f=v.relativeLuminance(i>>8);if(R(u,f)>8));if(I>8));return I>E?d:L}return d}let c=t(s,i,o),h=R(u,v.relativeLuminance(c>>8));if(h>8));return h>I?c:d}return c}}l.ensureContrastRatio=n;function e(s,i,o){let u=s>>24&255,f=s>>16&255,C=s>>8&255,c=i>>24&255,h=i>>16&255,d=i>>8&255,I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));for(;I0||h>0||d>0);)c-=Math.max(0,Math.ceil(c*.1)),h-=Math.max(0,Math.ceil(h*.1)),d-=Math.max(0,Math.ceil(d*.1)),I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));return(c<<24|h<<16|d<<8|255)>>>0}l.reduceLuminance=e;function t(s,i,o){let u=s>>24&255,f=s>>16&255,C=s>>8&255,c=i>>24&255,h=i>>16&255,d=i>>8&255,I=R(v.relativeLuminance2(c,h,d),v.relativeLuminance2(u,f,C));for(;I>>0}l.increaseLuminance=t;function r(s){return[s>>24&255,s>>16&255,s>>8&255,s&255]}l.toChannels=r})(B||={});function w(a){let n=a.toString(16);return n.length<2?"0"+n:n}function R(a,n){return a{let a=[x.toColor("#2e3436"),x.toColor("#cc0000"),x.toColor("#4e9a06"),x.toColor("#c4a000"),x.toColor("#3465a4"),x.toColor("#75507b"),x.toColor("#06989a"),x.toColor("#d3d7cf"),x.toColor("#555753"),x.toColor("#ef2929"),x.toColor("#8ae234"),x.toColor("#fce94f"),x.toColor("#729fcf"),x.toColor("#ad7fa8"),x.toColor("#34e2e2"),x.toColor("#eeeeec")],n=[0,95,135,175,215,255];for(let e=0;e<216;e++){let t=n[e/36%6|0],r=n[e/6%6|0],l=n[e%6];a.push({css:g.toCss(t,r,l),rgba:g.toRgba(t,r,l)})}for(let e=0;e<24;e++){let t=8+e*10;a.push({css:g.toCss(t,t,t),rgba:g.toRgba(t,t,t)})}return a})());function A(a,n,e){return Math.max(n,Math.min(a,e))}function z(a){switch(a){case"&":return"&";case"<":return"<"}return a}var S=class{constructor(n){this._buffer=n}serialize(n,e){let t=this._buffer.getNullCell(),r=this._buffer.getNullCell(),l=t,s=n.start.y,i=n.end.y,o=n.start.x,u=n.end.x;this._beforeSerialize(i-s,s,i);for(let f=s;f<=i;f++){let C=this._buffer.getLine(f);if(C){let c=f===n.start.y?o:0,h=f===n.end.y?u:C.length;for(let d=c;d0&&!F(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let r="";if(!t){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let l=this._buffer.getLine(e),s=this._buffer.getLine(e+1);if(!s.isWrapped)r=`\r +-`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{r="";let i=l.getCell(l.length-1,this._thisRowLastChar),o=l.getCell(l.length-2,this._thisRowLastSecondChar),u=s.getCell(0,this._nextRowFirstChar),f=u.getWidth()>1,C=!1;(u.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&F(i,u)&&(C=!0),f&&(o.getChars()||o.getWidth()===0)&&F(i,u)&&F(o,u)&&(C=!0)),C||(r="-".repeat(this._nullCellCount+1),r+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(r+="\x1B[A",r+=`\x1B[${l.length-this._nullCellCount}C`,r+=`\x1B[${this._nullCellCount}X`,r+=`\x1B[${l.length-this._nullCellCount}D`,r+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=r,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let r=[];if(U(e,t))return r;let l=!T(e,t),s=!F(e,t),i=!M(e,t);if(l||s||i)if(e.isAttributeDefault())t.isAttributeDefault()||r.push(0);else{if(l){let o=e.getFgColor();e.isFgRGB()?r.push(38,2,o>>>16&255,o>>>8&255,o&255):e.isFgPalette()?o>=16?r.push(38,5,o):r.push(o&8?90+(o&7):30+(o&7)):r.push(39)}if(s){let o=e.getBgColor();e.isBgRGB()?r.push(48,2,o>>>16&255,o>>>8&255,o&255):e.isBgPalette()?o>=16?r.push(48,5,o):r.push(o&8?100+(o&7):40+(o&7)):r.push(49)}if(i){if(e.isInverse()!==t.isInverse()&&r.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&r.push(e.isBold()?1:22),O(e,t))e.isUnderline()!==t.isUnderline()&&r.push(e.isUnderline()?4:24);else{let o=e.getUnderlineStyle();if(o===0)r.push(24);else if(o===1&&e.isUnderlineColorDefault())r.push(4);else if(r.push("4:"+o),!e.isUnderlineColorDefault()){let u=e.getUnderlineColor();e.isUnderlineColorRGB()?r.push("58:2::"+(u>>>16&255)+":"+(u>>>8&255)+":"+(u&255)):r.push("58:5:"+u)}}e.isOverline()!==t.isOverline()&&r.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&r.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&r.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&r.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&r.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&r.push(e.isStrikethrough()?9:29)}}return r}_nextCell(e,t,r,l){if(e.getWidth()===0)return;let i=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(i?!F(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(F(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=l,this._currentRow+=`\x1B[${o.join(";")}m`;let f=this._buffer.getLine(r);f!==void 0&&(f.getCell(l,this._cursorStyle),this._cursorStyleRow=r,this._cursorStyleCol=l)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(F(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=l+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let r="";for(let i=0;i{c>0?r+=`\x1B[${c}C`:c<0&&(r+=`\x1B[${-c}D`)};u&&((c=>{c>0?r+=`\x1B[${c}B`:c<0&&(r+=`\x1B[${-c}A`)})(i-this._lastCursorRow),f(o-this._lastCursorCol))}let l=this._terminal._core._inputHandler._curAttrData,s=this._diffStyle(l,this._cursorStyle);return s.length>0&&(r+=`\x1B[${s.join(";")}m`),r}},H=class{activate(n){this._terminal=n}_serializeBufferByScrollback(n,e,t){let r=e.length,l=t===void 0?r:A(t+n.rows,0,r);return this._serializeBufferByRange(n,e,{start:r-l,end:r-1},!1)}_serializeBufferByRange(n,e,t,r){return new y(e,n).serialize({start:{x:0,y:typeof t.start=="number"?t.start:t.start.line},end:{x:n.cols,y:typeof t.end=="number"?t.end:t.end.line}},r)}_serializeBufferAsHTML(n,e){let t=n.buffer.active,r=new D(t,n,e),l=e.onlySelection??!1,s=e.range;if(s)return r.serialize({start:{x:s.startCol,y:(typeof s.startLine=="number",s.startLine)},end:{x:n.cols,y:(typeof s.endLine=="number",s.endLine)}});if(!l){let o=t.length,u=e.scrollback,f=u===void 0?o:A(u+n.rows,0,o);return r.serialize({start:{x:0,y:o-f},end:{x:n.cols,y:o-1}})}let i=this._terminal?.getSelectionPosition();return i!==void 0?r.serialize({start:{x:i.start.x,y:i.start.y},end:{x:i.end.x,y:i.end.y}}):""}_serializeScrollRegion(n){let e=n._core.buffer,t=e.scrollTop,r=e.scrollBottom;return t!==0||r!==n.rows-1?`\x1B[${t+1};${r+1}r`:""}_serializeModes(n){let e="",t=n.modes;if(t.applicationCursorKeysMode&&(e+="\x1B[?1h"),t.applicationKeypadMode&&(e+="\x1B[?66h"),t.bracketedPasteMode&&(e+="\x1B[?2004h"),t.insertMode&&(e+="\x1B[4h"),t.originMode&&(e+="\x1B[?6h"),t.reverseWraparoundMode&&(e+="\x1B[?45h"),t.sendFocusMode&&(e+="\x1B[?1004h"),t.wraparoundMode===!1&&(e+="\x1B[?7l"),t.mouseTrackingMode!=="none")switch(t.mouseTrackingMode){case"x10":e+="\x1B[?9h";break;case"vt200":e+="\x1B[?1000h";break;case"drag":e+="\x1B[?1002h";break;case"any":e+="\x1B[?1003h";break}return t.showCursor||(e+="\x1B[?25l"),e}serialize(n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let e=n?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,n.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,n?.scrollback);if(!n?.excludeAltBuffer&&this._terminal.buffer.active.type==="alternate"){let t=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);e+=`\x1B[?1049h\x1B[H${t}`}return n?.excludeModes||(e+=this._serializeModes(this._terminal),e+=this._serializeScrollRegion(this._terminal)),e}serializeAsHTML(n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,n??{})}dispose(){}},D=class extends S{constructor(e,t,r){super(e);this._terminal=t;this._options=r;this._currentRow="";this._htmlContent="";t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=k}_beforeSerialize(e,t,r){this._htmlContent+="
";let l="#000000",s="#ffffff";(this._options.includeGlobalBackground??!1)&&(l=this._terminal.options.theme?.foreground??"#ffffff",s=this._terminal.options.theme?.background??"#000000");let i=[];i.push("color: "+l+";"),i.push("background-color: "+s+";"),i.push("font-family: "+this._terminal.options.fontFamily+";"),i.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let r=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[r>>16&255,r>>8&255,r&255].map(s=>s.toString(16).padStart(2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[r].css}_getUnderlineColor(e){if(e.isUnderlineColorDefault())return;let t=e.getUnderlineColor();return e.isUnderlineColorRGB()?"#"+[t>>16&255,t>>8&255,t&255].map(l=>l.toString(16).padStart(2,"0")).join(""):this._ansiColors[t].css}_getUnderlineStyle(e){switch(e.getUnderlineStyle()){case 1:return"underline";case 2:return"underline double";case 3:return"underline wavy";case 4:return"underline dotted";case 5:return"underline dashed";default:return"underline"}}_diffStyle(e,t){let r=[];if(U(e,t))return;let l=!T(e,t),s=!F(e,t),i=!M(e,t);if(l||s||i){let o=this._getHexColor(e,!0);o&&r.push("color: "+o+";");let u=this._getHexColor(e,!1);u&&r.push("background-color: "+u+";"),e.isInverse()&&r.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&r.push("font-weight: bold;");let f=[];if(e.isUnderline()&&f.push(this._getUnderlineStyle(e)),e.isOverline()&&f.push("overline"),e.isStrikethrough()&&f.push("line-through"),e.isBlink()&&f.push("blink"),f.length>0&&r.push("text-decoration: "+f.join(" ")+";"),e.isUnderline()){let C=this._getUnderlineColor(e);C&&r.push("text-decoration-color: "+C+";")}return e.isInvisible()&&r.push("visibility: hidden;"),e.isItalic()&&r.push("font-style: italic;"),e.isDim()&&r.push("opacity: 0.5;"),r}}_nextCell(e,t,r,l){if(e.getWidth()===0)return;let i=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"
":""),i?this._currentRow+=" ":this._currentRow+=z(e.getChars())}_serializeString(){return this._htmlContent}};export{D as HTMLSerializeHandler,H as SerializeAddon}; ++`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{r="";let i=l.getCell(l.length-1,this._thisRowLastChar),o=l.getCell(l.length-2,this._thisRowLastSecondChar),u=s.getCell(0,this._nextRowFirstChar),f=u.getWidth()>1,C=!1;(u.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&F(i,u)&&(C=!0),f&&(o.getChars()||o.getWidth()===0)&&F(i,u)&&F(o,u)&&(C=!0)),C||(r="-".repeat(this._nullCellCount+1),r+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(r+="\x1B[A",r+=`\x1B[${l.length-this._nullCellCount}C`,r+=`\x1B[${this._nullCellCount}X`,r+=`\x1B[${l.length-this._nullCellCount}D`,r+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=r,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let r=[];if(U(e,t))return r;let l=!T(e,t),s=!F(e,t),i=!M(e,t);if(l||s||i)if(e.isAttributeDefault())t.isAttributeDefault()||r.push(0);else{if(l){let o=e.getFgColor();e.isFgRGB()?r.push(38,2,o>>>16&255,o>>>8&255,o&255):e.isFgPalette()?o>=16?r.push(38,5,o):r.push(o&8?90+(o&7):30+(o&7)):r.push(39)}if(s){let o=e.getBgColor();e.isBgRGB()?r.push(48,2,o>>>16&255,o>>>8&255,o&255):e.isBgPalette()?o>=16?r.push(48,5,o):r.push(o&8?100+(o&7):40+(o&7)):r.push(49)}if(i){if(e.isInverse()!==t.isInverse()&&r.push(e.isInverse()?7:27),/* PATCH(orca): bold(1)/dim(2) share reset 22 - clear before re-set, as one group */((b,d)=>{if(b||d){const c=b&&!e.isBold()||d&&!e.isDim();c&&r.push(22),e.isBold()&&(b||c)&&r.push(1),e.isDim()&&(d||c)&&r.push(2)}})(e.isBold()!==t.isBold(),e.isDim()!==t.isDim()),O(e,t))e.isUnderline()!==t.isUnderline()&&r.push(e.isUnderline()?4:24);else{let o=e.getUnderlineStyle();if(o===0)r.push(24);else if(o===1&&e.isUnderlineColorDefault())r.push(4);else if(r.push("4:"+o),!e.isUnderlineColorDefault()){let u=e.getUnderlineColor();e.isUnderlineColorRGB()?r.push("58:2::"+(u>>>16&255)+":"+(u>>>8&255)+":"+(u&255)):r.push("58:5:"+u)}}e.isOverline()!==t.isOverline()&&r.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&r.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&r.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&r.push(e.isItalic()?3:23),e.isStrikethrough()!==t.isStrikethrough()&&r.push(e.isStrikethrough()?9:29)}}return r}_nextCell(e,t,r,l){if(e.getWidth()===0)return;let i=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(i?!F(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(F(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=l,this._currentRow+=`\x1B[${o.join(";")}m`;let f=this._buffer.getLine(r);f!==void 0&&(f.getCell(l,this._cursorStyle),this._cursorStyleRow=r,this._cursorStyleCol=l)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(F(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=r,this._lastContentCursorCol=this._lastCursorCol=l+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let r="";for(let i=0;i{c>0?r+=`\x1B[${c}C`:c<0&&(r+=`\x1B[${-c}D`)};u&&((c=>{c>0?r+=`\x1B[${c}B`:c<0&&(r+=`\x1B[${-c}A`)})(i-this._lastCursorRow),f(o-this._lastCursorCol))}let l=this._terminal._core._inputHandler._curAttrData,s=this._diffStyle(l,this._cursorStyle);return s.length>0&&(r+=`\x1B[${s.join(";")}m`),r}},H=class{activate(n){this._terminal=n}_serializeBufferByScrollback(n,e,t){let r=e.length,l=t===void 0?r:A(t+n.rows,0,r);return this._serializeBufferByRange(n,e,{start:r-l,end:r-1},!1)}_serializeBufferByRange(n,e,t,r){return new y(e,n).serialize({start:{x:0,y:typeof t.start=="number"?t.start:t.start.line},end:{x:n.cols,y:typeof t.end=="number"?t.end:t.end.line}},r)}_serializeBufferAsHTML(n,e){let t=n.buffer.active,r=new D(t,n,e),l=e.onlySelection??!1,s=e.range;if(s)return r.serialize({start:{x:s.startCol,y:(typeof s.startLine=="number",s.startLine)},end:{x:n.cols,y:(typeof s.endLine=="number",s.endLine)}});if(!l){let o=t.length,u=e.scrollback,f=u===void 0?o:A(u+n.rows,0,o);return r.serialize({start:{x:0,y:o-f},end:{x:n.cols,y:o-1}})}let i=this._terminal?.getSelectionPosition();return i!==void 0?r.serialize({start:{x:i.start.x,y:i.start.y},end:{x:i.end.x,y:i.end.y}}):""}_serializeScrollRegion(n){let e=n._core.buffer,t=e.scrollTop,r=e.scrollBottom;return t!==0||r!==n.rows-1?`\x1B[${t+1};${r+1}r`:""}_serializeModes(n){let e="",t=n.modes;if(t.applicationCursorKeysMode&&(e+="\x1B[?1h"),t.applicationKeypadMode&&(e+="\x1B[?66h"),t.bracketedPasteMode&&(e+="\x1B[?2004h"),t.insertMode&&(e+="\x1B[4h"),t.originMode&&(e+="\x1B[?6h"),t.reverseWraparoundMode&&(e+="\x1B[?45h"),t.sendFocusMode&&(e+="\x1B[?1004h"),t.wraparoundMode===!1&&(e+="\x1B[?7l"),t.mouseTrackingMode!=="none")switch(t.mouseTrackingMode){case"x10":e+="\x1B[?9h";break;case"vt200":e+="\x1B[?1000h";break;case"drag":e+="\x1B[?1002h";break;case"any":e+="\x1B[?1003h";break}return t.showCursor||(e+="\x1B[?25l"),e}serialize(n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let e=n?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,n.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,n?.scrollback);if(!n?.excludeAltBuffer&&this._terminal.buffer.active.type==="alternate"){let t=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);e+=`\x1B[?1049h\x1B[H${t}`}return n?.excludeModes||(e+=this._serializeModes(this._terminal),e+=this._serializeScrollRegion(this._terminal)),e}serializeAsHTML(n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,n??{})}dispose(){}},D=class extends S{constructor(e,t,r){super(e);this._terminal=t;this._options=r;this._currentRow="";this._htmlContent="";t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=k}_beforeSerialize(e,t,r){this._htmlContent+="
";let l="#000000",s="#ffffff";(this._options.includeGlobalBackground??!1)&&(l=this._terminal.options.theme?.foreground??"#ffffff",s=this._terminal.options.theme?.background??"#000000");let i=[];i.push("color: "+l+";"),i.push("background-color: "+s+";"),i.push("font-family: "+this._terminal.options.fontFamily+";"),i.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let r=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[r>>16&255,r>>8&255,r&255].map(s=>s.toString(16).padStart(2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[r].css}_getUnderlineColor(e){if(e.isUnderlineColorDefault())return;let t=e.getUnderlineColor();return e.isUnderlineColorRGB()?"#"+[t>>16&255,t>>8&255,t&255].map(l=>l.toString(16).padStart(2,"0")).join(""):this._ansiColors[t].css}_getUnderlineStyle(e){switch(e.getUnderlineStyle()){case 1:return"underline";case 2:return"underline double";case 3:return"underline wavy";case 4:return"underline dotted";case 5:return"underline dashed";default:return"underline"}}_diffStyle(e,t){let r=[];if(U(e,t))return;let l=!T(e,t),s=!F(e,t),i=!M(e,t);if(l||s||i){let o=this._getHexColor(e,!0);o&&r.push("color: "+o+";");let u=this._getHexColor(e,!1);u&&r.push("background-color: "+u+";"),e.isInverse()&&r.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&r.push("font-weight: bold;");let f=[];if(e.isUnderline()&&f.push(this._getUnderlineStyle(e)),e.isOverline()&&f.push("overline"),e.isStrikethrough()&&f.push("line-through"),e.isBlink()&&f.push("blink"),f.length>0&&r.push("text-decoration: "+f.join(" ")+";"),e.isUnderline()){let C=this._getUnderlineColor(e);C&&r.push("text-decoration-color: "+C+";")}return e.isInvisible()&&r.push("visibility: hidden;"),e.isItalic()&&r.push("font-style: italic;"),e.isDim()&&r.push("opacity: 0.5;"),r}}_nextCell(e,t,r,l){if(e.getWidth()===0)return;let i=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"
":""),i?this._currentRow+=" ":this._currentRow+=z(e.getChars())}_serializeString(){return this._htmlContent}};export{D as HTMLSerializeHandler,H as SerializeAddon}; + //# sourceMappingURL=addon-serialize.mjs.map +diff --git a/src/SerializeAddon.ts b/src/SerializeAddon.ts +index e1728feb219c362dfa2ecb602ff99f830d520757..672fdd5b86d73d8694446138835bbeccd43cfaae 100644 +--- a/src/SerializeAddon.ts ++++ b/src/SerializeAddon.ts +@@ -310,7 +310,20 @@ class StringSerializeHandler extends BaseSerializeHandler { + } + if (flagsChanged) { + if (cell.isInverse() !== oldCell.isInverse()) { sgrSeq.push(cell.isInverse() ? 7 : 27); } +- if (cell.isBold() !== oldCell.isBold()) { sgrSeq.push(cell.isBold() ? 1 : 22); } ++ // PATCH(orca): bold (1) and dim (2) share the single reset param 22, so ++ // they must be diffed as one intensity group with the clearing 22 emitted ++ // BEFORE any re-set. Upstream's independent per-flag diff could emit ++ // "1;22" (bold set, then wiped by dim's clear — \x1b[2mA\x1b[22m\x1b[1mB ++ // loses B's bold on round-trip) or a bare "22" that drops a still-set ++ // bold/dim, garbling Orca's hidden-terminal snapshot restores. ++ const boldChanged = cell.isBold() !== oldCell.isBold(); ++ const dimChanged = cell.isDim() !== oldCell.isDim(); ++ if (boldChanged || dimChanged) { ++ const clearsIntensity = (boldChanged && !cell.isBold()) || (dimChanged && !cell.isDim()); ++ if (clearsIntensity) { sgrSeq.push(22); } ++ if (cell.isBold() && (boldChanged || clearsIntensity)) { sgrSeq.push(1); } ++ if (cell.isDim() && (dimChanged || clearsIntensity)) { sgrSeq.push(2); } ++ } + if (!equalUnderline(cell, oldCell)) { + const style = cell.getUnderlineStyle(); + if (style === UnderlineStyle.NONE) { +@@ -337,7 +350,7 @@ class StringSerializeHandler extends BaseSerializeHandler { + if (cell.isBlink() !== oldCell.isBlink()) { sgrSeq.push(cell.isBlink() ? 5 : 25); } + if (cell.isInvisible() !== oldCell.isInvisible()) { sgrSeq.push(cell.isInvisible() ? 8 : 28); } + if (cell.isItalic() !== oldCell.isItalic()) { sgrSeq.push(cell.isItalic() ? 3 : 23); } +- if (cell.isDim() !== oldCell.isDim()) { sgrSeq.push(cell.isDim() ? 2 : 22); } ++ // PATCH(orca): dim handled in the intensity group above. + if (cell.isStrikethrough() !== oldCell.isStrikethrough()) { sgrSeq.push(cell.isStrikethrough() ? 9 : 29); } + } + } diff --git a/config/patches/@xterm__addon-webgl@0.20.0-beta.286.patch b/config/patches/@xterm__addon-webgl@0.20.0-beta.286.patch index 7ea9975151ce..5276bb1d813b 100644 --- a/config/patches/@xterm__addon-webgl@0.20.0-beta.286.patch +++ b/config/patches/@xterm__addon-webgl@0.20.0-beta.286.patch @@ -1,14 +1,14 @@ diff --git a/lib/addon-webgl.js b/lib/addon-webgl.js -index bd9997910ca3490aa85a140ea22913c6faacacb4..25d481fb52b8302f850fe7158ec50e5ffabf18c6 100644 +index bd9997910ca3490aa85a140ea22913c6faacacb4..074eb0c7ac6a20f81f6d349c63b114e7defab73a 100644 --- a/lib/addon-webgl.js +++ b/lib/addon-webgl.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.WebglAddon=e():t.WebglAddon=e()}(globalThis,()=>(()=>{"use strict";var t={105(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.WindowIntervalTimer=e.eventType=void 0,e.getWindow=r,e.addDisposableListener=o,e.addStandardDisposableListener=function(t,e,i,s){return o(t,e,i,s)},e.getDomNodePagePosition=function(t){const e=t.getBoundingClientRect(),i=r(t);return{left:e.left+i.scrollX,top:e.top+i.scrollY,width:e.width,height:e.height}},e.scheduleAtNextAnimationFrame=function(t,e,i=0){const s=h(t),r=new n(e,i);return s.next.push(r),s.animFrameRequested||(s.animFrameRequested=!0,t.requestAnimationFrame(()=>function(t){const e=h(t);for(e.animFrameRequested=!1,e.current=e.next,e.next=[],e.inAnimationFrameRunner=!0;e.current.length>0;)e.current.sort(n.sort),e.current.shift().execute();e.inAnimationFrameRunner=!1}(t))),r};const s=i(578);function r(t){const e=t;if(e?.ownerDocument?.defaultView)return e.ownerDocument.defaultView;const i=t;return i?.view?i.view:window}class a{constructor(t,e,i,s){this._node=t,this._type=e,this._handler=i,this._options=s,t.addEventListener(e,i,s)}dispose(){this._node&&this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}}function o(t,e,i,s){return new a(t,e,i,s)}e.eventType={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",KEY_DOWN:"keydown",KEY_UP:"keyup",INPUT:"input",BLUR:"blur",FOCUS:"focus",CHANGE:"change",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_UP:"pointerup",MOUSE_WHEEL:"wheel",WHEEL:"wheel"};class n{constructor(t,e){this._runner=t,this.priority=e,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(t){console.error(t)}}static sort(t,e){return e.priority-t.priority}}const L=new Map;function h(t){let e=L.get(t);return e||(e={next:[],current:[],animFrameRequested:!1,inAnimationFrameRunner:!1},L.set(t,e)),e}class T extends s.IntervalTimer{constructor(t){super(),this._defaultTarget=t?r(t):void 0}cancelAndSet(t,e,i){super.cancelAndSet(t,e,i??this._defaultTarget??window)}}e.WindowIntervalTimer=T},814(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.INVERTED_DEFAULT_COLOR=void 0,e.INVERTED_DEFAULT_COLOR=257},959(t,e){function i(t){return 57508<=t&&t<=57558}function s(t){return t>=128512&&t<=128591||t>=127744&&t<=128511||t>=128640&&t<=128767||t>=9728&&t<=9983||t>=9984&&t<=10175||t>=65024&&t<=65039||t>=129280&&t<=129535||t>=127462&&t<=127487}Object.defineProperty(e,"__esModule",{value:!0}),e.throwIfFalsy=function(t){if(!t)throw new Error("value must not be falsy");return t},e.isPowerlineGlyph=i,e.isRestrictedPowerlineGlyph=function(t){return 57520<=t&&t<=57527},e.isEmoji=s,e.allowRescaling=function(t,e,r,a){return 1===e&&r>Math.ceil(1.5*a)&&void 0!==t&&t>255&&!s(t)&&!i(t)&&!function(t){return 57344<=t&&t<=63743}(t)},e.treatGlyphAsBackgroundColor=function(t){return i(t)||function(t){return 9472<=t&&t<=9631}(t)},e.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},e.computeNextVariantOffset=function(t,e,i=0){return(t-(2*Math.round(e)-i))%(2*Math.round(e))}},948(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.createSelectionRenderModel=function(){return new i};class i{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(t,e,i,s=!1){if(this.selectionStart=e,this.selectionEnd=i,!e||!i||e[0]===i[0]&&e[1]===i[1])return void this.clear();const r=t.buffers.active.ydisp,a=e[1]-r,o=i[1]-r,n=Math.max(a,0),L=Math.min(o,t.rows-1);n>=t.rows||L<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=n,this.viewportCappedEndRow=L,this.startCol=e[0],this.endCol=i[0])}isCellSelected(t,e,i){return!!this.hasSelection&&(i-=t.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?e>=this.startCol&&i>=this.viewportCappedStartRow&&e=this.viewportCappedStartRow&&e>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&e=this.startCol)}}},536(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.TextBlinkStateManager=void 0;const s=i(426);class r extends s.Disposable{constructor(t,e,i){super(),this._renderCallback=t,this._coreBrowserService=e,this._optionsService=i,this._intervalDuration=0,this._blinkOn=!0,this._needsBlinkInViewport=!1,this._isViewportVisible=!0,this._register(this._optionsService.onSpecificOptionChange("blinkIntervalDuration",t=>{this.setIntervalDuration(t)})),this.setIntervalDuration(this._optionsService.rawOptions.blinkIntervalDuration),this._register((0,s.toDisposable)(()=>this._clearInterval()))}get isBlinkOn(){return this._blinkOn}get isEnabled(){return this._intervalDuration>0}setNeedsBlinkInViewport(t){this._needsBlinkInViewport!==t&&(this._needsBlinkInViewport=t,this._updateIntervalState())}setViewportVisible(t){this._isViewportVisible!==t&&(this._isViewportVisible=t,this._updateIntervalState())}setIntervalDuration(t){t!==this._intervalDuration&&(this._intervalDuration=t,this._clearInterval(),this._updateIntervalState())}_updateIntervalState(){if(this._intervalDuration>0&&this._needsBlinkInViewport&&this._isViewportVisible){if(void 0!==this._interval)return;const t=this._blinkOn;return this._blinkOn=!0,this._interval=this._coreBrowserService.window.setInterval(()=>{this._blinkOn=!this._blinkOn,this._renderCallback()},this._intervalDuration),void(t||this._renderCallback())}this._clearInterval(),this._blinkOn||(this._blinkOn=!0,this._renderCallback())}_clearInterval(){void 0!==this._interval&&(this._coreBrowserService.window.clearInterval(this._interval),this._interval=void 0)}}e.TextBlinkStateManager=r},578(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.IntervalTimer=e.MicrotaskTimer=e.TimeoutTimer=void 0,e.timeout=function(t){return new Promise(e=>setTimeout(e,t))},e.disposableTimeout=function(t,e=0,i){const r=setTimeout(()=>{t(),i&&a.dispose()},e),a=(0,s.toDisposable)(()=>{clearTimeout(r)});return i?.add(a),a};const s=i(426);e.TimeoutTimer=class{constructor(){this._token=-1,this._isDisposed=!1}dispose(){this.cancel(),this._isDisposed=!0}cancel(){-1!==this._token&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(t,e){if(this._isDisposed)throw new Error("Calling cancelAndSet on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,t()},e)}setIfNotSet(t,e){if(this._isDisposed)throw new Error("Calling setIfNotSet on a disposed TimeoutTimer");-1===this._token&&(this._token=setTimeout(()=>{this._token=-1,t()},e))}},e.MicrotaskTimer=class{constructor(){this._isScheduled=!1,this._isDisposed=!1}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._isScheduled=!1}set(t){if(this._isDisposed)throw new Error("Calling set on a disposed MicrotaskTimer");this._isScheduled||(this._isScheduled=!0,queueMicrotask(()=>{this._isScheduled&&(this._isScheduled=!1,t())}))}},e.IntervalTimer=class{constructor(){this._isDisposed=!1}cancel(){this._disposable?.dispose(),this._disposable=void 0}cancelAndSet(t,e,i=globalThis){if(this._isDisposed)throw new Error("Calling cancelAndSet on a disposed IntervalTimer");this.cancel();const s=i.setInterval(()=>{t()},e);this._disposable={dispose:()=>{i.clearInterval(s),this._disposable=void 0}}}dispose(){this.cancel(),this._isDisposed=!0}}},993(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.rgba=e.rgb=e.css=e.color=e.channels=e.NULL_COLOR=void 0,e.toPaddedHex=l,e.contrastRatio=d;let i=0,s=0,r=0,a=0;var o,n,L,h,T;function l(t){const e=t.toString(16);return e.length<2?"0"+e:e}function d(t,e){return t>>0},t.toColor=function(e,i,s,r){return{css:t.toCss(e,i,s,r),rgba:t.toRgba(e,i,s,r)}}}(o||(e.channels=o={})),function(t){function e(t,e){return a=Math.round(255*e),[i,s,r]=T.toChannels(t.rgba),{css:o.toCss(i,s,r,a),rgba:o.toRgba(i,s,r,a)}}t.blend=function(t,e){if(a=(255&e.rgba)/255,1===a)return{css:e.css,rgba:e.rgba};const n=e.rgba>>24&255,L=e.rgba>>16&255,h=e.rgba>>8&255,T=t.rgba>>24&255,l=t.rgba>>16&255,d=t.rgba>>8&255;return i=T+Math.round((n-T)*a),s=l+Math.round((L-l)*a),r=d+Math.round((h-d)*a),{css:o.toCss(i,s,r),rgba:o.toRgba(i,s,r)}},t.isOpaque=function(t){return!(255&~t.rgba)},t.ensureContrastRatio=function(t,e,i){const s=T.ensureContrastRatio(t.rgba,e.rgba,i);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},t.opaque=function(t){const e=(255|t.rgba)>>>0;return[i,s,r]=T.toChannels(e),{css:o.toCss(i,s,r),rgba:e}},t.opacity=e,t.multiplyOpacity=function(t,i){return a=255&t.rgba,e(t,a*i/255)},t.toColorRGB=function(t){return[t.rgba>>24&255,t.rgba>>16&255,t.rgba>>8&255]}}(n||(e.color=n={})),function(t){let e,n;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i=t.getContext("2d",{willReadFrequently:!0});i&&(e=i,e.globalCompositeOperation="copy",n=e.createLinearGradient(0,0,1,1))}catch{}t.toColor=function(t){if(t.match(/#[\da-f]{3,8}/i))switch(t.length){case 4:return i=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),r=parseInt(t.slice(3,4).repeat(2),16),o.toColor(i,s,r);case 5:return i=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),r=parseInt(t.slice(3,4).repeat(2),16),a=parseInt(t.slice(4,5).repeat(2),16),o.toColor(i,s,r,a);case 7:return{css:t,rgba:(parseInt(t.slice(1),16)<<8|255)>>>0};case 9:return{css:t,rgba:parseInt(t.slice(1),16)>>>0}}const L=t.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(L)return i=parseInt(L[1],10),s=parseInt(L[2],10),r=parseInt(L[3],10),a=Math.round(255*(void 0===L[5]?1:parseFloat(L[5]))),o.toColor(i,s,r,a);if("transparent"===t)return{css:"transparent",rgba:0};if(!e||!n)throw new Error("css.toColor: Unsupported css format");if(e.fillStyle=n,e.fillStyle=t,"string"!=typeof e.fillStyle)throw new Error("css.toColor: Unsupported css format");if(e.fillRect(0,0,1,1),[i,s,r,a]=e.getImageData(0,0,1,1).data,255!==a)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(i,s,r,a),css:t}}}(L||(e.css=L={})),function(t){function e(t,e,i){const s=t/255,r=e/255,a=i/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4))}t.relativeLuminance=function(t){return e(t>>16&255,t>>8&255,255&t)},t.relativeLuminance2=e}(h||(e.rgb=h={})),function(t){function e(t,e,i){const s=t>>24&255,r=t>>16&255,a=t>>8&255;let o=e>>24&255,n=e>>16&255,L=e>>8&255,T=d(h.relativeLuminance2(o,n,L),h.relativeLuminance2(s,r,a));for(;T0||n>0||L>0);)o-=Math.max(0,Math.ceil(.1*o)),n-=Math.max(0,Math.ceil(.1*n)),L-=Math.max(0,Math.ceil(.1*L)),T=d(h.relativeLuminance2(o,n,L),h.relativeLuminance2(s,r,a));return(o<<24|n<<16|L<<8|255)>>>0}function n(t,e,i){const s=t>>24&255,r=t>>16&255,a=t>>8&255;let o=e>>24&255,n=e>>16&255,L=e>>8&255,T=d(h.relativeLuminance2(o,n,L),h.relativeLuminance2(s,r,a));for(;T>>0}t.blend=function(t,e){if(a=(255&e)/255,1===a)return e;const n=e>>24&255,L=e>>16&255,h=e>>8&255,T=t>>24&255,l=t>>16&255,d=t>>8&255;return i=T+Math.round((n-T)*a),s=l+Math.round((L-l)*a),r=d+Math.round((h-d)*a),o.toRgba(i,s,r)},t.ensureContrastRatio=function(t,i,s){const r=h.relativeLuminance(t>>8),a=h.relativeLuminance(i>>8);if(d(r,a)>8));if(od(r,h.relativeLuminance(e>>8))?a:e}return a}const o=n(t,i,s),L=d(r,h.relativeLuminance(o>>8));if(Ld(r,h.relativeLuminance(a>>8))?o:a}return o}},t.reduceLuminance=e,t.increaseLuminance=n,t.toChannels=function(t){return[t>>24&255,t>>16&255,t>>8&255,255&t]}}(T||(e.rgba=T={}))},414(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.EventUtils=e.Emitter=void 0;const s=i(426);var r;e.Emitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=(t,e,i)=>{if(this._disposed)return(0,s.toDisposable)(()=>{});const r={fn:t,thisArgs:e};this._listeners.push(r);const a=(0,s.toDisposable)(()=>{const t=this._listeners.indexOf(r);-1!==t&&this._listeners.splice(t,1)});return i&&(Array.isArray(i)?i.push(a):i.add(a)),a}),this._event}fire(t){if(!this._disposed)switch(this._listeners.length){case 0:return;case 1:{const{fn:e,thisArgs:i}=this._listeners[0];return void e.call(i,t)}default:{const e=this._listeners.slice();for(const{fn:i,thisArgs:s}of e)i.call(s,t)}}}dispose(){this._disposed||(this._disposed=!0,this._listeners.length=0)}},function(t){t.forward=function(t,e){return t(t=>e.fire(t))},t.map=function(t,e){return(i,s,r)=>t(t=>i.call(s,e(t)),void 0,r)},t.any=function(...t){return(e,i,r)=>{const a=new s.DisposableStore;for(const s of t)a.add(s(t=>e.call(i,t)));return r&&(Array.isArray(r)?r.push(a):r.add(a)),a}},t.runAndSubscribe=function(t,e,i){return e(i),t(t=>e(t))}}(r||(e.EventUtils=r={}))},426(t,e){function i(t){return{dispose:t}}function s(t){if(!t)return t;if(Array.isArray(t)){for(const e of t)e.dispose();return[]}return t.dispose(),t}Object.defineProperty(e,"__esModule",{value:!0}),e.MutableDisposable=e.Disposable=e.DisposableStore=void 0,e.toDisposable=i,e.dispose=s,e.combinedDisposable=function(...t){return i(()=>s(t))};class r{constructor(){this._disposables=new Set,this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(t){return this._isDisposed?t.dispose():this._disposables.add(t),t}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(const t of this._disposables)t.dispose();this._disposables.clear()}}clear(){for(const t of this._disposables)t.dispose();this._disposables.clear()}}e.DisposableStore=r;class a{constructor(){this._store=new r}dispose(){this._store.dispose()}_register(t){return this._store.add(t)}}e.Disposable=a,a.None=Object.freeze({dispose(){}}),e.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(t){this._isDisposed||t===this._value||(this._value?.dispose(),this._value=t)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}}},836(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.FourKeyMap=e.TwoKeyMap=void 0;class i{constructor(){this._data={}}set(t,e,i){this._data[t]||(this._data[t]={}),this._data[t][e]=i}get(t,e){return this._data[t]?this._data[t][e]:void 0}clear(){this._data={}}}e.TwoKeyMap=i,e.FourKeyMap=class{constructor(){this._data=new i}set(t,e,s,r,a){this._data.get(t,e)||this._data.set(t,e,new i),this._data.get(t,e).set(s,r,a)}get(t,e,i,s){return this._data.get(t,e)?.get(i,s)}clear(){this._data.clear()}}},95(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.isChromeOS=e.isLinux=e.isWindows=e.isMac=e.isSafari=e.isLegacyEdge=e.isChrome=e.isFirefox=e.isNode=void 0,e.getZoomFactor=function(t){return 1},e.getSafariVersion=function(){if(!e.isSafari)return 0;const t=i.match(/Version\/(\d+)/);return null===t||t.length<2?0:parseInt(t[1],10)},e.isNode=!("undefined"==typeof process||!("title"in process)||"undefined"!=typeof navigator&&!navigator.userAgent.startsWith("Node.js/"));const i=e.isNode?"node":navigator.userAgent,s=e.isNode?"node":navigator.platform;e.isFirefox=i.includes("Firefox"),e.isChrome=i.includes("Chrome"),e.isLegacyEdge=i.includes("Edge"),e.isSafari=/^((?!chrome|android).)*safari/i.test(i),e.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(s),e.isWindows=["Windows","Win16","Win32","WinCE"].includes(s),e.isLinux=s.indexOf("Linux")>=0,e.isChromeOS=/\bCrOS\b/.test(i)},930(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.DebouncedIdleTask=e.IdleTaskQueue=e.PriorityTaskQueue=void 0;class i{constructor(t){this._tasks=[],this._i=0,this._logService=t}enqueue(t){this._tasks.push(t),this._start()}flush(){for(;this._ii)return r-e<-20&&this._logService.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-e))}ms`),void this._start();r=i}this.clear()}}class s extends i{_requestCallback(t){return setTimeout(()=>t(this._createDeadline(16)))}_cancelCallback(t){clearTimeout(t)}_createDeadline(t){const e=performance.now()+t;return{timeRemaining:()=>Math.max(0,e-performance.now())}}}e.PriorityTaskQueue=s,e.IdleTaskQueue="requestIdleCallback"in globalThis?class extends i{_requestCallback(t){return requestIdleCallback(t)}_cancelCallback(t){cancelIdleCallback(t)}}:s,e.DebouncedIdleTask=class{constructor(t){this._queue=new e.IdleTaskQueue(t)}set(t){this._queue.clear(),this._queue.enqueue(t)}flush(){this._queue.flush()}dispose(){this._queue.clear()}}},917(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.ExtendedAttrs=e.AttributeData=void 0;class i{constructor(){this.fg=0,this.bg=0,this.extended=new s}static toColorRGB(t){return[t>>>16&255,t>>>8&255,255&t]}static fromColorRGB(t){return(255&t[0])<<16|(255&t[1])<<8|255&t[2]}clone(){const t=new i;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)}isBgPalette(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?16777216==(50331648&this.extended.underlineColor)||33554432==(50331648&this.extended.underlineColor):this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}e.AttributeData=i;class s{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(t){this._ext&=-67108864,this._ext|=67108863&t}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){const t=(3758096384&this._ext)>>29;return t<0?4294967288^t:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}constructor(t=0,e=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=e}clone(){return new s(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}}e.ExtendedAttrs=s},721(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.CellData=void 0;const s=i(348),r=i(564),a=i(917);class o extends a.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new a.ExtendedAttrs,this.combinedData=""}static fromCharData(t){const e=new o;return e.setFromCharData(t),e}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,s.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(t){this.fg=t[r.CHAR_DATA_ATTR_INDEX],this.bg=0;let e=!1;if(t[r.CHAR_DATA_CHAR_INDEX].length>2)e=!0;else if(2===t[r.CHAR_DATA_CHAR_INDEX].length){const i=t[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=i&&i<=56319){const s=t[r.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=s&&s<=57343?this.content=1024*(i-55296)+s-56320+65536|t[r.CHAR_DATA_WIDTH_INDEX]<<22:e=!0}else e=!0}else this.content=t[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[r.CHAR_DATA_WIDTH_INDEX]<<22;e&&(this.combinedData=t[r.CHAR_DATA_CHAR_INDEX],this.content=2097152|t[r.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}attributesEquals(t){if(this.getFgColorMode()!==t.getFgColorMode()||this.getFgColor()!==t.getFgColor())return!1;if(this.getBgColorMode()!==t.getBgColorMode()||this.getBgColor()!==t.getBgColor())return!1;if(this.isInverse()!==t.isInverse())return!1;if(this.isBold()!==t.isBold())return!1;if(this.isUnderline()!==t.isUnderline())return!1;if(this.isUnderline()){if(this.getUnderlineStyle()!==t.getUnderlineStyle())return!1;const e=this.isUnderlineColorDefault(),i=t.isUnderlineColorDefault();if(!e||!i){if(e!==i)return!1;if(this.getUnderlineColor()!==t.getUnderlineColor())return!1;if(this.getUnderlineColorMode()!==t.getUnderlineColorMode())return!1}}return this.isOverline()===t.isOverline()&&this.isBlink()===t.isBlink()&&this.isInvisible()===t.isInvisible()&&this.isItalic()===t.isItalic()&&this.isDim()===t.isDim()&&this.isStrikethrough()===t.isStrikethrough()}}e.CellData=o},564(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.WHITESPACE_CELL_CODE=e.WHITESPACE_CELL_WIDTH=e.WHITESPACE_CELL_CHAR=e.NULL_CELL_CODE=e.NULL_CELL_WIDTH=e.NULL_CELL_CHAR=e.CHAR_DATA_CODE_INDEX=e.CHAR_DATA_WIDTH_INDEX=e.CHAR_DATA_CHAR_INDEX=e.CHAR_DATA_ATTR_INDEX=e.DEFAULT_EXT=e.DEFAULT_ATTR=e.DEFAULT_COLOR=void 0,e.DEFAULT_COLOR=0,e.DEFAULT_ATTR=e.DEFAULT_COLOR<<9|256,e.DEFAULT_EXT=0,e.CHAR_DATA_ATTR_INDEX=0,e.CHAR_DATA_CHAR_INDEX=1,e.CHAR_DATA_WIDTH_INDEX=2,e.CHAR_DATA_CODE_INDEX=3,e.NULL_CELL_CHAR="",e.NULL_CELL_WIDTH=1,e.NULL_CELL_CODE=0,e.WHITESPACE_CELL_CHAR=" ",e.WHITESPACE_CELL_WIDTH=1,e.WHITESPACE_CELL_CODE=32},348(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.Utf8ToUtf32=e.StringToUtf32=void 0,e.stringFromCodePoint=function(t){return t>65535?(t-=65536,String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):String.fromCharCode(t)},e.utf32ToString=function(t,e=0,i=t.length){let s="";for(let r=e;r65535?(e-=65536,s+=String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):s+=String.fromCharCode(e)}return s},e.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(t,e){const i=t.length;if(!i)return 0;let s=0,r=0;if(this._interim){const i=t.charCodeAt(r++);56320<=i&&i<=57343?e[s++]=1024*(this._interim-55296)+i-56320+65536:(e[s++]=this._interim,e[s++]=i),this._interim=0}for(let a=r;a=i)return this._interim=r,s;const o=t.charCodeAt(a);56320<=o&&o<=57343?e[s++]=1024*(r-55296)+o-56320+65536:(e[s++]=r,e[s++]=o);continue}65279!==r&&(e[s++]=r)}return s}},e.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(t,e){const i=t.length;if(!i)return 0;let s,r,a,o,n,L=0,h=0;if(this.interim[0]){let s=!1,r=this.interim[0];r&=192==(224&r)?31:224==(240&r)?15:7;let a,o=0;for(;(a=this.interim[++o])&&o<4;)r<<=6,r|=63&a;const n=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,T=n-o;for(;h=i)return 0;if(a=t[h++],128!=(192&a)){h--,s=!0;break}this.interim[o++]=a,r<<=6,r|=63&a}s||(2===n?r<128?h--:e[L++]=r:3===n?r<2048||r>=55296&&r<=57343||65279===r||(e[L++]=r):r<65536||r>1114111||(e[L++]=r)),this.interim.fill(0)}const T=i-4;let l=h;for(;l=i)return this.interim[0]=s,L;if(r=t[l++],128!=(192&r)){l--;continue}if(n=(31&s)<<6|63&r,n<128){l--;continue}e[L++]=n}else if(224==(240&s)){if(l>=i)return this.interim[0]=s,L;if(r=t[l++],128!=(192&r)){l--;continue}if(l>=i)return this.interim[0]=s,this.interim[1]=r,L;if(a=t[l++],128!=(192&a)){l--;continue}if(n=(15&s)<<12|(63&r)<<6|63&a,n<2048||n>=55296&&n<=57343||65279===n)continue;e[L++]=n}else if(240==(248&s)){if(l>=i)return this.interim[0]=s,L;if(r=t[l++],128!=(192&r)){l--;continue}if(l>=i)return this.interim[0]=s,this.interim[1]=r,L;if(a=t[l++],128!=(192&a)){l--;continue}if(l>=i)return this.interim[0]=s,this.interim[1]=r,this.interim[2]=a,L;if(o=t[l++],128!=(192&o)){l--;continue}if(n=(7&s)<<18|(63&r)<<12|(63&a)<<6|63&o,n<65536||n>1114111)continue;e[L++]=n}}return L}}},864(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.CellColorResolver=void 0;const s=i(564),r=i(993),a=i(959),o=i(915);let n,L=0,h=0,T=!1,l=!1,d=!1,c=0;e.CellColorResolver=class{constructor(t,e,i,s,r,a){this._terminal=t,this._optionService=e,this._selectionRenderModel=i,this._decorationService=s,this._coreBrowserService=r,this._themeService=a,this.result={fg:0,bg:0,ext:0}}resolve(t,e,i,_,Q){this.result.bg=t.bg,this.result.fg=t.fg,this.result.ext=268435456&t.bg?t.extended.ext:0,h=0,L=0,l=!1,T=!1,d=!1,n=this._themeService.colors,c=0;const u=t.getCode();if(u!==s.NULL_CELL_CODE&&4===t.extended.underlineStyle){const t=Math.max(1,Math.floor(this._optionService.rawOptions.fontSize*this._coreBrowserService.dpr/15));c=e*_%(2*Math.round(t))}if(0===c&&o.blockPatternCodepoints.has(u)&&(c=e*_%2*2+i*Q%2),this._decorationService.forEachDecorationAtCell(e,i,"bottom",t=>{t.backgroundColorRGB&&(h=t.backgroundColorRGB.rgba>>8&16777215,l=!0),t.foregroundColorRGB&&(L=t.foregroundColorRGB.rgba>>8&16777215,T=!0)}),d=this._selectionRenderModel.isCellSelected(this._terminal,e,i),d){if(67108864&this.result.fg||50331648&this.result.bg){if(67108864&this.result.fg)switch(50331648&this.result.fg){case 16777216:case 33554432:h=this._themeService.colors.ansi[255&this.result.fg].rgba;break;case 50331648:h=(16777215&this.result.fg)<<8|255;break;default:h=this._themeService.colors.foreground.rgba}else switch(50331648&this.result.bg){case 16777216:case 33554432:h=this._themeService.colors.ansi[255&this.result.bg].rgba;break;case 50331648:h=(16777215&this.result.bg)<<8|255}h=r.rgba.blend(h,4294967040&(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba|128)>>8&16777215}else h=(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba>>8&16777215;if(l=!0,n.selectionForeground&&(L=n.selectionForeground.rgba>>8&16777215,T=!0),(0,a.treatGlyphAsBackgroundColor)(t.getCode())){if(67108864&this.result.fg&&!(50331648&this.result.bg))L=(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba>>8&16777215;else{if(67108864&this.result.fg)switch(50331648&this.result.bg){case 16777216:case 33554432:L=this._themeService.colors.ansi[255&this.result.bg].rgba;break;case 50331648:L=(16777215&this.result.bg)<<8|255}else switch(50331648&this.result.fg){case 16777216:case 33554432:L=this._themeService.colors.ansi[255&this.result.fg].rgba;break;case 50331648:L=(16777215&this.result.fg)<<8|255;break;default:L=this._themeService.colors.foreground.rgba}L=r.rgba.blend(L,4294967040&(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba|128)>>8&16777215}T=!0}}this._decorationService.forEachDecorationAtCell(e,i,"top",t=>{t.backgroundColorRGB&&(h=t.backgroundColorRGB.rgba>>8&16777215,l=!0),t.foregroundColorRGB&&(L=t.foregroundColorRGB.rgba>>8&16777215,T=!0)}),l&&(h=d?-16777216&t.bg&-134217729|h|50331648:-16777216&t.bg|h|50331648),T&&(L=-16777216&t.fg&-67108865|L|50331648),67108864&this.result.fg&&(l&&!T&&(L=50331648&this.result.bg?-134217728&this.result.fg|67108863&this.result.bg:-134217728&this.result.fg|16777215&n.background.rgba>>8|50331648,T=!0),!l&&T&&(h=50331648&this.result.fg?-67108864&this.result.bg|67108863&this.result.fg:-67108864&this.result.bg|16777215&n.foreground.rgba>>8|50331648,l=!0)),n=void 0,this.result.bg=l?h:this.result.bg,this.result.fg=T?L:this.result.fg,this.result.ext&=536870911,this.result.ext|=c<<29&3758096384}}},670(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.acquireTextureAtlas=function(t,e,i,o,n,L,h,T,l,d=!0){const c=(0,r.generateConfig)(o,n,L,h,e,i,T,l,d);for(let e=0;e=0){if((0,r.configEquals)(i.config,c))return i.atlas;1===i.ownedBy.length?(i.atlas.dispose(),a.splice(e,1)):i.ownedBy.splice(s,1);break}}for(let e=0;e{this._renderCallback(),this._animationFrame=void 0})))}_restartInterval(t=600){this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout=this._coreBrowserService.window.setTimeout(()=>{if(this._animationTimeRestarted){const t=600-(Date.now()-this._animationTimeRestarted);if(this._animationTimeRestarted=void 0,t>0)return void this._restartInterval(t)}this.isCursorVisible=!1,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0}),this._blinkInterval=this._coreBrowserService.window.setInterval(()=>{if(this._animationTimeRestarted){const t=600-(Date.now()-this._animationTimeRestarted);return this._animationTimeRestarted=void 0,void this._restartInterval(t)}this.isCursorVisible=!this.isCursorVisible,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0})},600)},t)}pause(){this.isCursorVisible=!0,this._isIdlePaused=!1,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._idleTimeout&&(this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0)}resume(){this.pause(),this._animationTimeRestarted=void 0,this._restartInterval(),this._resetIdleTimer(),this.restartBlinkAnimation()}_resetIdleTimer(){this._isIdlePaused=!1,this._idleTimeout&&this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=this._coreBrowserService.window.setTimeout(()=>{this._stopBlinkingDueToIdle()},3e5)}_stopBlinkingDueToIdle(){this.isCursorVisible=!0,this._isIdlePaused=!0,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0,this._renderCallback()}}},697(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.observeDevicePixelDimensions=function(t,e,i){let r=new e.ResizeObserver(e=>{const s=e.find(e=>e.target===t);if(!s)return;if(!("devicePixelContentBoxSize"in s))return r?.disconnect(),void(r=void 0);const a=s.devicePixelContentBoxSize[0].inlineSize,o=s.devicePixelContentBoxSize[0].blockSize;a>0&&o>0&&i(a,o)});try{r.observe(t,{box:["device-pixel-content-box"]})}catch{r.disconnect(),r=void 0}return(0,s.toDisposable)(()=>r?.disconnect())};const s=i(426)},28(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.GlyphRenderer=void 0;const s=i(115),r=i(564),a=i(426),o=i(719),n=i(959);let L,h=0,T=0,l=0;class d extends a.Disposable{constructor(t,e,i,r,L){super(),this._terminal=t,this._gl=e,this._dimensions=i,this._optionsService=r,this._logService=L,this._activeBuffer=0,this._vertices={count:0,attributes:new Float32Array(0),attributesBuffers:[new Float32Array(0),new Float32Array(0)]};const h=this._gl;void 0===s.TextureAtlas.maxAtlasPages&&(s.TextureAtlas.maxAtlasPages=Math.min(32,(0,n.throwIfFalsy)(h.getParameter(h.MAX_TEXTURE_IMAGE_UNITS))),s.TextureAtlas.maxTextureSize=(0,n.throwIfFalsy)(h.getParameter(h.MAX_TEXTURE_SIZE))),this._program=(0,n.throwIfFalsy)((0,o.createProgram)(h,"#version 300 es\nlayout (location = 0) in vec2 a_unitquad;\nlayout (location = 1) in vec2 a_cellpos;\nlayout (location = 2) in vec2 a_offset;\nlayout (location = 3) in vec2 a_size;\nlayout (location = 4) in float a_texpage;\nlayout (location = 5) in vec2 a_texcoord;\nlayout (location = 6) in vec2 a_texsize;\n\nuniform mat4 u_projection;\nuniform vec2 u_resolution;\n\nout vec2 v_texcoord;\nflat out int v_texpage;\n\nvoid main() {\n vec2 zeroToOne = (a_offset / u_resolution) + a_cellpos + (a_unitquad * a_size);\n gl_Position = u_projection * vec4(zeroToOne, 0.0, 1.0);\n v_texpage = int(a_texpage);\n v_texcoord = a_texcoord + a_unitquad * a_texsize;\n}",function(t){let e="";for(let i=1;ih.deleteProgram(this._program))),this._projectionLocation=(0,n.throwIfFalsy)(h.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=(0,n.throwIfFalsy)(h.getUniformLocation(this._program,"u_resolution")),this._textureLocation=(0,n.throwIfFalsy)(h.getUniformLocation(this._program,"u_texture"));const T=this._vertexArrayObject=h.createVertexArray();this._register((0,a.toDisposable)(()=>h.deleteVertexArray(T))),h.bindVertexArray(T);const l=new Float32Array([0,0,1,0,0,1,1,1]),d=h.createBuffer();this._register((0,a.toDisposable)(()=>h.deleteBuffer(d))),h.bindBuffer(h.ARRAY_BUFFER,d),h.bufferData(h.ARRAY_BUFFER,l,h.STATIC_DRAW),h.enableVertexAttribArray(0),h.vertexAttribPointer(0,2,this._gl.FLOAT,!1,0,0);const c=new Uint8Array([0,1,2,3]),_=h.createBuffer();this._register((0,a.toDisposable)(()=>h.deleteBuffer(_))),h.bindBuffer(h.ELEMENT_ARRAY_BUFFER,_),h.bufferData(h.ELEMENT_ARRAY_BUFFER,c,h.STATIC_DRAW),this._attributesBuffer=(0,n.throwIfFalsy)(h.createBuffer()),this._register((0,a.toDisposable)(()=>h.deleteBuffer(this._attributesBuffer))),h.bindBuffer(h.ARRAY_BUFFER,this._attributesBuffer),h.enableVertexAttribArray(2),h.vertexAttribPointer(2,2,h.FLOAT,!1,44,0),h.vertexAttribDivisor(2,1),h.enableVertexAttribArray(3),h.vertexAttribPointer(3,2,h.FLOAT,!1,44,2*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(3,1),h.enableVertexAttribArray(4),h.vertexAttribPointer(4,1,h.FLOAT,!1,44,4*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(4,1),h.enableVertexAttribArray(5),h.vertexAttribPointer(5,2,h.FLOAT,!1,44,5*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(5,1),h.enableVertexAttribArray(6),h.vertexAttribPointer(6,2,h.FLOAT,!1,44,7*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(6,1),h.enableVertexAttribArray(1),h.vertexAttribPointer(1,2,h.FLOAT,!1,44,9*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(1,1),h.useProgram(this._program);const Q=new Int32Array(s.TextureAtlas.maxAtlasPages);for(let t=0;th.deleteTexture(e.texture))),h.activeTexture(h.TEXTURE0+t),h.bindTexture(h.TEXTURE_2D,e.texture),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texImage2D(h.TEXTURE_2D,0,h.RGBA,1,1,0,h.RGBA,h.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[t]=e}h.enable(h.BLEND),h.blendFunc(h.SRC_ALPHA,h.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){return!this._atlas||this._atlas.beginFrame()}updateCell(t,e,i,s,r,a,o,n,L){this._updateCell(this._vertices.attributes,t,e,i,s,r,a,o,n,L)}_updateCell(t,e,i,s,a,o,d,c,_,Q){h=11*(i*this._terminal.cols+e),s!==r.NULL_CELL_CODE&&void 0!==s?this._atlas&&(L=c&&c.length>1?this._atlas.getRasterizedGlyphCombinedChar(c,a,o,d,!1,this._terminal.element):this._atlas.getRasterizedGlyph(s,a,o,d,!1,this._terminal.element),T=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),a!==Q&&L.offset.x>T?(l=L.offset.x-T,t[h]=-(L.offset.x-l)+this._dimensions.device.char.left,t[h+1]=-L.offset.y+this._dimensions.device.char.top,t[h+2]=(L.size.x-l)/this._dimensions.device.canvas.width,t[h+3]=L.size.y/this._dimensions.device.canvas.height,t[h+4]=L.texturePage,t[h+5]=L.texturePositionClipSpace.x+l/this._atlas.pages[L.texturePage].canvas.width,t[h+6]=L.texturePositionClipSpace.y,t[h+7]=L.sizeClipSpace.x-l/this._atlas.pages[L.texturePage].canvas.width,t[h+8]=L.sizeClipSpace.y):(t[h]=-L.offset.x+this._dimensions.device.char.left,t[h+1]=-L.offset.y+this._dimensions.device.char.top,t[h+2]=L.size.x/this._dimensions.device.canvas.width,t[h+3]=L.size.y/this._dimensions.device.canvas.height,t[h+4]=L.texturePage,t[h+5]=L.texturePositionClipSpace.x,t[h+6]=L.texturePositionClipSpace.y,t[h+7]=L.sizeClipSpace.x,t[h+8]=L.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&(0,n.allowRescaling)(s,_,L.size.x,this._dimensions.device.cell.width)&&(t[h+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width)):t.fill(0,h,h+11-1-2)}clear(){const t=this._terminal,e=t.cols*t.rows*11;this._vertices.count!==e?this._vertices.attributes=new Float32Array(e):this._vertices.attributes.fill(0);let i=0;for(;iT.deleteProgram(this._program))),this._projectionLocation=(0,a.throwIfFalsy)(T.getUniformLocation(this._program,"u_projection"));const l=this._vertexArrayObject=T.createVertexArray();this._register((0,s.toDisposable)(()=>T.deleteVertexArray(l))),T.bindVertexArray(l);const d=new Float32Array([0,0,1,0,0,1,1,1]),c=T.createBuffer();this._register((0,s.toDisposable)(()=>T.deleteBuffer(c))),T.bindBuffer(T.ARRAY_BUFFER,c),T.bufferData(T.ARRAY_BUFFER,d,T.STATIC_DRAW),T.enableVertexAttribArray(3),T.vertexAttribPointer(3,2,this._gl.FLOAT,!1,0,0);const _=new Uint8Array([0,1,2,3]),Q=T.createBuffer();this._register((0,s.toDisposable)(()=>T.deleteBuffer(Q))),T.bindBuffer(T.ELEMENT_ARRAY_BUFFER,Q),T.bufferData(T.ELEMENT_ARRAY_BUFFER,_,T.STATIC_DRAW),this._attributesBuffer=(0,a.throwIfFalsy)(T.createBuffer()),this._register((0,s.toDisposable)(()=>T.deleteBuffer(this._attributesBuffer))),T.bindBuffer(T.ARRAY_BUFFER,this._attributesBuffer),T.enableVertexAttribArray(0),T.vertexAttribPointer(0,2,T.FLOAT,!1,o,0),T.vertexAttribDivisor(0,1),T.enableVertexAttribArray(1),T.vertexAttribPointer(1,2,T.FLOAT,!1,o,2*Float32Array.BYTES_PER_ELEMENT),T.vertexAttribDivisor(1,1),T.enableVertexAttribArray(2),T.vertexAttribPointer(2,4,T.FLOAT,!1,o,4*Float32Array.BYTES_PER_ELEMENT),T.vertexAttribDivisor(2,1),this._updateCachedColors(L.colors),this._register(this._themeService.onChangeColors(t=>{this._updateCachedColors(t),this._updateViewportRectangle()}))}renderBackgrounds(){this._renderVertices(this._vertices)}renderCursor(){this._renderVertices(this._verticesCursor)}_renderVertices(t){const e=this._gl;e.useProgram(this._program),e.bindVertexArray(this._vertexArrayObject),e.uniformMatrix4fv(this._projectionLocation,!1,r.PROJECTION_MATRIX),e.bindBuffer(e.ARRAY_BUFFER,this._attributesBuffer),e.bufferData(e.ARRAY_BUFFER,t.attributes,e.DYNAMIC_DRAW),e.drawElementsInstanced(this._gl.TRIANGLE_STRIP,4,e.UNSIGNED_BYTE,0,t.count)}handleResize(){this._updateViewportRectangle()}setDimensions(t){this._dimensions=t}_updateCachedColors(t){this._bgFloat=this._colorToFloat32Array(t.background),this._cursorFloat=this._colorToFloat32Array(t.cursor)}_updateViewportRectangle(){this._addRectangleFloat(this._vertices.attributes,0,0,0,this._terminal.cols*this._dimensions.device.cell.width,this._terminal.rows*this._dimensions.device.cell.height,this._bgFloat)}updateBackgrounds(t){const e=this._terminal,i=this._vertices;let s,r,a,o,n,L,h,T,l,d,c,_=1;for(s=0;s>24&255)/255,d=(L>>16&255)/255,c=(L>>8&255)/255,_=1,this._addRectangle(t.attributes,e,h,T,(o-a)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,l,d,c,_)}_addRectangle(t,e,i,s,r,a,o,n,L,h){t[e]=i/this._dimensions.device.canvas.width,t[e+1]=s/this._dimensions.device.canvas.height,t[e+2]=r/this._dimensions.device.canvas.width,t[e+3]=a/this._dimensions.device.canvas.height,t[e+4]=o,t[e+5]=n,t[e+6]=L,t[e+7]=h}_addRectangleFloat(t,e,i,s,r,a,o){t[e]=i/this._dimensions.device.canvas.width,t[e+1]=s/this._dimensions.device.canvas.height,t[e+2]=r/this._dimensions.device.canvas.width,t[e+3]=a/this._dimensions.device.canvas.height,t[e+4]=o[0],t[e+5]=o[1],t[e+6]=o[2],t[e+7]=o[3]}_colorToFloat32Array(t){return new Float32Array([(t.rgba>>24&255)/255,(t.rgba>>16&255)/255,(t.rgba>>8&255)/255,(255&t.rgba)/255])}}e.RectangleRenderer=Q},208(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.RenderModel=e.COMBINED_CHAR_BIT_MASK=void 0;const s=i(948);e.COMBINED_CHAR_BIT_MASK=2147483648,e.RenderModel=class{constructor(){this.cells=new Uint32Array(0),this.lineLengths=new Uint32Array(0),this.selection=(0,s.createSelectionRenderModel)()}resize(t,e){const i=t*e*4;i!==this.cells.length&&(this.cells=new Uint32Array(i),this.lineLengths=new Uint32Array(e))}clear(){this.cells.fill(0,0),this.lineLengths.fill(0,0)}}},115(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.TextureAtlas=void 0;const s=i(0),r=i(183),a=i(959),o=i(993),n=i(836),L=i(930),h=i(917),T=i(564),l=i(414),d={texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},offset:{x:0,y:0},size:{x:0,y:0},sizeClipSpace:{x:0,y:0}};let c;class _{get pages(){return this._pages}constructor(t,e,i,s){this._document=t,this._config=e,this._unicodeService=i,this._logService=s,this._didWarmUp=!1,this._cacheMap=new n.FourKeyMap,this._cacheMapCombined=new n.FourKeyMap,this._pages=[],this._activePages=[],this._workBoundingBox={top:0,left:0,bottom:0,right:0},this._workAttributeData=new h.AttributeData,this._textureSize=512,this._onAddTextureAtlasCanvas=new l.Emitter,this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=new l.Emitter,this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._requestClearModel=!1,this._createNewPage(),this._tmpCanvas=p(t,4*this._config.deviceCellWidth+4,this._config.deviceCellHeight+4),this._tmpCtx=(0,a.throwIfFalsy)(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:!0}))}dispose(){this._tmpCanvas.remove();for(const t of this.pages)t.canvas.remove();this._onAddTextureAtlasCanvas.dispose(),this._onRemoveTextureAtlasCanvas.dispose()}warmUp(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)}_doWarmUp(){const t=new L.IdleTaskQueue(this._logService);for(let e=33;e<126;e++)t.enqueue(()=>{if(!this._cacheMap.get(e,T.DEFAULT_COLOR,T.DEFAULT_COLOR,T.DEFAULT_EXT)){const t=this._drawToCache(e,T.DEFAULT_COLOR,T.DEFAULT_COLOR,T.DEFAULT_EXT,!1,void 0);this._cacheMap.set(e,T.DEFAULT_COLOR,T.DEFAULT_COLOR,T.DEFAULT_EXT,t)}})}beginFrame(){const t=this._requestClearModel;return this._requestClearModel=!1,t}clearTexture(){if(0!==this._pages[0].currentRow.x||0!==this._pages[0].currentRow.y){for(const t of this._pages)t.clear();this._cacheMap.clear(),this._cacheMapCombined.clear(),this._didWarmUp=!1}}_createNewPage(){if(_.maxAtlasPages&&this._pages.length>=Math.max(4,_.maxAtlasPages)){const t=this._pages.filter(t=>2*t.canvas.width<=(_.maxTextureSize||4096)).sort((t,e)=>e.canvas.width!==t.canvas.width?e.canvas.width-t.canvas.width:e.percentageUsed-t.percentageUsed);let e=-1,i=0;for(let s=0;st.canvas.width!==s[0].canvas.width)){const t=new Q(this._document,this._textureSize);return this._pages.push(t),this._activePages.push(t),this._onAddTextureAtlasCanvas.fire(t.canvas),t}const r=s.map(t=>t.glyphs[0].texturePage).sort((t,e)=>t-e),a=this.pages.length-s.length,o=this._mergePages(s,a);o.version=++Q.nextVersion;for(let t=r.length-1;t>=0;t--)this._deletePage(r[t]);this.pages.push(o),this._requestClearModel=!0,this._onAddTextureAtlasCanvas.fire(o.canvas)}const t=new Q(this._document,this._textureSize);return this._pages.push(t),this._activePages.push(t),this._onAddTextureAtlasCanvas.fire(t.canvas),t}_mergePages(t,e){const i=2*t[0].canvas.width,s=new Q(this._document,i,t);for(const[r,a]of t.entries()){const t=r*a.canvas.width%i,o=Math.floor(r/2)*a.canvas.height;s.ctx.drawImage(a.canvas,t,o);for(const s of a.glyphs)s.texturePage=e,s.sizeClipSpace.x=s.size.x/i,s.sizeClipSpace.y=s.size.y/i,s.texturePosition.x+=t,s.texturePosition.y+=o,s.texturePositionClipSpace.x=s.texturePosition.x/i,s.texturePositionClipSpace.y=s.texturePosition.y/i;this._onRemoveTextureAtlasCanvas.fire(a.canvas);const n=this._activePages.indexOf(a);-1!==n&&this._activePages.splice(n,1)}return s}_deletePage(t){this._pages.splice(t,1);for(let e=t;e=this._config.colors.ansi.length)throw new Error("No color found for idx "+t);return this._config.colors.ansi[t]}_getBackgroundColor(t,e,i,s){if(this._config.allowTransparency)return o.NULL_COLOR;let r;switch(t){case 16777216:case 33554432:r=this._getColorFromAnsiIndex(e);break;case 50331648:const t=h.AttributeData.toColorRGB(e);r=o.channels.toColor(t[0],t[1],t[2]);break;default:r=i?o.color.opaque(this._config.colors.foreground):this._config.colors.background}return this._config.allowTransparency||(r=o.color.opaque(r)),r}_getForegroundColor(t,e,i,r,a,n,L,T,l,d){const c=this._getMinimumContrastColor(t,e,i,r,a,n,L,l,T,d);if(c)return c;let _;switch(a){case 16777216:case 33554432:this._config.drawBoldTextInBrightColors&&l&&n<8&&(n+=8),_=this._getColorFromAnsiIndex(n);break;case 50331648:const t=h.AttributeData.toColorRGB(n);_=o.channels.toColor(t[0],t[1],t[2]);break;default:_=L?this._config.colors.background:this._config.colors.foreground}return this._config.allowTransparency&&(_=o.color.opaque(_)),T&&(_=o.color.multiplyOpacity(_,s.DIM_OPACITY)),_}_resolveBackgroundRgba(t,e,i){switch(t){case 16777216:case 33554432:return this._getColorFromAnsiIndex(e).rgba;case 50331648:return e<<8;default:return i?this._config.colors.foreground.rgba:this._config.colors.background.rgba}}_resolveForegroundRgba(t,e,i,s){switch(t){case 16777216:case 33554432:return this._config.drawBoldTextInBrightColors&&s&&e<8&&(e+=8),this._getColorFromAnsiIndex(e).rgba;case 50331648:return e<<8;default:return i?this._config.colors.background.rgba:this._config.colors.foreground.rgba}}_getMinimumContrastColor(t,e,i,s,r,a,n,L,h,T){if(1===this._config.minimumContrastRatio||T)return;const l=this._getContrastCache(h),d=l.getColor(t,s);if(void 0!==d)return d??void 0;const c=this._resolveBackgroundRgba(e,i,n),_=this._resolveForegroundRgba(r,a,n,L),Q=o.rgba.ensureContrastRatio(c,_,this._config.minimumContrastRatio/(h?2:1));if(!Q)return void l.setColor(t,s,null);const u=o.channels.toColor(Q>>24&255,Q>>16&255,Q>>8&255);return l.setColor(t,s,u),u}_getContrastCache(t){return t?this._config.colors.halfContrastCache:this._config.colors.contrastCache}_drawToCache(t,e,i,o,n,L){const T="number"==typeof t?String.fromCharCode(t):t;L&&this._tmpCanvas.parentElement!==L&&(this._tmpCanvas.style.display="none",L.append(this._tmpCanvas));const l=Math.min(this._config.deviceCellWidth*Math.max(T.length,2)+4,this._config.deviceMaxTextureSize);this._tmpCanvas.width=t?2*t-o:t-o;!1==!(o>=t)||0===_?(this._tmpCtx.setLineDash([Math.round(t),Math.round(t)]),this._tmpCtx.moveTo(h+_,s),this._tmpCtx.lineTo(T,s)):(this._tmpCtx.setLineDash([Math.round(t),Math.round(t)]),this._tmpCtx.moveTo(h,s),this._tmpCtx.lineTo(h+_,s),this._tmpCtx.moveTo(h+_+t,s),this._tmpCtx.lineTo(T,s)),o=(0,a.computeNextVariantOffset)(T-h,t,o);break;case 5:const Q=.6,u=.3,p=T-h,g=Math.floor(Q*p),M=Math.floor(u*p),y=p-g-M;this._tmpCtx.setLineDash([g,M,y]),this._tmpCtx.moveTo(h,s),this._tmpCtx.lineTo(T,s);break;default:this._tmpCtx.moveTo(h,s),this._tmpCtx.lineTo(T,s)}n||this._tmpCtx.stroke(),this._tmpCtx.restore()}if(this._tmpCtx.restore(),!O&&this._config.fontSize>=12&&!this._config.allowTransparency&&" "!==T){this._tmpCtx.save(),this._tmpCtx.textBaseline="alphabetic";const e=this._tmpCtx.measureText(T);if(this._tmpCtx.restore(),"actualBoundingBoxDescent"in e&&e.actualBoundingBoxDescent>0){this._tmpCtx.save();const e=new Path2D;e.rect(i,L-Math.ceil(t/2),this._config.deviceCellWidth*I,l-L+Math.ceil(t/2)),this._tmpCtx.clip(e),this._tmpCtx.lineWidth=3*this._config.devicePixelRatio,this._tmpCtx.strokeStyle=E.css,this._tmpCtx.strokeText(T,S,S+this._config.deviceCharHeight),this._tmpCtx.restore()}}}if(C){const t=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/15)),e=t%2==1?.5:0;this._tmpCtx.lineWidth=t,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(S,S+e),this._tmpCtx.lineTo(S+this._config.deviceCharWidth*I,S+e),this._tmpCtx.stroke()}if(O||this._tmpCtx.fillText(T,S,S+this._config.deviceCharHeight),"_"===T&&!this._config.allowTransparency){let t=u(this._tmpCtx.getImageData(S,S,this._config.deviceCellWidth,this._config.deviceCellHeight),E,D,W);if(t)for(let e=1;e<=5&&(this._tmpCtx.save(),this._tmpCtx.fillStyle=E.css,this._tmpCtx.fillRect(0,0,this._tmpCanvas.width,this._tmpCanvas.height),this._tmpCtx.restore(),this._tmpCtx.fillText(T,S,S+this._config.deviceCharHeight-e),t=u(this._tmpCtx.getImageData(S,S,this._config.deviceCellWidth,this._config.deviceCellHeight),E,D,W),t);e++);}if(f){const t=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/10)),e=this._tmpCtx.lineWidth%2==1?.5:0;this._tmpCtx.lineWidth=t,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(S,S+Math.floor(this._config.deviceCharHeight/2)-e),this._tmpCtx.lineTo(S+this._config.deviceCharWidth*I,S+Math.floor(this._config.deviceCharHeight/2)-e),this._tmpCtx.stroke()}this._tmpCtx.restore();const N=this._tmpCtx.getImageData(0,0,this._tmpCanvas.width,this._tmpCanvas.height);let P;if(P=this._config.allowTransparency?function(t){for(let e=0;e0)return!1;return!0}(N):u(N,E,D,W),P)return d;const B=this._findGlyphBoundingBox(N,this._workBoundingBox,l,Z,O,S);let $,F;for(;;){if(0===this._activePages.length){const t=this._createNewPage();$=t,F=t.currentRow,F.height=B.size.y;break}$=this._activePages[this._activePages.length-1],F=$.currentRow;for(const t of this._activePages)B.size.y<=t.currentRow.height&&($=t,F=t.currentRow);for(let t=this._activePages.length-1;t>=0;t--)for(const e of this._activePages[t].fixedRows)e.height<=F.height&&B.size.y<=e.height&&($=this._activePages[t],F=e);if(B.size.x>this._textureSize){this._overflowSizePage||(this._overflowSizePage=new Q(this._document,this._config.deviceMaxTextureSize),this.pages.push(this._overflowSizePage),this._requestClearModel=!0,this._onAddTextureAtlasCanvas.fire(this._overflowSizePage.canvas)),$=this._overflowSizePage,F=this._overflowSizePage.currentRow,F.x+B.size.x>=$.canvas.width&&(F.x=0,F.y+=F.height,F.height=0);break}if(F.y+B.size.y>=$.canvas.height||F.height>B.size.y+2){let t=!1;if($.currentRow.y+$.currentRow.height+B.size.y>=$.canvas.height){let e;for(const t of this._activePages)if(t.currentRow.y+t.currentRow.height+B.size.y=_.maxAtlasPages&&F.y+B.size.y<=$.canvas.height&&F.height>=B.size.y&&F.x+B.size.x<=$.canvas.width)t=!0;else{const e=this._createNewPage();$=e,F=e.currentRow,F.height=B.size.y,t=!0}}t||($.currentRow.height>0&&$.fixedRows.push($.currentRow),F={x:0,y:$.currentRow.y+$.currentRow.height,height:B.size.y},$.fixedRows.push(F),$.currentRow={x:0,y:F.y+F.height,height:0})}if(F.x+B.size.x<=$.canvas.width)break;F===$.currentRow?(F.x=0,F.y+=F.height,F.height=0):$.fixedRows.splice($.fixedRows.indexOf(F),1)}return B.texturePage=this._pages.indexOf($),B.texturePosition.x=F.x,B.texturePosition.y=F.y,B.texturePositionClipSpace.x=F.x/$.canvas.width,B.texturePositionClipSpace.y=F.y/$.canvas.height,B.sizeClipSpace.x/=$.canvas.width,B.sizeClipSpace.y/=$.canvas.height,F.height=Math.max(F.height,B.size.y),F.x+=B.size.x,$.ctx.putImageData(N,B.texturePosition.x-this._workBoundingBox.left,B.texturePosition.y-this._workBoundingBox.top,this._workBoundingBox.left,this._workBoundingBox.top,B.size.x,B.size.y),$.addGlyph(B),$.version=++Q.nextVersion,B}_findGlyphBoundingBox(t,e,i,s,r,a){e.top=0;const o=s?this._config.deviceCellHeight:this._tmpCanvas.height,n=s?this._config.deviceCellWidth:i;let L=!1;for(let i=0;i=a;i--){for(let s=0;s=0;i--){for(let s=0;s>>24,a=e.rgba>>>16&255,o=e.rgba>>>8&255,n=i.rgba>>>24,L=i.rgba>>>16&255,h=i.rgba>>>8&255,T=Math.floor((Math.abs(r-n)+Math.abs(a-L)+Math.abs(o-h))/12);let l=!0;for(let e=0;ethis._handleColorChange())),this._cellColorResolver=new s.CellColorResolver(this._terminal,this._optionsService,this._model.selection,this._decorationService,this._coreBrowserService,this._themeService),this._core=this._terminal._core,this._renderLayers=[new _.LinkRenderLayer(this._core.screenElement,2,this._terminal,this._core.linkifier,this._coreBrowserService,d,this._themeService)],this.dimensions=(0,g.createRenderDimensions)(),this._devicePixelRatio=this._coreBrowserService.dpr,this._updateDimensions(),this._updateCursorBlink(),this._register(d.onOptionChange(()=>this._handleOptionsChanged())),this._textBlinkStateManager=this._register(new T.TextBlinkStateManager(()=>this._requestRedrawViewport(),this._coreBrowserService,this._optionsService)),this._resetBlinkingRowState(),this._deviceMaxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._register((0,u.addDisposableListener)(this._canvas,"webglcontextlost",t=>{this._logService.debug("webglcontextlost event received"),t.preventDefault(),this._contextRestorationTimeout=setTimeout(()=>{this._contextRestorationTimeout=void 0,this._logService.warn("webgl context not restored; firing onContextLoss"),this._onContextLoss.fire(t)},3e3)})),this._register((0,u.addDisposableListener)(this._canvas,"webglcontextrestored",t=>{this._logService.warn("webglcontextrestored event received"),clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0,(0,r.removeTerminalFromCache)(this._terminal),this._initializeWebGLState(),this._requestRedrawViewport()})),this._observerDisposable.value=(0,o.observeDevicePixelDimensions)(this._canvas,this._coreBrowserService.window,(t,e)=>this._setCanvasDevicePixelDimensions(t,e)),this._register(this._coreBrowserService.onWindowChange(t=>{this._observerDisposable.value=(0,o.observeDevicePixelDimensions)(this._canvas,t,(t,e)=>this._setCanvasDevicePixelDimensions(t,e))})),this._register((0,u.addDisposableListener)(this._coreBrowserService.mainDocument,"mousedown",()=>this._cursorBlinkStateManager.value?.restartBlinkAnimation())),this._core.screenElement.appendChild(this._canvas),[this._rectangleRenderer.value,this._glyphRenderer.value]=this._initializeWebGLState(),this._isAttached=this._core.screenElement.isConnected,this._register((0,p.toDisposable)(()=>{clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0;for(const t of this._renderLayers)t.dispose();this._canvas.parentElement?.removeChild(this._canvas),(0,r.removeTerminalFromCache)(this._terminal)}))}get textureAtlas(){return this._charAtlas?.pages[0].canvas}_handleColorChange(){this._refreshCharAtlas(),this._clearModel(!0)}handleDevicePixelRatioChange(){this._devicePixelRatio!==this._coreBrowserService.dpr&&(this._devicePixelRatio=this._coreBrowserService.dpr,this.handleResize(this._terminal.cols,this._terminal.rows))}handleResize(t,e){this._updateDimensions(),this._model.resize(this._terminal.cols,this._terminal.rows),this._resetBlinkingRowState();for(const t of this._renderLayers)t.resize(this._terminal,this.dimensions);this._canvas.width=this.dimensions.device.canvas.width,this._canvas.height=this.dimensions.device.canvas.height,this._canvas.style.width=`${this.dimensions.css.canvas.width}px`,this._canvas.style.height=`${this.dimensions.css.canvas.height}px`,this._core.screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._core.screenElement.style.height=`${this.dimensions.css.canvas.height}px`,this._rectangleRenderer.value?.setDimensions(this.dimensions),this._rectangleRenderer.value?.handleResize(),this._glyphRenderer.value?.setDimensions(this.dimensions),this._glyphRenderer.value?.handleResize(),this._refreshCharAtlas(),this._clearModel(!1),this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1,sync:!0})}handleCharSizeChanged(){this.handleResize(this._terminal.cols,this._terminal.rows)}handleBlur(){for(const t of this._renderLayers)t.handleBlur(this._terminal);this._cursorBlinkStateManager.value?.pause(),this._requestRedrawViewport()}handleFocus(){for(const t of this._renderLayers)t.handleFocus(this._terminal);this._cursorBlinkStateManager.value?.resume(),this._requestRedrawViewport()}handleViewportVisibilityChange(t){this._textBlinkStateManager.setViewportVisible(t)}handleSelectionChanged(t,e,i){for(const s of this._renderLayers)s.handleSelectionChanged(this._terminal,t,e,i);this._model.selection.update(this._core,t,e,i),this._requestRedrawViewport()}handleCursorMove(){for(const t of this._renderLayers)t.handleCursorMove(this._terminal);this._cursorBlinkStateManager.value?.restartBlinkAnimation()}_handleOptionsChanged(){this._updateDimensions(),this._refreshCharAtlas(),this._updateCursorBlink()}_initializeWebGLState(){return this._rectangleRenderer.value=new d.RectangleRenderer(this._terminal,this._gl,this.dimensions,this._themeService,this._logService),this._glyphRenderer.value=new l.GlyphRenderer(this._terminal,this._gl,this.dimensions,this._optionsService,this._logService),this.handleCharSizeChanged(),[this._rectangleRenderer.value,this._glyphRenderer.value]}_refreshCharAtlas(){if(this.dimensions.device.char.width<=0&&this.dimensions.device.char.height<=0)return void(this._isAttached=!1);const t=(0,r.acquireTextureAtlas)(this._terminal,this._optionsService.rawOptions,this._themeService.colors,this.dimensions.device.cell.width,this.dimensions.device.cell.height,this.dimensions.device.char.width,this.dimensions.device.char.height,this._coreBrowserService.dpr,this._deviceMaxTextureSize,this._customGlyphs);this._charAtlas!==t&&(this._onChangeTextureAtlas.fire(t.pages[0].canvas),this._charAtlasDisposable.value=(0,p.combinedDisposable)(Q.EventUtils.forward(t.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas),Q.EventUtils.forward(t.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas))),this._charAtlas=t,this._charAtlas.warmUp(),this._glyphRenderer.value?.setAtlas(this._charAtlas)}_clearModel(t){this._model.clear(),t&&this._glyphRenderer.value?.clear()}clearTextureAtlas(){this._charAtlas?.clearTexture(),this._clearModel(!0),this._requestRedrawViewport()}clear(){this._clearModel(!0);for(const t of this._renderLayers)t.reset(this._terminal);this._resetBlinkingRowState(),this._textBlinkStateManager.setNeedsBlinkInViewport(!1),this._cursorBlinkStateManager.value?.restartBlinkAnimation(),this._updateCursorBlink()}renderRows(t,e){if(!this._isAttached){if(!(this._core.screenElement?.isConnected&&this._charSizeService.width&&this._charSizeService.height))return;this._updateDimensions(),this._refreshCharAtlas(),this._isAttached=!0}for(const i of this._renderLayers)i.handleGridChanged(this._terminal,t,e);if(!this._glyphRenderer.value||!this._rectangleRenderer.value)return;this._glyphRenderer.value.beginFrame()?(this._clearModel(!0),this._updateModel(0,this._terminal.rows-1)):this._updateModel(t,e);let i=!1,s=0;for(;this._charAtlas&&this._glyphRenderer.value.beginFrame()&&s++<32;)i=!0,this._clearModel(!0),this._updateModel(0,this._terminal.rows-1);i&&this._glyphRenderer.value.invalidateAtlasTextures(),this._rectangleRenderer.value.renderBackgrounds(),this._glyphRenderer.value.render(this._model),this._cursorBlinkStateManager.value&&!this._cursorBlinkStateManager.value.isCursorVisible||this._rectangleRenderer.value.renderCursor()}_updateCursorBlink(){this._coreService.decPrivateModes.cursorBlink??this._terminal.options.cursorBlink?this._cursorBlinkStateManager.value=new a.CursorBlinkStateManager(()=>{this._requestRedrawCursor()},this._coreBrowserService):this._cursorBlinkStateManager.clear(),this._requestRedrawCursor()}_updateModel(t,e){const i=this._core;let s,r,a,o,n,L,T,l,d,_,Q,u,p,g,M,f,C,m=this._workCell;t=v(t,i.rows-1,0),e=v(e,i.rows-1,0);const w=this._coreService.decPrivateModes.cursorStyle??i.options.cursorStyle??"block",x=this._terminal.buffer.active.baseY+this._terminal.buffer.active.cursorY,b=x-i.buffer.ydisp,E=Math.min(this._terminal.buffer.active.cursorX,i.cols-1);let R=-1;const k=this._coreService.isCursorInitialized&&!this._coreService.isCursorHidden&&(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible);this._model.cursor=void 0;let A=!1;for(r=t;r<=e;r++){a=r+i.buffer.ydisp;const t=i.buffer.lines.get(a);if(!t){for(this._model.lineLengths[r]=0,f=0;f=T,d=f,n.length>0&&f===n[0][0]&&l){_=n.shift();const t=this._model.selection.isCellSelected(this._terminal,_[0],a);for(M=_[0]+1;M<_[1];M++)l&&=t===this._model.selection.isCellSelected(this._terminal,M,a);l&&=!Q||E<_[0]||E>=_[1],l?(L=!0,m=new y(m,o.translateToString(!0,_[0],_[1]),_[1]-_[0]),d=_[1]-1):T=_[1]}if(u=m.getChars(),p=m.getCode(),M=4*(r*i.cols+f),!e&&m.isBlink()&&(e=!0),this._cellColorResolver.resolve(m,f,a,this.dimensions.device.cell.width,this.dimensions.device.cell.height),k&&a===x&&(f===E&&(this._model.cursor={x:E,y:b,width:m.getWidth(),style:this._coreBrowserService.isFocused?w:i.options.cursorInactiveStyle,cursorWidth:i.options.cursorWidth,dpr:this._devicePixelRatio},R=E+m.getWidth()-1),f>=E&&f<=R&&(this._coreBrowserService.isFocused&&"block"===w||!1===this._coreBrowserService.isFocused&&"block"===i.options.cursorInactiveStyle)&&(this._cellColorResolver.result.fg=50331648|this._themeService.colors.cursorAccent.rgba>>8&16777215,this._cellColorResolver.result.bg=50331648|this._themeService.colors.cursor.rgba>>8&16777215)),this._textBlinkStateManager.isEnabled&&!this._textBlinkStateManager.isBlinkOn&&m.isBlink()&&(this._cellColorResolver.result.fg|=1073741824),p!==h.NULL_CELL_CODE&&(this._model.lineLengths[r]=f+1),(this._model.cells[M]!==p||this._model.cells[M+1]!==this._cellColorResolver.result.bg||this._model.cells[M+2]!==this._cellColorResolver.result.fg||this._model.cells[M+3]!==this._cellColorResolver.result.ext)&&(A=!0,u.length>1&&(p|=c.COMBINED_CHAR_BIT_MASK),this._model.cells[M]=p,this._model.cells[M+1]=this._cellColorResolver.result.bg,this._model.cells[M+2]=this._cellColorResolver.result.fg,this._model.cells[M+3]=this._cellColorResolver.result.ext,g=m.getWidth(),this._glyphRenderer.value.updateCell(f,r,p,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext,u,g,s),L)){for(m=this._workCell,f++;f<=d;f++)C=4*(r*i.cols+f),this._nullModelCell(f,r,C,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext);f--}}this._setRowBlinkState(r,e)}A&&this._rectangleRenderer.value.updateBackgrounds(this._model),this._rectangleRenderer.value.updateCursor(this._model),this._updateTextBlinkState()}_nullModelCell(t,e,i,s,r,a){this._glyphRenderer.value.updateCell(t,e,h.NULL_CELL_CODE,s,r,a,h.NULL_CELL_CHAR,0,0),this._model.cells[i]=h.NULL_CELL_CODE,this._model.cells[i+1]=s,this._model.cells[i+2]=r,this._model.cells[i+3]=a}_resetBlinkingRowState(){this._rowHasBlinkingCells=new Array(this._terminal.rows).fill(!1),this._rowHasBlinkingCellsCount=0}_setRowBlinkState(t,e){this._rowHasBlinkingCells[t]!==e&&(this._rowHasBlinkingCells[t]=e,this._rowHasBlinkingCellsCount+=e?1:-1)}_updateTextBlinkState(){this._textBlinkStateManager.setNeedsBlinkInViewport(this._rowHasBlinkingCellsCount>0)}_updateDimensions(){this._charSizeService.width&&this._charSizeService.height&&(this.dimensions.device.char.width=Math.floor(this._charSizeService.width*this._devicePixelRatio),this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*this._devicePixelRatio),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.top=1===this._optionsService.rawOptions.lineHeight?0:Math.round((this.dimensions.device.cell.height-this.dimensions.device.char.height)/2),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.char.left=Math.floor(this._optionsService.rawOptions.letterSpacing/2),this.dimensions.device.canvas.height=this._terminal.rows*this.dimensions.device.cell.height,this.dimensions.device.canvas.width=this._terminal.cols*this.dimensions.device.cell.width,this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/this._devicePixelRatio),this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/this._devicePixelRatio),this.dimensions.css.cell.height=this.dimensions.device.cell.height/this._devicePixelRatio,this.dimensions.css.cell.width=this.dimensions.device.cell.width/this._devicePixelRatio)}_setCanvasDevicePixelDimensions(t,e){this._canvas.width===t&&this._canvas.height===e||(this._canvas.width=t,this._canvas.height=e,this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1,sync:!0}))}_requestRedrawViewport(){this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1})}_requestRedrawCursor(){const t=this._terminal.buffer.active.cursorY;this._onRequestRedraw.fire({start:t,end:t})}}e.WebglRenderer=M;class y extends n.AttributeData{constructor(t,e,i){super(),this.content=0,this.combinedData="",this.fg=t.fg,this.bg=t.bg,this.combinedData=e,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(t){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}function v(t,e,i=0){return Math.max(Math.min(t,e),i)}e.JoinedCellData=y},719(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.GLTexture=e.PROJECTION_MATRIX=void 0,e.createProgram=function(t,e,i,a){const o=(0,s.throwIfFalsy)(t.createProgram());if(t.attachShader(o,(0,s.throwIfFalsy)(r(t,t.VERTEX_SHADER,e,a))),t.attachShader(o,(0,s.throwIfFalsy)(r(t,t.FRAGMENT_SHADER,i,a))),t.linkProgram(o),t.getProgramParameter(o,t.LINK_STATUS))return o;a.error(t.getProgramInfoLog(o)),t.deleteProgram(o)},e.createShader=r,e.expandFloat32Array=function(t,e){const i=Math.min(2*t.length,e),s=new Float32Array(i);for(let e=0;e{const e=[],i=[3/8,2/8,3/8],s=[0,3/8,5/8];for(let r=0;r<3;r++){const a=t>>2*r&1,o=t>>2*r+1&1;a&&o?e.push(`M0,${s[r]} L1,${s[r]} L1,${s[r]+i[r]} L0,${s[r]+i[r]} Z`):a?e.push(`M0,${s[r]} L0.5,${s[r]} L0.5,${s[r]+i[r]} L0,${s[r]+i[r]} Z`):o&&e.push(`M0.5,${s[r]} L1,${s[r]} L1,${s[r]+i[r]} L0.5,${s[r]+i[r]} Z`)}return e.join(" ")}}}function r(t){const e=[],i=.15,s=.015,r=.075,a=.0375,o=.95;if(64&t){const t=.175,a=.2125,n=.25,L=.2+s,h=o-i-s;e.push(`M${L},${a} L${L+r},${t} L${h-r},${t} L${h},${a} L${h-r},${n} L${L+r},${n} Z`)}if(32&t){const t=o-i,s=.875,r=o,n=.265,L=.485;e.push(`M${s},${n} L${r},${n+a} L${r},${L-a} L${s},${L} L${t},${L-a} L${t},${n+a} Z`)}if(16&t){const t=o-i,s=.875,r=o,n=.515,L=.735;e.push(`M${s},${n} L${r},${n+a} L${r},${L-a} L${s},${L} L${t},${L-a} L${t},${n+a} Z`)}if(8&t){const t=.75,a=.7875,n=.825,L=.2+s,h=o-i-s;e.push(`M${L},${a} L${L+r},${t} L${h-r},${t} L${h},${a} L${h-r},${n} L${L+r},${n} Z`)}if(4&t){const t=.05,i=.125,s=.2,r=.515,o=.735;e.push(`M${i},${r} L${s},${r+a} L${s},${o-a} L${i},${o} L${t},${o-a} L${t},${r+a} Z`)}if(2&t){const t=.05,i=.125,s=.2,r=.265,o=.485;e.push(`M${i},${r} L${s},${r+a} L${s},${o-a} L${i},${o} L${t},${o-a} L${t},${r+a} Z`)}if(1&t){const t=.4625,a=.5,n=.5375,L=.2+s,h=o-i-s;e.push(`M${L},${a} L${L+r},${t} L${h-r},${t} L${h},${a} L${h-r},${n} L${L+r},${n} Z`)}return e.join(" ")}Object.defineProperty(e,"__esModule",{value:!0}),e.blockPatternCodepoints=e.customGlyphDefinitions=void 0,function(t){t.LINE_H=Object.freeze({type:2,data:"M0,.5 L1,.5",strokeWidth:1}),t.LINE_V=Object.freeze({type:2,data:"M.5,0 L.5,1",strokeWidth:1}),t.FADE_RIGHT=Object.freeze({type:2,data:"M0,.5 L.28,.5 M.32,.5 L.52,.5 M.60,.5 L.72,.5 M.84,.5 L.90,.5",strokeWidth:1}),t.FADE_LEFT=Object.freeze({type:2,data:"M.10,.5 L.16,.5 M.28,.5 L.40,.5 M.48,.5 L.68,.5 M.72,.5 L1,.5",strokeWidth:1}),t.FADE_DOWN=Object.freeze({type:2,data:"M.5,0 L.5,.28 M.5,.32 L.5,.52 M.5,.60 L.5,.72 M.5,.84 L.5,.90",strokeWidth:1}),t.FADE_UP=Object.freeze({type:2,data:"M.5,.10 L.5,.16 M.5,.28 L.5,.40 M.5,.48 L.5,.68 M.5,.72 L.5,1",strokeWidth:1}),t.CURVE_DOWN_RIGHT=Object.freeze({type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,1,.5`,strokeWidth:1}),t.CURVE_DOWN_LEFT=Object.freeze({type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,0,.5`,strokeWidth:1}),t.CURVE_UP_RIGHT=Object.freeze({type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,1,.5`,strokeWidth:1}),t.CURVE_UP_LEFT=Object.freeze({type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,0,.5`,strokeWidth:1}),t.NODE_FILL=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5"}),t.NODE_STROKE=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5",strokeWidth:1}),t.NODE_LINE_RIGHT=Object.freeze({type:3,data:"M1,.5 L.85,.5",strokeWidth:1}),t.NODE_LINE_LEFT=Object.freeze({type:3,data:"M0,.5 L.15,.5",strokeWidth:1}),t.NODE_LINE_DOWN=Object.freeze({type:3,data:"M.5,1 L.5,.7",strokeWidth:1}),t.NODE_LINE_UP=Object.freeze({type:3,data:"M.5,0 L.5,.3",strokeWidth:1})}(i||(i={})),e.customGlyphDefinitions={"─":{type:2,data:"M0,.5 L1,.5",strokeWidth:1},"━":{type:2,data:"M0,.5 L1,.5",strokeWidth:3},"│":{type:2,data:"M.5,0 L.5,1",strokeWidth:1},"┃":{type:2,data:"M.5,0 L.5,1",strokeWidth:3},"┄":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:1},"┅":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:3},"┆":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:1},"┇":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:3},"┈":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:1},"┉":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:3},"┊":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:1},"┋":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:3},"┌":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},"┍":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┎":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┏":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3},"┐":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},"┑":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┒":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┓":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3},"└":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},"┕":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┖":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┗":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3},"┘":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},"┙":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┚":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┛":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3},"├":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},"┝":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┞":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┟":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┠":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"┡":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"┢":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"┣":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3},"┤":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},"┥":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┦":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┧":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┨":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"┩":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"┪":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"┫":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3},"┬":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},"┭":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┮":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┯":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"┰":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┱":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"┲":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"┳":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3},"┴":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:1},"┵":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┶":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┷":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"┸":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┹":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"┺":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"┻":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:3},"┼":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:1},"┽":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┾":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┿":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"╀":[{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"╁":[{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"╂":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"╃":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"╄":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"╅":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"╆":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"╇":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:3}],"╈":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3}],"╉":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3}],"╊":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3}],"╋":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:3},"╌":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:1},"╍":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:3},"╎":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:1},"╏":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:3},"═":{type:2,data:(t,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"║":{type:2,data:(t,e)=>`M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1`,strokeWidth:1},"╒":{type:2,data:(t,e)=>`M.5,1 L.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"╓":{type:2,data:(t,e)=>`M${.5-t},1 L${.5-t},.5 L1,.5 M${.5+t},.5 L${.5+t},1`,strokeWidth:1},"╔":{type:2,data:(t,e)=>`M1,${.5-e} L${.5-t},${.5-e} L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1`,strokeWidth:1},"╕":{type:2,data:(t,e)=>`M0,${.5-e} L.5,${.5-e} L.5,1 M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"╖":{type:2,data:(t,e)=>`M${.5+t},1 L${.5+t},.5 L0,.5 M${.5-t},.5 L${.5-t},1`,strokeWidth:1},"╗":{type:2,data:(t,e)=>`M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M0,${.5-e} L${.5+t},${.5-e} L${.5+t},1`,strokeWidth:1},"╘":{type:2,data:(t,e)=>`M.5,0 L.5,${.5+e} L1,${.5+e} M.5,${.5-e} L1,${.5-e}`,strokeWidth:1},"╙":{type:2,data:(t,e)=>`M1,.5 L${.5-t},.5 L${.5-t},0 M${.5+t},.5 L${.5+t},0`,strokeWidth:1},"╚":{type:2,data:(t,e)=>`M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0 M1,${.5+e} L${.5-t},${.5+e} L${.5-t},0`,strokeWidth:1},"╛":{type:2,data:(t,e)=>`M0,${.5+e} L.5,${.5+e} L.5,0 M0,${.5-e} L.5,${.5-e}`,strokeWidth:1},"╜":{type:2,data:(t,e)=>`M0,.5 L${.5+t},.5 L${.5+t},0 M${.5-t},.5 L${.5-t},0`,strokeWidth:1},"╝":{type:2,data:(t,e)=>`M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0 M0,${.5+e} L${.5+t},${.5+e} L${.5+t},0`,strokeWidth:1},"╞":{type:2,data:(t,e)=>`M.5,0 L.5,1 M.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"╟":{type:2,data:(t,e)=>`M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1 M${.5+t},.5 L1,.5`,strokeWidth:1},"╠":{type:2,data:(t,e)=>`M${.5-t},0 L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1 M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0`,strokeWidth:1},"╡":{type:2,data:(t,e)=>`M.5,0 L.5,1 M0,${.5-e} L.5,${.5-e} M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"╢":{type:2,data:(t,e)=>`M0,.5 L${.5-t},.5 M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1`,strokeWidth:1},"╣":{type:2,data:(t,e)=>`M${.5+t},0 L${.5+t},1 M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0`,strokeWidth:1},"╤":{type:2,data:(t,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e} M.5,${.5+e} L.5,1`,strokeWidth:1},"╥":{type:2,data:(t,e)=>`M0,.5 L1,.5 M${.5-t},.5 L${.5-t},1 M${.5+t},.5 L${.5+t},1`,strokeWidth:1},"╦":{type:2,data:(t,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1`,strokeWidth:1},"╧":{type:2,data:(t,e)=>`M.5,0 L.5,${.5-e} M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"╨":{type:2,data:(t,e)=>`M0,.5 L1,.5 M${.5-t},.5 L${.5-t},0 M${.5+t},.5 L${.5+t},0`,strokeWidth:1},"╩":{type:2,data:(t,e)=>`M0,${.5+e} L1,${.5+e} M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0 M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0`,strokeWidth:1},"╪":{type:2,data:(t,e)=>`M.5,0 L.5,1 M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"╫":{type:2,data:(t,e)=>`M0,.5 L1,.5 M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1`,strokeWidth:1},"╬":{type:2,data:(t,e)=>`M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1 M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0 M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0`,strokeWidth:1},"╭":{type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"╮":{type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"╯":{type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"╰":{type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"╱":{type:2,data:"M1,0 L0,1",strokeWidth:1},"╲":{type:2,data:"M0,0 L1,1",strokeWidth:1},"╳":{type:2,data:"M1,0 L0,1 M0,0 L1,1",strokeWidth:1},"╴":{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},"╵":{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},"╶":{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},"╷":{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},"╸":{type:2,data:"M.5,.5 L0,.5",strokeWidth:3},"╹":{type:2,data:"M.5,.5 L.5,0",strokeWidth:3},"╺":{type:2,data:"M.5,.5 L1,.5",strokeWidth:3},"╻":{type:2,data:"M.5,.5 L.5,1",strokeWidth:3},"╼":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"╽":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"╾":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"╿":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"▀":{type:0,data:[{x:0,y:0,w:8,h:4}]},"▁":{type:0,data:[{x:0,y:7,w:8,h:1}]},"▂":{type:0,data:[{x:0,y:6,w:8,h:2}]},"▃":{type:0,data:[{x:0,y:5,w:8,h:3}]},"▄":{type:0,data:[{x:0,y:4,w:8,h:4}]},"▅":{type:0,data:[{x:0,y:3,w:8,h:5}]},"▆":{type:0,data:[{x:0,y:2,w:8,h:6}]},"▇":{type:0,data:[{x:0,y:1,w:8,h:7}]},"█":{type:0,data:[{x:0,y:0,w:8,h:8}]},"▉":{type:0,data:[{x:0,y:0,w:7,h:8}]},"▊":{type:0,data:[{x:0,y:0,w:6,h:8}]},"▋":{type:0,data:[{x:0,y:0,w:5,h:8}]},"▌":{type:0,data:[{x:0,y:0,w:4,h:8}]},"▍":{type:0,data:[{x:0,y:0,w:3,h:8}]},"▎":{type:0,data:[{x:0,y:0,w:2,h:8}]},"▏":{type:0,data:[{x:0,y:0,w:1,h:8}]},"▐":{type:0,data:[{x:4,y:0,w:4,h:8}]},"░":{type:1,data:[[1,0],[0,0]]},"▒":{type:1,data:[[1,0],[0,1]]},"▓":{type:1,data:[[1,1],[1,0]]},"▔":{type:0,data:[{x:0,y:0,w:8,h:1}]},"▕":{type:0,data:[{x:7,y:0,w:1,h:8}]},"▖":{type:0,data:[{x:0,y:4,w:4,h:4}]},"▗":{type:0,data:[{x:4,y:4,w:4,h:4}]},"▘":{type:0,data:[{x:0,y:0,w:4,h:4}]},"▙":{type:0,data:[{x:0,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"▚":{type:0,data:[{x:0,y:0,w:4,h:4},{x:4,y:4,w:4,h:4}]},"▛":{type:0,data:[{x:0,y:0,w:4,h:8},{x:4,y:0,w:4,h:4}]},"▜":{type:0,data:[{x:0,y:0,w:8,h:4},{x:4,y:0,w:4,h:8}]},"▝":{type:0,data:[{x:4,y:0,w:4,h:4}]},"▞":{type:0,data:[{x:4,y:0,w:4,h:4},{x:0,y:4,w:4,h:4}]},"▟":{type:0,data:[{x:4,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"":{type:5,data:{d:"M.3,1 L.03,1 L.03,.88 C.03,.82,.06,.78,.11,.73 C.15,.7,.2,.68,.28,.65 L.43,.6 C.49,.58,.53,.56,.56,.53 C.59,.5,.6,.47,.6,.43 L.6,.27 L.4,.27 L.69,.1 L.98,.27 L.78,.27 L.78,.46 C.78,.52,.76,.56,.72,.61 C.68,.66,.63,.67,.56,.7 L.48,.72 C.42,.74,.38,.76,.35,.78 C.32,.8,.31,.84,.31,.88 L.31,1 M.3,.5 L.03,.59 L.03,.09 L.3,.09 L.3,.655",type:0}},"":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.355,.03 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"":{type:5,data:{d:"M.25,.94 C.16,.94,.11,.92,.11,.87 L.11,.53 C.11,.48,.15,.455,.23,.45 L.23,.3 C.23,.25,.26,.22,.31,.19 C.36,.16,.43,.15,.51,.15 C.59,.15,.66,.16,.71,.19 C.77,.22,.79,.26,.79,.3 L.79,.45 C.87,.45,.91,.48,.91,.53 L.91,.87 C.91,.92,.86,.94,.77,.94 L.24,.94 M.53,.2 C.49,.2,.45,.21,.42,.23 C.39,.25,.38,.27,.38,.3 L.38,.45 L.68,.45 L.68,.3 C.68,.27,.67,.25,.64,.23 C.61,.21,.58,.2,.53,.2 M.58,.82 L.58,.66 C.63,.65,.65,.63,.65,.6 C.65,.58,.64,.57,.61,.56 C.58,.55,.56,.54,.52,.54 C.48,.54,.46,.55,.43,.56 C.4,.57,.39,.59,.39,.6 C.39,.63,.41,.64,.46,.66 L.46,.82 L.57,.82",type:0}},"":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.7,.03 L.7,.1 L.355,.1 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"":{type:5,data:{d:"M0,0 L1,.5 L0,1",type:0,rightPadding:2}},"":{type:5,data:{d:"M-1,-.5 L1,.5 L-1,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M1,0 L0,.5 L1,1",type:0,leftPadding:2}},"":{type:5,data:{d:"M2,-.5 L0,.5 L2,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M0,0 L0,1 C0.552,1,1,0.776,1,.5 C1,0.224,0.552,0,0,0",type:0,rightPadding:1}},"":{type:5,data:{d:"M.2,1 C.422,1,.8,.826,.78,.5 C.8,.174,0.422,0,.2,0",type:1,rightPadding:1}},"":{type:5,data:{d:"M1,0 L1,1 C0.448,1,0,0.776,0,.5 C0,0.224,0.448,0,1,0",type:0,leftPadding:1}},"":{type:5,data:{d:"M.8,1 C0.578,1,0.2,.826,.22,.5 C0.2,0.174,0.578,0,0.8,0",type:1,leftPadding:1}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L-.5,1.5",type:0}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L1.5,1.5",type:0}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L-.5,-.5",type:0}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L1.5,-.5",type:0}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M0.8069,0.6075 Q0.7991,0.612,0.7815,0.6218 T0.7542,0.6369 T0.7282,0.6508 T0.7016,0.6644 T0.6778,0.6758 T0.6551,0.6854 T0.637,0.6911 T0.622,0.6936 Q0.6186,0.6936,0.6128,0.6942 T0.6018,0.6952 T0.5894,0.6956 T0.5757,0.6952 T0.561,0.693 T0.5451,0.6879 Q0.5342,0.6834,0.5193,0.6756 T0.4925,0.6614 T0.4673,0.6485 T0.4436,0.6389 T0.4239,0.6363 T0.4089,0.6422 Q0.4045,0.6467,0.3958,0.6554 T0.3843,0.6669 T0.3748,0.6746 T0.3613,0.683 T0.3442,0.6903 L0.3499,0.6956 Q0.3584,0.7042,0.3679,0.7177 T0.3836,0.7403 T0.4019,0.7583 T0.4295,0.7703 Q0.4688,0.7785,0.5203,0.7605 Q0.4902,0.7817,0.449,0.7911 T0.3696,0.8001 Q0.3567,0.7997,0.341,0.7942 T0.3111,0.7813 T0.2805,0.766 T0.2493,0.753 T0.218,0.7472 T0.187,0.754 Q0.1762,0.7589,0.1653,0.7681 T0.1453,0.7895 T0.1308,0.818 T0.1264,0.8507 L0.1264,0.858 Q0.1453,0.8462,0.1607,0.8433 T0.1899,0.8452 T0.2226,0.8625 Q0.2344,0.8707,0.2485,0.8752 T0.2813,0.8831 T0.3089,0.889 Q0.2981,0.8915,0.2846,0.8956 T0.2603,0.9037 T0.2368,0.9115 T0.2129,0.9174 T0.1894,0.9194 T0.1653,0.9155 Q0.1504,0.9115,0.1328,0.9196 T0.0986,0.9421 T0.0655,0.9708 T0.0317,0.9943 T0,1 Q0.001,0.94,0.0017,0.6508 T0.0024,0.2322 Q0.002,0.2109,0.0007,0.1379 T0,0.0249 Q0.0058,0.0253,0.009,0.0257 T0.0156,0.0288 T0.0203,0.0333 T0.0264,0.0422 T0.0349,0.0539 Q0.044,0.0657,0.0542,0.072 T0.0752,0.0789 T0.096,0.0775 T0.1175,0.0694 T0.1379,0.0573 T0.1579,0.0432 Q0.2141,0,0.2673,0.0318 Q0.2588,0.0318,0.2517,0.033 T0.239,0.0361 T0.2276,0.0424 T0.218,0.0504 T0.2085,0.0612 T0.1997,0.0732 T0.1899,0.0875 T0.1795,0.1028 Q0.1748,0.1093,0.1507,0.1234 T0.1186,0.1448 Q0.0999,0.1612,0.1108,0.1783 Q0.1162,0.1877,0.1238,0.1928 T0.1404,0.1979 T0.158,0.1967 T0.1775,0.1895 T0.1963,0.1791 T0.2151,0.1663 T0.2314,0.1534 T0.2458,0.141 T0.2561,0.1322 Q0.2815,0.1106,0.3017,0.101 T0.344,0.0926 T0.3919,0.1077 Q0.4099,0.1175,0.4265,0.1206 T0.4588,0.1202 T0.488,0.1098 T0.5176,0.0914 Q0.5071,0.1032,0.4963,0.1122 T0.4722,0.1285 T0.4497,0.1401 T0.4223,0.1518 T0.3943,0.1636 Q0.374,0.1726,0.3623,0.1863 T0.3482,0.2162 Q0.3445,0.2403,0.3608,0.2605 T0.4072,0.2876 Q0.4194,0.2909,0.4326,0.2899 T0.457,0.2856 T0.4805,0.2764 T0.5032,0.264 T0.5256,0.2497 T0.5478,0.2352 T0.5698,0.2222 T0.5921,0.2118 Q0.6982,0.173,0.81,0.2436 Q0.833,0.2583,0.8496,0.2674 T0.887,0.2846 T0.925,0.294 T0.9617,0.2911 T1,0.2746 Q0.9817,0.2946,0.96,0.3056 T0.9175,0.3191 T0.8731,0.3209 T0.8277,0.3164 T0.7818,0.3109 T0.7359,0.3101 T0.6907,0.3197 T0.647,0.3448 Q0.6443,0.3472,0.6333,0.3562 T0.6194,0.3674 T0.6076,0.3766 T0.594,0.386 T0.5815,0.3931 T0.5661,0.4007 T0.5501,0.4064 L0.5556,0.4121 Q0.5627,0.4198,0.5722,0.4251 T0.5926,0.4337 T0.6131,0.439 T0.6343,0.4431 T0.6521,0.4468 Q0.6762,0.4529,0.7056,0.4463 Q0.6772,0.4623,0.6543,0.471 T0.604,0.4814 Q0.5962,0.4818,0.5815,0.4825 T0.5591,0.4835 T0.5393,0.4857 T0.519,0.4908 T0.5007,0.4996 T0.4812,0.5141 T0.4627,0.5353 L0.4549,0.5451 L0.4661,0.543 Q0.4759,0.541,0.4909,0.55 T0.5315,0.5796 T0.5684,0.6083 Q0.5799,0.6161,0.5915,0.6212 T0.6181,0.6308 L0.6331,0.6353 Q0.6514,0.6418,0.7004,0.633 T0.8069,0.6075 Z",type:0}},"":{type:5,data:{d:"M0.011,0.0469 Q0.0152,0.0412,0.02,0.0361 T0.0292,0.0281 T0.0365,0.0253 Q0.0426,0.0257,0.0461,0.0263 T0.0534,0.03 T0.0582,0.0345 T0.0645,0.0434 T0.0723,0.0546 Q0.0807,0.0653,0.0897,0.0712 T0.1081,0.0775 T0.1255,0.0765 T0.1438,0.0695 T0.1605,0.0593 T0.1772,0.0473 Q0.2388,0,0.2927,0.0326 L0.2614,0.0767 L0.2581,0.0767 Q0.2494,0.0767,0.2444,0.0773 T0.2359,0.0789 T0.2291,0.0842 T0.2233,0.0922 T0.2146,0.1054 T0.2026,0.1236 Q0.1943,0.1354,0.1843,0.1444 T0.1675,0.1574 T0.1526,0.1654 T0.1429,0.1701 Q0.1436,0.1717,0.1446,0.1733 Q0.1504,0.1823,0.1581,0.1866 T0.1733,0.1915 T0.1909,0.1884 T0.2085,0.1809 T0.2265,0.169 T0.2427,0.1564 T0.2575,0.1436 T0.2688,0.1338 Q0.2969,0.1101,0.3195,0.0995 T0.3643,0.0901 T0.4114,0.1048 Q0.4279,0.1138,0.4426,0.1168 T0.4705,0.117 T0.4945,0.1089 T0.5186,0.0942 L0.5211,0.0926 L0.5289,0.0922 Q0.5411,0.095,0.5189,0.1203 Q0.505,0.1358,0.4913,0.1474 T0.4634,0.167 T0.4389,0.1796 T0.4121,0.1909 T0.3866,0.2011 Q0.3782,0.2047,0.3727,0.2092 Q0.3717,0.2117,0.3714,0.2141 Q0.3695,0.2263,0.3751,0.2388 T0.394,0.2616 T0.4253,0.2761 Q0.4398,0.2785,0.4513,0.2779 T0.4756,0.2724 T0.4987,0.2616 T0.5216,0.2476 T0.5453,0.2321 T0.5703,0.217 T0.5976,0.2043 Q0.7015,0.166,0.8099,0.2345 Q0.8361,0.2512,0.8572,0.2616 T0.9006,0.2779 T0.9432,0.281 T0.9819,0.2663 L0.9887,0.2671 Q1,0.272,0.9768,0.2969 Q0.9558,0.3193,0.9319,0.333 T0.8858,0.3513 T0.8391,0.3569 T0.793,0.3546 T0.7485,0.3497 T0.7065,0.3473 T0.6681,0.3522 T0.6344,0.3699 Q0.5963,0.4005,0.5847,0.4082 Q0.595,0.4139,0.6079,0.4174 T0.6367,0.4237 T0.6586,0.4278 Q0.6793,0.4331,0.7044,0.4278 Q0.7057,0.4278,0.707,0.4274 Q0.7067,0.429,0.7062,0.4313 T0.7036,0.4398 T0.6993,0.4513 T0.6931,0.4619 T0.6851,0.4698 Q0.6573,0.4857,0.6336,0.4947 T0.5831,0.5053 Q0.577,0.5057,0.5615,0.5065 T0.5394,0.508 T0.5221,0.51 T0.5042,0.5139 T0.4905,0.5204 Q0.5008,0.5232,0.515,0.5328 T0.549,0.5585 T0.5799,0.5824 Q0.5905,0.5897,0.6013,0.5946 T0.6262,0.6036 T0.6409,0.6081 Q0.6567,0.6134,0.7035,0.605 T0.8028,0.5816 L0.7974,0.5922 T0.7867,0.6134 L0.7812,0.624 Q0.7799,0.6248,0.7786,0.6252 Q0.7709,0.6297,0.7573,0.6372 T0.7346,0.6499 T0.7123,0.6621 T0.6897,0.6741 T0.6686,0.6847 T0.648,0.6941 T0.6297,0.7013 T0.6129,0.7062 T0.5995,0.7076 Q0.5992,0.7076,0.5831,0.7092 T0.5529,0.7092 T0.525,0.7019 Q0.5105,0.6958,0.4824,0.6811 T0.4356,0.6586 T0.4079,0.6533 Q0.3872,0.6741,0.3827,0.6782 Q0.3872,0.6835,0.3934,0.6929 T0.4037,0.7078 T0.4142,0.7198 T0.4284,0.7304 T0.4466,0.7365 Q0.4824,0.7443,0.5292,0.728 L0.5292,0.7294 T0.529,0.7333 T0.5284,0.7392 T0.5266,0.7463 T0.5236,0.7539 T0.5186,0.7612 T0.5111,0.7679 Q0.5086,0.77,0.5056,0.7716 Q0.4466,0.8104,0.3591,0.8091 Q0.344,0.8091,0.3246,0.802 T0.2893,0.7863 T0.2543,0.77 T0.2206,0.76 T0.1894,0.7643 Q0.1804,0.7684,0.1733,0.7753 Q0.1591,0.7892,0.1601,0.8169 Q0.1784,0.8067,0.1938,0.8053 T0.2212,0.8087 T0.2507,0.825 Q0.2614,0.8324,0.2744,0.8365 T0.3053,0.844 T0.332,0.8499 L0.303,0.894 L0.2998,0.8948 Q0.2904,0.8968,0.278,0.9009 T0.2554,0.9086 T0.233,0.9158 T0.2099,0.9213 T0.1868,0.9229 T0.1633,0.9192 Q0.1517,0.916,0.1367,0.9241 T0.1065,0.9462 T0.0753,0.9737 T0.041,0.9955 T0.0061,1 Q0,0.9984,0.0068,0.9845 Q0.009,0.9804,0.0123,0.9755 Q0.0187,0.9666,0.0261,0.9606 T0.0374,0.9555 Q0.0481,0.958,0.0629,0.949 T0.0931,0.9262 T0.1247,0.8987 T0.1597,0.8777 T0.1949,0.8752 Q0.213,0.8805,0.2343,0.8772 Q0.2249,0.8736,0.2172,0.8683 Q0.1914,0.8511,0.1738,0.8497 T0.1349,0.8617 Q0.1304,0.865,0.1273,0.8646 T0.1242,0.8605 L0.1239,0.8536 Q0.1226,0.8295,0.1354,0.8016 T0.1723,0.7496 Q0.1914,0.7308,0.2104,0.7219 Q0.2259,0.7145,0.2425,0.7141 T0.273,0.7182 T0.3022,0.7296 T0.3301,0.7439 T0.3569,0.7571 T0.3821,0.7643 Q0.373,0.7561,0.3598,0.7367 T0.3382,0.7088 L0.3327,0.7035 Q0.3282,0.699,0.3353,0.6884 T0.3517,0.6692 L0.3611,0.6607 Q0.3711,0.657,0.3751,0.6554 T0.3837,0.6507 T0.3898,0.6458 T0.3979,0.637 T0.4111,0.6236 Q0.4172,0.6175,0.4234,0.6138 Q0.4327,0.6081,0.4439,0.6077 T0.4655,0.6105 T0.4884,0.6201 T0.5113,0.633 T0.5347,0.6468 T0.5573,0.6578 Q0.5705,0.6635,0.5833,0.665 T0.6112,0.665 T0.6286,0.6635 Q0.6421,0.6631,0.6718,0.6501 Q0.626,0.6578,0.6089,0.6517 Q0.6063,0.6509,0.6002,0.6491 T0.5884,0.6454 T0.5757,0.6409 T0.561,0.6344 T0.5466,0.6256 Q0.536,0.6183,0.5108,0.5989 T0.4722,0.5712 T0.4527,0.564 L0.4418,0.5661 Q0.4308,0.5681,0.4366,0.5563 Q0.4401,0.5485,0.4476,0.5392 L0.455,0.5298 Q0.4631,0.5188,0.4714,0.51 T0.4866,0.4947 T0.5021,0.4831 T0.516,0.4749 T0.53,0.4694 T0.5428,0.4657 T0.5558,0.4637 T0.5674,0.4629 T0.5795,0.4625 Q0.5489,0.4543,0.534,0.4384 L0.5286,0.4327 Q0.5244,0.4282,0.5318,0.4174 T0.5486,0.398 L0.5579,0.3899 Q0.567,0.387,0.5749,0.3834 T0.5878,0.3772 T0.6012,0.3687 T0.6126,0.3603 T0.6268,0.3487 T0.6421,0.3361 Q0.6567,0.3242,0.6712,0.3159 T0.7009,0.3034 T0.7277,0.2973 T0.7556,0.2961 T0.7809,0.2977 T0.8074,0.301 Q0.8096,0.3014,0.8109,0.3016 T0.8143,0.302 T0.818,0.3026 Q0.8012,0.2936,0.7767,0.2781 Q0.6718,0.2117,0.5744,0.2476 Q0.5637,0.2516,0.5492,0.2604 T0.5218,0.2779 T0.4923,0.2965 T0.461,0.3124 T0.4282,0.3216 T0.394,0.3206 Q0.3637,0.3136,0.3474,0.2936 T0.3353,0.2459 Q0.3385,0.2247,0.355,0.2023 Q0.3646,0.1892,0.3763,0.179 Q0.3898,0.1672,0.4063,0.1595 Q0.3927,0.1562,0.3785,0.1485 Q0.3604,0.1387,0.3453,0.1354 T0.3161,0.1354 T0.2899,0.1458 T0.2627,0.166 Q0.262,0.1664,0.254,0.1733 T0.2414,0.1841 T0.2267,0.196 T0.2094,0.2086 T0.1915,0.2196 T0.1725,0.2288 T0.1546,0.2337 T0.1373,0.2343 T0.1223,0.228 T0.1097,0.2145 Q0.0962,0.1929,0.1258,0.1582 Q0.131,0.1517,0.1371,0.1464 Q0.1462,0.1387,0.156,0.1321 T0.1752,0.1205 T0.1878,0.1134 Q0.1891,0.1117,0.1947,0.103 T0.2035,0.0899 T0.2125,0.0781 T0.2243,0.064 Q0.1949,0.0616,0.1672,0.0828 Q0.153,0.0934,0.1412,0.1009 T0.1146,0.1146 T0.0873,0.1213 T0.0616,0.116 T0.0374,0.0962 Q0.0339,0.0909,0.0295,0.0846 T0.024,0.0767 T0.0202,0.0728 T0.0148,0.0704 T0.0068,0.0697 Q0.0003,0.0693,0.0058,0.0567 Q0.0077,0.0522,0.011,0.0469 Z",type:0}},"":{type:5,data:{d:"M0.1934,0.6075 Q0.2012,0.612,0.2188,0.6218 T0.2459,0.6369 T0.2718,0.6508 T0.2983,0.6644 T0.322,0.6758 T0.3447,0.6854 T0.363,0.6911 T0.3783,0.6936 Q0.3796,0.6936,0.396,0.6952 T0.4265,0.6952 T0.4548,0.6879 Q0.4656,0.6834,0.4805,0.6756 T0.5073,0.6614 T0.5327,0.6485 T0.5564,0.6389 T0.5759,0.6363 T0.5909,0.6422 Q0.5953,0.6467,0.604,0.6554 T0.6155,0.6669 T0.6251,0.6746 T0.6387,0.683 T0.6556,0.6903 L0.6498,0.6956 Q0.6414,0.7042,0.6319,0.7177 T0.6162,0.7403 T0.5979,0.7583 T0.5703,0.7703 Q0.5313,0.7785,0.4799,0.7605 Q0.5097,0.7817,0.5508,0.7911 T0.6302,0.8001 Q0.6431,0.7997,0.659,0.7942 T0.6888,0.7813 T0.7194,0.766 T0.7506,0.753 T0.7819,0.7472 T0.8131,0.754 Q0.8239,0.7589,0.8346,0.7681 T0.8544,0.7895 T0.8689,0.818 T0.8737,0.8507 L0.8733,0.858 Q0.8591,0.849,0.8474,0.845 T0.8242,0.8421 T0.8021,0.8482 T0.7772,0.8625 Q0.7653,0.8707,0.7513,0.8752 T0.7184,0.8831 T0.6908,0.889 Q0.7017,0.8915,0.7152,0.8956 T0.7396,0.9037 T0.7633,0.9115 T0.7872,0.9174 T0.8107,0.9194 T0.8347,0.9155 Q0.8493,0.9115,0.8671,0.9196 T0.9015,0.9421 T0.9345,0.9708 T0.9682,0.9943 T0.9997,1 Q0.999,0.94,0.9983,0.6508 T0.9976,0.2322 Q0.9976,0.2109,0.9992,0.1379 T1,0.0249 Q0.9949,0.0249,0.9917,0.0257 T0.9863,0.0273 T0.9817,0.0308 T0.9776,0.0357 T0.9721,0.0437 T0.9651,0.0539 Q0.956,0.0657,0.9456,0.072 T0.9247,0.0789 T0.904,0.0775 T0.8823,0.0694 T0.862,0.0573 T0.8422,0.0432 Q0.7856,0,0.7328,0.0318 Q0.7392,0.0318,0.7452,0.0324 T0.756,0.0345 T0.7657,0.0386 T0.7741,0.0437 T0.7821,0.0506 T0.7894,0.0588 T0.7966,0.0683 T0.8039,0.0787 T0.8119,0.0904 T0.8202,0.1028 Q0.8249,0.1093,0.849,0.1234 T0.8811,0.1448 Q0.8998,0.1612,0.8893,0.1783 Q0.8835,0.1877,0.8759,0.1928 T0.8593,0.1979 T0.8417,0.1967 T0.8222,0.1895 T0.8034,0.1791 T0.7848,0.1663 T0.7687,0.1534 T0.7543,0.141 T0.744,0.1322 Q0.7186,0.1106,0.6984,0.101 T0.6559,0.0926 T0.6082,0.1077 Q0.5899,0.1175,0.5733,0.1206 T0.5411,0.1202 T0.5122,0.1098 T0.4822,0.0914 Q0.4927,0.1032,0.5036,0.1122 T0.5276,0.1285 T0.5503,0.1401 T0.5777,0.1518 T0.6055,0.1636 Q0.6258,0.1726,0.6375,0.1863 T0.6519,0.2162 Q0.6556,0.2403,0.6392,0.2605 T0.5926,0.2876 Q0.5804,0.2909,0.5672,0.2899 T0.5428,0.2856 T0.5193,0.2764 T0.4966,0.264 T0.4744,0.2497 T0.4523,0.2352 T0.4301,0.2222 T0.4077,0.2118 Q0.3021,0.173,0.1903,0.2436 Q0.1669,0.2583,0.1504,0.2674 T0.1129,0.2846 T0.075,0.294 T0.0384,0.2911 T0,0.2746 Q0.021,0.297,0.0459,0.3082 T0.0953,0.3207 T0.146,0.3193 T0.1988,0.3131 T0.2508,0.3095 T0.3029,0.3176 T0.3529,0.3448 Q0.3566,0.348,0.3652,0.355 T0.3771,0.3645 T0.3877,0.3731 T0.3993,0.3815 T0.4103,0.3884 T0.4226,0.3953 T0.4352,0.4009 T0.4497,0.4064 L0.4443,0.4121 Q0.4372,0.4198,0.4277,0.4251 T0.4072,0.4337 T0.3867,0.439 T0.3656,0.4431 T0.3481,0.4468 Q0.3241,0.4529,0.2943,0.4463 Q0.3227,0.4623,0.3458,0.471 T0.3959,0.4814 Q0.404,0.4818,0.4187,0.4825 T0.4409,0.4835 T0.4605,0.4857 T0.4809,0.4908 T0.4992,0.4996 T0.5186,0.5141 T0.5371,0.5353 L0.5449,0.5451 L0.5337,0.543 Q0.5242,0.541,0.5091,0.55 T0.4683,0.5796 T0.4314,0.6083 Q0.4203,0.6161,0.4086,0.6212 T0.382,0.6308 T0.3667,0.6353 Q0.3485,0.6418,0.2995,0.633 T0.1934,0.6075 Z",type:0}},"":{type:5,data:{d:"M0.989,0.0469 Q0.9829,0.0379,0.9753,0.0316 T0.9635,0.0253 Q0.9574,0.0257,0.9539,0.0263 T0.9466,0.03 T0.9418,0.0345 T0.9355,0.0434 T0.9277,0.0546 Q0.9193,0.0653,0.9103,0.0712 T0.8919,0.0775 T0.8745,0.0765 T0.8564,0.0695 T0.8396,0.0593 T0.8228,0.0473 Q0.7612,0,0.7073,0.0326 L0.7386,0.0767 L0.7419,0.0767 Q0.7506,0.0767,0.7556,0.0773 T0.7641,0.0789 T0.7709,0.0842 T0.7767,0.0922 T0.7854,0.1054 T0.7974,0.1236 Q0.8057,0.1354,0.8157,0.1444 T0.8325,0.1574 T0.8474,0.1654 T0.8571,0.1701 Q0.8564,0.1717,0.8554,0.1733 Q0.8503,0.1815,0.844,0.186 T0.8301,0.1909 T0.8153,0.1903 T0.7993,0.1845 T0.7836,0.1758 T0.768,0.1648 T0.754,0.1535 T0.741,0.1425 T0.7312,0.1338 Q0.7031,0.1101,0.6805,0.0995 T0.6357,0.0901 T0.5886,0.1048 Q0.5721,0.1138,0.5574,0.1168 T0.5295,0.117 T0.5055,0.1089 T0.4814,0.0942 L0.4789,0.0926 L0.4711,0.0922 Q0.4589,0.095,0.4811,0.1203 Q0.495,0.1358,0.5087,0.1474 T0.5366,0.167 T0.5611,0.1796 T0.5879,0.1909 T0.6134,0.2011 Q0.6218,0.2047,0.6273,0.2092 Q0.6283,0.2117,0.6286,0.2141 Q0.6305,0.2263,0.6249,0.2388 T0.606,0.2616 T0.5747,0.2761 Q0.5602,0.2785,0.5487,0.2779 T0.5245,0.2724 T0.5015,0.2616 T0.4784,0.2476 T0.4547,0.2321 T0.4297,0.217 T0.4024,0.2043 Q0.2985,0.166,0.1901,0.2345 Q0.1694,0.248,0.1523,0.2569 T0.1165,0.2726 T0.0818,0.2812 T0.0494,0.2796 T0.0181,0.2663 L0.0116,0.2671 Q0,0.272,0.0232,0.2969 Q0.0468,0.3222,0.0742,0.3365 T0.1278,0.3542 T0.1807,0.3564 T0.233,0.352 T0.2815,0.3473 T0.3269,0.3509 T0.3656,0.3699 Q0.4037,0.4005,0.4153,0.4082 Q0.405,0.4139,0.3921,0.4174 T0.3633,0.4237 T0.3414,0.4278 Q0.3207,0.4331,0.2956,0.4278 Q0.2943,0.4278,0.293,0.4274 Q0.2933,0.429,0.2938,0.4313 T0.2964,0.4398 T0.3007,0.4513 T0.3069,0.4619 T0.3149,0.4698 Q0.3427,0.4857,0.3664,0.4947 T0.4169,0.5053 Q0.423,0.5057,0.4385,0.5065 T0.4606,0.508 T0.4779,0.51 T0.4958,0.5139 T0.5095,0.5204 Q0.4992,0.5232,0.485,0.5328 T0.451,0.5585 T0.4201,0.5824 Q0.4095,0.5897,0.3987,0.5946 T0.3738,0.6036 T0.3591,0.6081 Q0.3433,0.6134,0.2965,0.605 T0.1972,0.5816 L0.2026,0.5922 T0.2133,0.6134 L0.2188,0.624 Q0.2201,0.6248,0.2214,0.6252 Q0.2291,0.6297,0.2486,0.6405 T0.2786,0.657 T0.3066,0.6721 T0.3353,0.6866 T0.3598,0.6972 T0.383,0.7051 T0.4005,0.7076 Q0.4008,0.7076,0.4169,0.7092 T0.4471,0.7092 T0.475,0.7019 Q0.4895,0.6958,0.5176,0.6811 T0.5644,0.6586 T0.5921,0.6533 Q0.6128,0.6741,0.6173,0.6782 Q0.6131,0.6835,0.6068,0.6929 T0.5963,0.7078 T0.5858,0.7198 T0.5716,0.7304 T0.5534,0.7365 Q0.5179,0.7443,0.4708,0.728 L0.4708,0.7294 T0.471,0.7333 T0.4716,0.7392 T0.4734,0.7463 T0.4764,0.7539 T0.4814,0.7612 T0.4889,0.7679 Q0.4914,0.77,0.4944,0.7716 Q0.5534,0.8104,0.6409,0.8091 Q0.6521,0.8091,0.6654,0.8053 T0.6907,0.7959 T0.7157,0.7838 T0.741,0.772 T0.7652,0.7631 T0.7888,0.7594 T0.8106,0.7643 Q0.8196,0.7684,0.8267,0.7753 Q0.8409,0.7892,0.8399,0.8169 Q0.8216,0.8067,0.8062,0.8053 T0.7788,0.8087 T0.7493,0.825 Q0.7386,0.8324,0.7256,0.8365 T0.6947,0.844 T0.668,0.8499 L0.697,0.894 L0.7002,0.8948 Q0.7099,0.8968,0.7222,0.9009 T0.7446,0.9086 T0.767,0.9158 T0.7901,0.9213 T0.8132,0.9229 T0.8367,0.9192 Q0.8483,0.916,0.8633,0.9241 T0.8937,0.9462 T0.9248,0.9737 T0.959,0.9955 T0.9939,1 Q1,0.9984,0.9932,0.9845 Q0.991,0.9804,0.9877,0.9755 Q0.9813,0.9666,0.9739,0.9606 T0.9626,0.9555 Q0.9519,0.958,0.9372,0.949 T0.9071,0.9262 T0.8753,0.8987 T0.8403,0.8777 T0.8051,0.8752 Q0.787,0.8805,0.7657,0.8772 Q0.7751,0.8736,0.7828,0.8683 Q0.8086,0.8511,0.8262,0.8497 T0.8651,0.8617 Q0.8696,0.865,0.8727,0.8646 T0.8758,0.8605 L0.8761,0.8536 Q0.8774,0.8295,0.8646,0.8016 T0.8277,0.7496 Q0.8086,0.7308,0.7896,0.7219 Q0.7741,0.7145,0.7575,0.7141 T0.727,0.7182 T0.6978,0.7296 T0.6699,0.7439 T0.6433,0.7571 T0.6179,0.7643 Q0.627,0.7561,0.6402,0.7367 T0.6618,0.7088 L0.6673,0.7035 Q0.6718,0.699,0.6647,0.6884 T0.6483,0.6692 L0.6389,0.6607 Q0.6289,0.657,0.6249,0.6554 T0.6163,0.6507 T0.6102,0.6458 T0.6021,0.637 T0.5889,0.6236 Q0.5828,0.6175,0.5766,0.6138 Q0.5673,0.6081,0.5561,0.6077 T0.5345,0.6105 T0.5116,0.6201 T0.4887,0.633 T0.4653,0.6468 T0.4427,0.6578 Q0.4295,0.6635,0.4167,0.665 T0.3888,0.665 T0.3714,0.6635 Q0.3579,0.6631,0.3282,0.6501 Q0.374,0.6578,0.3911,0.6517 Q0.3937,0.6509,0.4024,0.6482 T0.4179,0.6434 T0.4348,0.6364 T0.4534,0.6256 Q0.464,0.6183,0.4892,0.5989 T0.5278,0.5712 T0.5476,0.564 L0.5582,0.5661 Q0.5692,0.5681,0.5634,0.5563 Q0.5599,0.5485,0.5524,0.5392 L0.545,0.5298 Q0.5369,0.5188,0.5286,0.51 T0.5134,0.4947 T0.4979,0.4831 T0.484,0.4749 T0.47,0.4694 T0.4572,0.4657 T0.4442,0.4637 T0.4326,0.4629 T0.4205,0.4625 Q0.4511,0.4543,0.466,0.4384 L0.4714,0.4327 Q0.4795,0.4237,0.4469,0.394 L0.4421,0.3899 Q0.433,0.387,0.4251,0.3834 T0.4122,0.3772 T0.3988,0.3687 T0.3874,0.3603 T0.3732,0.3487 T0.3579,0.3361 Q0.3433,0.3242,0.3288,0.3159 T0.2993,0.3034 T0.2725,0.2973 T0.2446,0.2961 T0.2193,0.2977 T0.1926,0.301 Q0.1855,0.3022,0.182,0.3026 Q0.1991,0.2936,0.2233,0.2781 Q0.3282,0.2117,0.4256,0.2476 Q0.4363,0.2516,0.451,0.2604 T0.4784,0.2779 T0.5077,0.2965 T0.539,0.3124 T0.5718,0.3216 T0.606,0.3206 Q0.6363,0.3136,0.6526,0.2936 T0.6647,0.2459 Q0.6615,0.2247,0.645,0.2023 Q0.6354,0.1892,0.6237,0.179 Q0.6102,0.1672,0.5937,0.1595 Q0.6073,0.1562,0.6215,0.1485 Q0.6396,0.1387,0.6547,0.1354 T0.6839,0.1354 T0.7101,0.1458 T0.7373,0.166 Q0.738,0.1664,0.746,0.1733 T0.7586,0.1841 T0.7733,0.196 T0.7907,0.2086 T0.8086,0.2196 T0.8275,0.2288 T0.8454,0.2337 T0.8627,0.2343 T0.8777,0.228 T0.8903,0.2145 Q0.9038,0.1929,0.8742,0.1582 Q0.869,0.1517,0.8629,0.1464 Q0.8538,0.1387,0.844,0.1321 T0.8248,0.1205 T0.8122,0.1134 Q0.8109,0.1117,0.8053,0.103 T0.7965,0.0899 T0.7875,0.0781 T0.7757,0.064 Q0.8051,0.0616,0.8328,0.0828 Q0.847,0.0934,0.8588,0.1009 T0.8854,0.1146 T0.9127,0.1213 T0.9384,0.116 T0.9626,0.0962 Q0.9664,0.0909,0.9706,0.0846 T0.976,0.0767 T0.9798,0.0728 T0.9852,0.0704 T0.9932,0.0697 Q0.9997,0.0693,0.9942,0.0567 Q0.9923,0.0522,0.989,0.0469 Z",type:0}},"":{type:5,data:{d:"M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0.9099,0.1158 L0.9099,0.1888 L0.9951,0.1888 L0.9951,0.1158 L0.9099,0.1158 Z M0.9075,0.1116 L0.9976,0.1116 Q1,0.1116,1,0.1137 L1,0.1909 Q1,0.193,0.9976,0.193 L0.9075,0.193 Q0.905,0.193,0.905,0.1909 L0.905,0.1137 Q0.905,0.1116,0.9075,0.1116 Z M0.7852,0.6086 L0.7852,0.682 L0.8704,0.682 L0.8704,0.6086 L0.7852,0.6086 Z M0.7828,0.6044 L0.8729,0.6044 Q0.8753,0.6044,0.8753,0.6065 L0.8753,0.6841 Q0.8753,0.6862,0.8729,0.6862 L0.7828,0.6862 Q0.7803,0.6862,0.7803,0.6841 L0.7803,0.6065 Q0.7803,0.6044,0.7828,0.6044 Z M0.66,0.1137 L0.7501,0.1137 L0.7501,0.1909 L0.66,0.1909 L0.66,0.1137 Z M0.6624,0.4102 L0.6624,0.4836 L0.7477,0.4836 L0.7477,0.4102 L0.6624,0.4102 Z M0.66,0.406 L0.7501,0.406 Q0.7526,0.406,0.7526,0.4081 L0.7526,0.4857 Q0.7526,0.4878,0.7501,0.4878 L0.66,0.4878 Q0.6576,0.4878,0.6576,0.4857 L0.6576,0.4081 Q0.6576,0.406,0.66,0.406 Z M0.6624,0.7131 L0.6624,0.7865 L0.7477,0.7865 L0.7477,0.7131 L0.6624,0.7131 Z M0.66,0.7089 L0.7501,0.7089 Q0.7526,0.7089,0.7526,0.711 L0.7526,0.7886 Q0.7526,0.7907,0.7501,0.7907 L0.66,0.7907 Q0.6576,0.7907,0.6576,0.7886 L0.6576,0.711 Q0.6576,0.7089,0.66,0.7089 Z M0.5407,0.2227 L0.5407,0.2836 L0.6113,0.2836 L0.6113,0.2227 L0.5407,0.2227 Z M0.5309,0.206 L0.621,0.206 Q0.623,0.206,0.6249,0.2068 T0.6281,0.2089 T0.6301,0.2116 T0.6308,0.2143 L0.6308,0.2919 Q0.6308,0.2957,0.6276,0.298 T0.621,0.3003 L0.5309,0.3003 Q0.5265,0.3003,0.5239,0.2976 T0.5212,0.2919 L0.5212,0.2143 Q0.5212,0.211,0.5244,0.2085 T0.5309,0.206 Z M0.5407,0.3184 L0.5407,0.3792 L0.6113,0.3792 L0.6113,0.3184 L0.5407,0.3184 Z M0.5309,0.3016 L0.621,0.3016 Q0.6254,0.3016,0.6281,0.3043 T0.6308,0.31 L0.6308,0.3876 Q0.6308,0.3914,0.6276,0.3937 T0.621,0.396 L0.5309,0.396 Q0.5265,0.396,0.5239,0.3932 T0.5212,0.3876 L0.5212,0.31 Q0.5212,0.3062,0.5244,0.3039 T0.5309,0.3016 Z M0.5309,0.4081 L0.621,0.4081 L0.621,0.4857 L0.5309,0.4857 L0.5309,0.4081 Z M0.5309,0.5059 L0.621,0.5059 L0.621,0.5835 L0.5309,0.5835 L0.5309,0.5059 Z M0.5407,0.6149 L0.5407,0.6758 L0.6113,0.6758 L0.6113,0.6149 L0.5407,0.6149 Z M0.5309,0.5982 L0.621,0.5982 Q0.6254,0.5982,0.6281,0.6009 T0.6308,0.6065 L0.6308,0.6841 Q0.6308,0.6879,0.6276,0.6902 T0.621,0.6925 L0.5309,0.6925 Q0.5265,0.6925,0.5239,0.6898 T0.5212,0.6841 L0.5212,0.6065 Q0.5212,0.6028,0.5244,0.6005 T0.5309,0.5982 Z M0.4062,0.1137 L0.4963,0.1137 L0.4963,0.1909 L0.4062,0.1909 L0.4062,0.1137 Z M0.4062,0.2143 L0.4963,0.2143 L0.4963,0.2919 L0.4062,0.2919 L0.4062,0.2143 Z M0.4184,0.4186 L0.4184,0.4753 L0.4842,0.4753 L0.4842,0.4186 L0.4184,0.4186 Z M0.4062,0.3977 L0.4963,0.3977 Q0.5017,0.3977,0.5051,0.401 T0.5085,0.4081 L0.5085,0.4857 Q0.5085,0.4904,0.5046,0.4933 T0.4963,0.4962 L0.4062,0.4962 Q0.4009,0.4962,0.3975,0.4929 T0.3941,0.4857 L0.3941,0.4081 Q0.3941,0.4035,0.398,0.4006 T0.4062,0.3977 Z M0.4062,0.5059 L0.4963,0.5059 L0.4963,0.5835 L0.4062,0.5835 L0.4062,0.5059 Z M0.4087,0.7131 L0.4087,0.7865 L0.4939,0.7865 L0.4939,0.7131 L0.4087,0.7131 Z M0.4062,0.7089 L0.4963,0.7089 Q0.4988,0.7089,0.4988,0.711 L0.4988,0.7886 Q0.4988,0.7907,0.4963,0.7907 L0.4062,0.7907 Q0.4038,0.7907,0.4038,0.7886 L0.4038,0.711 Q0.4038,0.7089,0.4062,0.7089 Z M0.2689,0.1137 L0.359,0.1137 L0.359,0.1909 L0.2689,0.1909 L0.2689,0.1137 Z M0.2689,0.2143 L0.359,0.2143 L0.359,0.2919 L0.2689,0.2919 L0.2689,0.2143 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.31 L0.359,0.31 L0.359,0.3876 L0.2689,0.3876 L0.2689,0.31 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.4081 L0.359,0.4081 L0.359,0.4857 L0.2689,0.4857 L0.2689,0.4081 Z M0.2689,0.5059 L0.359,0.5059 L0.359,0.5835 L0.2689,0.5835 L0.2689,0.5059 Z M0.2689,0.711 L0.359,0.711 L0.359,0.7886 L0.2689,0.7886 L0.2689,0.711 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.1374,0.1137 L0.2275,0.1137 L0.2275,0.1909 L0.1374,0.1909 L0.1374,0.1137 Z M0.1374,0.2143 L0.2275,0.2143 L0.2275,0.2919 L0.1374,0.2919 L0.1374,0.2143 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.31 L0.2275,0.31 L0.2275,0.3876 L0.1374,0.3876 L0.1374,0.31 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.4081 L0.2275,0.4081 L0.2275,0.4857 L0.1374,0.4857 L0.1374,0.4081 Z M0.1374,0.5059 L0.2275,0.5059 L0.2275,0.5835 L0.1374,0.5835 L0.1374,0.5059 Z M0.1374,0.6065 L0.2275,0.6065 L0.2275,0.6841 L0.1374,0.6841 L0.1374,0.6065 Z M0.1374,0.711 L0.2275,0.711 L0.2275,0.7886 L0.1374,0.7886 L0.1374,0.711 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0,0.1137 L0.0901,0.1137 L0.0901,0.1909 L0,0.1909 L0,0.1137 Z M0,0.2143 L0.0901,0.2143 L0.0901,0.2919 L0,0.2919 L0,0.2143 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.31 L0.0901,0.31 L0.0901,0.3876 L0,0.3876 L0,0.31 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.4081 L0.0901,0.4081 L0.0901,0.4857 L0,0.4857 L0,0.4081 Z M0,0.5059 L0.0901,0.5059 L0.0901,0.5835 L0,0.5835 L0,0.5059 Z M0,0.6065 L0.0901,0.6065 L0.0901,0.6841 L0,0.6841 L0,0.6065 Z M0,0.711 L0.0901,0.711 L0.0901,0.7886 L0,0.7886 L0,0.711 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z",type:0}},"":{type:5,data:{d:"M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M0.0901,0.1158 L0.0901,0.1888 L0.0049,0.1888 L0.0049,0.1158 L0.0901,0.1158 Z M0.0925,0.1116 L0.0024,0.1116 Q0,0.1116,0,0.1137 L0,0.1909 Q0,0.193,0.0024,0.193 L0.0925,0.193 Q0.095,0.193,0.095,0.1909 L0.095,0.1137 Q0.095,0.1116,0.0925,0.1116 Z M0.2148,0.6086 L0.2148,0.682 L0.1296,0.682 L0.1296,0.6086 L0.2148,0.6086 Z M0.2172,0.6044 L0.1271,0.6044 Q0.1247,0.6044,0.1247,0.6065 L0.1247,0.6841 Q0.1247,0.6862,0.1271,0.6862 L0.2172,0.6862 Q0.2197,0.6862,0.2197,0.6841 L0.2197,0.6065 Q0.2197,0.6044,0.2172,0.6044 Z M0.34,0.1137 L0.2499,0.1137 L0.2499,0.1909 L0.34,0.1909 L0.34,0.1137 Z M0.3376,0.4102 L0.3376,0.4836 L0.2523,0.4836 L0.2523,0.4102 L0.3376,0.4102 Z M0.34,0.406 L0.2499,0.406 Q0.2474,0.406,0.2474,0.4081 L0.2474,0.4857 Q0.2474,0.4878,0.2499,0.4878 L0.34,0.4878 Q0.3424,0.4878,0.3424,0.4857 L0.3424,0.4081 Q0.3424,0.406,0.34,0.406 Z M0.3376,0.7131 L0.3376,0.7865 L0.2523,0.7865 L0.2523,0.7131 L0.3376,0.7131 Z M0.34,0.7089 L0.2499,0.7089 Q0.2474,0.7089,0.2474,0.711 L0.2474,0.7886 Q0.2474,0.7907,0.2499,0.7907 L0.34,0.7907 Q0.3424,0.7907,0.3424,0.7886 L0.3424,0.711 Q0.3424,0.7089,0.34,0.7089 Z M0.4593,0.2227 L0.4593,0.2836 L0.3887,0.2836 L0.3887,0.2227 L0.4593,0.2227 Z M0.4691,0.206 L0.379,0.206 Q0.3746,0.206,0.3719,0.2087 T0.3692,0.2143 L0.3692,0.2919 Q0.3692,0.2957,0.3724,0.298 T0.379,0.3003 L0.4691,0.3003 Q0.4735,0.3003,0.4761,0.2976 T0.4788,0.2919 L0.4788,0.2143 Q0.4788,0.211,0.4756,0.2085 T0.4691,0.206 Z M0.4593,0.3184 L0.4593,0.3792 L0.3887,0.3792 L0.3887,0.3184 L0.4593,0.3184 Z M0.4691,0.3016 L0.379,0.3016 Q0.3746,0.3016,0.3719,0.3043 T0.3692,0.31 L0.3692,0.3876 Q0.3692,0.3914,0.3724,0.3937 T0.379,0.396 L0.4691,0.396 Q0.4735,0.396,0.4761,0.3932 T0.4788,0.3876 L0.4788,0.31 Q0.4788,0.3062,0.4756,0.3039 T0.4691,0.3016 Z M0.4691,0.4081 L0.379,0.4081 L0.379,0.4857 L0.4691,0.4857 L0.4691,0.4081 Z M0.4691,0.5059 L0.379,0.5059 L0.379,0.5835 L0.4691,0.5835 L0.4691,0.5059 Z M0.4593,0.6149 L0.4593,0.6758 L0.3887,0.6758 L0.3887,0.6149 L0.4593,0.6149 Z M0.4691,0.5982 L0.379,0.5982 Q0.3746,0.5982,0.3719,0.6009 T0.3692,0.6065 L0.3692,0.6841 Q0.3692,0.6879,0.3724,0.6902 T0.379,0.6925 L0.4691,0.6925 Q0.4735,0.6925,0.4761,0.6898 T0.4788,0.6841 L0.4788,0.6065 Q0.4788,0.6028,0.4756,0.6005 T0.4691,0.5982 Z M0.5938,0.1137 L0.5037,0.1137 L0.5037,0.1909 L0.5938,0.1909 L0.5938,0.1137 Z M0.5938,0.2143 L0.5037,0.2143 L0.5037,0.2919 L0.5938,0.2919 L0.5938,0.2143 Z M0.5816,0.4186 L0.5816,0.4753 L0.5158,0.4753 L0.5158,0.4186 L0.5816,0.4186 Z M0.5938,0.3977 L0.5037,0.3977 Q0.4983,0.3977,0.4949,0.401 T0.4915,0.4081 L0.4915,0.4857 Q0.4915,0.4904,0.4954,0.4933 T0.5037,0.4962 L0.5938,0.4962 Q0.5991,0.4962,0.6025,0.4929 T0.6059,0.4857 L0.6059,0.4081 Q0.6059,0.4035,0.602,0.4006 T0.5938,0.3977 Z M0.5938,0.5059 L0.5037,0.5059 L0.5037,0.5835 L0.5938,0.5835 L0.5938,0.5059 Z M0.5913,0.7131 L0.5913,0.7865 L0.5061,0.7865 L0.5061,0.7131 L0.5913,0.7131 Z M0.5938,0.7089 L0.5037,0.7089 Q0.5012,0.7089,0.5012,0.711 L0.5012,0.7886 Q0.5012,0.7907,0.5037,0.7907 L0.5938,0.7907 Q0.5962,0.7907,0.5962,0.7886 L0.5962,0.711 Q0.5962,0.7089,0.5938,0.7089 Z M0.7311,0.1137 L0.641,0.1137 L0.641,0.1909 L0.7311,0.1909 L0.7311,0.1137 Z M0.7311,0.2143 L0.641,0.2143 L0.641,0.2919 L0.7311,0.2919 L0.7311,0.2143 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.31 L0.641,0.31 L0.641,0.3876 L0.7311,0.3876 L0.7311,0.31 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.4081 L0.641,0.4081 L0.641,0.4857 L0.7311,0.4857 L0.7311,0.4081 Z M0.7311,0.5059 L0.641,0.5059 L0.641,0.5835 L0.7311,0.5835 L0.7311,0.5059 Z M0.7311,0.711 L0.641,0.711 L0.641,0.7886 L0.7311,0.7886 L0.7311,0.711 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.8626,0.1137 L0.7725,0.1137 L0.7725,0.1909 L0.8626,0.1909 L0.8626,0.1137 Z M0.8626,0.2143 L0.7725,0.2143 L0.7725,0.2919 L0.8626,0.2919 L0.8626,0.2143 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.31 L0.7725,0.31 L0.7725,0.3876 L0.8626,0.3876 L0.8626,0.31 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.4081 L0.7725,0.4081 L0.7725,0.4857 L0.8626,0.4857 L0.8626,0.4081 Z M0.8626,0.5059 L0.7725,0.5059 L0.7725,0.5835 L0.8626,0.5835 L0.8626,0.5059 Z M0.8626,0.6065 L0.7725,0.6065 L0.7725,0.6841 L0.8626,0.6841 L0.8626,0.6065 Z M0.8626,0.711 L0.7725,0.711 L0.7725,0.7886 L0.8626,0.7886 L0.8626,0.711 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M1,0.1137 L0.9099,0.1137 L0.9099,0.1909 L1,0.1909 L1,0.1137 Z M1,0.2143 L0.9099,0.2143 L0.9099,0.2919 L1,0.2919 L1,0.2143 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.31 L0.9099,0.31 L0.9099,0.3876 L1,0.3876 L1,0.31 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.4081 L0.9099,0.4081 L0.9099,0.4857 L1,0.4857 L1,0.4081 Z M1,0.5059 L0.9099,0.5059 L0.9099,0.5835 L1,0.5835 L1,0.5059 Z M1,0.6065 L0.9099,0.6065 L0.9099,0.6841 L1,0.6841 L1,0.6065 Z M1,0.711 L0.9099,0.711 L0.9099,0.7886 L1,0.7886 L1,0.711 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z",type:0}},"":{type:5,data:{d:"M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0.8574,0.3217 L0.8574,0.4098 L0.9691,0.4098 L0.9691,0.3217 L0.8574,0.3217 Z M0.8419,0.2978 L0.9846,0.2978 Q0.9892,0.2978,0.9928,0.2997 T0.9982,0.3043 T1,0.31 L1,0.4216 Q1,0.427,0.9951,0.4304 T0.9846,0.4337 L0.8419,0.4337 Q0.8352,0.4337,0.8308,0.4299 T0.8265,0.4216 L0.8265,0.31 Q0.8265,0.3062,0.829,0.3035 T0.835,0.2993 T0.8419,0.2978 Z M0.8574,0.888 L0.8574,0.9757 L0.9691,0.9757 L0.9691,0.888 L0.8574,0.888 Z M0.8419,0.8637 L0.9846,0.8637 Q0.9892,0.8637,0.9928,0.8658 T0.9982,0.8706 T1,0.8758 L1,0.9878 Q1,0.9929,0.9951,0.9964 T0.9846,1 L0.8419,1 Q0.8352,1,0.8308,0.996 T0.8265,0.9878 L0.8265,0.8758 Q0.8265,0.8708,0.8314,0.8672 T0.8419,0.8637 Z M0.6509,0.169 L0.6509,0.2706 L0.7806,0.2706 L0.7806,0.169 L0.6509,0.169 Z M0.6442,0.159 L0.7868,0.159 Q0.7899,0.159,0.7917,0.1604 T0.7935,0.164 L0.7935,0.2756 Q0.7935,0.2781,0.7915,0.2796 T0.7868,0.281 L0.6442,0.281 Q0.6416,0.281,0.6395,0.2794 T0.6375,0.2756 L0.6375,0.164 Q0.6375,0.1619,0.6398,0.1604 T0.6442,0.159 Z M0.6632,0.6044 L0.6632,0.6858 L0.7678,0.6858 L0.7678,0.6044 L0.6632,0.6044 Z M0.6442,0.5742 L0.7868,0.5742 Q0.7951,0.5742,0.8007,0.5791 T0.8064,0.5893 L0.8064,0.7013 Q0.8064,0.7076,0.8002,0.712 T0.7868,0.7164 L0.6442,0.7164 Q0.6359,0.7164,0.6305,0.7114 T0.6251,0.7013 L0.6251,0.5893 Q0.6251,0.5847,0.6282,0.5812 T0.6357,0.5759 T0.6442,0.5742 Z M0.4264,0.164 L0.5695,0.164 L0.5695,0.2756 L0.4264,0.2756 L0.4264,0.164 Z M0.4325,0.315 L0.4325,0.4165 L0.5628,0.4165 L0.5628,0.315 L0.4325,0.315 Z M0.4264,0.3049 L0.5695,0.3049 Q0.5721,0.3049,0.5739,0.3064 T0.5757,0.31 L0.5757,0.4216 Q0.5757,0.4237,0.5736,0.4251 T0.5695,0.4266 L0.4264,0.4266 Q0.4238,0.4266,0.422,0.4251 T0.4202,0.4216 L0.4202,0.31 Q0.4202,0.3087,0.4207,0.3077 T0.4222,0.306 T0.4243,0.3052 T0.4264,0.3049 Z M0.4264,0.4476 L0.5695,0.4476 L0.5695,0.5596 L0.4264,0.5596 L0.4264,0.4476 Z M0.4392,0.7408 L0.4392,0.8326 L0.5561,0.8326 L0.5561,0.7408 L0.4392,0.7408 Z M0.4264,0.7206 L0.5695,0.7206 Q0.5747,0.7206,0.5783,0.724 T0.5819,0.7307 L0.5819,0.8427 Q0.5819,0.8469,0.5778,0.8498 T0.5695,0.8528 L0.4264,0.8528 Q0.4207,0.8528,0.4171,0.8496 T0.4135,0.8427 L0.4135,0.7307 Q0.4135,0.7265,0.4176,0.7236 T0.4264,0.7206 Z M0.2178,0.164 L0.3605,0.164 L0.3605,0.2756 L0.2178,0.2756 L0.2178,0.164 Z M0.2178,0.31 L0.3605,0.31 L0.3605,0.4216 L0.2178,0.4216 L0.2178,0.31 Z M0.2178,0.5893 L0.3605,0.5893 L0.3605,0.7013 L0.2178,0.7013 L0.2178,0.5893 Z M0.2178,0.7307 L0.3605,0.7307 L0.3605,0.8427 L0.2178,0.8427 L0.2178,0.7307 Z M0.2178,0.8758 L0.3605,0.8758 L0.3605,0.9878 L0.2178,0.9878 L0.2178,0.8758 Z M0,0.164 L0.1432,0.164 L0.1432,0.2756 L0,0.2756 L0,0.164 Z M0,0.31 L0.1432,0.31 L0.1432,0.4216 L0,0.4216 L0,0.31 Z M0,0.4476 L0.1432,0.4476 L0.1432,0.5596 L0,0.5596 L0,0.4476 Z M0,0.5893 L0.1432,0.5893 L0.1432,0.7013 L0,0.7013 L0,0.5893 Z M0,0.7307 L0.1432,0.7307 L0.1432,0.8427 L0,0.8427 L0,0.7307 Z M0,0.8758 L0.1432,0.8758 L0.1432,0.9878 L0,0.9878 L0,0.8758 Z",type:0}},"":{type:5,data:{d:"M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M0.1432,0.3217 L0.1432,0.4098 L0.0309,0.4098 L0.0309,0.3217 L0.1432,0.3217 Z M0.1586,0.2978 L0.0154,0.2978 Q0.0088,0.2978,0.0044,0.3016 T0,0.31 L0,0.4216 Q0,0.427,0.0049,0.4304 T0.0154,0.4337 L0.1586,0.4337 Q0.1648,0.4337,0.1694,0.4299 T0.174,0.4216 L0.174,0.31 Q0.174,0.3062,0.1715,0.3035 T0.1653,0.2993 T0.1586,0.2978 Z M0.1432,0.888 L0.1432,0.9757 L0.0309,0.9757 L0.0309,0.888 L0.1432,0.888 Z M0.1586,0.8637 L0.0154,0.8637 Q0.0108,0.8637,0.0072,0.8658 T0.0018,0.8706 T0,0.8758 L0,0.9878 Q0,0.9929,0.0049,0.9964 T0.0154,1 L0.1586,1 Q0.1648,1,0.1694,0.996 T0.174,0.9878 L0.174,0.8758 Q0.174,0.8725,0.1715,0.8695 T0.1653,0.8651 T0.1586,0.8637 Z M0.3496,0.169 L0.3496,0.2706 L0.2194,0.2706 L0.2194,0.169 L0.3496,0.169 Z M0.3563,0.159 L0.2132,0.159 Q0.2106,0.159,0.2088,0.1604 T0.207,0.164 L0.207,0.2756 Q0.207,0.2781,0.2091,0.2796 T0.2132,0.281 L0.3563,0.281 Q0.3589,0.281,0.3607,0.2794 T0.3625,0.2756 L0.3625,0.164 Q0.3625,0.1619,0.3605,0.1604 T0.3563,0.159 Z M0.3368,0.6044 L0.3368,0.6858 L0.2327,0.6858 L0.2327,0.6044 L0.3368,0.6044 Z M0.3563,0.5742 L0.2132,0.5742 Q0.2049,0.5742,0.1993,0.5791 T0.1936,0.5893 L0.1936,0.7013 Q0.1936,0.7076,0.2001,0.712 T0.2132,0.7164 L0.3563,0.7164 Q0.3641,0.7164,0.3697,0.7114 T0.3754,0.7013 L0.3754,0.5893 Q0.3754,0.5847,0.3723,0.5812 T0.3648,0.5759 T0.3563,0.5742 Z M0.5736,0.164 L0.431,0.164 L0.431,0.2756 L0.5736,0.2756 L0.5736,0.164 Z M0.5675,0.315 L0.5675,0.4165 L0.4377,0.4165 L0.4377,0.315 L0.5675,0.315 Z M0.5736,0.3049 L0.431,0.3049 Q0.4284,0.3049,0.4264,0.3064 T0.4243,0.31 L0.4243,0.4216 Q0.4243,0.4237,0.4266,0.4251 T0.431,0.4266 L0.5736,0.4266 Q0.5767,0.4266,0.5785,0.4251 T0.5803,0.4216 L0.5803,0.31 Q0.5803,0.3087,0.5798,0.3077 T0.5783,0.306 T0.5762,0.3052 T0.5736,0.3049 Z M0.5736,0.4476 L0.431,0.4476 L0.431,0.5596 L0.5736,0.5596 L0.5736,0.4476 Z M0.5613,0.7408 L0.5613,0.8326 L0.4439,0.8326 L0.4439,0.7408 L0.5613,0.7408 Z M0.5736,0.7206 L0.431,0.7206 Q0.4253,0.7206,0.4217,0.724 T0.4181,0.7307 L0.4181,0.8427 Q0.4181,0.8469,0.4222,0.8498 T0.431,0.8528 L0.5736,0.8528 Q0.5778,0.8528,0.5808,0.8511 T0.5855,0.8471 T0.587,0.8427 L0.587,0.7307 Q0.587,0.7265,0.5826,0.7236 T0.5736,0.7206 Z M0.7827,0.164 L0.6395,0.164 L0.6395,0.2756 L0.7827,0.2756 L0.7827,0.164 Z M0.7827,0.31 L0.6395,0.31 L0.6395,0.4216 L0.7827,0.4216 L0.7827,0.31 Z M0.7827,0.5893 L0.6395,0.5893 L0.6395,0.7013 L0.7827,0.7013 L0.7827,0.5893 Z M0.7827,0.7307 L0.6395,0.7307 L0.6395,0.8427 L0.7827,0.8427 L0.7827,0.7307 Z M0.7827,0.8758 L0.6395,0.8758 L0.6395,0.9878 L0.7827,0.9878 L0.7827,0.8758 Z M1,0.164 L0.8574,0.164 L0.8574,0.2756 L1,0.2756 L1,0.164 Z M1,0.31 L0.8574,0.31 L0.8574,0.4216 L1,0.4216 L1,0.31 Z M1,0.4476 L0.8574,0.4476 L0.8574,0.5596 L1,0.5596 L1,0.4476 Z M1,0.5893 L0.8574,0.5893 L0.8574,0.7013 L1,0.7013 L1,0.5893 Z M1,0.7307 L0.8574,0.7307 L0.8574,0.8427 L1,0.8427 L1,0.7307 Z M1,0.8758 L0.8574,0.8758 L0.8574,0.9878 L1,0.9878 L1,0.8758 Z",type:0}},"":{type:5,data:{d:"M0.0008,0.9979 Q0.0008,1,0.0032,1 Q0.0482,1,0.0602,0.9975 Q0.0667,0.9963,0.0847,0.9917 T0.1084,0.9859 Q0.1124,0.9851,0.1221,0.9851 L0.1253,0.9851 L0.1285,0.9851 Q0.1518,0.9851,0.1655,0.9809 Q0.1695,0.9801,0.1731,0.9788 T0.1791,0.9766 T0.1839,0.9747 T0.1888,0.9732 L0.1936,0.972 T0.1988,0.9712 T0.2048,0.971 L0.2096,0.971 Q0.2201,0.9714,0.2233,0.9714 T0.2345,0.9693 Q0.2386,0.9685,0.2502,0.9674 T0.2715,0.966 L0.2811,0.9656 Q0.2916,0.9647,0.2916,0.9573 Q0.2916,0.954,0.2892,0.9515 T0.2819,0.9486 Q0.2755,0.9482,0.2683,0.9482 Q0.2643,0.9482,0.2582,0.9484 T0.2498,0.9486 Q0.2426,0.9486,0.2402,0.9473 Q0.2386,0.9469,0.2317,0.943 T0.2161,0.937 Q0.2104,0.9357,0.1992,0.933 T0.1831,0.9291 Q0.1807,0.9287,0.1783,0.9285 T0.1739,0.928 T0.1703,0.9276 T0.1675,0.9272 T0.1655,0.9266 T0.1639,0.9253 Q0.1598,0.9216,0.1462,0.9216 L0.143,0.9216 L0.1398,0.9216 L0.1365,0.9216 Q0.1197,0.9195,0.1197,0.9154 L0.1197,0.9154 Q0.1205,0.9121,0.1373,0.9088 T0.1703,0.9054 Q0.1791,0.9054,0.1863,0.904 T0.1984,0.9011 T0.2064,0.8992 Q0.2402,0.8967,0.2506,0.8934 Q0.2538,0.8926,0.2602,0.8899 T0.2707,0.8872 Q0.2715,0.8872,0.2731,0.8876 Q0.2795,0.8884,0.2884,0.8884 Q0.3068,0.8884,0.3092,0.8826 L0.3092,0.8797 Q0.3092,0.8772,0.3076,0.8747 T0.3044,0.8706 T0.3028,0.8681 Q0.3076,0.8656,0.3237,0.8656 Q0.3317,0.8656,0.3622,0.8623 Q0.3655,0.8623,0.3867,0.8617 T0.4217,0.8602 Q0.4241,0.8598,0.4289,0.8598 L0.4345,0.8598 L0.441,0.8598 Q0.4578,0.8598,0.4667,0.8586 Q0.4739,0.8573,0.4851,0.8567 T0.5004,0.8552 Q0.5012,0.8552,0.5108,0.855 T0.5269,0.853 T0.5333,0.8461 Q0.5333,0.8445,0.5325,0.8432 T0.5309,0.8409 T0.5289,0.8391 T0.5261,0.8378 L0.5229,0.837 T0.5185,0.8362 T0.5133,0.8355 T0.5076,0.8349 T0.502,0.8341 Q0.4932,0.8324,0.4859,0.8324 Q0.4827,0.8324,0.4787,0.8328 T0.4731,0.8333 Q0.4707,0.8333,0.4683,0.8324 Q0.4482,0.825,0.4394,0.825 Q0.4369,0.825,0.4345,0.8254 Q0.4225,0.827,0.4153,0.827 Q0.4088,0.827,0.4064,0.8258 Q0.3976,0.8204,0.3751,0.8204 Q0.3703,0.8204,0.3667,0.8214 T0.3622,0.8225 Q0.3598,0.8225,0.3558,0.82 Q0.351,0.8175,0.3402,0.8167 T0.3177,0.8156 T0.3028,0.8146 L0.2956,0.8121 T0.2871,0.8094 T0.2771,0.8073 T0.2635,0.8063 Q0.261,0.8063,0.2586,0.8067 Q0.2378,0.8071,0.2273,0.8071 Q0.2072,0.8071,0.2024,0.8051 Q0.1976,0.8034,0.1932,0.8026 T0.1867,0.8013 T0.1847,0.8001 L0.1847,0.7993 Q0.1855,0.7984,0.1855,0.7978 T0.1859,0.7966 T0.1867,0.7959 T0.188,0.7955 T0.1896,0.7951 T0.1916,0.7949 T0.1944,0.7945 T0.1984,0.7941 T0.2032,0.7939 Q0.212,0.7926,0.2325,0.7918 T0.2562,0.7905 Q0.2691,0.7893,0.2787,0.7847 Q0.2835,0.7827,0.2968,0.7791 T0.3149,0.7756 Q0.3189,0.7756,0.3305,0.7733 T0.3446,0.771 L0.3454,0.771 Q0.3462,0.771,0.3498,0.7721 T0.3574,0.774 T0.3655,0.7748 Q0.3703,0.7748,0.3743,0.7731 T0.3823,0.7708 T0.3916,0.77 T0.3992,0.7694 Q0.4008,0.7694,0.4076,0.7688 T0.4205,0.7675 L0.4305,0.7665 Q0.4345,0.7657,0.4402,0.7617 T0.4458,0.7545 Q0.4458,0.7503,0.4353,0.7487 Q0.4297,0.7478,0.4209,0.7462 T0.4044,0.7433 T0.3904,0.7416 L0.3847,0.7416 Q0.3807,0.7416,0.3747,0.7422 T0.3663,0.7428 T0.3606,0.7424 Q0.3582,0.742,0.3562,0.7418 T0.3522,0.7412 T0.3482,0.7406 T0.3446,0.7401 T0.341,0.7397 T0.3373,0.7393 T0.3341,0.7391 L0.3293,0.7391 Q0.3277,0.7395,0.3253,0.7395 Q0.3205,0.7395,0.3052,0.7387 T0.2835,0.7379 Q0.2755,0.7379,0.253,0.7325 Q0.2506,0.7316,0.2462,0.731 T0.2382,0.7296 T0.2305,0.7271 T0.2181,0.7234 T0.2048,0.7196 T0.2,0.7155 Q0.2,0.7142,0.2016,0.713 Q0.208,0.7059,0.2285,0.6978 T0.2618,0.6898 Q0.2739,0.6898,0.2831,0.6848 T0.2956,0.6794 Q0.3028,0.6786,0.3289,0.6765 T0.3566,0.674 Q0.3582,0.674,0.3855,0.6723 T0.4406,0.6688 T0.4755,0.6653 Q0.5004,0.6607,0.5124,0.6599 L0.5165,0.6599 Q0.5213,0.6599,0.5277,0.6605 T0.5373,0.6611 Q0.543,0.6611,0.5494,0.6599 Q0.592,0.6524,0.6,0.6524 Q0.6064,0.6524,0.61,0.6499 T0.6161,0.6474 Q0.6177,0.6474,0.6261,0.6495 T0.6418,0.6516 L0.6482,0.6516 Q0.653,0.6512,0.6651,0.6506 T0.6876,0.6493 T0.7084,0.6477 T0.7229,0.645 Q0.7269,0.6437,0.7333,0.6437 Q0.7373,0.6437,0.7458,0.6443 T0.7574,0.645 Q0.7614,0.645,0.7631,0.6445 T0.7655,0.6441 Q0.7671,0.6441,0.7723,0.6448 T0.7823,0.6454 Q0.788,0.6454,0.7952,0.6445 Q0.8233,0.6408,0.8723,0.6367 Q0.9012,0.6342,0.9092,0.6342 L0.9165,0.6342 L0.9205,0.6342 Q0.9277,0.6342,0.9382,0.6323 T0.9526,0.6304 Q0.9534,0.6304,0.9594,0.6307 T0.9695,0.6309 Q0.9976,0.6309,0.9992,0.6234 Q1,0.6201,1,0.618 Q1,0.6089,0.9775,0.608 Q0.9703,0.6076,0.9582,0.6076 Q0.9518,0.6076,0.9394,0.6078 T0.9213,0.608 Q0.9036,0.608,0.8972,0.6072 Q0.894,0.6068,0.8871,0.6058 T0.8751,0.6039 T0.8627,0.6024 T0.8506,0.6018 L0.8474,0.6018 Q0.841,0.6022,0.8281,0.6041 T0.8112,0.606 Q0.8096,0.606,0.808,0.6056 Q0.7783,0.6002,0.7647,0.6002 Q0.7598,0.6002,0.7454,0.6006 T0.7261,0.601 Q0.7221,0.601,0.7145,0.6022 T0.7036,0.6035 Q0.6996,0.6035,0.6964,0.6022 Q0.6723,0.5902,0.6442,0.5902 Q0.6426,0.5902,0.6386,0.5904 T0.6337,0.5906 Q0.6273,0.5906,0.6249,0.5894 L0.6177,0.5856 T0.6116,0.5838 T0.6016,0.5825 T0.5855,0.5823 Q0.5719,0.5823,0.5574,0.5798 T0.5373,0.5774 L0.5341,0.5774 Q0.5293,0.5778,0.5213,0.5786 T0.51,0.5794 Q0.5036,0.5794,0.4988,0.5769 Q0.4932,0.574,0.4771,0.574 Q0.4723,0.574,0.4631,0.5745 T0.4498,0.5749 Q0.4418,0.5749,0.4394,0.5736 Q0.4353,0.5724,0.4305,0.5715 T0.4225,0.5707 T0.4145,0.5705 T0.4056,0.5699 Q0.4008,0.5691,0.398,0.5689 T0.394,0.5689 T0.3908,0.5686 T0.3855,0.5674 Q0.3831,0.567,0.3811,0.5662 T0.3779,0.5645 T0.3743,0.563 T0.3695,0.5624 Q0.3655,0.5624,0.3594,0.5635 T0.3494,0.5645 T0.3406,0.5635 T0.3325,0.5624 Q0.3309,0.5624,0.3301,0.5628 L0.3141,0.5628 Q0.2635,0.5628,0.2506,0.5612 Q0.2474,0.5608,0.2434,0.5608 Q0.2402,0.5608,0.2349,0.561 T0.2273,0.5612 Q0.2209,0.5612,0.2177,0.5595 Q0.2145,0.557,0.2145,0.5558 Q0.2169,0.5537,0.2345,0.5521 Q0.2876,0.5475,0.3028,0.5425 Q0.3068,0.5413,0.3149,0.5396 T0.3309,0.5367 T0.3478,0.5338 T0.3606,0.5309 Q0.3631,0.5305,0.3755,0.5259 T0.3968,0.5214 Q0.3992,0.5214,0.4024,0.5218 T0.4096,0.5222 Q0.4161,0.5222,0.4213,0.5209 T0.4313,0.5185 T0.4402,0.5172 Q0.4418,0.5168,0.447,0.5168 L0.4558,0.5168 T0.4639,0.5162 T0.4707,0.5141 T0.4731,0.5102 Q0.4731,0.5089,0.4723,0.5081 Q0.4699,0.5019,0.4627,0.4994 T0.4369,0.4965 Q0.4273,0.4961,0.4193,0.4946 T0.4048,0.4915 T0.3952,0.4894 Q0.392,0.4886,0.388,0.4886 Q0.3847,0.4886,0.3775,0.4892 T0.3647,0.4898 Q0.3598,0.4898,0.355,0.4894 Q0.3165,0.4861,0.3141,0.4853 Q0.2779,0.4774,0.2715,0.4774 Q0.2699,0.4774,0.2683,0.4776 T0.2627,0.4778 Q0.2498,0.4778,0.2281,0.4762 Q0.2241,0.4749,0.2233,0.4737 Q0.2249,0.472,0.2321,0.4708 Q0.2402,0.4695,0.2554,0.4695 L0.2675,0.4695 L0.2795,0.4695 Q0.294,0.4695,0.2996,0.4679 Q0.3141,0.4629,0.3373,0.4616 Q0.3414,0.4612,0.3466,0.4606 T0.3582,0.4589 T0.3687,0.4562 T0.3727,0.4525 Q0.3727,0.4509,0.3703,0.4492 Q0.3639,0.4455,0.3474,0.4419 T0.3213,0.4384 L0.3157,0.4384 L0.31,0.4384 Q0.294,0.4384,0.2859,0.4363 Q0.2795,0.4347,0.2691,0.4347 L0.2618,0.4347 L0.2546,0.4347 Q0.2458,0.4347,0.2394,0.4338 Q0.2257,0.4318,0.2193,0.4303 T0.2092,0.4266 T0.2052,0.4224 T0.2024,0.4154 T0.196,0.4052 Q0.1912,0.3994,0.1867,0.3949 T0.1807,0.3884 T0.1791,0.3849 Q0.1791,0.3824,0.1839,0.3745 Q0.1871,0.3687,0.1944,0.3637 T0.2072,0.3561 T0.2221,0.3501 T0.2321,0.3463 Q0.2353,0.3455,0.241,0.3445 T0.2522,0.3428 T0.2639,0.3411 T0.2731,0.3384 T0.2956,0.3351 T0.3197,0.3326 Q0.3213,0.3322,0.3237,0.3322 T0.3325,0.3331 T0.3414,0.3339 Q0.3478,0.3339,0.3518,0.3314 Q0.3606,0.3264,0.3703,0.3264 Q0.3775,0.3264,0.3847,0.3293 Q0.3888,0.331,0.396,0.331 Q0.4024,0.331,0.4116,0.3295 T0.4265,0.3266 T0.4414,0.3227 T0.4514,0.3202 Q0.4578,0.3181,0.4839,0.3152 T0.5112,0.3123 T0.5177,0.3119 T0.5285,0.3111 T0.5398,0.3096 T0.549,0.3065 T0.5526,0.3015 Q0.5526,0.2999,0.5518,0.2982 Q0.547,0.2903,0.5386,0.2883 T0.5165,0.2862 Q0.5116,0.2862,0.5056,0.2866 T0.4972,0.287 Q0.4884,0.287,0.4787,0.2833 Q0.4594,0.2758,0.4265,0.2758 Q0.4169,0.2758,0.4129,0.2766 Q0.4112,0.2771,0.4104,0.2771 Q0.4088,0.2771,0.4056,0.2748 T0.3968,0.2721 Q0.3695,0.2696,0.359,0.2659 Q0.355,0.2646,0.351,0.2646 T0.3426,0.2661 T0.3365,0.2675 T0.3333,0.2659 Q0.3277,0.2605,0.3116,0.2553 T0.2859,0.2501 L0.2843,0.2501 L0.2819,0.2501 Q0.2779,0.2501,0.2723,0.2493 T0.2586,0.2472 T0.2474,0.2455 Q0.1799,0.236,0.1719,0.236 Q0.1663,0.236,0.1606,0.235 T0.1502,0.2316 T0.1454,0.2265 Q0.1454,0.2223,0.1558,0.2173 Q0.1679,0.2115,0.1859,0.2092 T0.2185,0.207 T0.2353,0.2057 Q0.2369,0.2049,0.2502,0.2041 T0.2799,0.2022 T0.302,0.2007 Q0.3084,0.1999,0.3245,0.1954 T0.347,0.1908 Q0.3502,0.1908,0.3534,0.1916 Q0.3663,0.197,0.388,0.197 Q0.404,0.197,0.4088,0.1929 Q0.4096,0.192,0.4108,0.192 T0.4177,0.1945 T0.4277,0.197 T0.4369,0.1949 Q0.4442,0.1908,0.4843,0.1875 Q0.4892,0.1871,0.4968,0.1839 T0.5084,0.1808 L0.5108,0.1808 Q0.5213,0.1825,0.5454,0.1825 Q0.5823,0.1825,0.5992,0.1779 Q0.6096,0.1746,0.6217,0.1746 Q0.6249,0.1746,0.6309,0.1748 T0.6394,0.175 Q0.6434,0.175,0.6466,0.1746 Q0.6474,0.1746,0.6594,0.1738 T0.6787,0.1713 T0.6892,0.1659 Q0.6924,0.1634,0.6924,0.1593 Q0.6924,0.1547,0.6888,0.151 T0.6795,0.1472 Q0.6779,0.1472,0.6763,0.1477 Q0.6699,0.1493,0.6667,0.1493 Q0.661,0.1493,0.6506,0.1456 Q0.6329,0.1394,0.6129,0.1394 Q0.6048,0.1394,0.5992,0.1377 T0.5888,0.136 T0.5803,0.1377 T0.5751,0.1394 Q0.5711,0.1394,0.5639,0.1369 Q0.5365,0.1273,0.5116,0.1273 Q0.4876,0.1273,0.4667,0.1253 Q0.4627,0.1248,0.4542,0.1211 T0.4337,0.1174 L0.4305,0.1174 Q0.4217,0.1178,0.4153,0.119 T0.408,0.1203 Q0.4056,0.1203,0.4,0.117 Q0.3976,0.1153,0.396,0.1136 T0.3932,0.1112 T0.39,0.1099 T0.3847,0.1095 Q0.3799,0.1095,0.3687,0.1103 Q0.355,0.1112,0.3434,0.1141 T0.3301,0.117 Q0.3261,0.117,0.3229,0.1145 Q0.3181,0.1116,0.3052,0.1087 T0.2787,0.1043 T0.2546,0.1029 Q0.2506,0.1029,0.2474,0.1033 Q0.2418,0.1037,0.2349,0.1054 T0.2249,0.107 Q0.2225,0.107,0.2193,0.1066 Q0.2024,0.1024,0.1863,0.1024 Q0.1823,0.1024,0.1562,0.0971 T0.1269,0.0917 T0.1161,0.0896 T0.106,0.0854 Q0.1076,0.0846,0.11,0.0842 Q0.1173,0.0821,0.1261,0.0821 Q0.1301,0.0821,0.1369,0.0825 T0.1462,0.083 Q0.1494,0.083,0.151,0.0825 T0.1831,0.0813 T0.2201,0.0784 T0.243,0.074 T0.2667,0.0718 Q0.2707,0.0718,0.2755,0.0724 T0.2843,0.073 T0.2936,0.0724 T0.3024,0.0705 T0.3072,0.068 T0.3092,0.0657 T0.3108,0.0647 Q0.3116,0.0643,0.3133,0.0643 L0.3157,0.0643 L0.3181,0.0643 Q0.3446,0.0643,0.3446,0.0556 T0.3205,0.0469 L0.3189,0.0469 Q0.3157,0.0469,0.3157,0.0465 Q0.3084,0.0427,0.2835,0.0386 Q0.2739,0.0369,0.2675,0.0342 T0.2538,0.0299 Q0.249,0.029,0.245,0.029 T0.2378,0.0303 T0.2321,0.0315 Q0.2305,0.0315,0.2273,0.0307 Q0.2201,0.0286,0.2004,0.0272 T0.1775,0.0245 Q0.1735,0.0228,0.1663,0.0226 T0.1522,0.0197 T0.1345,0.0145 T0.1124,0.0079 Q0.0996,0.0033,0.0671,0.0044 T0.0297,0.0041 Q0.0169,0,0.0024,0.0017 Q0,0.0021,0,0.0037 Z M0.0064,0.9954 L0.0056,0.0058 Q0.0177,0.005,0.0281,0.0083 Q0.0345,0.01,0.0675,0.0089 T0.1108,0.012 Q0.1221,0.0162,0.1329,0.0187 T0.1498,0.0236 T0.1606,0.0268 T0.1691,0.0274 T0.1759,0.0286 Q0.1807,0.0303,0.2,0.0315 T0.2257,0.0348 Q0.2305,0.0361,0.2337,0.0361 Q0.2361,0.0361,0.2398,0.0348 T0.2466,0.0336 Q0.249,0.0336,0.2522,0.034 Q0.2586,0.0353,0.2655,0.0382 T0.2827,0.0427 Q0.3068,0.0469,0.3124,0.0502 Q0.3157,0.0523,0.3237,0.0523 L0.3277,0.0523 L0.3309,0.0523 Q0.3398,0.0523,0.3398,0.0556 Q0.3398,0.0581,0.3341,0.0587 T0.3205,0.0593 T0.3092,0.0603 T0.3036,0.0643 T0.2932,0.068 Q0.2884,0.0684,0.2843,0.0684 Q0.2811,0.0684,0.2763,0.0678 T0.2667,0.0672 Q0.2586,0.0672,0.2422,0.0697 T0.2177,0.0747 Q0.2137,0.0759,0.1831,0.0767 T0.1494,0.0784 L0.1474,0.0784 T0.1398,0.078 T0.1285,0.0776 Q0.1173,0.0776,0.1084,0.08 Q0.1004,0.0817,0.1004,0.0846 Q0.1004,0.0867,0.104,0.0888 T0.1124,0.0923 T0.1213,0.0948 T0.1269,0.0958 T0.155,0.1014 T0.1863,0.107 Q0.2016,0.107,0.2185,0.1107 Q0.2217,0.1116,0.2257,0.1116 Q0.2289,0.1116,0.2365,0.1099 T0.2482,0.1074 L0.2538,0.1074 Q0.2683,0.1074,0.2912,0.1107 T0.3197,0.1182 Q0.3245,0.1215,0.3301,0.1215 Q0.3333,0.1215,0.3454,0.1184 T0.3687,0.1145 Q0.3735,0.1141,0.3779,0.1139 T0.3843,0.1134 T0.3871,0.1132 Q0.3896,0.1132,0.39,0.1136 T0.392,0.1161 T0.3968,0.1203 Q0.404,0.1248,0.408,0.1248 Q0.4096,0.1248,0.4165,0.1234 T0.4305,0.1215 L0.4337,0.1215 Q0.4442,0.1215,0.4518,0.1251 T0.4659,0.1294 Q0.4876,0.1319,0.5116,0.1319 T0.5622,0.141 Q0.5703,0.1439,0.5751,0.1439 Q0.5791,0.1439,0.5831,0.1423 T0.5888,0.1406 Q0.592,0.1406,0.5944,0.1412 T0.6012,0.1427 T0.6129,0.1435 Q0.6313,0.1435,0.649,0.1497 Q0.6602,0.1535,0.6667,0.1535 Q0.6715,0.1535,0.6779,0.1522 Q0.6787,0.1518,0.6795,0.1518 Q0.6827,0.1518,0.6847,0.1541 T0.6867,0.1593 Q0.6867,0.1618,0.6851,0.1634 Q0.6835,0.1655,0.6775,0.1667 T0.6598,0.169 T0.6458,0.1705 T0.6402,0.1709 Q0.6378,0.1709,0.6321,0.1705 T0.6225,0.1701 Q0.6096,0.1701,0.5968,0.1738 Q0.5823,0.1779,0.5446,0.1779 Q0.5205,0.1779,0.5116,0.1767 Q0.51,0.1763,0.5084,0.1763 Q0.5028,0.1763,0.4944,0.1796 T0.4835,0.1829 L0.4771,0.1833 T0.4659,0.1844 L0.4546,0.1858 T0.443,0.1881 T0.4337,0.1912 Q0.4321,0.1916,0.4305,0.1916 Q0.4273,0.1916,0.4209,0.1895 T0.412,0.1875 Q0.408,0.1875,0.4056,0.19 Q0.4024,0.1925,0.388,0.1925 Q0.3663,0.1925,0.3558,0.1879 Q0.3518,0.1862,0.3462,0.1862 Q0.3373,0.1862,0.3213,0.191 T0.3012,0.1962 Q0.2964,0.1966,0.2799,0.1976 T0.2494,0.1997 T0.2313,0.2024 L0.2313,0.2024 L0.2293,0.2024 L0.2261,0.2024 L0.2217,0.2024 Q0.204,0.2024,0.1851,0.2047 T0.1526,0.2136 Q0.1406,0.2198,0.1406,0.226 Q0.1406,0.2319,0.1518,0.2362 T0.1719,0.2406 Q0.1791,0.2406,0.2466,0.2497 Q0.2498,0.2501,0.2574,0.2516 T0.2711,0.2538 T0.2819,0.2547 L0.2851,0.2547 Q0.2851,0.2543,0.2859,0.2543 Q0.294,0.2543,0.3096,0.2592 T0.3285,0.2684 Q0.3317,0.2721,0.3373,0.2721 Q0.3406,0.2721,0.3462,0.2708 T0.3542,0.2696 Q0.3558,0.2696,0.3574,0.27 Q0.3679,0.2737,0.3968,0.2762 Q0.3984,0.2766,0.4004,0.2779 L0.4044,0.2804 T0.4096,0.2816 Q0.412,0.2816,0.4145,0.2808 Q0.4177,0.2804,0.4249,0.2804 Q0.4586,0.2804,0.4763,0.287 Q0.4867,0.2912,0.4972,0.2912 Q0.5004,0.2912,0.5064,0.2908 T0.5165,0.2903 Q0.5293,0.2903,0.5361,0.2922 T0.547,0.3003 L0.547,0.3011 Q0.547,0.3036,0.5414,0.3049 T0.5249,0.3067 T0.51,0.3082 Q0.5092,0.3082,0.4831,0.3111 T0.4498,0.3161 Q0.408,0.3264,0.3952,0.3264 Q0.3896,0.3264,0.3863,0.3252 Q0.3783,0.3223,0.3703,0.3223 Q0.359,0.3223,0.3494,0.3277 Q0.347,0.3293,0.343,0.3293 Q0.3414,0.3293,0.3353,0.3285 T0.3253,0.3277 T0.3181,0.3285 Q0.3149,0.3289,0.2952,0.3306 T0.2699,0.3347 Q0.2675,0.3364,0.2598,0.3372 T0.2434,0.3395 T0.2297,0.3426 L0.2205,0.3461 T0.2048,0.3523 T0.1908,0.3606 T0.1791,0.3725 Q0.1743,0.3803,0.1743,0.3845 Q0.1743,0.3874,0.1763,0.3901 T0.1827,0.3976 T0.1912,0.4073 T0.198,0.4189 T0.2032,0.4276 T0.2137,0.4326 T0.2386,0.438 Q0.2458,0.4392,0.2562,0.4392 L0.2639,0.4392 L0.2699,0.4392 Q0.2795,0.4392,0.2843,0.4405 Q0.2932,0.443,0.3092,0.443 L0.3157,0.443 L0.3213,0.443 Q0.3293,0.443,0.3458,0.4463 T0.3671,0.4525 Q0.3598,0.4558,0.3373,0.4571 Q0.3124,0.4587,0.298,0.4637 Q0.294,0.465,0.2811,0.465 L0.2703,0.465 L0.2586,0.465 Q0.241,0.465,0.2305,0.4666 Q0.2185,0.4687,0.2185,0.4728 Q0.2185,0.4745,0.2205,0.4764 T0.2241,0.4791 L0.2265,0.4803 L0.2273,0.4803 Q0.2506,0.4824,0.261,0.4824 Q0.2675,0.4824,0.2699,0.482 Q0.2699,0.4815,0.2707,0.4815 Q0.2771,0.4815,0.3124,0.4898 Q0.3173,0.4907,0.3229,0.4913 T0.3386,0.4925 T0.3542,0.4936 T0.3663,0.494 Q0.3711,0.494,0.3787,0.4936 T0.3888,0.4932 Q0.392,0.4932,0.3944,0.4936 T0.4032,0.4959 T0.4181,0.499 T0.4369,0.5006 Q0.449,0.501,0.455,0.5021 T0.4639,0.5048 T0.4675,0.5093 L0.4675,0.5097 Q0.4675,0.5106,0.4663,0.511 T0.4622,0.5116 L0.4566,0.512 T0.4486,0.5124 T0.4402,0.5127 Q0.4345,0.5131,0.4257,0.5153 T0.4096,0.5176 Q0.4064,0.5176,0.4024,0.5172 L0.3968,0.5172 Q0.3863,0.5172,0.3731,0.522 T0.359,0.5268 Q0.355,0.528,0.3317,0.5321 T0.3004,0.5388 Q0.2867,0.5433,0.2337,0.5479 Q0.2096,0.55,0.2096,0.5562 Q0.2096,0.5591,0.2145,0.5628 Q0.2193,0.5662,0.2289,0.5662 Q0.2313,0.5662,0.2373,0.5657 T0.2458,0.5653 L0.2498,0.5653 Q0.2635,0.5674,0.3124,0.5674 Q0.3261,0.5674,0.3301,0.567 L0.3317,0.567 Q0.3341,0.567,0.3394,0.568 T0.3486,0.5691 Q0.3542,0.5691,0.3606,0.5678 T0.3699,0.5666 T0.3759,0.5686 T0.3839,0.5718 T0.3908,0.573 T0.3964,0.5734 T0.4048,0.5742 T0.4165,0.5751 T0.4277,0.5757 T0.4369,0.5778 Q0.4426,0.5794,0.4538,0.5794 Q0.4586,0.5794,0.4679,0.5792 T0.4811,0.579 Q0.4924,0.579,0.4956,0.5807 Q0.502,0.584,0.5108,0.584 L0.5137,0.584 T0.5173,0.5838 L0.5205,0.5834 L0.5237,0.583 L0.5269,0.5825 T0.5305,0.5821 T0.5341,0.5819 L0.5365,0.5819 Q0.5414,0.5819,0.5562,0.5842 T0.5855,0.5865 Q0.5912,0.5865,0.5948,0.5867 T0.6012,0.5869 T0.6064,0.5873 T0.61,0.5877 T0.6133,0.5886 T0.6157,0.5896 L0.6185,0.591 T0.6217,0.5931 Q0.6265,0.5952,0.6369,0.5952 L0.6418,0.5952 L0.6466,0.5952 Q0.6723,0.5952,0.6932,0.606 Q0.698,0.608,0.7044,0.608 Q0.7084,0.608,0.7161,0.6068 T0.7261,0.6056 Q0.7309,0.6056,0.7454,0.6051 T0.7647,0.6047 Q0.7775,0.6047,0.8072,0.6101 Q0.8096,0.6105,0.812,0.6105 Q0.8177,0.6105,0.8297,0.6085 T0.8474,0.606 L0.8506,0.606 Q0.8562,0.606,0.8647,0.607 T0.8831,0.6095 T0.8964,0.6118 Q0.9036,0.6122,0.9221,0.6122 L0.9406,0.6122 L0.959,0.6122 L0.9767,0.6122 Q0.9952,0.613,0.9952,0.6172 Q0.9952,0.6176,0.9944,0.6221 Q0.9936,0.6259,0.9574,0.6259 L0.955,0.6259 L0.9526,0.6259 Q0.9478,0.6259,0.9373,0.628 T0.9205,0.63 L0.9173,0.63 Q0.9133,0.6296,0.9084,0.6296 Q0.9004,0.6296,0.8715,0.6321 Q0.8233,0.6367,0.7944,0.64 Q0.7888,0.6408,0.7839,0.6408 T0.7739,0.6402 T0.7671,0.6396 Q0.7639,0.6396,0.7622,0.64 Q0.7614,0.6404,0.759,0.6404 Q0.7574,0.6404,0.749,0.6398 T0.7357,0.6392 Q0.7261,0.6392,0.7213,0.6412 Q0.7173,0.6425,0.7032,0.6437 T0.6711,0.6458 T0.6474,0.647 Q0.645,0.6474,0.6418,0.6474 Q0.6353,0.6474,0.6277,0.6454 T0.6161,0.6433 Q0.6104,0.6433,0.6072,0.6456 T0.6,0.6479 Q0.5912,0.6479,0.5486,0.6557 Q0.5422,0.657,0.5373,0.657 Q0.5349,0.657,0.5289,0.6564 T0.5173,0.6557 L0.5124,0.6557 Q0.4996,0.6562,0.4739,0.6611 Q0.4675,0.6624,0.4398,0.6645 T0.3851,0.668 T0.3558,0.6698 Q0.355,0.6698,0.3285,0.6721 T0.2948,0.6752 Q0.2892,0.6761,0.2843,0.6786 T0.2747,0.6831 T0.2618,0.6852 Q0.253,0.6852,0.2394,0.6893 T0.2141,0.6993 T0.1968,0.7105 Q0.1944,0.713,0.1944,0.7155 Q0.1944,0.7196,0.2012,0.7229 T0.2177,0.7285 T0.2281,0.7308 Q0.2321,0.7329,0.2365,0.7339 T0.245,0.7356 T0.2514,0.7366 Q0.2522,0.737,0.2554,0.7379 T0.2614,0.7393 T0.2679,0.7406 T0.2755,0.7416 T0.2835,0.742 Q0.29,0.742,0.3048,0.7428 T0.3253,0.7437 L0.3301,0.7437 L0.3333,0.7437 Q0.3341,0.7437,0.3598,0.7466 Q0.3639,0.7474,0.3671,0.7474 T0.3759,0.7466 T0.3855,0.7457 Q0.388,0.7457,0.3904,0.7462 Q0.3984,0.7466,0.4137,0.7495 T0.4349,0.7532 T0.441,0.7557 Q0.441,0.7599,0.4289,0.7619 Q0.4257,0.7628,0.4197,0.7634 T0.4072,0.7644 T0.3984,0.7652 Q0.3968,0.7652,0.3912,0.7655 T0.3811,0.7665 T0.3719,0.7694 Q0.3695,0.7702,0.3655,0.7702 T0.3546,0.7686 T0.3462,0.7665 L0.3446,0.7665 Q0.3406,0.7665,0.3293,0.769 T0.3149,0.7715 Q0.3084,0.7715,0.2952,0.7748 T0.2763,0.781 Q0.2675,0.7847,0.2554,0.7864 Q0.253,0.7864,0.2325,0.7874 T0.2024,0.7893 Q0.2008,0.7893,0.1984,0.7897 T0.1948,0.7901 T0.1916,0.7903 T0.1888,0.7908 T0.1867,0.7914 T0.1847,0.7922 L0.1831,0.793 T0.1819,0.7943 L0.1811,0.7959 T0.1799,0.7976 Q0.1791,0.7993,0.1791,0.8001 Q0.1791,0.8034,0.1831,0.8051 T0.1932,0.8078 T0.2,0.8092 Q0.2072,0.8117,0.2257,0.8117 Q0.2337,0.8117,0.2586,0.8109 L0.2635,0.8109 Q0.2707,0.8109,0.2767,0.8117 T0.2859,0.8136 T0.2936,0.8163 T0.3012,0.8187 Q0.3068,0.82,0.3277,0.8206 T0.3526,0.8237 Q0.3582,0.8266,0.3622,0.8266 Q0.3647,0.8266,0.3687,0.8258 T0.3751,0.825 Q0.396,0.825,0.404,0.8291 Q0.408,0.8316,0.4161,0.8316 Q0.4217,0.8316,0.4353,0.8295 L0.4394,0.8295 Q0.4466,0.8295,0.4659,0.8366 Q0.4699,0.8378,0.4747,0.8378 Q0.4763,0.8378,0.4807,0.8374 T0.4884,0.837 Q0.494,0.837,0.5004,0.8382 Q0.5052,0.8391,0.5124,0.8399 Q0.5221,0.8411,0.5249,0.8422 T0.5277,0.8461 Q0.5277,0.8482,0.5233,0.849 T0.5112,0.8501 T0.4996,0.8511 Q0.4964,0.8519,0.4851,0.8523 T0.4659,0.8544 Q0.4578,0.8557,0.4402,0.8557 L0.4349,0.8557 L0.4297,0.8557 L0.4209,0.8557 Q0.408,0.8565,0.3867,0.8571 T0.3614,0.8582 Q0.3317,0.8611,0.3237,0.8611 L0.3225,0.8611 L0.3213,0.8611 Q0.2972,0.8611,0.2972,0.8681 Q0.2972,0.8714,0.3008,0.8747 T0.3044,0.8805 Q0.3044,0.881,0.3036,0.8814 Q0.3012,0.8839,0.2851,0.8839 Q0.2779,0.8839,0.2739,0.883 Q0.2723,0.8826,0.2699,0.8826 T0.2643,0.8835 T0.259,0.8853 T0.2542,0.8876 T0.249,0.8893 Q0.2386,0.8922,0.2056,0.8946 Q0.2016,0.8951,0.1916,0.898 T0.1703,0.9009 Q0.1518,0.9009,0.1337,0.9044 T0.1149,0.9146 L0.1149,0.9158 Q0.1149,0.9175,0.1157,0.9187 T0.1173,0.921 T0.1201,0.9226 T0.1233,0.9237 T0.1269,0.9245 L0.1305,0.9251 T0.1337,0.9255 L0.1357,0.9258 Q0.139,0.9262,0.1446,0.9262 T0.1542,0.9266 T0.1598,0.9282 Q0.1614,0.9303,0.1647,0.9314 T0.1739,0.9328 T0.1815,0.9336 Q0.1863,0.9345,0.1976,0.9372 T0.2145,0.9415 Q0.2225,0.9432,0.2285,0.9467 T0.2378,0.9515 Q0.2426,0.9531,0.2514,0.9531 Q0.2538,0.9531,0.2602,0.9529 T0.2707,0.9527 Q0.2763,0.9527,0.2815,0.9531 T0.2867,0.9569 T0.2811,0.9614 Q0.2434,0.9627,0.2329,0.9652 Q0.2249,0.9672,0.2241,0.9672 L0.2096,0.9668 L0.2056,0.9668 Q0.2,0.9668,0.196,0.9672 T0.1884,0.9687 T0.1815,0.9708 T0.1731,0.9737 T0.1639,0.9772 Q0.1518,0.9805,0.1285,0.9805 L0.1253,0.9805 Q0.1124,0.9805,0.1076,0.9818 Q0.1012,0.983,0.0831,0.9876 T0.0594,0.9934 Q0.049,0.9954,0.0064,0.9954 Z M0.0032,0.9979 L0.0024,0.0037 Q0.0161,0.0021,0.0289,0.0062 Q0.0337,0.0075,0.0671,0.0066 T0.1116,0.01 T0.1337,0.0166 T0.151,0.022 Q0.1582,0.0249,0.1659,0.0251 T0.1767,0.0265 Q0.1807,0.0278,0.2,0.0292 T0.2265,0.0328 Q0.2305,0.034,0.2329,0.034 T0.239,0.0326 T0.2458,0.0311 T0.253,0.0319 Q0.2578,0.0332,0.2614,0.0342 T0.2667,0.0363 T0.2723,0.0384 T0.2827,0.0406 Q0.3084,0.0448,0.3141,0.0485 Q0.3149,0.0494,0.3225,0.0494 T0.3361,0.0504 T0.3422,0.0554 T0.3357,0.0606 T0.3205,0.0618 T0.31,0.0626 Q0.3092,0.0626,0.3056,0.0659 T0.2932,0.0701 Q0.2884,0.0709,0.2843,0.0709 Q0.2811,0.0709,0.2759,0.0701 T0.2667,0.0693 Q0.2586,0.0693,0.2422,0.0718 T0.2193,0.0763 Q0.2137,0.0784,0.1831,0.079 T0.1502,0.0805 Q0.1494,0.0809,0.147,0.0809 Q0.1454,0.0809,0.1386,0.0803 T0.1277,0.0796 Q0.1173,0.0796,0.1092,0.0821 Q0.1036,0.0834,0.1036,0.0854 Q0.1036,0.0879,0.1129,0.0908 T0.1269,0.0937 Q0.1293,0.0937,0.1558,0.0991 T0.1863,0.1045 Q0.2016,0.1045,0.2193,0.1087 Q0.2225,0.1091,0.2249,0.1091 Q0.2289,0.1091,0.2357,0.1076 T0.2482,0.1054 Q0.2506,0.1049,0.2546,0.1049 Q0.2699,0.1049,0.2924,0.1085 T0.3213,0.1165 Q0.3253,0.119,0.3301,0.119 Q0.3325,0.119,0.3446,0.1161 T0.3687,0.1124 Q0.3831,0.1112,0.3863,0.1112 T0.3908,0.1118 T0.3936,0.1145 T0.3984,0.1186 Q0.4048,0.1228,0.408,0.1228 Q0.4096,0.1228,0.4161,0.1213 T0.4305,0.1195 L0.4337,0.1195 Q0.4426,0.1195,0.4474,0.1211 T0.4566,0.1246 T0.4667,0.1273 Q0.4876,0.1298,0.5116,0.1298 Q0.5365,0.1298,0.5631,0.1389 Q0.5703,0.1414,0.5751,0.1414 Q0.5783,0.1414,0.5819,0.1398 T0.5888,0.1381 Q0.5928,0.1381,0.5984,0.1398 T0.6129,0.1414 Q0.6321,0.1414,0.6498,0.1477 Q0.661,0.1514,0.6667,0.1514 Q0.6707,0.1514,0.6771,0.1501 Q0.6787,0.1497,0.6795,0.1497 Q0.6835,0.1497,0.6863,0.1526 T0.6892,0.1593 Q0.6892,0.1626,0.6876,0.1647 Q0.6851,0.1672,0.6799,0.1686 T0.6695,0.1705 T0.6566,0.1715 T0.6458,0.1725 Q0.6434,0.173,0.6402,0.173 Q0.6378,0.173,0.6317,0.1727 T0.6225,0.1725 Q0.6096,0.1725,0.5984,0.1759 Q0.5823,0.1804,0.5454,0.1804 Q0.5205,0.1804,0.5116,0.1788 L0.5084,0.1788 Q0.5036,0.1788,0.4956,0.1819 T0.4843,0.185 Q0.4434,0.1887,0.4353,0.1929 Q0.4321,0.1945,0.4289,0.1945 T0.4197,0.1922 T0.4112,0.19 T0.4072,0.1912 Q0.4032,0.1949,0.388,0.1949 Q0.3663,0.1949,0.3542,0.19 Q0.351,0.1883,0.3462,0.1883 Q0.3406,0.1883,0.3321,0.1906 T0.3153,0.1954 T0.302,0.1983 Q0.2972,0.1991,0.2859,0.1997 T0.2643,0.201 T0.245,0.2024 T0.2337,0.2041 Q0.2321,0.2045,0.2181,0.2045 T0.1851,0.207 T0.1542,0.2157 Q0.143,0.2211,0.143,0.226 Q0.143,0.2314,0.153,0.2348 T0.1719,0.2381 Q0.1791,0.2381,0.2474,0.2476 Q0.2506,0.248,0.2558,0.2489 T0.2651,0.2505 T0.2739,0.252 T0.2819,0.2526 Q0.2835,0.2526,0.2851,0.2522 L0.2859,0.2522 Q0.2948,0.2522,0.3104,0.2574 T0.3309,0.2671 Q0.3333,0.2696,0.3365,0.2696 Q0.339,0.2696,0.3442,0.2684 T0.3526,0.2671 T0.3582,0.2679 Q0.3687,0.2717,0.3968,0.2742 Q0.4,0.2746,0.4036,0.2771 T0.4096,0.2796 Q0.4112,0.2796,0.4137,0.2787 Q0.4169,0.2779,0.4257,0.2779 Q0.4594,0.2779,0.4779,0.2849 Q0.4876,0.2891,0.4972,0.2891 Q0.4996,0.2891,0.506,0.2887 T0.5165,0.2883 Q0.5253,0.2883,0.5305,0.2889 T0.541,0.292 T0.5494,0.299 L0.5494,0.3015 Q0.5494,0.3036,0.5466,0.3051 T0.5386,0.3073 T0.5285,0.3086 T0.5181,0.3094 T0.5108,0.3102 Q0.5068,0.3107,0.494,0.3121 L0.4683,0.315 T0.4506,0.3181 Q0.449,0.3181,0.4426,0.32 T0.4313,0.3229 T0.4197,0.3256 T0.4064,0.3281 T0.3952,0.3289 Q0.3888,0.3289,0.3855,0.3273 Q0.3783,0.3243,0.3703,0.3243 Q0.3598,0.3243,0.351,0.3297 Q0.3478,0.3314,0.3422,0.3314 Q0.3398,0.3314,0.3337,0.3306 T0.3245,0.3297 T0.3189,0.3306 Q0.3149,0.3314,0.2956,0.3328 T0.2715,0.3368 Q0.2691,0.338,0.2635,0.3391 T0.2522,0.3407 T0.2406,0.3424 T0.2313,0.3447 Q0.2305,0.3447,0.2213,0.348 T0.206,0.354 T0.1924,0.3621 T0.1815,0.3733 Q0.1767,0.3816,0.1767,0.3849 Q0.1767,0.387,0.1783,0.3893 T0.1847,0.3961 T0.1936,0.4063 T0.2004,0.4181 T0.2052,0.4264 T0.2145,0.4309 T0.2386,0.4359 Q0.2458,0.4372,0.2554,0.4372 Q0.2578,0.4372,0.2627,0.437 T0.2699,0.4367 Q0.2795,0.4367,0.2851,0.4384 Q0.294,0.4409,0.3092,0.4409 Q0.3116,0.4409,0.3157,0.4407 T0.3213,0.4405 Q0.3301,0.4405,0.3466,0.444 T0.3687,0.4509 Q0.3703,0.4517,0.3703,0.4525 Q0.3703,0.4575,0.3373,0.4596 Q0.3133,0.4608,0.2988,0.4658 Q0.294,0.4674,0.2803,0.4674 Q0.2763,0.4674,0.2687,0.4672 T0.257,0.467 Q0.2402,0.467,0.2313,0.4687 Q0.2209,0.4708,0.2209,0.4737 Q0.2209,0.4741,0.2213,0.4749 T0.2229,0.4764 L0.2249,0.4774 T0.2265,0.4778 L0.2273,0.4782 Q0.2498,0.4803,0.2618,0.4803 Q0.2667,0.4803,0.2691,0.4799 Q0.2699,0.4795,0.2715,0.4795 Q0.2779,0.4795,0.3133,0.4873 Q0.3181,0.4886,0.3233,0.4892 T0.3386,0.4905 T0.3542,0.4915 T0.3655,0.4919 Q0.3703,0.4919,0.3779,0.4915 T0.3888,0.4911 T0.3952,0.4915 Q0.3976,0.4919,0.4008,0.4927 L0.4072,0.4944 T0.4149,0.4961 T0.4249,0.4975 T0.4369,0.4985 Q0.449,0.499,0.4554,0.5 T0.4651,0.5031 T0.4699,0.5085 Q0.4707,0.5093,0.4707,0.5097 Q0.4707,0.5114,0.4687,0.5124 T0.4631,0.5139 T0.4562,0.5145 T0.4478,0.5147 L0.4402,0.5147 Q0.4353,0.5151,0.4265,0.5174 T0.4096,0.5197 L0.4024,0.5197 Q0.4,0.5193,0.3968,0.5193 Q0.3896,0.5193,0.3831,0.5209 T0.3703,0.5253 T0.3598,0.5288 Q0.3558,0.5301,0.3321,0.5342 T0.302,0.5409 Q0.2876,0.5454,0.2337,0.55 Q0.2112,0.5521,0.2112,0.5558 Q0.2112,0.5574,0.2161,0.5612 Q0.2201,0.5637,0.2281,0.5637 Q0.2305,0.5637,0.2361,0.5633 T0.2442,0.5628 Q0.2474,0.5628,0.2498,0.5633 Q0.2635,0.5653,0.3133,0.5653 Q0.3261,0.5653,0.3301,0.5649 L0.3325,0.5649 Q0.3349,0.5649,0.3402,0.5657 T0.3494,0.5666 Q0.3542,0.5666,0.3598,0.5657 Q0.3663,0.5645,0.3695,0.5645 Q0.3735,0.5645,0.3775,0.5666 T0.3847,0.5695 Q0.3888,0.5707,0.3912,0.5709 T0.3968,0.5711 T0.4048,0.572 Q0.4096,0.5724,0.4165,0.5726 T0.4281,0.5734 T0.4378,0.5757 Q0.4418,0.5774,0.4522,0.5774 Q0.4562,0.5774,0.4655,0.5769 T0.4795,0.5765 Q0.4932,0.5765,0.4972,0.579 Q0.5028,0.5819,0.51,0.5819 Q0.5141,0.5819,0.5221,0.5809 T0.5341,0.5798 L0.5373,0.5798 Q0.5422,0.5798,0.557,0.5821 T0.5855,0.5844 L0.5936,0.5844 L0.5992,0.5844 T0.604,0.5848 T0.6076,0.5852 T0.6108,0.5859 T0.6137,0.5865 T0.6161,0.5873 T0.6181,0.5881 T0.6209,0.5896 L0.6233,0.591 Q0.6265,0.5927,0.6353,0.5927 L0.6402,0.5927 L0.645,0.5927 Q0.6723,0.5927,0.6948,0.6039 Q0.6988,0.606,0.7036,0.606 Q0.7076,0.606,0.7153,0.6045 T0.7261,0.6031 Q0.7309,0.6031,0.7454,0.6027 T0.7647,0.6022 Q0.7783,0.6022,0.808,0.608 L0.812,0.608 Q0.8169,0.608,0.8293,0.6062 T0.8474,0.6039 L0.8506,0.6039 Q0.857,0.6039,0.8655,0.6049 T0.8835,0.6074 T0.8972,0.6093 Q0.9036,0.6101,0.9213,0.6101 L0.9398,0.6101 L0.959,0.6101 L0.9767,0.6101 Q0.9976,0.6109,0.9976,0.6176 Q0.9976,0.6188,0.9968,0.6226 Q0.9952,0.6284,0.9671,0.6284 L0.959,0.6284 L0.9526,0.6284 Q0.9486,0.6284,0.9382,0.6302 T0.9205,0.6321 L0.9173,0.6321 Q0.9133,0.6317,0.9092,0.6317 Q0.9012,0.6317,0.8715,0.6346 Q0.8233,0.6387,0.7944,0.6421 Q0.7888,0.6429,0.7831,0.6429 Q0.7783,0.6429,0.7731,0.6425 T0.7663,0.6421 L0.7622,0.6421 Q0.7614,0.6425,0.7586,0.6425 T0.7474,0.6421 T0.7349,0.6416 Q0.7261,0.6416,0.7221,0.6429 Q0.7173,0.645,0.7032,0.646 T0.6711,0.6479 T0.6482,0.6491 Q0.645,0.6495,0.6418,0.6495 Q0.6353,0.6495,0.6273,0.6474 T0.6161,0.6454 Q0.612,0.6454,0.6088,0.6477 T0.6,0.6499 Q0.5912,0.6499,0.5494,0.6578 Q0.5422,0.6591,0.5373,0.6591 Q0.5341,0.6591,0.5281,0.6584 T0.5173,0.6578 L0.5124,0.6578 Q0.5004,0.6582,0.4747,0.6632 Q0.4675,0.6649,0.4398,0.6667 T0.3851,0.6703 T0.3566,0.6719 Q0.3534,0.6723,0.3406,0.6734 T0.3141,0.6757 T0.2948,0.6773 Q0.2908,0.6781,0.2819,0.6829 T0.2618,0.6877 Q0.2482,0.6877,0.2273,0.6958 T0.1992,0.7117 Q0.1976,0.7138,0.1976,0.7155 Q0.1976,0.7188,0.2032,0.7213 T0.2181,0.7258 T0.2289,0.7292 Q0.2337,0.7308,0.2378,0.7316 L0.2458,0.7333 T0.2522,0.7345 Q0.2747,0.7399,0.2835,0.7399 Q0.29,0.7399,0.3048,0.7408 T0.3253,0.7416 Q0.3277,0.7416,0.3297,0.7414 T0.3341,0.7412 L0.3598,0.7445 Q0.3639,0.7449,0.3663,0.7449 Q0.3695,0.7449,0.3751,0.7443 T0.3855,0.7437 L0.3904,0.7437 Q0.3984,0.7441,0.4141,0.7472 T0.4353,0.7507 Q0.4434,0.752,0.4434,0.7553 Q0.4434,0.7578,0.439,0.7605 T0.4297,0.764 Q0.4257,0.7648,0.4201,0.7655 T0.4076,0.7665 T0.3984,0.7673 Q0.3968,0.7673,0.3912,0.7677 T0.3815,0.7688 T0.3735,0.771 T0.3655,0.7727 Q0.3606,0.7727,0.3534,0.7708 T0.3458,0.769 L0.3446,0.769 Q0.3414,0.769,0.3297,0.7713 T0.3149,0.7735 Q0.3092,0.7735,0.296,0.7771 T0.2771,0.7831 Q0.2683,0.7872,0.2554,0.7885 Q0.253,0.7889,0.2325,0.7897 T0.2032,0.7914 Q0.2008,0.7918,0.198,0.792 T0.194,0.7924 T0.1912,0.7928 T0.1888,0.793 T0.1867,0.7934 T0.1851,0.7943 T0.1843,0.7953 T0.1835,0.7968 T0.1823,0.7984 T0.1815,0.8001 Q0.1815,0.8022,0.1847,0.8032 T0.1932,0.8053 T0.2008,0.8071 Q0.2072,0.8092,0.2265,0.8092 Q0.2361,0.8092,0.2586,0.8088 L0.2635,0.8088 Q0.2731,0.8088,0.2795,0.8098 T0.2928,0.8134 T0.302,0.8167 Q0.306,0.8179,0.3277,0.8183 T0.3542,0.8221 Q0.359,0.8246,0.3622,0.8246 Q0.3639,0.8246,0.3675,0.8237 T0.3751,0.8229 Q0.3968,0.8229,0.4048,0.8275 Q0.4088,0.8291,0.4161,0.8291 Q0.4225,0.8291,0.4353,0.8275 Q0.4369,0.827,0.4394,0.827 Q0.4474,0.827,0.4675,0.8345 Q0.4707,0.8358,0.4739,0.8358 Q0.4755,0.8358,0.4799,0.8353 T0.4876,0.8349 Q0.494,0.8349,0.5012,0.8362 L0.5076,0.837 T0.5133,0.8376 T0.5181,0.8382 T0.5221,0.8391 L0.5253,0.8399 T0.5277,0.8409 L0.5293,0.8422 T0.5301,0.8438 L0.5301,0.8461 Q0.5301,0.8499,0.5249,0.8511 T0.5112,0.8526 T0.5004,0.8532 Q0.4964,0.854,0.4851,0.8546 T0.4667,0.8565 Q0.4578,0.8577,0.441,0.8577 L0.4345,0.8577 L0.4289,0.8577 L0.4209,0.8577 Q0.4153,0.8582,0.4088,0.8586 T0.3968,0.8592 T0.3855,0.8594 T0.3755,0.8596 T0.3675,0.86 T0.3622,0.8602 Q0.3317,0.8635,0.3237,0.8635 Q0.2996,0.8635,0.2996,0.8681 Q0.2996,0.8698,0.3032,0.8733 T0.3068,0.8797 L0.3068,0.8822 Q0.3052,0.8859,0.2859,0.8859 Q0.2787,0.8859,0.2739,0.8851 L0.2699,0.8851 Q0.2659,0.8851,0.259,0.888 T0.2498,0.8913 Q0.2394,0.8946,0.2056,0.8971 Q0.2032,0.8971,0.1928,0.9002 T0.1703,0.9034 Q0.1526,0.9034,0.1353,0.9067 T0.1173,0.915 L0.1173,0.9158 Q0.1173,0.9166,0.1177,0.9175 T0.1189,0.9191 T0.1205,0.9204 T0.1229,0.9212 T0.1257,0.922 T0.1285,0.9226 T0.1309,0.9231 T0.1337,0.9235 T0.1365,0.9237 L0.1446,0.9237 T0.1554,0.9243 T0.1614,0.9268 T0.1659,0.9293 T0.1743,0.9303 T0.1823,0.9316 Q0.1863,0.932,0.1912,0.9332 T0.2028,0.9361 T0.2153,0.939 Q0.2233,0.9411,0.2297,0.9448 T0.2386,0.9494 Q0.2426,0.9506,0.2506,0.9506 Q0.253,0.9506,0.2594,0.9504 T0.2699,0.9502 Q0.2763,0.9502,0.2819,0.9511 Q0.2851,0.9511,0.2871,0.9529 T0.2892,0.9573 Q0.2892,0.9627,0.2811,0.9635 Q0.2434,0.9652,0.2337,0.9672 Q0.2257,0.9693,0.2241,0.9693 Q0.2217,0.9693,0.2096,0.9689 L0.2056,0.9689 Q0.1976,0.9689,0.1924,0.9699 T0.1787,0.9741 L0.1647,0.9793 Q0.1518,0.983,0.1285,0.983 L0.1261,0.983 L0.1237,0.983 Q0.1124,0.983,0.1076,0.9838 Q0.102,0.9851,0.0839,0.9896 T0.0602,0.9954 T0.0406,0.9971 T0.0153,0.9979 L0.0032,0.9979 Z",type:0}},"":{type:5,data:{d:"M0.9992,0.998 Q0.9992,1,0.9968,1 Q0.9521,1,0.9392,0.998 Q0.9335,0.997,0.9152,0.9921 T0.8913,0.9862 Q0.8873,0.9852,0.8783,0.9852 L0.8747,0.9852 L0.871,0.9852 Q0.8483,0.9852,0.8345,0.9812 Q0.8289,0.9792,0.8228,0.9773 T0.8135,0.9743 T0.8054,0.9723 T0.7948,0.9713 L0.7908,0.9713 L0.777,0.9713 T0.7656,0.9693 Q0.7616,0.9683,0.7498,0.9674 T0.7283,0.9664 L0.7186,0.9654 Q0.708,0.9644,0.708,0.9575 Q0.708,0.9545,0.7109,0.952 T0.7178,0.9486 L0.7315,0.9486 L0.7417,0.9486 L0.7502,0.9486 Q0.7575,0.9486,0.7599,0.9476 Q0.7616,0.9466,0.7685,0.9426 T0.7843,0.9377 Q0.7899,0.9357,0.8009,0.9332 T0.8175,0.9298 Q0.82,0.9288,0.8228,0.9283 T0.8277,0.9278 T0.8313,0.9273 T0.8341,0.9263 T0.8362,0.9258 Q0.8402,0.9219,0.854,0.9219 L0.8569,0.9219 L0.8597,0.9219 L0.8637,0.9219 Q0.88,0.9199,0.88,0.9159 L0.88,0.9149 Q0.88,0.913,0.8719,0.911 T0.852,0.9075 T0.8297,0.906 Q0.8224,0.906,0.8167,0.905 T0.8074,0.9031 T0.8001,0.9006 T0.794,0.8991 Q0.7599,0.8971,0.7494,0.8942 Q0.7461,0.8932,0.7397,0.8902 T0.7299,0.8872 L0.7267,0.8872 Q0.721,0.8882,0.7121,0.8882 Q0.6926,0.8882,0.691,0.8833 L0.691,0.8803 Q0.691,0.8773,0.6922,0.8749 T0.6955,0.8704 L0.6975,0.8684 Q0.6926,0.8655,0.6764,0.8655 Q0.6683,0.8655,0.6375,0.8625 Q0.6358,0.8625,0.629,0.862 T0.6148,0.8615 T0.5973,0.861 T0.5791,0.8605 L0.5718,0.8605 L0.5661,0.8605 L0.5596,0.8605 Q0.5426,0.8605,0.5337,0.8586 Q0.5264,0.8576,0.515,0.8571 T0.4996,0.8556 Q0.498,0.8556,0.4947,0.8551 T0.4882,0.8546 T0.4809,0.8541 T0.474,0.8531 T0.4692,0.8506 T0.4672,0.8467 Q0.4672,0.8437,0.468,0.8422 T0.4704,0.8398 T0.4736,0.8383 T0.4781,0.8368 T0.4838,0.8358 T0.4911,0.8353 T0.4988,0.8338 Q0.5069,0.8328,0.5142,0.8328 Q0.5174,0.8328,0.5215,0.8333 T0.5264,0.8338 Q0.5296,0.8338,0.532,0.8328 Q0.5523,0.8249,0.5604,0.8249 L0.5653,0.8249 Q0.5775,0.8269,0.5848,0.8269 Q0.5912,0.8269,0.5937,0.8259 Q0.6026,0.821,0.6253,0.821 Q0.6294,0.821,0.6334,0.822 T0.6383,0.8229 Q0.6399,0.8229,0.644,0.82 Q0.6504,0.817,0.6723,0.816 T0.6975,0.814 Q0.6999,0.814,0.7048,0.8121 T0.7129,0.8091 T0.7226,0.8071 T0.7372,0.8061 L0.7421,0.8061 Q0.7624,0.8071,0.7721,0.8071 Q0.7924,0.8071,0.7981,0.8051 Q0.8021,0.8032,0.807,0.8027 T0.8135,0.8017 T0.8151,0.8002 L0.8151,0.7992 Q0.8143,0.7962,0.8127,0.7957 T0.8045,0.7943 Q0.7997,0.7943,0.7964,0.7933 Q0.7883,0.7933,0.7676,0.7923 T0.7437,0.7903 Q0.7307,0.7893,0.7218,0.7844 Q0.7194,0.7834,0.7141,0.7819 L0.7036,0.7789 T0.693,0.7765 T0.6853,0.7755 Q0.6805,0.7755,0.6691,0.773 T0.6553,0.7705 Q0.6545,0.7705,0.6545,0.7715 Q0.6537,0.7715,0.65,0.7725 T0.6423,0.774 T0.635,0.7745 Q0.6294,0.7745,0.6257,0.773 T0.618,0.771 T0.6083,0.77 T0.601,0.7695 Q0.5985,0.7695,0.5921,0.769 T0.5795,0.7676 T0.5702,0.7666 Q0.5653,0.7656,0.5596,0.7616 T0.5539,0.7547 Q0.5539,0.7498,0.5645,0.7488 Q0.5693,0.7478,0.5852,0.7448 T0.6099,0.7418 L0.6148,0.7418 Q0.6196,0.7418,0.6253,0.7423 T0.6338,0.7428 L0.6399,0.7428 Q0.6431,0.7418,0.6488,0.7409 T0.6586,0.7394 T0.6659,0.7389 L0.6707,0.7389 Q0.6723,0.7399,0.6748,0.7399 Q0.6796,0.7399,0.6946,0.7389 T0.7161,0.7379 Q0.7251,0.7379,0.7478,0.7319 Q0.7494,0.7319,0.7539,0.7315 T0.762,0.73 T0.7697,0.727 T0.7818,0.723 T0.7948,0.7196 T0.7997,0.7151 Q0.7997,0.7141,0.7989,0.7132 Q0.7924,0.7062,0.7717,0.6978 T0.738,0.6894 Q0.7267,0.6894,0.717,0.6845 T0.7048,0.6795 Q0.6975,0.6785,0.6711,0.6766 T0.6431,0.6746 Q0.6415,0.6736,0.6144,0.6721 T0.5596,0.6686 T0.5247,0.6657 Q0.4996,0.6607,0.4874,0.6597 L0.4834,0.6597 Q0.4785,0.6597,0.4724,0.6607 T0.4631,0.6617 Q0.4574,0.6617,0.4501,0.6597 Q0.4088,0.6518,0.4006,0.6518 Q0.3933,0.6518,0.3901,0.6499 T0.3844,0.6479 T0.3739,0.6499 T0.3585,0.6518 L0.352,0.6518 Q0.3471,0.6508,0.335,0.6503 T0.3122,0.6494 T0.2912,0.6479 T0.2766,0.6449 Q0.2733,0.6439,0.2668,0.6439 Q0.2628,0.6439,0.2543,0.6444 T0.2425,0.6449 T0.2368,0.6439 L0.2344,0.6439 Q0.2336,0.6439,0.2283,0.6444 T0.2182,0.6449 Q0.2117,0.6449,0.2052,0.6439 Q0.1768,0.6409,0.1281,0.637 Q0.0989,0.634,0.0916,0.634 L0.0835,0.634 L0.0795,0.634 Q0.0722,0.634,0.0616,0.632 T0.0479,0.6301 Q0.0462,0.6301,0.0406,0.6306 T0.0308,0.6311 Q0.0032,0.6311,0.0008,0.6231 Q0,0.6202,0,0.6182 Q0,0.6083,0.0227,0.6083 Q0.03,0.6073,0.0422,0.6073 Q0.0487,0.6073,0.0608,0.6078 T0.0787,0.6083 Q0.0973,0.6083,0.103,0.6073 Q0.1062,0.6063,0.1131,0.6053 T0.1253,0.6039 T0.1375,0.6024 T0.1492,0.6014 L0.1533,0.6014 Q0.1598,0.6024,0.1723,0.6044 T0.189,0.6063 Q0.1906,0.6063,0.1922,0.6053 Q0.2214,0.6004,0.236,0.6004 Q0.2409,0.6004,0.2551,0.6009 T0.2741,0.6014 Q0.2782,0.6014,0.2859,0.6024 T0.2968,0.6034 Q0.3009,0.6034,0.3041,0.6024 Q0.3277,0.5905,0.356,0.5905 L0.3613,0.5905 L0.3666,0.5905 Q0.3731,0.5905,0.3755,0.5895 Q0.382,0.5856,0.3844,0.5846 T0.3938,0.5831 T0.4144,0.5826 T0.4428,0.5801 T0.4631,0.5776 L0.4663,0.5776 Q0.4704,0.5776,0.4785,0.5786 T0.4899,0.5796 Q0.4964,0.5796,0.5012,0.5767 Q0.5069,0.5737,0.5223,0.5737 Q0.5272,0.5737,0.5369,0.5742 T0.5499,0.5747 Q0.558,0.5747,0.5612,0.5737 Q0.5661,0.5717,0.5714,0.5712 T0.5835,0.5702 T0.5945,0.5692 T0.6018,0.5687 L0.6062,0.5687 T0.6095,0.5682 T0.6148,0.5678 Q0.6172,0.5668,0.6196,0.5653 T0.6245,0.5633 T0.631,0.5628 T0.6407,0.5638 T0.6504,0.5648 T0.6594,0.5638 T0.6675,0.5628 L0.6707,0.5628 L0.6861,0.5628 Q0.7364,0.5628,0.7494,0.5608 L0.7567,0.5608 L0.7652,0.5608 L0.7729,0.5608 Q0.7794,0.5608,0.7818,0.5589 Q0.7851,0.5569,0.7859,0.5559 Q0.7835,0.5539,0.7656,0.5519 Q0.7121,0.547,0.6975,0.543 Q0.6934,0.541,0.6853,0.5396 L0.6691,0.5366 T0.6525,0.5336 T0.6391,0.5312 Q0.6367,0.5302,0.6245,0.5257 T0.6034,0.5213 L0.5977,0.5213 Q0.5945,0.5223,0.5904,0.5223 Q0.5839,0.5223,0.5787,0.5208 T0.5685,0.5183 T0.5596,0.5173 Q0.558,0.5173,0.5552,0.5168 T0.5495,0.5163 L0.5434,0.5163 T0.5373,0.5158 T0.532,0.5148 T0.5284,0.5129 T0.5272,0.5104 L0.5272,0.5074 Q0.5304,0.5015,0.5377,0.499 T0.5629,0.4965 Q0.5734,0.4955,0.5811,0.4946 T0.5953,0.4916 T0.605,0.4896 Q0.6083,0.4886,0.6123,0.4886 Q0.6148,0.4886,0.6225,0.4891 T0.635,0.4896 L0.6456,0.4896 Q0.6837,0.4857,0.6861,0.4857 Q0.7226,0.4768,0.7283,0.4768 Q0.7307,0.4768,0.732,0.4773 T0.7372,0.4777 Q0.7502,0.4777,0.7721,0.4758 Q0.7753,0.4748,0.777,0.4738 Q0.7745,0.4718,0.768,0.4708 Q0.7599,0.4688,0.7445,0.4688 Q0.7405,0.4688,0.7324,0.4693 T0.721,0.4698 Q0.7056,0.4698,0.6999,0.4679 Q0.6861,0.4629,0.6626,0.4619 Q0.6586,0.4609,0.6533,0.4604 T0.6419,0.459 T0.6314,0.456 T0.6269,0.452 Q0.6269,0.451,0.6302,0.4491 Q0.6358,0.4451,0.6525,0.4416 T0.6788,0.4382 L0.6845,0.4382 L0.6902,0.4382 Q0.7064,0.4382,0.7145,0.4362 Q0.7202,0.4342,0.7307,0.4342 L0.7356,0.4342 L0.7409,0.4342 L0.7453,0.4342 Q0.7543,0.4342,0.7607,0.4332 Q0.7778,0.4313,0.7847,0.4288 T0.7932,0.4248 T0.7972,0.4169 T0.8045,0.4045 L0.8094,0.3986 T0.8135,0.3942 L0.8167,0.3912 T0.8191,0.3887 T0.8204,0.3867 T0.8208,0.3848 Q0.8208,0.3818,0.8167,0.3739 Q0.8127,0.3689,0.8054,0.3635 T0.7924,0.3556 T0.7778,0.3497 T0.768,0.3462 Q0.764,0.3442,0.7478,0.3427 T0.7267,0.3383 Q0.7234,0.3363,0.7044,0.3348 T0.6805,0.3323 L0.6764,0.3323 T0.6679,0.3328 T0.6586,0.3333 Q0.6521,0.3333,0.648,0.3314 Q0.6391,0.3264,0.6294,0.3264 Q0.6229,0.3264,0.6156,0.3294 Q0.6115,0.3304,0.6042,0.3304 Q0.5977,0.3304,0.5888,0.3289 T0.5738,0.3264 T0.5584,0.3225 L0.5491,0.3195 Q0.5418,0.3185,0.5162,0.3155 T0.4895,0.3121 T0.4826,0.3116 T0.4716,0.3111 T0.4607,0.3096 T0.4513,0.3066 T0.4477,0.3017 Q0.4477,0.2997,0.4485,0.2977 Q0.4526,0.2898,0.4611,0.2878 T0.4842,0.2859 Q0.4882,0.2859,0.4943,0.2864 T0.5028,0.2868 Q0.5118,0.2868,0.5215,0.2829 Q0.5401,0.276,0.5734,0.276 Q0.5831,0.276,0.5872,0.277 L0.5904,0.277 T0.5949,0.2745 T0.6034,0.272 Q0.631,0.269,0.6407,0.2661 Q0.6448,0.2641,0.6488,0.2641 T0.6573,0.2656 T0.6634,0.2671 Q0.6659,0.2671,0.6675,0.2651 Q0.6723,0.2601,0.6886,0.2552 T0.7137,0.2502 L0.7153,0.2502 L0.7178,0.2502 Q0.7218,0.2502,0.7279,0.2493 T0.7417,0.2468 T0.7526,0.2453 Q0.8208,0.2354,0.8281,0.2354 Q0.8337,0.2354,0.8394,0.2344 T0.8496,0.2315 T0.854,0.2265 Q0.854,0.2216,0.8443,0.2176 Q0.8354,0.2127,0.8216,0.2102 T0.7972,0.2072 T0.777,0.2067 T0.7648,0.2057 Q0.7632,0.2047,0.7498,0.2038 T0.7202,0.2018 T0.6983,0.1998 Q0.6918,0.1998,0.676,0.1949 T0.6537,0.1899 Q0.6496,0.1899,0.6472,0.1919 Q0.6342,0.1968,0.6123,0.1968 Q0.5961,0.1968,0.5912,0.1929 Q0.5904,0.1919,0.5892,0.1919 T0.5823,0.1944 T0.5722,0.1968 T0.5637,0.1949 Q0.5556,0.1909,0.5158,0.1869 Q0.5109,0.1869,0.5032,0.1835 T0.4915,0.18 Q0.4907,0.18,0.4891,0.181 Q0.4793,0.182,0.455,0.182 Q0.4177,0.182,0.4015,0.1771 Q0.3901,0.1741,0.3779,0.1741 Q0.3747,0.1741,0.369,0.1746 T0.3609,0.1751 Q0.3569,0.1751,0.3536,0.1741 Q0.3512,0.1741,0.3459,0.1736 T0.3358,0.1726 T0.3256,0.1716 T0.3167,0.1696 T0.3106,0.1662 Q0.3082,0.1632,0.3082,0.1592 Q0.3082,0.1543,0.3114,0.1508 T0.3204,0.1474 L0.3236,0.1474 Q0.3301,0.1494,0.3333,0.1494 Q0.339,0.1494,0.3496,0.1454 Q0.3674,0.1385,0.3869,0.1385 Q0.395,0.1385,0.4011,0.137 T0.4116,0.1355 T0.4197,0.1375 T0.425,0.1395 Q0.429,0.1395,0.4355,0.1365 Q0.4631,0.1266,0.4882,0.1266 Q0.5126,0.1266,0.5337,0.1246 Q0.5369,0.1246,0.5458,0.1207 T0.5661,0.1167 L0.5693,0.1167 Q0.5791,0.1177,0.5852,0.1187 T0.5921,0.1197 Q0.5945,0.1197,0.6002,0.1167 Q0.6026,0.1147,0.605,0.1123 T0.6091,0.1093 T0.6156,0.1088 T0.6318,0.1098 Q0.6456,0.1108,0.6569,0.1137 T0.6707,0.1167 Q0.674,0.1167,0.6772,0.1147 Q0.6821,0.1108,0.6946,0.1083 T0.721,0.1044 T0.7453,0.1029 L0.7526,0.1029 Q0.7583,0.1039,0.7652,0.1053 T0.7753,0.1068 Q0.7778,0.1068,0.7802,0.1058 Q0.7981,0.1019,0.8143,0.1019 Q0.8175,0.1019,0.8439,0.0964 T0.8735,0.091 Q0.8759,0.091,0.8836,0.089 T0.8938,0.0851 Q0.8929,0.0841,0.8905,0.0841 Q0.8832,0.0821,0.8735,0.0821 Q0.8694,0.0821,0.8629,0.0826 T0.854,0.0831 Q0.8508,0.0831,0.8491,0.0821 Q0.8475,0.0821,0.8171,0.0811 T0.7802,0.0781 T0.7571,0.0737 T0.7332,0.0712 Q0.7299,0.0712,0.7247,0.0717 T0.7161,0.0722 L0.7064,0.0722 Q0.7032,0.0712,0.7003,0.0707 T0.6959,0.0692 T0.693,0.0678 T0.6914,0.0663 T0.6902,0.0648 T0.689,0.0643 L0.6869,0.0643 L0.6845,0.0643 L0.6821,0.0643 Q0.6553,0.0643,0.6553,0.0554 T0.6796,0.0465 L0.6813,0.0465 L0.6845,0.0465 Q0.6918,0.0425,0.717,0.0376 Q0.7226,0.0366,0.7267,0.0356 T0.7324,0.0336 T0.7376,0.0317 T0.747,0.0297 Q0.7518,0.0287,0.7551,0.0287 T0.762,0.0297 T0.768,0.0307 L0.7729,0.0307 Q0.7802,0.0277,0.7997,0.0267 T0.8224,0.0237 Q0.8273,0.0227,0.8341,0.0223 T0.8475,0.0193 T0.8654,0.0143 T0.8873,0.0079 Q0.9002,0.003,0.9331,0.004 T0.97,0.004 Q0.9838,0,0.9976,0.001 Q1,0.001,1,0.003 Z M0.9935,0.996 L0.9951,0.0049 Q0.9822,0.0049,0.9716,0.0079 Q0.9659,0.0099,0.9327,0.0089 T0.8897,0.0119 Q0.8775,0.0158,0.8666,0.0183 T0.85,0.0237 Q0.8418,0.0267,0.8341,0.0272 T0.8248,0.0277 Q0.82,0.0297,0.8001,0.0312 T0.7745,0.0346 Q0.7697,0.0356,0.7664,0.0356 Q0.764,0.0356,0.7603,0.0341 T0.7534,0.0326 Q0.751,0.0326,0.7478,0.0336 Q0.7429,0.0346,0.7397,0.0356 T0.7344,0.0376 T0.7283,0.0401 T0.7178,0.0425 Q0.6926,0.0465,0.6878,0.0495 Q0.6845,0.0514,0.6764,0.0514 L0.6723,0.0514 L0.6691,0.0514 Q0.6602,0.0514,0.6602,0.0554 Q0.6602,0.0574,0.6659,0.0579 T0.6796,0.0589 T0.691,0.0603 T0.6967,0.0643 T0.7072,0.0673 Q0.7121,0.0682,0.7153,0.0682 T0.7238,0.0678 T0.7332,0.0673 Q0.7413,0.0673,0.7579,0.0692 T0.7818,0.0742 Q0.7867,0.0752,0.8171,0.0762 T0.8508,0.0781 L0.852,0.0781 T0.8601,0.0776 T0.8719,0.0772 Q0.8832,0.0772,0.8921,0.0791 Q0.8994,0.0811,0.8994,0.0841 T0.8933,0.0895 T0.8812,0.094 T0.8735,0.0959 T0.8451,0.1014 T0.8143,0.1068 Q0.7989,0.1068,0.7818,0.1098 Q0.7778,0.1108,0.7745,0.1108 T0.768,0.1103 T0.7603,0.1088 T0.7518,0.1068 L0.7461,0.1068 Q0.7315,0.1068,0.7088,0.1103 T0.6805,0.1177 Q0.6756,0.1207,0.6699,0.1207 Q0.6667,0.1207,0.6545,0.1177 T0.631,0.1147 Q0.6269,0.1137,0.6225,0.1133 T0.616,0.1128 L0.6123,0.1128 T0.6103,0.1133 L0.6083,0.1157 T0.6034,0.1197 Q0.5961,0.1246,0.5921,0.1246 Q0.5904,0.1246,0.5835,0.1231 T0.5693,0.1217 L0.5661,0.1217 Q0.558,0.1217,0.5535,0.1231 T0.5446,0.1266 T0.5345,0.1296 Q0.5126,0.1316,0.4882,0.1316 T0.438,0.1405 Q0.4298,0.1434,0.425,0.1434 Q0.4209,0.1434,0.4173,0.1419 T0.4112,0.1405 T0.4027,0.1419 T0.3869,0.1434 Q0.3682,0.1434,0.3512,0.1494 Q0.3398,0.1533,0.3333,0.1533 Q0.3285,0.1533,0.3228,0.1513 L0.3212,0.1513 Q0.3179,0.1513,0.3155,0.1538 T0.3131,0.1592 Q0.3131,0.1612,0.3147,0.1632 Q0.3171,0.1652,0.3232,0.1667 T0.3406,0.1691 T0.3544,0.1701 L0.3601,0.1701 L0.3678,0.1701 L0.3771,0.1701 Q0.3909,0.1701,0.4031,0.1731 Q0.4177,0.178,0.4558,0.178 Q0.4793,0.178,0.4882,0.1761 L0.4915,0.1761 Q0.498,0.1761,0.5061,0.179 T0.5158,0.183 Q0.5166,0.183,0.5231,0.1835 T0.5341,0.1845 T0.545,0.1855 T0.5572,0.1874 T0.5661,0.1909 Q0.5677,0.1919,0.5702,0.1919 T0.5791,0.1894 T0.588,0.1869 Q0.5921,0.1869,0.5945,0.1899 Q0.5977,0.1919,0.6123,0.1919 Q0.6334,0.1919,0.6448,0.1879 Q0.6488,0.186,0.6537,0.186 Q0.6626,0.186,0.6784,0.1909 T0.6983,0.1958 Q0.704,0.1968,0.7206,0.1973 T0.7506,0.1993 T0.7689,0.2018 L0.7705,0.2018 L0.7741,0.2018 L0.7786,0.2018 Q0.8248,0.2018,0.8475,0.2136 Q0.8597,0.2196,0.8597,0.2255 T0.8483,0.2359 T0.8281,0.2404 Q0.8208,0.2404,0.7534,0.2493 Q0.7502,0.2502,0.7425,0.2512 T0.7287,0.2532 T0.7178,0.2542 L0.7153,0.2542 L0.7137,0.2542 Q0.7064,0.2542,0.6906,0.2591 T0.6715,0.2681 T0.6626,0.272 Q0.6594,0.272,0.6541,0.2705 T0.6464,0.269 T0.6431,0.27 Q0.6318,0.273,0.6034,0.276 Q0.6018,0.276,0.5998,0.2774 T0.5957,0.2799 T0.5904,0.2809 L0.5856,0.2809 Q0.5823,0.2799,0.575,0.2799 Q0.541,0.2799,0.5239,0.2868 Q0.5134,0.2908,0.5028,0.2908 Q0.4996,0.2908,0.4935,0.2903 T0.4842,0.2898 Q0.4704,0.2898,0.4635,0.2918 T0.4534,0.2997 L0.4534,0.3007 Q0.4534,0.3037,0.459,0.3046 T0.4753,0.3066 T0.4899,0.3076 Q0.4907,0.3076,0.5166,0.3106 T0.5507,0.3155 Q0.5921,0.3264,0.605,0.3264 Q0.6107,0.3264,0.6131,0.3254 Q0.6212,0.3225,0.6294,0.3225 Q0.6407,0.3225,0.6513,0.3274 Q0.6529,0.3294,0.6569,0.3294 Q0.6594,0.3294,0.665,0.3284 T0.6748,0.3274 T0.6821,0.3284 Q0.6861,0.3294,0.6967,0.3299 T0.7165,0.3314 T0.7299,0.3343 Q0.7324,0.3363,0.7486,0.3383 T0.7697,0.3422 Q0.7713,0.3432,0.7774,0.3452 T0.7887,0.3492 T0.8005,0.3546 T0.8127,0.3625 T0.8208,0.3719 Q0.8256,0.3798,0.8256,0.3848 Q0.8256,0.3877,0.8236,0.3902 T0.8171,0.3976 T0.809,0.4075 T0.8021,0.4189 T0.7968,0.4273 T0.7867,0.4322 T0.7616,0.4382 Q0.7543,0.4392,0.7437,0.4392 L0.7364,0.4392 L0.7299,0.4392 Q0.7202,0.4392,0.7161,0.4402 Q0.7072,0.4431,0.691,0.4431 L0.6845,0.4431 L0.6788,0.4431 Q0.6707,0.4431,0.6545,0.4461 T0.6334,0.452 Q0.6399,0.456,0.6626,0.457 Q0.6878,0.458,0.7024,0.4639 Q0.7064,0.4649,0.7186,0.4649 L0.7295,0.4649 L0.7413,0.4649 Q0.7591,0.4649,0.7697,0.4669 Q0.7818,0.4688,0.7818,0.4728 Q0.7818,0.4748,0.7798,0.4763 T0.7753,0.4787 L0.7737,0.4797 L0.7729,0.4797 Q0.7494,0.4827,0.7388,0.4827 Q0.7332,0.4827,0.7307,0.4817 L0.7291,0.4817 Q0.7226,0.4817,0.6878,0.4896 Q0.6829,0.4906,0.6772,0.4911 T0.6618,0.4921 T0.646,0.4931 T0.6342,0.4936 T0.6212,0.4931 T0.6115,0.4926 Q0.6083,0.4926,0.6058,0.4931 T0.5969,0.4955 T0.5819,0.499 T0.5629,0.5005 Q0.5572,0.5005,0.5527,0.501 T0.545,0.502 T0.5397,0.503 T0.5361,0.5045 T0.5337,0.5064 T0.5328,0.5094 L0.532,0.5094 Q0.532,0.5104,0.5337,0.5109 T0.5381,0.5114 T0.5438,0.5119 T0.5515,0.5124 L0.5604,0.5124 Q0.5661,0.5134,0.5746,0.5153 T0.5912,0.5173 L0.5977,0.5173 L0.6026,0.5173 Q0.6139,0.5173,0.6273,0.5218 T0.6407,0.5272 Q0.6448,0.5282,0.6683,0.5321 T0.6991,0.5381 Q0.7137,0.543,0.7664,0.548 Q0.7908,0.55,0.7908,0.5559 Q0.7908,0.5589,0.7859,0.5628 Q0.781,0.5658,0.7713,0.5658 Q0.7689,0.5658,0.7628,0.5653 T0.7543,0.5648 T0.7502,0.5658 Q0.7364,0.5678,0.6878,0.5678 Q0.674,0.5678,0.6699,0.5668 L0.6683,0.5668 Q0.6659,0.5668,0.6606,0.5678 T0.6513,0.5687 Q0.6464,0.5687,0.6391,0.5678 Q0.6334,0.5668,0.6302,0.5668 T0.6241,0.5687 T0.6164,0.5717 Q0.6123,0.5727,0.6099,0.5727 L0.6062,0.5727 T0.6022,0.5732 T0.5953,0.5737 Q0.5904,0.5747,0.5839,0.5747 T0.5726,0.5752 T0.5629,0.5776 T0.5458,0.5796 Q0.5418,0.5796,0.5324,0.5791 T0.5191,0.5786 Q0.5077,0.5786,0.5045,0.5806 Q0.498,0.5836,0.4899,0.5836 Q0.4858,0.5836,0.4777,0.5826 T0.4655,0.5816 L0.4631,0.5816 Q0.4582,0.5816,0.4436,0.5841 T0.4144,0.5865 L0.4051,0.5865 L0.3986,0.5865 T0.3933,0.587 T0.3897,0.5875 T0.3869,0.5885 T0.3844,0.5895 T0.3812,0.591 T0.3779,0.5925 Q0.3739,0.5955,0.3633,0.5955 L0.3585,0.5955 L0.3536,0.5955 Q0.3277,0.5955,0.3066,0.6053 Q0.3017,0.6083,0.296,0.6083 Q0.2912,0.6083,0.2839,0.6068 T0.2741,0.6053 Q0.2693,0.6053,0.2547,0.6048 T0.236,0.6044 Q0.2222,0.6044,0.193,0.6103 L0.1882,0.6103 Q0.1825,0.6103,0.1703,0.6083 T0.1525,0.6063 L0.15,0.6063 Q0.1436,0.6063,0.135,0.6073 T0.1168,0.6098 T0.1038,0.6113 Q0.0973,0.6123,0.0787,0.6123 L0.06,0.6123 L0.0414,0.6123 L0.0235,0.6123 Q0.0049,0.6133,0.0049,0.6172 L0.0057,0.6222 Q0.0073,0.6261,0.043,0.6261 L0.0454,0.6261 L0.0479,0.6261 Q0.0527,0.6261,0.0633,0.6281 T0.0803,0.6301 L0.0835,0.6301 L0.0916,0.6301 Q0.0998,0.6301,0.129,0.632 Q0.1768,0.636,0.206,0.64 Q0.2117,0.6409,0.2165,0.6409 Q0.2206,0.6409,0.2263,0.6405 T0.2336,0.64 L0.2384,0.64 L0.2409,0.64 T0.251,0.6395 T0.2644,0.639 Q0.2741,0.639,0.279,0.6409 Q0.283,0.6429,0.2972,0.6439 T0.3293,0.6459 T0.3528,0.6469 L0.3577,0.6469 Q0.3642,0.6469,0.3723,0.6449 T0.3844,0.6429 Q0.3901,0.6429,0.3933,0.6454 T0.4006,0.6479 Q0.4088,0.6479,0.4517,0.6558 Q0.4582,0.6568,0.4623,0.6568 Q0.4655,0.6568,0.4716,0.6563 T0.4826,0.6558 L0.4882,0.6558 Q0.5004,0.6558,0.5255,0.6607 Q0.5328,0.6627,0.5604,0.6647 T0.6152,0.6682 T0.644,0.6696 T0.6719,0.6721 T0.7056,0.6756 Q0.7113,0.6756,0.7198,0.6805 T0.738,0.6855 Q0.7453,0.6855,0.7551,0.6879 T0.7741,0.6939 T0.7912,0.7018 T0.8029,0.7102 Q0.8054,0.7132,0.8054,0.7151 Q0.8054,0.7191,0.8009,0.7216 T0.7908,0.7255 T0.779,0.7285 T0.7721,0.731 Q0.7672,0.7329,0.7632,0.7339 T0.7551,0.7354 T0.7486,0.7369 Q0.7478,0.7369,0.7445,0.7379 T0.7388,0.7394 T0.7324,0.7404 L0.7242,0.7413 T0.7161,0.7418 Q0.7105,0.7418,0.6955,0.7428 T0.6748,0.7438 L0.6699,0.7438 L0.6667,0.7438 Q0.6659,0.7438,0.6407,0.7468 Q0.6367,0.7478,0.6334,0.7478 T0.6245,0.7468 T0.6148,0.7458 L0.6099,0.7458 Q0.6018,0.7468,0.5864,0.7498 T0.5653,0.7532 T0.5596,0.7557 Q0.5596,0.7596,0.571,0.7616 Q0.5742,0.7626,0.5803,0.7631 T0.5929,0.7641 T0.6018,0.7656 L0.6087,0.7656 T0.6192,0.7666 T0.6277,0.7695 Q0.631,0.7705,0.6342,0.7705 Q0.6383,0.7705,0.6452,0.7685 T0.6537,0.7666 L0.6553,0.7666 Q0.6602,0.7666,0.6711,0.769 T0.6853,0.7715 Q0.691,0.7715,0.7048,0.775 T0.7242,0.7814 Q0.7324,0.7854,0.7445,0.7864 Q0.7478,0.7864,0.768,0.7873 T0.7972,0.7893 Q0.7989,0.7893,0.8017,0.7898 T0.8054,0.7903 L0.8082,0.7903 T0.811,0.7908 T0.8131,0.7913 T0.8151,0.7918 L0.8167,0.7928 T0.8179,0.7943 T0.8191,0.7957 T0.8204,0.7977 T0.8208,0.8002 Q0.8208,0.8032,0.8171,0.8051 T0.8074,0.8081 T0.7997,0.8091 Q0.7932,0.8121,0.7737,0.8121 Q0.7664,0.8121,0.7413,0.8111 L0.7364,0.8111 Q0.7275,0.8111,0.7214,0.8121 T0.7084,0.8155 T0.6991,0.819 Q0.6934,0.82,0.6723,0.8205 T0.6472,0.8239 Q0.6423,0.8269,0.6375,0.8269 Q0.6358,0.8269,0.6338,0.8264 T0.6294,0.8254 T0.6253,0.8249 Q0.6042,0.8249,0.5961,0.8289 Q0.5921,0.8318,0.5839,0.8318 Q0.5783,0.8318,0.5645,0.8299 L0.5604,0.8299 Q0.5531,0.8299,0.5337,0.8368 Q0.5296,0.8378,0.5255,0.8378 Q0.5239,0.8378,0.5195,0.8373 T0.5118,0.8368 Q0.5061,0.8368,0.4996,0.8388 Q0.4947,0.8388,0.4882,0.8398 Q0.4777,0.8417,0.4753,0.8427 T0.4728,0.8467 Q0.4728,0.8487,0.4769,0.8492 T0.4886,0.8501 T0.5004,0.8516 Q0.5036,0.8516,0.515,0.8521 T0.5345,0.8546 Q0.5426,0.8556,0.5596,0.8556 L0.5649,0.8556 L0.5702,0.8556 L0.5791,0.8556 Q0.5921,0.8566,0.6135,0.8571 T0.6383,0.8586 Q0.6683,0.8615,0.6764,0.8615 L0.6776,0.8615 L0.6788,0.8615 Q0.7032,0.8615,0.7032,0.8684 Q0.7032,0.8714,0.6995,0.8749 T0.6959,0.8803 L0.6959,0.8813 Q0.6991,0.8843,0.7153,0.8843 Q0.7218,0.8843,0.7259,0.8833 L0.7299,0.8833 Q0.7324,0.8833,0.7348,0.8838 T0.7393,0.8848 T0.7433,0.8863 L0.7474,0.8882 T0.751,0.8892 Q0.7616,0.8922,0.7948,0.8952 Q0.7981,0.8952,0.8082,0.8981 T0.8297,0.9011 T0.8528,0.9026 T0.8747,0.907 T0.8856,0.9149 L0.8856,0.9159 Q0.8856,0.9179,0.8848,0.9189 T0.8828,0.9209 T0.88,0.9228 T0.8767,0.9243 T0.8731,0.9248 T0.8698,0.9253 T0.8666,0.9258 L0.8646,0.9258 Q0.8621,0.9258,0.8577,0.9263 T0.85,0.9268 T0.8439,0.9273 T0.8402,0.9278 Q0.8386,0.9298,0.8358,0.9308 T0.8305,0.9322 T0.8244,0.9332 T0.8183,0.9337 Q0.8135,0.9347,0.8025,0.9372 T0.7859,0.9416 Q0.7778,0.9436,0.7717,0.9471 T0.7624,0.9515 Q0.7575,0.9535,0.7486,0.9535 Q0.7461,0.9535,0.7397,0.953 T0.7291,0.9525 Q0.7234,0.9525,0.7186,0.953 T0.7137,0.957 T0.7194,0.9614 Q0.7567,0.9634,0.7664,0.9654 Q0.7745,0.9674,0.7762,0.9674 L0.7908,0.9674 Q0.7924,0.9664,0.7948,0.9664 Q0.8029,0.9664,0.8082,0.9679 T0.8224,0.9723 T0.8362,0.9773 Q0.8483,0.9812,0.871,0.9812 L0.8751,0.9812 Q0.8873,0.9812,0.8929,0.9822 T0.9165,0.9876 T0.9408,0.9931 Q0.9513,0.996,0.9935,0.996 Z M0.9968,0.998 L0.9976,0.003 Q0.9838,0.002,0.9708,0.0059 Q0.9659,0.0069,0.9327,0.0059 T0.8881,0.0099 Q0.8767,0.0138,0.8658,0.0163 T0.8491,0.0218 Q0.8418,0.0247,0.8341,0.0247 T0.8232,0.0257 Q0.8191,0.0277,0.7997,0.0292 T0.7737,0.0326 Q0.7697,0.0336,0.7672,0.0336 T0.7612,0.0321 T0.7543,0.0307 T0.747,0.0317 Q0.7397,0.0326,0.7336,0.0356 T0.717,0.0406 Q0.6918,0.0445,0.6861,0.0475 Q0.6845,0.0485,0.6772,0.0485 T0.6638,0.05 T0.6577,0.0549 T0.6642,0.0598 T0.6796,0.0613 T0.6902,0.0623 Q0.691,0.0623,0.6946,0.0658 T0.7064,0.0702 L0.7161,0.0702 Q0.7194,0.0702,0.7242,0.0697 T0.7332,0.0692 Q0.7413,0.0692,0.7579,0.0717 T0.781,0.0762 Q0.7867,0.0781,0.8171,0.0786 T0.85,0.0801 L0.8532,0.0801 Q0.8548,0.0801,0.8613,0.0796 T0.8727,0.0791 Q0.8832,0.0791,0.8913,0.0811 Q0.897,0.0831,0.897,0.0851 Q0.897,0.088,0.8873,0.0905 T0.8735,0.093 Q0.871,0.093,0.8447,0.0984 T0.8143,0.1039 Q0.7981,0.1039,0.781,0.1078 Q0.7778,0.1088,0.7745,0.1088 T0.7644,0.1073 T0.7518,0.1048 L0.7453,0.1048 Q0.7299,0.1048,0.7076,0.1083 T0.6788,0.1157 Q0.6748,0.1187,0.6699,0.1187 Q0.6675,0.1187,0.6557,0.1157 T0.6318,0.1118 Q0.6164,0.1108,0.6135,0.1108 T0.6095,0.1113 T0.6067,0.1142 T0.6018,0.1187 Q0.5953,0.1227,0.5921,0.1227 Q0.5904,0.1227,0.5839,0.1212 T0.5693,0.1187 L0.5661,0.1187 Q0.558,0.1187,0.5527,0.1207 T0.5434,0.1246 T0.5337,0.1266 Q0.5126,0.1296,0.4882,0.1296 T0.4371,0.1385 Q0.4298,0.1414,0.425,0.1414 Q0.4225,0.1414,0.4189,0.1395 T0.4112,0.1375 Q0.4079,0.1375,0.4019,0.1395 T0.3869,0.1414 Q0.3682,0.1414,0.3504,0.1474 Q0.3398,0.1513,0.3333,0.1513 Q0.3293,0.1513,0.3228,0.1494 L0.3204,0.1494 Q0.3179,0.1494,0.3155,0.1508 T0.3118,0.1543 T0.3106,0.1592 T0.3127,0.1642 T0.32,0.1677 T0.3305,0.1701 T0.3435,0.1716 T0.3544,0.1721 Q0.3569,0.1731,0.3601,0.1731 Q0.3625,0.1731,0.3686,0.1726 T0.3779,0.1721 Q0.3901,0.1721,0.4023,0.1751 Q0.4177,0.18,0.455,0.18 Q0.4793,0.18,0.4882,0.178 L0.4915,0.178 Q0.4964,0.178,0.5045,0.1815 T0.5158,0.185 Q0.5564,0.1889,0.5645,0.1929 Q0.5677,0.1939,0.571,0.1939 Q0.575,0.1939,0.5807,0.1919 T0.5888,0.1899 T0.5929,0.1909 Q0.5969,0.1949,0.6123,0.1949 Q0.6334,0.1949,0.6456,0.1899 Q0.6488,0.1879,0.6537,0.1879 Q0.661,0.1879,0.6772,0.1929 T0.6983,0.1978 Q0.704,0.1988,0.7206,0.1998 T0.7502,0.2018 T0.7664,0.2038 Q0.7672,0.2038,0.7818,0.2043 T0.8151,0.2067 T0.8459,0.2156 Q0.8573,0.2206,0.8573,0.2255 Q0.8573,0.2295,0.8516,0.2324 T0.8394,0.2369 T0.8281,0.2384 Q0.8208,0.2384,0.7526,0.2473 Q0.7494,0.2483,0.7421,0.2493 T0.7287,0.2512 T0.7178,0.2522 L0.7153,0.2522 L0.7137,0.2522 Q0.7056,0.2522,0.6898,0.2572 T0.6691,0.2671 Q0.6667,0.269,0.6634,0.269 Q0.661,0.269,0.6557,0.2681 T0.6472,0.2671 Q0.6448,0.2671,0.6415,0.2681 Q0.631,0.271,0.6034,0.274 Q0.5994,0.274,0.5961,0.2765 T0.5904,0.2789 L0.5864,0.2789 Q0.5831,0.2779,0.5742,0.2779 Q0.541,0.2779,0.5223,0.2849 Q0.5126,0.2888,0.5028,0.2888 Q0.5004,0.2888,0.4943,0.2883 T0.4842,0.2878 Q0.4704,0.2878,0.4627,0.2898 T0.4509,0.2987 Q0.4501,0.2997,0.4501,0.3007 Q0.4501,0.3046,0.4574,0.3066 T0.4765,0.3091 T0.4899,0.3096 Q0.4931,0.3106,0.5061,0.3121 T0.5316,0.315 T0.5499,0.3175 Q0.5507,0.3175,0.5572,0.3195 T0.5685,0.3225 T0.5803,0.3254 T0.5933,0.3279 T0.605,0.3284 T0.6148,0.3274 Q0.6221,0.3244,0.6294,0.3244 Q0.6399,0.3244,0.6496,0.3294 Q0.6529,0.3314,0.6577,0.3314 Q0.6602,0.3314,0.6663,0.3304 T0.6756,0.3294 T0.6813,0.3304 Q0.6837,0.3304,0.6873,0.3309 L0.6946,0.3318 T0.7024,0.3323 T0.7105,0.3328 T0.7178,0.3338 T0.7238,0.3348 T0.7283,0.3363 Q0.7324,0.3383,0.7482,0.3403 T0.7689,0.3442 Q0.7697,0.3442,0.779,0.3477 T0.794,0.3536 T0.8074,0.3615 T0.8183,0.3729 Q0.8232,0.3808,0.8232,0.3848 Q0.8232,0.3867,0.8216,0.3892 T0.8151,0.3961 T0.8062,0.406 T0.7997,0.4179 T0.7952,0.4263 T0.7855,0.4308 T0.7616,0.4362 Q0.7543,0.4372,0.7445,0.4372 L0.7372,0.4372 L0.7307,0.4372 Q0.7202,0.4372,0.7153,0.4382 Q0.7064,0.4402,0.691,0.4402 L0.6845,0.4402 L0.6788,0.4402 Q0.6699,0.4402,0.6533,0.4436 T0.6318,0.451 Q0.6302,0.451,0.6302,0.452 Q0.6302,0.457,0.6626,0.459 Q0.6869,0.4609,0.7015,0.4659 Q0.7064,0.4669,0.7202,0.4669 L0.7311,0.4669 L0.7429,0.4669 Q0.7599,0.4669,0.7689,0.4688 Q0.7794,0.4708,0.7794,0.4738 L0.7786,0.4748 T0.777,0.4763 T0.7749,0.4773 L0.7737,0.4777 L0.7729,0.4777 Q0.7502,0.4797,0.738,0.4797 L0.7315,0.4797 L0.7291,0.4797 Q0.7226,0.4797,0.6869,0.4876 Q0.6821,0.4886,0.6768,0.4891 T0.6614,0.4901 T0.6456,0.4916 L0.6342,0.4916 Q0.6294,0.4916,0.6217,0.4911 T0.6115,0.4906 Q0.6083,0.4906,0.6054,0.4911 T0.5961,0.4936 T0.5815,0.4965 T0.5629,0.4985 Q0.5507,0.4985,0.5442,0.4995 T0.5345,0.5025 T0.5304,0.5084 L0.5296,0.5094 Q0.5296,0.5114,0.5316,0.5124 T0.5373,0.5138 T0.5442,0.5143 L0.5523,0.5143 L0.5604,0.5143 Q0.5637,0.5153,0.5677,0.5158 T0.5742,0.5173 T0.5811,0.5188 T0.5904,0.5193 L0.5977,0.5193 L0.6026,0.5193 Q0.6107,0.5193,0.6168,0.5208 T0.6294,0.5252 T0.6399,0.5292 Q0.6448,0.5302,0.6679,0.5341 T0.6983,0.541 Q0.7129,0.545,0.7664,0.55 Q0.7883,0.5519,0.7883,0.5559 Q0.7883,0.5579,0.7843,0.5608 T0.7721,0.5638 Q0.7697,0.5638,0.764,0.5633 T0.7559,0.5628 L0.7502,0.5628 Q0.7364,0.5648,0.6869,0.5648 L0.6699,0.5648 L0.6675,0.5648 Q0.665,0.5648,0.6602,0.5658 T0.6513,0.5668 Q0.6464,0.5668,0.6399,0.5658 Q0.6342,0.5648,0.6302,0.5648 T0.6225,0.5668 T0.6156,0.5697 Q0.6107,0.5707,0.6087,0.5707 T0.6034,0.5712 T0.5953,0.5717 Q0.5904,0.5727,0.5835,0.5727 T0.5718,0.5732 T0.562,0.5757 Q0.558,0.5767,0.5483,0.5767 L0.5349,0.5767 L0.5207,0.5767 Q0.5069,0.5767,0.5028,0.5786 Q0.4972,0.5816,0.4899,0.5816 Q0.4858,0.5816,0.4781,0.5806 T0.4663,0.5796 L0.4631,0.5796 Q0.4582,0.5796,0.4432,0.5821 T0.4144,0.5846 L0.4071,0.5846 L0.4011,0.5846 T0.3958,0.5851 T0.3921,0.5856 T0.3889,0.5861 T0.3865,0.5865 T0.384,0.5875 L0.382,0.5885 L0.3796,0.5895 L0.3771,0.5905 Q0.3731,0.5925,0.365,0.5925 L0.3601,0.5925 L0.3552,0.5925 Q0.3277,0.5925,0.3049,0.6044 Q0.3017,0.6053,0.296,0.6053 Q0.292,0.6053,0.2847,0.6044 T0.2741,0.6034 Q0.2693,0.6034,0.2547,0.6029 T0.236,0.6024 Q0.2222,0.6024,0.1922,0.6073 Q0.1906,0.6083,0.1882,0.6083 Q0.1833,0.6083,0.1711,0.6063 T0.1533,0.6044 Q0.1517,0.6034,0.1492,0.6034 Q0.1436,0.6034,0.135,0.6048 T0.1168,0.6078 T0.103,0.6093 Q0.0973,0.6103,0.0787,0.6103 L0.0604,0.6103 L0.0414,0.6103 L0.0235,0.6103 Q0.0024,0.6113,0.0024,0.6172 Q0.0024,0.6192,0.0032,0.6231 Q0.0049,0.6281,0.0333,0.6281 L0.0414,0.6281 L0.0479,0.6281 Q0.0519,0.6281,0.0624,0.6301 T0.0803,0.632 L0.0835,0.632 L0.0916,0.632 Q0.0989,0.632,0.1281,0.634 L0.206,0.6419 Q0.2117,0.6429,0.2174,0.6429 Q0.2214,0.6429,0.2271,0.6424 T0.2344,0.6419 L0.2376,0.6419 Q0.2393,0.6429,0.2417,0.6429 T0.2526,0.6419 T0.2652,0.6409 Q0.2741,0.6409,0.2782,0.6429 T0.2968,0.6459 T0.3293,0.6479 T0.352,0.6489 Q0.3552,0.6499,0.3585,0.6499 Q0.365,0.6499,0.3731,0.6474 T0.3844,0.6449 Q0.3885,0.6449,0.3917,0.6474 T0.4006,0.6499 Q0.4088,0.6499,0.4509,0.6578 Q0.4574,0.6588,0.4631,0.6588 Q0.4655,0.6588,0.4716,0.6583 T0.4834,0.6578 L0.4874,0.6578 Q0.5004,0.6588,0.5255,0.6637 Q0.532,0.6647,0.56,0.6667 T0.6148,0.6701 T0.644,0.6716 Q0.6464,0.6726,0.6594,0.6736 T0.6861,0.6756 T0.7048,0.6775 Q0.7097,0.6775,0.7186,0.6825 T0.738,0.6874 Q0.7518,0.6874,0.7729,0.6958 T0.8005,0.7122 Q0.8029,0.7141,0.8029,0.7151 Q0.8029,0.7191,0.7968,0.7216 T0.7818,0.726 T0.7705,0.729 L0.764,0.731 T0.7583,0.7324 T0.753,0.7334 T0.7486,0.7349 Q0.7251,0.7399,0.7161,0.7399 Q0.7097,0.7399,0.6951,0.7409 T0.6748,0.7418 L0.6703,0.7418 L0.6667,0.7418 Q0.6659,0.7418,0.6399,0.7448 L0.6334,0.7448 Q0.631,0.7448,0.6249,0.7443 T0.6148,0.7438 L0.6099,0.7438 Q0.601,0.7448,0.5856,0.7473 T0.5645,0.7507 Q0.5572,0.7517,0.5572,0.7547 T0.5616,0.7606 T0.5702,0.7646 Q0.5734,0.7646,0.5779,0.7651 T0.5864,0.7661 T0.5949,0.7671 T0.6018,0.7676 L0.6071,0.7676 T0.6135,0.7681 T0.62,0.769 T0.6269,0.771 T0.6342,0.7725 Q0.6391,0.7725,0.6464,0.7705 T0.6541,0.7685 L0.6553,0.7685 Q0.6586,0.7685,0.6699,0.771 T0.6853,0.7735 Q0.6902,0.7735,0.704,0.777 T0.7226,0.7834 Q0.7315,0.7873,0.7445,0.7883 Q0.747,0.7883,0.7676,0.7893 T0.7972,0.7913 Q0.7989,0.7913,0.8017,0.7918 T0.8058,0.7923 T0.809,0.7928 T0.8114,0.7933 T0.8131,0.7938 T0.8147,0.7943 T0.8159,0.7953 L0.8171,0.7967 T0.8175,0.7982 Q0.8183,0.7992,0.8183,0.8002 Q0.8183,0.8022,0.8155,0.8032 T0.807,0.8051 T0.7989,0.8071 Q0.7932,0.8091,0.7737,0.8091 L0.7413,0.8091 L0.7372,0.8091 Q0.7275,0.8091,0.721,0.8101 T0.7072,0.8136 T0.6983,0.817 Q0.6942,0.818,0.6825,0.818 T0.6602,0.819 T0.6456,0.822 Q0.6415,0.8249,0.6375,0.8249 Q0.6367,0.8249,0.6326,0.8239 T0.6253,0.8229 Q0.6034,0.8229,0.5953,0.8279 Q0.5912,0.8289,0.5848,0.8289 Q0.5775,0.8289,0.5645,0.8279 Q0.5629,0.8269,0.5604,0.8269 Q0.5523,0.8269,0.5328,0.8348 Q0.5296,0.8358,0.5264,0.8358 Q0.5247,0.8358,0.5203,0.8353 T0.5126,0.8348 Q0.5061,0.8348,0.4988,0.8358 Q0.4947,0.8368,0.4882,0.8378 Q0.4826,0.8388,0.4797,0.8388 T0.474,0.8398 T0.4704,0.8422 T0.4696,0.8462 T0.472,0.8501 T0.4781,0.8521 T0.4854,0.8526 L0.4935,0.8526 T0.4996,0.8536 Q0.5036,0.8536,0.515,0.8546 T0.5337,0.8566 Q0.5426,0.8576,0.5596,0.8576 L0.5657,0.8576 L0.571,0.8576 L0.5791,0.8576 Q0.5921,0.8586,0.6135,0.8591 T0.6383,0.8605 Q0.6683,0.8635,0.6764,0.8635 Q0.6999,0.8635,0.6999,0.8684 Q0.6999,0.8694,0.6967,0.8734 T0.6934,0.8803 L0.6934,0.8823 Q0.6951,0.8863,0.7137,0.8863 Q0.7218,0.8863,0.7267,0.8853 L0.7299,0.8853 Q0.734,0.8853,0.7409,0.8882 T0.7502,0.8912 Q0.7607,0.8942,0.794,0.8971 Q0.7972,0.8971,0.8078,0.9001 T0.8297,0.9031 Q0.8475,0.9031,0.8646,0.9065 T0.8824,0.9149 L0.8824,0.9159 Q0.8824,0.9169,0.882,0.9179 T0.8808,0.9194 L0.8792,0.9204 T0.8767,0.9214 T0.8743,0.9224 T0.8715,0.9228 L0.8686,0.9228 T0.8662,0.9233 T0.8637,0.9238 L0.8556,0.9238 T0.8447,0.9243 T0.8386,0.9268 Q0.837,0.9278,0.835,0.9288 T0.8305,0.9303 T0.8244,0.9308 T0.8175,0.9318 Q0.8127,0.9327,0.8017,0.9352 T0.7851,0.9397 Q0.777,0.9416,0.7705,0.9451 T0.7616,0.9496 Q0.7575,0.9505,0.7494,0.9505 L0.7405,0.9505 L0.7307,0.9505 Q0.7234,0.9505,0.7178,0.9515 Q0.7145,0.9515,0.7125,0.9535 T0.7105,0.9575 Q0.7105,0.9624,0.7194,0.9634 Q0.7567,0.9654,0.7664,0.9674 Q0.7745,0.9693,0.7762,0.9693 L0.7908,0.9693 L0.7948,0.9693 Q0.8005,0.9693,0.8058,0.9698 T0.8143,0.9718 T0.824,0.9753 T0.8354,0.9792 Q0.8483,0.9832,0.871,0.9832 L0.8739,0.9832 L0.8767,0.9832 Q0.8873,0.9832,0.8921,0.9842 Q0.8978,0.9852,0.9157,0.9896 T0.94,0.996 Q0.9424,0.996,0.9469,0.9965 T0.9566,0.997 T0.9676,0.9975 T0.9781,0.998 L0.9874,0.998 L0.9943,0.998 L0.9968,0.998 Z",type:0}},"":{type:5,data:{d:"M1,0.5071 L0.8623,0.7102 L0.5865,0.7102 L0.4489,0.5071 L0.5865,0.3045 L0.8623,0.3045 Z M0.4135,0.7974 L0.2758,1 L0,1 L0,0.5944 L0.2758,0.5944 Z M0.4135,0.2026 L0.2758,0.4056 L0,0.4056 L0,0 L0.2758,0 Z",type:0}},"":{type:5,data:{d:"M0.9726,0.5071 L0.8451,0.3184 L0.59,0.3184 L0.4624,0.5071 L0.59,0.6955 L0.8451,0.6955 Z M1,0.5071 L0.8588,0.716 L0.5768,0.716 L0.4355,0.5071 L0.5768,0.2982 L0.8588,0.2982 Z M0.401,0.7911 L0.2735,0.6028 L0.0236,0.6028 L0.0236,0.9799 L0.2735,0.9799 Z M0.4284,0.7911 L0.2872,1 L0,1 L0,0.5826 L0.2872,0.5826 Z M0.401,0.2089 L0.2735,0.0201 L0.0236,0.0201 L0.0236,0.3972 L0.2735,0.3972 Z M0.4284,0.2089 L0.2872,0.4174 L0,0.4174 L0,0 L0.2872,0 Z",type:0}},"":{type:5,data:{d:"M1,0.4996 Q1,0.5365,0.9924,0.568 T0.9718,0.6177 T0.9433,0.6363 L0.9425,0.6367 Q0.9355,0.6367,0.9285,0.6326 L0.9308,0.6326 Q0.9129,0.6195,0.9013,0.587 T0.8871,0.5164 T0.8943,0.4373 T0.9254,0.3687 L0.9254,0.3691 Q0.9339,0.3628,0.9425,0.3628 Q0.9584,0.3628,0.9716,0.3811 T0.9924,0.431 T1,0.4996 Z M0.9234,0.6321 L0.8776,0.7169 Q0.8791,0.732,0.8791,0.7441 Q0.8791,0.781,0.8716,0.8123 T0.8508,0.862 T0.8224,0.8809 L0.8216,0.8809 Q0.8154,0.8809,0.8092,0.8775 L0.8088,0.8775 Q0.7905,0.8633,0.7792,0.8297 T0.766,0.7571 T0.775,0.6768 T0.8088,0.6086 L0.7431,0.6065 Q0.719,0.6313,0.7072,0.6705 T0.6965,0.7487 T0.7097,0.823 T0.7423,0.8763 L0.7913,0.8775 L0.7314,0.9895 L0.4648,0.5038 L0.7299,0.0176 L0.7882,0.1229 L0.7404,0.1212 Q0.7244,0.138,0.7136,0.1617 T0.6982,0.2108 T0.6943,0.2632 T0.7003,0.3144 T0.7159,0.3586 T0.7396,0.3909 L0.8072,0.3926 Q0.7894,0.3796,0.7777,0.3479 T0.7635,0.2789 T0.7697,0.2011 T0.7987,0.1326 Q0.8092,0.1225,0.8204,0.1225 Q0.8321,0.1225,0.8426,0.1332 T0.8609,0.1623 T0.8731,0.2062 T0.8776,0.2592 Q0.8776,0.268,0.8768,0.2815 L0.9219,0.3628 L0.8644,0.3612 Q0.8403,0.3855,0.8284,0.4247 T0.8177,0.5029 T0.8309,0.5772 T0.8632,0.6305 Z M0.6759,0.6384 Q0.6576,0.625,0.6457,0.5914 T0.6319,0.5185 T0.6407,0.4375 T0.6751,0.3691 L0.609,0.367 Q0.5849,0.3918,0.5731,0.431 T0.5626,0.509 T0.5758,0.5833 T0.6082,0.6367 Z M0.6459,0.0025 L0.391,0.4551 L0.0035,0.4551 L0.246,0 Z M0.6553,1 L0.2421,1 L0,0.5449 L0.3875,0.5449 Z",type:0}},"":{type:5,data:{d:"M0.4996,0 Q0.5562,0,0.5961,0.0166 T0.6364,0.0566 L0.6368,0.0575 Q0.6368,0.0646,0.6324,0.0713 L0.6324,0.0692 Q0.6196,0.0868,0.5872,0.0986 T0.5166,0.1128 T0.4373,0.1057 T0.3689,0.0747 L0.3694,0.0747 Q0.3627,0.0663,0.3627,0.0575 Q0.3627,0.0336,0.4028,0.0168 T0.4996,0 Z M0.6324,0.0768 L0.717,0.1225 Q0.7321,0.1212,0.744,0.1212 Q0.8007,0.1212,0.8406,0.1378 T0.8809,0.1779 L0.8813,0.1783 Q0.8813,0.1846,0.8778,0.1909 Q0.8636,0.2093,0.8299,0.2208 T0.7573,0.2343 T0.6769,0.2253 T0.6089,0.1913 L0.6067,0.2567 Q0.6315,0.281,0.6707,0.2928 T0.7489,0.3035 T0.8231,0.2903 T0.8764,0.258 L0.8778,0.2085 L0.9898,0.2685 L0.504,0.5352 L0.0177,0.2701 L0.1227,0.2118 L0.1213,0.2596 Q0.1457,0.2836,0.1851,0.2955 T0.2635,0.3062 T0.3377,0.293 T0.3911,0.2605 L0.3928,0.193 Q0.38,0.2106,0.3483,0.2221 T0.2792,0.2364 T0.2013,0.2303 T0.1324,0.2013 Q0.1222,0.1909,0.1222,0.1795 Q0.1222,0.156,0.1623,0.1393 T0.2591,0.1225 Q0.2679,0.1225,0.2817,0.1233 L0.3627,0.078 L0.3609,0.1359 Q0.3857,0.1598,0.4249,0.1718 T0.5031,0.1825 T0.5773,0.1693 T0.6306,0.1367 Z M0.6386,0.3242 Q0.6253,0.3427,0.5917,0.3544 T0.5186,0.3683 T0.4376,0.3595 T0.3689,0.3251 L0.3671,0.3909 Q0.3915,0.4148,0.4309,0.4268 T0.5093,0.4375 T0.5835,0.4243 T0.6368,0.3918 Z M0.0027,0.354 L0.4553,0.6091 L0.4553,0.9962 L0,0.7542 Z M1,0.3448 L1,0.7576 L0.5447,1 L0.5447,0.6128 Z",type:0}},"":{type:5,data:{d:"M0,0.7699 Q0,0.7172,0.0277,0.6731 T0.103,0.6032 T0.2066,0.5774 Q0.2487,0.5774,0.2865,0.5922 T0.3526,0.6339 L0.3935,0.6715 Q0.4218,0.6984,0.438,0.7336 T0.4541,0.8075 Q0.4541,0.8602,0.4264,0.9046 T0.3511,0.9745 T0.2475,1 Q0.2054,1,0.1676,0.9852 T0.1016,0.9435 L0.0606,0.9059 Q0.0317,0.879,0.0159,0.8438 T0,0.7699 Z M0.5459,0.7699 Q0.5459,0.7172,0.5736,0.6731 T0.6489,0.6032 T0.7525,0.5774 Q0.7946,0.5774,0.8324,0.5922 T0.8984,0.6339 L0.9394,0.6715 Q0.9579,0.6892,0.9714,0.7105 T0.9925,0.7567 T1,0.8075 Q1,0.8602,0.9723,0.9046 T0.897,0.9745 T0.7934,1 Q0.7513,1,0.7135,0.9852 T0.6474,0.9435 L0.6065,0.9059 Q0.5776,0.879,0.5617,0.8438 T0.5459,0.7699 Z M0,0.1925 Q0,0.1398,0.0277,0.0957 T0.103,0.0258 T0.2066,0 Q0.2487,0,0.2865,0.0148 T0.3526,0.0565 L0.3935,0.0941 Q0.4218,0.121,0.438,0.1562 T0.4541,0.2301 Q0.4541,0.2828,0.4264,0.3269 T0.3511,0.3968 T0.2475,0.4226 Q0.2054,0.4226,0.1676,0.4078 T0.1016,0.3661 L0.0606,0.3285 Q0.0317,0.3016,0.0159,0.2664 T0,0.1925 Z M0.5459,0.1925 Q0.5459,0.1398,0.5736,0.0957 T0.6489,0.0258 T0.7525,0 Q0.7946,0,0.8324,0.0148 T0.8984,0.0565 L0.9394,0.0941 Q0.9677,0.121,0.9838,0.1562 T1,0.2301 Q1,0.2828,0.9723,0.3269 T0.897,0.3968 T0.7934,0.4226 Q0.7513,0.4226,0.7135,0.4078 T0.6474,0.3661 L0.6065,0.3285 Q0.5874,0.3108,0.5741,0.2895 T0.5534,0.2433 T0.5459,0.1925 Z M0.3301,0.6403 Q0.3306,0.6403,0.3312,0.6409 L0.3272,0.6371 L0.3272,0.6371 Z M0.8759,0.6403 Q0.8765,0.6403,0.8771,0.6409 Q0.8748,0.6387,0.8725,0.6371 L0.8731,0.6371 Z M0.3301,0.0629 Q0.3306,0.0629,0.3312,0.0634 L0.3272,0.0597 L0.3272,0.0602 Z M0.8759,0.0629 Q0.8765,0.0629,0.8771,0.0634 Q0.8748,0.0613,0.8725,0.0597 Q0.8731,0.0597,0.8731,0.0602 Z M0.779,0.4113 L0.7501,0.3849 Q0.7046,0.3844,0.6636,0.3661 Q0.7132,0.407,0.779,0.4113 Z M0.7957,0.4118 Q0.8477,0.4113,0.8918,0.3874 T0.9619,0.3223 T0.9885,0.2323 L0.9585,0.2048 Q0.9538,0.2769,0.8987,0.3282 T0.7657,0.3844 Z M0.9879,0.2167 Q0.9827,0.1554,0.9388,0.1097 Q0.9585,0.1478,0.959,0.1898 Z M0.2331,0.4113 L0.2043,0.3849 Q0.1587,0.3844,0.1177,0.3661 Q0.1673,0.407,0.2331,0.4113 Z M0.2499,0.4118 Q0.2885,0.4118,0.324,0.3973 T0.3852,0.3589 T0.4264,0.3019 T0.4426,0.2323 L0.4126,0.2048 Q0.408,0.2769,0.3529,0.3282 T0.2198,0.3844 Z M0.442,0.2167 Q0.4368,0.1554,0.393,0.1097 Q0.4126,0.1478,0.4132,0.1903 Z M0.779,0.9887 L0.7501,0.9624 Q0.7046,0.9618,0.6636,0.9435 Q0.7132,0.9844,0.779,0.9887 Z M0.7957,0.9892 Q0.8477,0.9887,0.8918,0.9648 T0.9619,0.8997 T0.9885,0.8097 L0.9585,0.7823 Q0.9538,0.8543,0.8987,0.9056 T0.7657,0.9618 Z M0.9879,0.7941 Q0.9827,0.7328,0.9388,0.6871 Q0.9585,0.7253,0.959,0.7672 Z M0.2331,0.9887 L0.2043,0.9624 Q0.1587,0.9618,0.1177,0.9435 Q0.1673,0.9844,0.2331,0.9887 Z M0.2499,0.9892 Q0.3018,0.9887,0.3459,0.9648 T0.416,0.8997 T0.4426,0.8102 L0.4126,0.7823 Q0.408,0.8543,0.3529,0.9056 T0.2198,0.9618 Z M0.442,0.7941 Q0.4368,0.7328,0.393,0.6871 Q0.4126,0.7253,0.4132,0.7672 Z M0.3191,0.6452 Q0.2943,0.622,0.2643,0.6091 T0.2066,0.5962 Q0.1795,0.5962,0.1497,0.6091 T0.0949,0.6441 T0.0537,0.6995 T0.0375,0.7699 Q0.0375,0.8419,0.0941,0.8941 Q0.1189,0.9172,0.1489,0.9304 T0.2066,0.9435 Q0.2337,0.9435,0.2634,0.9304 T0.3182,0.8952 T0.3595,0.8398 T0.3756,0.7699 Q0.3756,0.6978,0.3191,0.6452 Z M0.026,0.7731 L0.026,0.7699 Q0.026,0.6935,0.0854,0.6376 Q0.0658,0.6538,0.0514,0.6739 T0.0289,0.718 T0.0202,0.7677 Z M0.0271,0.7892 L0.0208,0.7833 Q0.0254,0.8419,0.0681,0.886 Q0.0664,0.8828,0.0646,0.879 Q0.0329,0.8382,0.0271,0.7892 Z M0.3866,0.7823 Q0.382,0.8511,0.3278,0.9016 Q0.3843,0.8565,0.3918,0.7871 Z M0.3872,0.7677 L0.393,0.7726 L0.393,0.7699 Q0.393,0.7349,0.3791,0.7038 Q0.3739,0.6973,0.3681,0.6914 Q0.3866,0.7274,0.3872,0.7677 Z M0.865,0.6452 Q0.8402,0.622,0.8102,0.6091 T0.7525,0.5962 Q0.7305,0.5962,0.7072,0.6043 T0.6619,0.628 T0.6223,0.6642 T0.5941,0.7124 T0.5834,0.7699 Q0.5834,0.8419,0.6399,0.8941 Q0.6561,0.9097,0.6757,0.9207 T0.7149,0.9376 T0.7525,0.9435 Q0.7796,0.9435,0.8093,0.9304 T0.8641,0.8952 T0.9054,0.8398 T0.9215,0.7699 Q0.9215,0.6978,0.865,0.6452 Z M0.5718,0.7731 L0.5718,0.7699 Q0.5718,0.6935,0.6313,0.6376 Q0.6013,0.6618,0.584,0.6954 T0.5661,0.7677 Z M0.573,0.7892 L0.5666,0.7833 Q0.5713,0.8419,0.614,0.886 Q0.6122,0.8828,0.6105,0.879 Q0.5788,0.8382,0.573,0.7892 Z M0.9325,0.7823 Q0.9279,0.8511,0.8736,0.9016 Q0.9308,0.8565,0.9377,0.7871 Z M0.9331,0.7672 L0.9388,0.7726 L0.9388,0.7699 Q0.9388,0.7349,0.925,0.7038 Q0.9198,0.6973,0.914,0.6914 Q0.9325,0.7274,0.9331,0.7672 Z M0.3191,0.0677 Q0.2943,0.0446,0.2643,0.0317 T0.2066,0.0188 Q0.1795,0.0188,0.1497,0.0317 T0.0949,0.0667 T0.0537,0.122 T0.0375,0.1925 Q0.0375,0.2645,0.0941,0.3167 Q0.1189,0.3398,0.1489,0.353 T0.2066,0.3661 Q0.2337,0.3661,0.2634,0.353 T0.3182,0.3177 T0.3595,0.2624 T0.3756,0.1925 Q0.3756,0.1204,0.3191,0.0677 Z M0.026,0.1957 L0.026,0.1925 Q0.026,0.1161,0.0854,0.0602 Q0.0554,0.0844,0.0381,0.118 T0.0202,0.1903 Z M0.0271,0.2118 L0.0208,0.2059 Q0.0254,0.2645,0.0681,0.3086 Q0.0664,0.3054,0.0646,0.3016 Q0.0329,0.2608,0.0271,0.2118 Z M0.3866,0.2048 Q0.382,0.2737,0.3278,0.3242 Q0.3849,0.279,0.3918,0.2097 Z M0.3872,0.1903 L0.393,0.1952 L0.393,0.1925 Q0.393,0.1581,0.3791,0.1263 Q0.3739,0.1199,0.3681,0.114 Q0.3866,0.15,0.3872,0.1903 Z M0.865,0.0677 Q0.8402,0.0446,0.8102,0.0317 T0.7525,0.0188 Q0.7253,0.0188,0.6956,0.0317 T0.6408,0.0667 T0.5995,0.122 T0.5834,0.1925 Q0.5834,0.2645,0.6399,0.3167 Q0.6647,0.3398,0.6947,0.353 T0.7525,0.3661 Q0.7796,0.3661,0.8093,0.353 T0.8641,0.3177 T0.9054,0.2624 T0.9215,0.1925 Q0.9215,0.1204,0.865,0.0677 Z M0.5718,0.1957 L0.5718,0.1925 Q0.5718,0.1161,0.6313,0.0602 Q0.6013,0.0844,0.584,0.118 T0.5661,0.1903 Z M0.573,0.2118 L0.5666,0.2059 Q0.5713,0.2645,0.614,0.3086 Q0.6122,0.3054,0.6105,0.3016 Q0.5788,0.2608,0.573,0.2118 Z M0.9325,0.2048 Q0.9279,0.2737,0.8736,0.3242 Q0.9308,0.279,0.9377,0.2097 Z M0.9331,0.1898 L0.9388,0.1952 L0.9388,0.1925 Q0.9388,0.1575,0.925,0.1263 Q0.9198,0.1199,0.914,0.114 Q0.9325,0.15,0.9331,0.1898 Z",type:0}},"":{type:5,data:{d:"M0.7639,0.1974 L0.9593,0.1974 L0.9593,0.1443 L0.7639,0.1443 L0.7639,0.1974 Z M0.7586,0.109 L0.9727,0.109 Q0.9839,0.109,0.992,0.1153 T1,0.1291 L1,0.382 Q1,0.3906,0.9912,0.3964 T0.9727,0.4021 L0.7586,0.4021 Q0.7468,0.4021,0.739,0.3956 T0.7313,0.382 L0.7313,0.1291 Q0.7313,0.1246,0.7339,0.1207 T0.7406,0.1143 T0.7495,0.1104 T0.7586,0.109 Z M0.7639,0.6575 L0.9593,0.6575 L0.9593,0.6044 L0.7639,0.6044 L0.7639,0.6575 Z M0.7313,0.8347 L0.7313,0.5843 Q0.7313,0.5757,0.7401,0.5699 T0.7586,0.5641 L0.9706,0.5641 Q0.9818,0.5641,0.9898,0.5705 T0.9979,0.5843 L0.9979,0.8347 Q0.9979,0.8433,0.989,0.8491 T0.9706,0.8549 L0.7586,0.8549 Q0.7468,0.8549,0.739,0.8483 T0.7313,0.8347 Z M0,1 L0,0 L0.7607,0 L0.7607,1 L0,1 Z",type:0}},"":{type:5,data:{d:"M0.9764,0.0029 L0.3179,0.4552 L0,0.4552 L0,0 Z M1,1 L0,1 L0,0.5448 L0.3091,0.5448 Z",type:0}},"":{type:5,data:{d:"M0.0236,0.0029 L0.6824,0.4552 L1,0.4552 L1,0 Z M0,1 L1,1 L1,0.5448 L0.6912,0.5448 Z",type:0}},"":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z"},"":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z"},"":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z"},"":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z M.25,.15 L1,.15 L1,.85 L.25,.85 Z"},"":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z M0,.15 L1,.15 L1,.85 L0,.85 Z"},"":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z M0,.15 L.75,.15 L.75,.85 L0,.85 Z"},"":{type:5,data:{d:"M0.6574,0.303 Q0.623,0.291,0.5852,0.285 T0.5082,0.279 T0.4311,0.285 T0.359,0.303 L0.3082,0.248 Q0.3525,0.232,0.4041,0.2235 T0.5082,0.215 T0.6123,0.2235 T0.7082,0.248 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.8557,0.582 L0.7656,0.551 Q0.7852,0.53,0.7951,0.507 T0.8049,0.46 Q0.8049,0.424,0.782,0.3905 T0.718,0.332 T0.6221,0.293 T0.5082,0.279 L0.5082,0.215 Q0.5607,0.215,0.6123,0.2235 T0.709,0.248 T0.7918,0.287 T0.8557,0.3375 T0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.582 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.5082,0.705 Q0.482,0.705,0.4557,0.703 T0.4049,0.697 L0.4311,0.635 Q0.4508,0.638,0.4697,0.6395 T0.5082,0.641 Q0.5672,0.641,0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 Q0.8049,0.436,0.7951,0.413 T0.7656,0.369 L0.8557,0.338 Q0.882,0.365,0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 L0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 T0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 L0.9098,0.46 Q0.9098,0.492,0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.338 L0.2508,0.369 Q0.2311,0.39,0.2213,0.413 T0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 Q0.5279,0.641,0.5467,0.6395 T0.5852,0.635 L0.6115,0.697 Q0.5869,0.701,0.5607,0.703 T0.5082,0.705 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.1607,0.582 Q0.1344,0.555,0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.3375 T0.2246,0.287 T0.3074,0.248 T0.4041,0.2235 T0.5082,0.215 L0.5082,0.279 Q0.4492,0.279,0.3943,0.293 T0.2984,0.332 T0.2344,0.3905 T0.2115,0.46 Q0.2115,0.484,0.2213,0.507 T0.2508,0.551 Z",type:0},scaleType:1},"":i.LINE_H,"":i.LINE_V,"":i.FADE_RIGHT,"":i.FADE_LEFT,"":i.FADE_DOWN,"":i.FADE_UP,"":i.CURVE_DOWN_RIGHT,"":i.CURVE_DOWN_LEFT,"":i.CURVE_UP_RIGHT,"":i.CURVE_UP_LEFT,"":[i.LINE_V,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_DOWN_RIGHT],"":[i.CURVE_DOWN_RIGHT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_UP_LEFT],"":[i.LINE_V,i.CURVE_DOWN_LEFT],"":[i.CURVE_DOWN_LEFT,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_DOWN_LEFT],"":[i.LINE_H,i.CURVE_DOWN_RIGHT],"":[i.CURVE_DOWN_LEFT,i.CURVE_DOWN_RIGHT],"":[i.LINE_H,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_UP_RIGHT],"":[i.CURVE_UP_LEFT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_UP_LEFT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_DOWN_LEFT,i.CURVE_DOWN_RIGHT],"":[i.LINE_H,i.CURVE_DOWN_LEFT,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_DOWN_RIGHT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_DOWN_RIGHT,i.CURVE_UP_LEFT],"":[i.LINE_V,i.CURVE_DOWN_LEFT,i.CURVE_UP_RIGHT],"":[i.LINE_H,i.CURVE_DOWN_RIGHT,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_DOWN_LEFT,i.CURVE_UP_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE],"":i.NODE_STROKE,"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN],"":[i.NODE_STROKE,i.NODE_LINE_DOWN],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP],"":[i.NODE_STROKE,i.NODE_LINE_UP],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_UP],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_UP],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"🬀":s(1),"🬁":s(2),"🬂":s(3),"🬃":s(4),"🬄":s(5),"🬅":s(6),"🬆":s(7),"🬇":s(8),"🬈":s(9),"🬉":s(10),"🬊":s(11),"🬋":s(12),"🬌":s(13),"🬍":s(14),"🬎":s(15),"🬏":s(16),"🬐":s(17),"🬑":s(18),"🬒":s(19),"🬓":s(20),"🬔":s(22),"🬕":s(23),"🬖":s(24),"🬗":s(25),"🬘":s(26),"🬙":s(27),"🬚":s(28),"🬛":s(29),"🬜":s(30),"🬝":s(31),"🬞":s(32),"🬟":s(33),"🬠":s(34),"🬡":s(35),"🬢":s(36),"🬣":s(37),"🬤":s(38),"🬥":s(39),"🬦":s(40),"🬧":s(41),"🬨":s(43),"🬩":s(44),"🬪":s(45),"🬫":s(46),"🬬":s(47),"🬭":s(48),"🬮":s(49),"🬯":s(50),"🬰":s(51),"🬱":s(52),"🬲":s(53),"🬳":s(54),"🬴":s(55),"🬵":s(56),"🬶":s(57),"🬷":s(58),"🬸":s(59),"🬹":s(60),"🬺":s(61),"🬻":s(62),"🬼":{type:3,data:"M0,0.6667 L0,1 L0.5,1 Z"},"🬽":{type:3,data:"M0,0.6667 L0,1 L1,1 Z"},"🬾":{type:3,data:"M0,0.3333 L0,1 L0.5,1 Z"},"🬿":{type:3,data:"M0,0.3333 L0,1 L1,1 Z"},"🭀":{type:3,data:"M0,0 L0,1 L0.5,1 Z"},"🭁":{type:3,data:"M0,0.3333 L0.5,0 L1,0 L1,1 L0,1 Z"},"🭂":{type:3,data:"M0,0.3333 L1,0 L1,1 L0,1 Z"},"🭃":{type:3,data:"M0,0.6667 L0.5,0 L1,0 L1,1 L0,1 Z"},"🭄":{type:3,data:"M0,0.6667 L1,0 L1,1 L0,1 Z"},"🭅":{type:3,data:"M0,1 L0.5,0 L1,0 L1,1 Z"},"🭆":{type:3,data:"M0,0.6667 L1,0.3333 L1,1 L0,1 Z"},"🭇":{type:3,data:"M0.5,1 L1,0.6667 L1,1 Z"},"🭈":{type:3,data:"M0,1 L1,0.6667 L1,1 Z"},"🭉":{type:3,data:"M0.5,1 L1,0.3333 L1,1 Z"},"🭊":{type:3,data:"M0,1 L1,0.3333 L1,1 Z"},"🭋":{type:3,data:"M0.5,1 L1,0 L1,1 Z"},"🭌":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.3333 Z"},"🭍":{type:3,data:"M0,0 L0,1 L1,1 L1,0.3333 Z"},"🭎":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.6667 Z"},"🭏":{type:3,data:"M0,0 L0,1 L1,1 L1,0.6667 Z"},"🭐":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 Z"},"🭑":{type:3,data:"M0,0.3333 L0,1 L1,1 L1,0.6667 Z"},"🭒":{type:3,data:"M0,0.6667 L0.5,1 L1,1 L1,0 L0,0 Z"},"🭓":{type:3,data:"M0,0.6667 L1,1 L1,0 L0,0 Z"},"🭔":{type:3,data:"M0,0.3333 L0.5,1 L1,1 L1,0 L0,0 Z"},"🭕":{type:3,data:"M0,0.3333 L1,1 L1,0 L0,0 Z"},"🭖":{type:3,data:"M0,0 L0.5,1 L1,1 L1,0 Z"},"🭗":{type:3,data:"M0,0.3333 L0,0 L0.5,0 Z"},"🭘":{type:3,data:"M0,0.3333 L0,0 L1,0 Z"},"🭙":{type:3,data:"M0,0.6667 L0,0 L0.5,0 Z"},"🭚":{type:3,data:"M0,0.6667 L0,0 L1,0 Z"},"🭛":{type:3,data:"M0,1 L0,0 L0.5,0 Z"},"🭜":{type:3,data:"M0,0.6667 L0,0 L1,0 L1,0.3333 Z"},"🭝":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.6667 Z"},"🭞":{type:3,data:"M0,1 L0,0 L1,0 L1,0.6667 Z"},"🭟":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.3333 Z"},"🭠":{type:3,data:"M0,1 L0,0 L1,0 L1,0.3333 Z"},"🭡":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 Z"},"🭢":{type:3,data:"M0.5,0 L1,0 L1,0.3333 Z"},"🭣":{type:3,data:"M0,0 L1,0 L1,0.3333 Z"},"🭤":{type:3,data:"M0.5,0 L1,0 L1,0.6667 Z"},"🭥":{type:3,data:"M0,0 L1,0 L1,0.6667 Z"},"🭦":{type:3,data:"M0.5,0 L1,0 L1,1 Z"},"🭧":{type:3,data:"M0,0.3333 L1,0.6667 L1,0 L0,0 Z"},"🭨":{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0.5,0.5 Z"},"🭩":{type:3,data:"M0,0 L0.5,0.5 L1,0 L1,1 L0,1 Z"},"🭪":{type:3,data:"M0,0 L1,0 L0.5,0.5 L1,1 L0,1 Z"},"🭫":{type:3,data:"M0,0 L1,0 L1,1 L0.5,0.5 L0,1 Z"},"🭬":{type:3,data:"M0,0 L0.5,0.5 L0,1 Z"},"🭭":{type:3,data:"M0,0 L1,0 L0.5,0.5 Z"},"🭮":{type:3,data:"M1,0 L1,1 L0.5,0.5 Z"},"🭯":{type:3,data:"M0,1 L1,1 L0.5,0.5 Z"},"🭰":{type:0,data:[{x:1,y:0,w:1,h:8}]},"🭱":{type:0,data:[{x:2,y:0,w:1,h:8}]},"🭲":{type:0,data:[{x:3,y:0,w:1,h:8}]},"🭳":{type:0,data:[{x:4,y:0,w:1,h:8}]},"🭴":{type:0,data:[{x:5,y:0,w:1,h:8}]},"🭵":{type:0,data:[{x:6,y:0,w:1,h:8}]},"🭶":{type:0,data:[{x:0,y:1,w:8,h:1}]},"🭷":{type:0,data:[{x:0,y:2,w:8,h:1}]},"🭸":{type:0,data:[{x:0,y:3,w:8,h:1}]},"🭹":{type:0,data:[{x:0,y:4,w:8,h:1}]},"🭺":{type:0,data:[{x:0,y:5,w:8,h:1}]},"🭻":{type:0,data:[{x:0,y:6,w:8,h:1}]},"🭼":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"🭽":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"🭾":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"🭿":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"🮀":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:7,w:8,h:1}]},"🮁":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:2,w:8,h:1},{x:0,y:4,w:8,h:1},{x:0,y:7,w:8,h:1}]},"🮂":{type:0,data:[{x:0,y:0,w:8,h:2}]},"🮃":{type:0,data:[{x:0,y:0,w:8,h:3}]},"🮄":{type:0,data:[{x:0,y:0,w:8,h:5}]},"🮅":{type:0,data:[{x:0,y:0,w:8,h:6}]},"🮆":{type:0,data:[{x:0,y:0,w:8,h:7}]},"🮇":{type:0,data:[{x:6,y:0,w:2,h:8}]},"🮈":{type:0,data:[{x:5,y:0,w:3,h:8}]},"🮉":{type:0,data:[{x:3,y:0,w:5,h:8}]},"🮊":{type:0,data:[{x:2,y:0,w:6,h:8}]},"🮋":{type:0,data:[{x:1,y:0,w:7,h:8}]},"🮌":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},"🮍":{type:1,data:[[1,0],[0,1]],clipPath:"M0.5,0 L1,0 L1,1 L0.5,1 Z"},"🮎":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},"🮏":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},"🮐":{type:1,data:[[0,1],[1,0]]},"🮑":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},{type:0,data:[{x:0,y:0,w:8,h:4}]}],"🮒":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},{type:0,data:[{x:0,y:4,w:8,h:4}]}],"🮔":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},{type:0,data:[{x:4,y:0,w:4,h:8}]}],"🮕":{type:0,data:[{x:0,y:0,w:2,h:2},{x:4,y:0,w:2,h:2},{x:2,y:2,w:2,h:2},{x:6,y:2,w:2,h:2},{x:0,y:4,w:2,h:2},{x:4,y:4,w:2,h:2},{x:2,y:6,w:2,h:2},{x:6,y:6,w:2,h:2}]},"🮖":{type:0,data:[{x:2,y:0,w:2,h:2},{x:6,y:0,w:2,h:2},{x:0,y:2,w:2,h:2},{x:4,y:2,w:2,h:2},{x:2,y:4,w:2,h:2},{x:6,y:4,w:2,h:2},{x:0,y:6,w:2,h:2},{x:4,y:6,w:2,h:2}]},"🮗":{type:0,data:[{x:0,y:2,w:8,h:2},{x:0,y:6,w:8,h:2}]},"🮘":{type:2,data:"M-0.25,-0.25 L1.25,1.25 M-0.25,0 L1,1.25 M-0.25,0.25 L0.75,1.25 M-0.25,0.5 L0.5,1.25 M0,-0.25 L1.25,1 M0.25,-0.25 L1.25,0.75 M0.5,-0.25 L1.25,0.5 M-0.25,0.75 L0.25,1.25 M0.75,-0.25 L1.25,0.25",strokeWidth:1},"🮙":{type:2,data:"M-0.25,0.5 L0.5,-0.25 M-0.25,0.75 L0.75,-0.25 M-0.25,1 L1,-0.25 M-0.25,1.25 L1.25,-0.25 M0,1.25 L1.25,0 M0.25,1.25 L1.25,0.25 M0.5,1.25 L1.25,0.5 M-0.25,0.25 L0.25,-0.25 M0.75,1.25 L1.25,0.75",strokeWidth:1},"🮚":{type:5,data:{d:"M0,0 L.5,.5 L0,1 L1,1 L.5,.5 L1,0",type:0}},"🮛":{type:5,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1",type:0}},"🮜":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L0,1 Z"},"🮝":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,1 Z"},"🮞":{type:1,data:[[1,0],[0,1]],clipPath:"M1,0 L1,1 L0,1 Z"},"🮟":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,1 L0,1 Z"},"🮠":{type:2,data:"M.5,0 L0,.5",strokeWidth:1},"🮡":{type:2,data:"M.5,0 L1,.5",strokeWidth:1},"🮢":{type:2,data:"M0,.5 L.5,1",strokeWidth:1},"🮣":{type:2,data:"M1,.5 L.5,1",strokeWidth:1},"🮤":{type:2,data:"M.5,0 L0,.5 L.5,1",strokeWidth:1},"🮥":{type:2,data:"M.5,0 L1,.5 L.5,1",strokeWidth:1},"🮦":{type:2,data:"M0,.5 L.5,1 L1,.5",strokeWidth:1},"🮧":{type:2,data:"M0,.5 L.5,0 L1,.5",strokeWidth:1},"🮨":{type:2,data:"M.5,0 L0,.5 M1,.5 L.5,1",strokeWidth:1},"🮩":{type:2,data:"M.5,0 L1,.5 M0,.5 L.5,1",strokeWidth:1},"🮪":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5",strokeWidth:1},"🮫":{type:2,data:"M.5,0 L0,.5 L.5,1 L1,.5",strokeWidth:1},"🮬":{type:2,data:"M0,.5 L.5,0 L1,.5 L.5,1",strokeWidth:1},"🮭":{type:2,data:"M1,.5 L.5,0 L0,.5 L.5,1",strokeWidth:1},"🮮":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5 Z",strokeWidth:1},"🮯":{type:2,data:"M0,.5 L1,.5 M.5,.35 L.5,.65",strokeWidth:1},"🮰":{type:3,data:"M0.1,0.2 L0.1,.8 L.4,.6 L.9,0.6 Z",scaleType:1},"🮱":{type:4,data:{d:"M.1,.525 L.35,.675 L.9,.35",type:1},scaleType:1},"🮲":{type:3,data:"M.29,.27 L0.13,.56 L.22,.59 L.35,0.35 L.67,.35 L.57,.57 L.71,.76 L.22,.76 L.42,1 L.53,.98 L.43,.86 L.9,.86 L.71,.6 L1,.6 L1,.52 L.83,.52 L.92,.36 L1,.36 L1,.27Z M.99,.13 A.12,.12,0,1,1,.75,.13 A.12,.12,0,1,1,.99,.13"},"🮳":{type:3,data:"M0,.27 L.3,.27 L.55,.12 L.63,.18 L.33,.36 L0,.36 M0,.52 L.33,.52 L.59,.89 L.73,.89 L.73,.98 L.53,.98 L.28,.6 L0,.6"},"🮴":{type:4,data:{d:"M.15,.55 L.5,.4 L.5,.45 L.65,.45 L.65,.35 L.85,.35 L.85,.625 L.5,.625 L.5,.7 Z",type:0},scaleType:1},"🮵":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.15,.5 L.5,.35 L.5,.425 L.85,.425 L.85,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"🮶":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.85,.5 L.5,.35 L.5,.425 L.15,.425 L.15,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"🮷":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.675 L.2,.5 L.35,.5 L.35,.325 L.65,.325 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"🮸":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.325 L.2,.5 L.35,.5 L.35,.675 L.65,.675 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"🮹":{type:5,data:{d:"M1,.89 L.11,.89 L.11,.37 L.36,.12 L.74,.12 L.96,.34 L1,.34 L1,.405 L.92,.405 L.69,.185 L.41,.185 L.21,.42 L.21,.825 L1,.825 Z",type:0}},"🮺":{type:5,data:{d:"M0,.89 L0,.825 L.78,.825 L.78,.53 L.7,.415 L0,.415 L0,.35 L.75,.35 L.88,.48 L.88,.89 Z",type:0}},"🮻":{type:5,data:{d:"M.31,.275 L.44,.275 L.44,.47 L.05,.47 L.05,.405 L.31,.405 Z M.56,.275 L.69,.275 L.69,.405 L.95,.405 L.95,.47 L.56,.47 Z M.05,.53 L.44,.53 L.44,.725 L.31,.725 L.31,.595 L.05,.595 Z M.56,.53 L.95,.53 L.95,.595 L.69,.595 L.69,.725 L.56,.725 Z",type:0},scaleType:1},"🮼":[{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0,.935 L.885,.935 L.885,.065 L0,.065 Z"},{type:3,data:"M.67,.5 A.17,.085,0,1,1,.33,.5 A.17,.085,0,1,1,.67,.5",scaleType:1}],"🮽":{type:4,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1 Z",type:1}},"🮾":{type:4,data:{d:"M1,.5 L.5,1",type:1}},"🮿":{type:4,data:{d:"M.5,0 L1,.5 L.5,1 L0,.5 Z",type:1}},"🯀":{type:3,data:"M.16,.445 A.02,.01,0,0,1,.39,.33 L.5,.375 L.61,.33 A.02,.01,0,0,1,.84,.445 L.75,.5 L.84,.555 A.02,.01,0,0,1,.61,.67 L.5,.625 L.39,.67 A.02,.01,0,0,1,.16,.555 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",scaleType:1},"🯁":{type:3,data:"M0.142308,0.924 Q0.130770,0.924,0.120193,0.922 T0.101924,0.916 T0.089424,0.9065 T0.084616,0.895 V0.025 Q0.084616,0.019,0.089424,0.0135 T0.101924,0.004 T0.120193,-0.002 T0.142308,-0.004 Q0.150000,-0.004,0.157693,-0.003 T0.173078,0.000 L0.430770,0.085 Q0.451924,0.059,0.494232,0.041 T0.587501,0.013 T0.692309,-0.0005 T0.800001,-0.004 H1 V0.055 H0.800001 Q0.771155,0.055,0.742309,0.056 T0.685578,0.060 T0.630770,0.0685 T0.580770,0.0825 T0.543270,0.1045 T0.528847,0.133 V0.647 H0.530770 Q0.596155,0.645,0.659616,0.638 T0.782693,0.6165 T0.893270,0.5805 T1,0.531 V0.623 Q0.934616,0.644,0.880770,0.6595 T0.769232,0.685 T0.650963,0.700 T0.528847,0.707 V0.787 Q0.528847,0.802,0.543270,0.8155 T0.580770,0.8375 T0.630770,0.8515 T0.685578,0.860 T0.742309,0.864 T0.800001,0.865 H1 V0.924 H0.800001 Q0.746155,0.924,0.692309,0.9205 T0.587501,0.907 T0.494232,0.879 T0.430770,0.835 L0.173078,0.920 Q0.165386,0.922,0.157693,0.923 T0.142308,0.924 Z M0.2,0.841 L0.415385,0.770 V0.150 L0.2,0.079 V0.841 Z M1,0.698 Q0.973077,0.694,0.969231,0.6885 T0.965385,0.677 Q0.965385,0.672,0.969231,0.6665 T1,0.657 V0.698 Z"},"🯂":{type:3,data:"M0,0.623 V0.531 Q0.044231,0.512,0.0625,0.4905 T0.092308,0.4465 T0.108654,0.4005 T0.113462,0.354 V0.351 Q0.113462,0.345,0.117308,0.3395 T0.129808,0.3305 T0.148846,0.3245 T0.171154,0.323 H0.501923 Q0.532692,0.323,0.563462,0.3185 T0.617308,0.303 T0.651923,0.2765 T0.663462,0.2435 V0.241 Q0.663462,0.219,0.657692,0.197 T0.639423,0.1545 T0.604808,0.115 T0.549615,0.082 T0.475577,0.0615 T0.392308,0.055 H0 V-0.004 H1 V0.055 H0.667308 Q0.694231,0.071,0.713462,0.09 T0.746154,0.129 T0.766346,0.1705 T0.775,0.213 H1 V0.316 Q0.971154,0.305,0.955769,0.2965 T0.920192,0.2825 T0.876923,0.2745 T0.830769,0.272 H0.773077 Q0.767308,0.297,0.743269,0.319 T0.680769,0.355 T0.595192,0.375 T0.501923,0.381 H0.227308 Q0.223462,0.415,0.211,0.4485 T0.172692,0.5135 T0.108269,0.573 T0,0.623 Z M0.611538,0.924 H0 V0.865 H0.611538 Q0.642308,0.865,0.673077,0.8605 T0.727885,0.845 T0.762308,0.8185 T0.773077,0.787 V0.785 Q0.773077,0.769,0.762308,0.7535 T0.727885,0.727 T0.673077,0.7115 T0.611538,0.707 H0.059615 Q0.048077,0.707,0.037115,0.7045 T0,0.694 V0.653 Q0.026923,0.648,0.037115,0.646 T0.059615,0.644 H0.722692 Q0.753462,0.644,0.784231,0.6395 T0.839038,0.624 T0.873846,0.5975 T0.884615,0.566 V0.564 Q0.884615,0.548,0.873846,0.532 T0.839038,0.5055 T0.784231,0.49 T0.722692,0.4855 H0.392308 Q0.380769,0.4855,0.370192,0.483 T0.351923,0.4765 T0.339423,0.467 T0.334615,0.4555 T0.339423,0.444 T0.351923,0.4345 T0.370192,0.428 T0.392308,0.4255 H0.832692 Q0.855769,0.4255,0.878846,0.4235 T0.922115,0.416 T0.957692,0.4015 T1,0.3815 V0.4685 Q0.975,0.4705,0.966346,0.4725 T0.95,0.4765 Q0.961538,0.4835,0.969231,0.4915 T1,0.5075 V0.6205 Q0.965385,0.6455,0.926923,0.665 T0.84,0.6935 Q0.866923,0.7115,0.877596,0.7345 T0.894231,0.7855 V0.787 Q0.894231,0.815,0.876923,0.8425 T0.820192,0.8895 T0.726923,0.916 T0.611538,0.924 Z"},"🯃":{type:3,data:"M0,0.473 V0.386 Q0.025490,0.378,0.028431,0.3695 T0.031373,0.352 V0.35 Q0.031373,0.342,0.028431,0.333 T0,0.316 V0.213 H0.652941 Q0.684314,0.213,0.715686,0.2085 T0.770588,0.193 T0.804902,0.1665 T0.815686,0.135 V0.133 Q0.815686,0.117,0.804902,0.101 T0.770588,0.0745 T0.715686,0.0595 T0.652941,0.055 H0 V-0.004 H0.652941 Q0.707843,-0.004,0.761765,0.004 T0.856863,0.031 T0.915686,0.0775 T0.933333,0.133 V0.135 Q0.933333,0.163,0.915686,0.1905 T0.856863,0.237 T0.761765,0.264 T0.652941,0.272 H0.109804 Q0.131373,0.29,0.140196,0.31 T0.149020,0.35 V0.352 Q0.149020,0.37,0.142157,0.388 T0.118627,0.4225 T0.076471,0.452 T0,0.473 Z M0,0.625 V0.513 Q0.029412,0.526,0.032353,0.54 T0.035294,0.568 V0.57 Q0.035294,0.584,0.032353,0.598 T0,0.625 Z"},"🯄":{type:3,data:"M0.019231,1.085 V-0.165 H0.980769 V1.085 H0.019231 Z M0.446154,0.527 H0.553846 Q0.553846,0.511,0.5625,0.495 T0.591346,0.466 T0.631731,0.4405 T0.666346,0.4135 T0.688462,0.3825 T0.696154,0.35 Q0.696154,0.33,0.682692,0.311 T0.641346,0.2785 T0.575,0.259 T0.498077,0.253 T0.421154,0.259 T0.356731,0.279 T0.315385,0.3125 T0.301923,0.352 V0.357 H0.409615 V0.354 Q0.409615,0.345,0.414423,0.335 T0.431731,0.318 T0.4625,0.3075 T0.498077,0.304 Q0.517308,0.304,0.534615,0.307 T0.564423,0.3165 T0.582692,0.332 T0.588462,0.35 Q0.588462,0.366,0.572115,0.3805 T0.535577,0.4075 T0.496154,0.4335 T0.465385,0.4625 T0.45,0.4945 T0.446154,0.527 Z M0.5,0.667 Q0.519231,0.667,0.5375,0.664 T0.569231,0.654 T0.588462,0.637 T0.594231,0.617 T0.588462,0.5975 T0.569231,0.581 T0.5375,0.571 T0.5,0.568 T0.4625,0.571 T0.430769,0.581 T0.411538,0.5975 T0.405769,0.617 T0.411538,0.637 T0.430769,0.654 T0.4625,0.664 T0.5,0.667 Z",scaleType:1},"🯅":{type:5,data:{d:"M.44,.425 L.44,.51 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.51 L.56,.425 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯆":{type:5,data:{d:"M.44,.425 L.44,.46 L.23,.385 L.19,.43 L.44,.51 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.61,.735 L.7,.71 L.56,.56 L.56,.51 L.81,.43 L.77,.385 L.56,.46 L.56,.425 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯇":{type:5,data:{d:"M.44,.425 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.425 Z M.18,.53 L.23,.575 L.81,.43 L.77,.385 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯈":{type:5,data:{d:"M.44,.425 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.62,.735 L.71,.71 L.56,.56 L.56,.425 Z M.23,.385 L.18,.43 L.77,.575 L.81,.53 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯉":{type:5,data:{d:"M.44,.425 L.45,.495 L.15,.645 L.34,.645 L.34,.7 L.44,.7 L.44,.645 L.56,.645 L.56,.7 L.66,.7 L.66,.645 L.84,.645 L.54,.495 L.56,.425 Z M.39,.6 L.5,.55 L.60,.6 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯊":{type:5,data:{d:"M.26,.375 L.5,.255 L.74,.375 L.74,.665 L.5,.55 L.26,.665 Z M.37,.395 L.37,.54 L.5,.475 L.63,.54 L.63,.395 L.5,.33 Z",type:0},scaleType:1},"🯋":{type:5,data:{d:"M.09,.41 L.32,.295 L.5,.375 L.68,.295 L.91,.41 L.75,.5 L.91,.59 L.68,.705 L.5,.625 L.32,.705 L.09,.59 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",type:0},scaleType:1},"🯌":{type:5,data:{d:"M.55,.305 L.88,.305 L.88,.355 L.65,.355 L.65,.47 L.88,.47 L.88,.52 L.55,.52 Z",type:0},scaleType:1},"🯍":{type:5,data:{d:"M.38,.39 L.5,.33 L.62,.39 L.62,.53 L.5,.47 L.38,.53 Z",type:0},scaleType:1},"🯎":{type:3,data:"M0,0 L0.6667,0 L0.6667,1 L0,1 Z"},"🯏":{type:3,data:"M0,0 L0.3333,0 L0.3333,1 L0,1 Z"},"🯐":{type:2,data:"M1,.5 L0,1",strokeWidth:1},"🯑":{type:2,data:"M1,0 L0,.5",strokeWidth:1},"🯒":{type:2,data:"M0,0 L1,.5",strokeWidth:1},"🯓":{type:2,data:"M0,.5 L1,1",strokeWidth:1},"🯔":{type:2,data:"M0,0 L.5,1",strokeWidth:1},"🯕":{type:2,data:"M.5,0 L1,1",strokeWidth:1},"🯖":{type:2,data:"M1,0 L.5,1",strokeWidth:1},"🯗":{type:2,data:"M.5,0 L0,1",strokeWidth:1},"🯘":{type:2,data:"M0,0 L.5,.5 L1,0",strokeWidth:1},"🯙":{type:2,data:"M1,0 L.5,.5 L1,1",strokeWidth:1},"🯚":{type:2,data:"M0,1 L.5,.5 L1,1",strokeWidth:1},"🯛":{type:2,data:"M0,0 L.5,.5 L0,1",strokeWidth:1},"🯜":{type:2,data:"M0,0 L.5,1 L1,0",strokeWidth:1},"🯝":{type:2,data:"M1,0 L0,.5 L1,1",strokeWidth:1},"🯞":{type:2,data:"M0,1 L.5,0 L1,1",strokeWidth:1},"🯟":{type:2,data:"M0,0 L1,.5 L0,1",strokeWidth:1},"🯠":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0",type:1}},"🯡":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1",type:1}},"🯢":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1",type:1}},"🯣":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1",type:1}},"🯤":{type:0,data:[{x:2,y:0,w:4,h:4}]},"🯥":{type:0,data:[{x:2,y:4,w:4,h:4}]},"🯦":{type:0,data:[{x:0,y:2,w:4,h:4}]},"🯧":{type:0,data:[{x:4,y:2,w:4,h:4}]},"🯨":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0 Z",type:0}},"🯩":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1 Z",type:0}},"🯪":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1 Z",type:0}},"🯫":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1 Z",type:0}},"🯬":{type:5,data:{d:"M1,0 L.5,0 C.5,.276,.724,.5,1,.5 Z",type:0}},"🯭":{type:5,data:{d:"M0,1 L.5,1 C.5,.724,.276,.5,0,.5 Z",type:0}},"🯮":{type:5,data:{d:"M1,1 L1,.5 C.724,.5,.5,.724,.5,1 Z",type:0}},"🯯":{type:5,data:{d:"M0,0 L0,.5 C.276,.5,.5,.276,.5,0 Z",type:0}},"🯰":{type:5,data:{d:r(126),type:0},scaleType:1},"🯱":{type:5,data:{d:r(48),type:0},scaleType:1},"🯲":{type:5,data:{d:r(109),type:0},scaleType:1},"🯳":{type:5,data:{d:r(121),type:0},scaleType:1},"🯴":{type:5,data:{d:r(51),type:0},scaleType:1},"🯵":{type:5,data:{d:r(91),type:0},scaleType:1},"🯶":{type:5,data:{d:r(95),type:0},scaleType:1},"🯷":{type:5,data:{d:r(114),type:0},scaleType:1},"🯸":{type:5,data:{d:r(127),type:0},scaleType:1},"🯹":{type:5,data:{d:r(123),type:0},scaleType:1},"🯺":{type:5,data:{d:"M.5,.175 C.2,.175,.15,.305,.15,.435 L.05,.63 L.35,.63 C.35,.682,.42,.76,.5,.76 C.58,.76,.65,.682,.65,.63 L.95,.63 L.85,.435 C.85,.305,.8,.175,.5,.175 Z",type:0},scaleType:1},...Object.fromEntries(Array.from({length:256},(t,e)=>[String.fromCodePoint(10240+e),{type:6,data:e}]))},e.blockPatternCodepoints=new Set([9617,9618,9619,129932,129933,129934,129935,129936,129937,129938,129940,129948,129949,129950,129951])},183(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.tryDrawCustomGlyph=function(t,e,i,s,o,n,L,h,T,l,d,c,_=0){const Q=r.customGlyphDefinitions[e];if(Q){const e=Array.isArray(Q)?Q:[Q];for(const r of e)a(t,r,i,s,o,n,L,h,T,l,d,c,_);return!0}return!1};const s=i(959),r=i(915);function a(t,e,i,r,a,h,d,c,_,Q,u,p,g=0){let M=a,y=h,v=i,f=r;switch(1===e.scaleType&&(M=d,y=c,v=i+(a-d)/2,f=r+(h-c)/2),e.clipPath&&(t.save(),function(t,e,i,s,r,a){t.beginPath();for(const o of e.split(" ")){const e=o[0];if("Z"===e){t.closePath();continue}const n=o.substring(1).split(",");if(!n[0]||!n[1])continue;const L=i+parseFloat(n[0])*r,h=s+parseFloat(n[1])*a;"M"===e?t.moveTo(L,h):"L"===e&&t.lineTo(L,h)}t.clip()}(t,e.clipPath,v,f,M,y)),e.type){case 0:!function(t,e,i,s,r,a){for(let o=0;o7&&parseInt(T.slice(7,9),16)||1;else{if(!T.startsWith("rgba"))throw new Error(`Unexpected fillStyle color format "${T}" when drawing pattern glyph`);[L,d,c,_]=T.substring(5,T.length-1).split(",").map(t=>parseFloat(t))}for(let t=0;t>1&1,c=1&n;0!==d||0!==c?l.setTransform((new DOMMatrix).translateSelf(-d,-c)):l.setTransform(new DOMMatrix),t.fillStyle=l,t.fillRect(i,r,a,o)}(t,e.data,v,f,M,y,g);break;case 2:!function(t,e,i,s,r,a,o,n,L){let h;t.save(),t.beginPath(),t.rect(i,s,r,a),t.clip(),t.beginPath(),h="function"==typeof e?e(.15,.15/a*r):e;const d={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(const e of h.split(" ")){const L=e[0];if("Z"===L){t.closePath(),d.lastCommand=L;continue}const h=T[L];if(!h){n.error(`Could not find drawing instructions for "${L}"`);continue}const c=e.substring(1).split(",");c[0]&&c[1]&&(h(t,l(c,r,a,i,s,!0,o,0,0,!1),d),d.lastCommand=L)}void 0!==L?(t.strokeStyle=t.fillStyle,t.lineWidth=o*L,t.stroke()):t.fill(),t.closePath(),t.restore()}(t,e.data,v,f,M,y,Q,u,e.strokeWidth);break;case 3:!function(t,e,i,s,r,a,o,L){const h="string"==typeof e?e:e(0,0);t.beginPath();let T=0,l=0,d=0,c=0,_="";for(const e of h.split(" ")){const o=e[0],L=e.substring(1).split(",");if("Z"===o){t.closePath(),_=o;continue}if("V"===o){const e=s+parseFloat(L[0])*a;t.lineTo(T,e),l=e,d=T,c=l,_=o;continue}if("H"===o){const e=i+parseFloat(L[0])*r;t.lineTo(e,l),T=e,d=T,c=l,_=o;continue}if(!L[0]||!L[1])continue;if("A"===o){const e=parseFloat(L[0])*r,o=parseFloat(L[1])*a,h=parseFloat(L[2])*Math.PI/180,d=parseInt(L[3],10),c=parseInt(L[4],10),_=i+parseFloat(L[5])*r,Q=s+parseFloat(L[6])*a;n(t,T,l,e,o,h,d,c,_,Q),T=_,l=Q;continue}const h=L.map((t,e)=>{const o=parseFloat(t);return e%2==0?i+o*r:s+o*a});if("M"===o)t.moveTo(h[0],h[1]),T=h[0],l=h[1],d=T,c=l;else if("L"===o)t.lineTo(h[0],h[1]),T=h[0],l=h[1],d=T,c=l;else if("Q"===o)t.quadraticCurveTo(h[0],h[1],h[2],h[3]),d=h[0],c=h[1],T=h[2],l=h[3];else if("T"===o){let e,i;"Q"===_||"T"===_?(e=2*T-d,i=2*l-c):(e=T,i=l),t.quadraticCurveTo(e,i,h[0],h[1]),d=e,c=i,T=h[0],l=h[1]}else"C"===o&&(t.bezierCurveTo(h[0],h[1],h[2],h[3],h[4],h[5]),d=h[2],c=h[3],T=h[4],l=h[5]);_=o}void 0!==L?(t.strokeStyle=t.fillStyle,t.lineWidth=o*L,t.stroke()):t.fill()}(t,e.data,v,f,M,y,Q,e.strokeWidth);break;case 4:!function(t,e,i,s,r,a,o,n){t.save(),t.fillRect(i,s,r,a),n&&(t.fillStyle=n,t.strokeStyle=n),t.lineWidth=o,t.lineCap="square",t.beginPath();for(const o of e.d.split(" ")){const e=o[0],n=o.substring(1).split(",");if(!n[0]||!n[1]){"Z"===e&&t.closePath();continue}const L=n.map((t,e)=>{const o=parseFloat(t);return e%2==0?i+o*r:s+o*a});"M"===e?t.moveTo(L[0],L[1]):"L"===e&&t.lineTo(L[0],L[1])}1===e.type?t.stroke():t.fill(),t.restore()}(t,e.data,v,f,M,y,Q,p);break;case 5:!function(t,e,i,s,r,a,o,n,L){const h=new Path2D;h.rect(i,s,r,a),t.clip(h),t.beginPath();const d=o/12;t.lineWidth=n*d;const c={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(const o of e.d.split(" ")){const h=o[0];if("Z"===h){t.closePath(),c.lastCommand=h;continue}const _=T[h];if(!_){L.error(`Could not find drawing instructions for "${h}"`);continue}const Q=o.substring(1).split(",");Q[0]&&Q[1]&&(_(t,l(Q,r,a,i,s,!1,n,(e.leftPadding??0)*(d/2),(e.rightPadding??0)*(d/2)),c),c.lastCommand=h)}1===e.type?(t.strokeStyle=t.fillStyle,t.stroke()):t.fill(),t.closePath()}(t,e.data,v,f,M,y,_,Q,u);break;case 6:!function(t,e,i,s,r,a){const n=r/8,L=.1*a,h=.8*a/8,T=Math.min(n,h);for(let r=0;r<8;r++)if(e&1<1){const t=Math.sqrt(y);u=(s*=t)*s,p=(r*=t)*r}let v=(u*p-u*M-p*g)/(u*M+p*g);v<0&&(v=0);const f=(o===n?-1:1)*Math.sqrt(v),C=f*(s*Q/r),m=f*(-r*_/s),w=T*C-l*m+(e+L)/2,x=l*C+T*m+(i+h)/2,b=(_-C)/s,E=(Q-m)/r,R=(-_-C)/s,k=(-Q-m)/r,A=Math.atan2(E,b);let Z=Math.atan2(k,R)-A;0===n&&Z>0?Z-=2*Math.PI:1===n&&Z<0&&(Z+=2*Math.PI);const D=A+Z;t.ellipse(w,x,s,r,a,A,D,0===n)}const L=new Map;function h(t,e,i=0){return Math.max(Math.min(t,e),i)}const T={C:(t,e,i)=>{t.bezierCurveTo(e[0],e[1],e[2],e[3],e[4],e[5]),i.lastControlX=e[2],i.lastControlY=e[3],i.currentX=e[4],i.currentY=e[5]},L:(t,e,i)=>{t.lineTo(e[0],e[1]),i.lastControlX=i.currentX=e[0],i.lastControlY=i.currentY=e[1]},M:(t,e,i)=>{t.moveTo(e[0],e[1]),i.lastControlX=i.currentX=e[0],i.lastControlY=i.currentY=e[1]},Q:(t,e,i)=>{t.quadraticCurveTo(e[0],e[1],e[2],e[3]),i.lastControlX=e[0],i.lastControlY=e[1],i.currentX=e[2],i.currentY=e[3]},T:(t,e,i)=>{let s,r;"Q"===i.lastCommand||"T"===i.lastCommand?(s=2*i.currentX-i.lastControlX,r=2*i.currentY-i.lastControlY):(s=i.currentX,r=i.currentY),t.quadraticCurveTo(s,r,e[0],e[1]),i.lastControlX=s,i.lastControlY=r,i.currentX=e[0],i.currentY=e[1]}};function l(t,e,i,s,r,a,o,n=0,L=0,T=!0){const l=t.map(t=>parseFloat(t)||parseInt(t));if(l.length<2)throw new Error("Too few arguments for instruction");for(let t=0;t{this._refreshCharAtlas(t,e),this.reset(t)})),this._register((0,r.toDisposable)(()=>{this._canvas.remove()}))}_initCanvas(){this._ctx=(0,a.throwIfFalsy)(this._canvas.getContext("2d",{alpha:this._alpha})),this._alpha||this._clearAll()}handleBlur(t){}handleFocus(t){}handleCursorMove(t){}handleGridChanged(t,e,i){}handleSelectionChanged(t,e,i,s=!1){}_setTransparency(t,e){if(e===this._alpha)return;const i=this._canvas;this._alpha=e,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,i),this._refreshCharAtlas(t,this._themeService.colors),this.handleGridChanged(t,0,t.rows-1)}_refreshCharAtlas(t,e){this._deviceCharWidth<=0&&this._deviceCharHeight<=0||(this._charAtlas=(0,s.acquireTextureAtlas)(t,this._optionsService.rawOptions,e,this._deviceCellWidth,this._deviceCellHeight,this._deviceCharWidth,this._deviceCharHeight,this._coreBrowserService.dpr,2048),this._charAtlas.warmUp())}resize(t,e){this._deviceCellWidth=e.device.cell.width,this._deviceCellHeight=e.device.cell.height,this._deviceCharWidth=e.device.char.width,this._deviceCharHeight=e.device.char.height,this._deviceCharLeft=e.device.char.left,this._deviceCharTop=e.device.char.top,this._canvas.width=e.device.canvas.width,this._canvas.height=e.device.canvas.height,this._canvas.style.width=`${e.css.canvas.width}px`,this._canvas.style.height=`${e.css.canvas.height}px`,this._alpha||this._clearAll(),this._refreshCharAtlas(t,this._themeService.colors)}_fillBottomLineAtCells(t,e,i=1){this._ctx.fillRect(t*this._deviceCellWidth,(e+1)*this._deviceCellHeight-this._coreBrowserService.dpr-1,i*this._deviceCellWidth,this._coreBrowserService.dpr)}_clearAll(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))}_clearCells(t,e,i,s){this._alpha?this._ctx.clearRect(t*this._deviceCellWidth,e*this._deviceCellHeight,i*this._deviceCellWidth,s*this._deviceCellHeight):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(t*this._deviceCellWidth,e*this._deviceCellHeight,i*this._deviceCellWidth,s*this._deviceCellHeight))}_fillCharTrueColor(t,e,i,s){this._ctx.font=this._getFont(t,!1,!1),this._ctx.textBaseline=o.TEXT_BASELINE,this._clipCell(i,s,e.getWidth()),this._ctx.fillText(e.getChars(),i*this._deviceCellWidth+this._deviceCharLeft,s*this._deviceCellHeight+this._deviceCharTop+this._deviceCharHeight)}_clipCell(t,e,i){this._ctx.beginPath(),this._ctx.rect(t*this._deviceCellWidth,e*this._deviceCellHeight,i*this._deviceCellWidth,this._deviceCellHeight),this._ctx.clip()}_getFont(t,e,i){return`${i?"italic":""} ${e?t.options.fontWeightBold:t.options.fontWeight} ${t.options.fontSize*this._coreBrowserService.dpr}px ${t.options.fontFamily}`}}e.BaseRenderLayer=n},306(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.LinkRenderLayer=void 0;const s=i(657),r=i(814),a=i(133);class o extends a.BaseRenderLayer{constructor(t,e,i,s,r,a,o){super(i,t,"link",e,!0,r,a,o),this._register(s.onShowLinkUnderline(t=>this._handleShowLinkUnderline(t))),this._register(s.onHideLinkUnderline(t=>this._handleHideLinkUnderline(t)))}resize(t,e){super.resize(t,e),this._state=void 0}reset(t){this._clearCurrentLink()}_clearCurrentLink(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);const t=this._state.y2-this._state.y1-1;t>0&&this._clearCells(0,this._state.y1+1,this._state.cols,t),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}}_handleShowLinkUnderline(t){if(t.fg===r.INVERTED_DEFAULT_COLOR?this._ctx.fillStyle=this._themeService.colors.background.css:void 0!==t.fg&&(0,s.is256Color)(t.fg)?this._ctx.fillStyle=this._themeService.colors.ansi[t.fg].css:this._ctx.fillStyle=this._themeService.colors.foreground.css,t.y1===t.y2)this._fillBottomLineAtCells(t.x1,t.y1,t.x2-t.x1);else{this._fillBottomLineAtCells(t.x1,t.y1,t.cols-t.x1);for(let e=t.y1+1;e{var t=s;Object.defineProperty(t,"__esModule",{value:!0}),t.WebglAddon=void 0;const e=i(426),r=i(95),a=i(399),o=i(414);class n extends e.Disposable{constructor(t){if(r.isSafari&&(0,r.getSafariVersion)()<16){const t={antialias:!1,depth:!1,preserveDrawingBuffer:!0};if(!document.createElement("canvas").getContext("webgl2",t))throw new Error("WebGL2 is only supported on Safari 16 and above")}super(),this._onChangeTextureAtlas=this._register(new o.Emitter),this.onChangeTextureAtlas=this._onChangeTextureAtlas.event,this._onAddTextureAtlasCanvas=this._register(new o.Emitter),this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=this._register(new o.Emitter),this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._onContextLoss=this._register(new o.Emitter),this.onContextLoss=this._onContextLoss.event,this._customGlyphs=t?.customGlyphs??!0,this._preserveDrawingBuffer=t?.preserveDrawingBuffer}activate(t){const i=t._core;if(!t.element)return void this._register(i.onWillOpen(()=>this.activate(t)));this._terminal=t;const s=i.coreService,r=i.optionsService,n=i,L=n._renderService,h=n._characterJoinerService,T=n._charSizeService,l=n._coreBrowserService,d=n._decorationService,c=n._logService,_=n._themeService;this._renderer=this._register(new a.WebglRenderer(t,h,T,l,s,d,c,r,_,this._customGlyphs,this._preserveDrawingBuffer)),this._register(o.EventUtils.forward(this._renderer.onContextLoss,this._onContextLoss)),this._register(o.EventUtils.forward(this._renderer.onChangeTextureAtlas,this._onChangeTextureAtlas)),this._register(o.EventUtils.forward(this._renderer.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas)),this._register(o.EventUtils.forward(this._renderer.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas)),L.setRenderer(this._renderer),this._register((0,e.toDisposable)(()=>{if(this._terminal._core._store._isDisposed)return;const e=this._terminal._core._renderService;e.setRenderer(this._terminal._core._createRenderer()),e.handleResize(t.cols,t.rows)}))}get textureAtlas(){return this._renderer?.textureAtlas}clearTextureAtlas(){this._renderer?.clearTextureAtlas()}}t.WebglAddon=n})(),s})()); -+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.WebglAddon=e():t.WebglAddon=e()}(globalThis,()=>(()=>{"use strict";var t={105(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.WindowIntervalTimer=e.eventType=void 0,e.getWindow=r,e.addDisposableListener=o,e.addStandardDisposableListener=function(t,e,i,s){return o(t,e,i,s)},e.getDomNodePagePosition=function(t){const e=t.getBoundingClientRect(),i=r(t);return{left:e.left+i.scrollX,top:e.top+i.scrollY,width:e.width,height:e.height}},e.scheduleAtNextAnimationFrame=function(t,e,i=0){const s=h(t),r=new n(e,i);return s.next.push(r),s.animFrameRequested||(s.animFrameRequested=!0,t.requestAnimationFrame(()=>function(t){const e=h(t);for(e.animFrameRequested=!1,e.current=e.next,e.next=[],e.inAnimationFrameRunner=!0;e.current.length>0;)e.current.sort(n.sort),e.current.shift().execute();e.inAnimationFrameRunner=!1}(t))),r};const s=i(578);function r(t){const e=t;if(e?.ownerDocument?.defaultView)return e.ownerDocument.defaultView;const i=t;return i?.view?i.view:window}class a{constructor(t,e,i,s){this._node=t,this._type=e,this._handler=i,this._options=s,t.addEventListener(e,i,s)}dispose(){this._node&&this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}}function o(t,e,i,s){return new a(t,e,i,s)}e.eventType={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",KEY_DOWN:"keydown",KEY_UP:"keyup",INPUT:"input",BLUR:"blur",FOCUS:"focus",CHANGE:"change",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_UP:"pointerup",MOUSE_WHEEL:"wheel",WHEEL:"wheel"};class n{constructor(t,e){this._runner=t,this.priority=e,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(t){console.error(t)}}static sort(t,e){return e.priority-t.priority}}const L=new Map;function h(t){let e=L.get(t);return e||(e={next:[],current:[],animFrameRequested:!1,inAnimationFrameRunner:!1},L.set(t,e)),e}class T extends s.IntervalTimer{constructor(t){super(),this._defaultTarget=t?r(t):void 0}cancelAndSet(t,e,i){super.cancelAndSet(t,e,i??this._defaultTarget??window)}}e.WindowIntervalTimer=T},814(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.INVERTED_DEFAULT_COLOR=void 0,e.INVERTED_DEFAULT_COLOR=257},959(t,e){function i(t){return 57508<=t&&t<=57558}function s(t){return t>=128512&&t<=128591||t>=127744&&t<=128511||t>=128640&&t<=128767||t>=9728&&t<=9983||t>=9984&&t<=10175||t>=65024&&t<=65039||t>=129280&&t<=129535||t>=127462&&t<=127487}Object.defineProperty(e,"__esModule",{value:!0}),e.throwIfFalsy=function(t){if(!t)throw new Error("value must not be falsy");return t},e.isPowerlineGlyph=i,e.isRestrictedPowerlineGlyph=function(t){return 57520<=t&&t<=57527},e.isEmoji=s,e.allowRescaling=function(t,e,r,a){return 1===e&&r>Math.ceil(1.5*a)&&void 0!==t&&t>255&&!s(t)&&!i(t)&&!function(t){return 57344<=t&&t<=63743}(t)},e.treatGlyphAsBackgroundColor=function(t){return i(t)||function(t){return 9472<=t&&t<=9631}(t)},e.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},e.computeNextVariantOffset=function(t,e,i=0){return(t-(2*Math.round(e)-i))%(2*Math.round(e))}},948(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.createSelectionRenderModel=function(){return new i};class i{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(t,e,i,s=!1){if(this.selectionStart=e,this.selectionEnd=i,!e||!i||e[0]===i[0]&&e[1]===i[1])return void this.clear();const r=t.buffers.active.ydisp,a=e[1]-r,o=i[1]-r,n=Math.max(a,0),L=Math.min(o,t.rows-1);n>=t.rows||L<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=n,this.viewportCappedEndRow=L,this.startCol=e[0],this.endCol=i[0])}isCellSelected(t,e,i){return!!this.hasSelection&&(i-=t.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?e>=this.startCol&&i>=this.viewportCappedStartRow&&e=this.viewportCappedStartRow&&e>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&e=this.startCol)}}},536(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.TextBlinkStateManager=void 0;const s=i(426);class r extends s.Disposable{constructor(t,e,i){super(),this._renderCallback=t,this._coreBrowserService=e,this._optionsService=i,this._intervalDuration=0,this._blinkOn=!0,this._needsBlinkInViewport=!1,this._isViewportVisible=!0,this._register(this._optionsService.onSpecificOptionChange("blinkIntervalDuration",t=>{this.setIntervalDuration(t)})),this.setIntervalDuration(this._optionsService.rawOptions.blinkIntervalDuration),this._register((0,s.toDisposable)(()=>this._clearInterval()))}get isBlinkOn(){return this._blinkOn}get isEnabled(){return this._intervalDuration>0}setNeedsBlinkInViewport(t){this._needsBlinkInViewport!==t&&(this._needsBlinkInViewport=t,this._updateIntervalState())}setViewportVisible(t){this._isViewportVisible!==t&&(this._isViewportVisible=t,this._updateIntervalState())}setIntervalDuration(t){t!==this._intervalDuration&&(this._intervalDuration=t,this._clearInterval(),this._updateIntervalState())}_updateIntervalState(){if(this._intervalDuration>0&&this._needsBlinkInViewport&&this._isViewportVisible){if(void 0!==this._interval)return;const t=this._blinkOn;return this._blinkOn=!0,this._interval=this._coreBrowserService.window.setInterval(()=>{this._blinkOn=!this._blinkOn,this._renderCallback()},this._intervalDuration),void(t||this._renderCallback())}this._clearInterval(),this._blinkOn||(this._blinkOn=!0,this._renderCallback())}_clearInterval(){void 0!==this._interval&&(this._coreBrowserService.window.clearInterval(this._interval),this._interval=void 0)}}e.TextBlinkStateManager=r},578(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.IntervalTimer=e.MicrotaskTimer=e.TimeoutTimer=void 0,e.timeout=function(t){return new Promise(e=>setTimeout(e,t))},e.disposableTimeout=function(t,e=0,i){const r=setTimeout(()=>{t(),i&&a.dispose()},e),a=(0,s.toDisposable)(()=>{clearTimeout(r)});return i?.add(a),a};const s=i(426);e.TimeoutTimer=class{constructor(){this._token=-1,this._isDisposed=!1}dispose(){this.cancel(),this._isDisposed=!0}cancel(){-1!==this._token&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(t,e){if(this._isDisposed)throw new Error("Calling cancelAndSet on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,t()},e)}setIfNotSet(t,e){if(this._isDisposed)throw new Error("Calling setIfNotSet on a disposed TimeoutTimer");-1===this._token&&(this._token=setTimeout(()=>{this._token=-1,t()},e))}},e.MicrotaskTimer=class{constructor(){this._isScheduled=!1,this._isDisposed=!1}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._isScheduled=!1}set(t){if(this._isDisposed)throw new Error("Calling set on a disposed MicrotaskTimer");this._isScheduled||(this._isScheduled=!0,queueMicrotask(()=>{this._isScheduled&&(this._isScheduled=!1,t())}))}},e.IntervalTimer=class{constructor(){this._isDisposed=!1}cancel(){this._disposable?.dispose(),this._disposable=void 0}cancelAndSet(t,e,i=globalThis){if(this._isDisposed)throw new Error("Calling cancelAndSet on a disposed IntervalTimer");this.cancel();const s=i.setInterval(()=>{t()},e);this._disposable={dispose:()=>{i.clearInterval(s),this._disposable=void 0}}}dispose(){this.cancel(),this._isDisposed=!0}}},993(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.rgba=e.rgb=e.css=e.color=e.channels=e.NULL_COLOR=void 0,e.toPaddedHex=l,e.contrastRatio=d;let i=0,s=0,r=0,a=0;var o,n,L,h,T;function l(t){const e=t.toString(16);return e.length<2?"0"+e:e}function d(t,e){return t>>0},t.toColor=function(e,i,s,r){return{css:t.toCss(e,i,s,r),rgba:t.toRgba(e,i,s,r)}}}(o||(e.channels=o={})),function(t){function e(t,e){return a=Math.round(255*e),[i,s,r]=T.toChannels(t.rgba),{css:o.toCss(i,s,r,a),rgba:o.toRgba(i,s,r,a)}}t.blend=function(t,e){if(a=(255&e.rgba)/255,1===a)return{css:e.css,rgba:e.rgba};const n=e.rgba>>24&255,L=e.rgba>>16&255,h=e.rgba>>8&255,T=t.rgba>>24&255,l=t.rgba>>16&255,d=t.rgba>>8&255;return i=T+Math.round((n-T)*a),s=l+Math.round((L-l)*a),r=d+Math.round((h-d)*a),{css:o.toCss(i,s,r),rgba:o.toRgba(i,s,r)}},t.isOpaque=function(t){return!(255&~t.rgba)},t.ensureContrastRatio=function(t,e,i){const s=T.ensureContrastRatio(t.rgba,e.rgba,i);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},t.opaque=function(t){const e=(255|t.rgba)>>>0;return[i,s,r]=T.toChannels(e),{css:o.toCss(i,s,r),rgba:e}},t.opacity=e,t.multiplyOpacity=function(t,i){return a=255&t.rgba,e(t,a*i/255)},t.toColorRGB=function(t){return[t.rgba>>24&255,t.rgba>>16&255,t.rgba>>8&255]}}(n||(e.color=n={})),function(t){let e,n;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i=t.getContext("2d",{willReadFrequently:!0});i&&(e=i,e.globalCompositeOperation="copy",n=e.createLinearGradient(0,0,1,1))}catch{}t.toColor=function(t){if(t.match(/#[\da-f]{3,8}/i))switch(t.length){case 4:return i=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),r=parseInt(t.slice(3,4).repeat(2),16),o.toColor(i,s,r);case 5:return i=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),r=parseInt(t.slice(3,4).repeat(2),16),a=parseInt(t.slice(4,5).repeat(2),16),o.toColor(i,s,r,a);case 7:return{css:t,rgba:(parseInt(t.slice(1),16)<<8|255)>>>0};case 9:return{css:t,rgba:parseInt(t.slice(1),16)>>>0}}const L=t.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(L)return i=parseInt(L[1],10),s=parseInt(L[2],10),r=parseInt(L[3],10),a=Math.round(255*(void 0===L[5]?1:parseFloat(L[5]))),o.toColor(i,s,r,a);if("transparent"===t)return{css:"transparent",rgba:0};if(!e||!n)throw new Error("css.toColor: Unsupported css format");if(e.fillStyle=n,e.fillStyle=t,"string"!=typeof e.fillStyle)throw new Error("css.toColor: Unsupported css format");if(e.fillRect(0,0,1,1),[i,s,r,a]=e.getImageData(0,0,1,1).data,255!==a)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(i,s,r,a),css:t}}}(L||(e.css=L={})),function(t){function e(t,e,i){const s=t/255,r=e/255,a=i/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4))}t.relativeLuminance=function(t){return e(t>>16&255,t>>8&255,255&t)},t.relativeLuminance2=e}(h||(e.rgb=h={})),function(t){function e(t,e,i){const s=t>>24&255,r=t>>16&255,a=t>>8&255;let o=e>>24&255,n=e>>16&255,L=e>>8&255,T=d(h.relativeLuminance2(o,n,L),h.relativeLuminance2(s,r,a));for(;T0||n>0||L>0);)o-=Math.max(0,Math.ceil(.1*o)),n-=Math.max(0,Math.ceil(.1*n)),L-=Math.max(0,Math.ceil(.1*L)),T=d(h.relativeLuminance2(o,n,L),h.relativeLuminance2(s,r,a));return(o<<24|n<<16|L<<8|255)>>>0}function n(t,e,i){const s=t>>24&255,r=t>>16&255,a=t>>8&255;let o=e>>24&255,n=e>>16&255,L=e>>8&255,T=d(h.relativeLuminance2(o,n,L),h.relativeLuminance2(s,r,a));for(;T>>0}t.blend=function(t,e){if(a=(255&e)/255,1===a)return e;const n=e>>24&255,L=e>>16&255,h=e>>8&255,T=t>>24&255,l=t>>16&255,d=t>>8&255;return i=T+Math.round((n-T)*a),s=l+Math.round((L-l)*a),r=d+Math.round((h-d)*a),o.toRgba(i,s,r)},t.ensureContrastRatio=function(t,i,s){const r=h.relativeLuminance(t>>8),a=h.relativeLuminance(i>>8);if(d(r,a)>8));if(od(r,h.relativeLuminance(e>>8))?a:e}return a}const o=n(t,i,s),L=d(r,h.relativeLuminance(o>>8));if(Ld(r,h.relativeLuminance(a>>8))?o:a}return o}},t.reduceLuminance=e,t.increaseLuminance=n,t.toChannels=function(t){return[t>>24&255,t>>16&255,t>>8&255,255&t]}}(T||(e.rgba=T={}))},414(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.EventUtils=e.Emitter=void 0;const s=i(426);var r;e.Emitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=(t,e,i)=>{if(this._disposed)return(0,s.toDisposable)(()=>{});const r={fn:t,thisArgs:e};this._listeners.push(r);const a=(0,s.toDisposable)(()=>{const t=this._listeners.indexOf(r);-1!==t&&this._listeners.splice(t,1)});return i&&(Array.isArray(i)?i.push(a):i.add(a)),a}),this._event}fire(t){if(!this._disposed)switch(this._listeners.length){case 0:return;case 1:{const{fn:e,thisArgs:i}=this._listeners[0];return void e.call(i,t)}default:{const e=this._listeners.slice();for(const{fn:i,thisArgs:s}of e)i.call(s,t)}}}dispose(){this._disposed||(this._disposed=!0,this._listeners.length=0)}},function(t){t.forward=function(t,e){return t(t=>e.fire(t))},t.map=function(t,e){return(i,s,r)=>t(t=>i.call(s,e(t)),void 0,r)},t.any=function(...t){return(e,i,r)=>{const a=new s.DisposableStore;for(const s of t)a.add(s(t=>e.call(i,t)));return r&&(Array.isArray(r)?r.push(a):r.add(a)),a}},t.runAndSubscribe=function(t,e,i){return e(i),t(t=>e(t))}}(r||(e.EventUtils=r={}))},426(t,e){function i(t){return{dispose:t}}function s(t){if(!t)return t;if(Array.isArray(t)){for(const e of t)e.dispose();return[]}return t.dispose(),t}Object.defineProperty(e,"__esModule",{value:!0}),e.MutableDisposable=e.Disposable=e.DisposableStore=void 0,e.toDisposable=i,e.dispose=s,e.combinedDisposable=function(...t){return i(()=>s(t))};class r{constructor(){this._disposables=new Set,this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(t){return this._isDisposed?t.dispose():this._disposables.add(t),t}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(const t of this._disposables)t.dispose();this._disposables.clear()}}clear(){for(const t of this._disposables)t.dispose();this._disposables.clear()}}e.DisposableStore=r;class a{constructor(){this._store=new r}dispose(){this._store.dispose()}_register(t){return this._store.add(t)}}e.Disposable=a,a.None=Object.freeze({dispose(){}}),e.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(t){this._isDisposed||t===this._value||(this._value?.dispose(),this._value=t)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}}},836(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.FourKeyMap=e.TwoKeyMap=void 0;class i{constructor(){this._data={}}set(t,e,i){this._data[t]||(this._data[t]={}),this._data[t][e]=i}get(t,e){return this._data[t]?this._data[t][e]:void 0}clear(){this._data={}}}e.TwoKeyMap=i,e.FourKeyMap=class{constructor(){this._data=new i}set(t,e,s,r,a){this._data.get(t,e)||this._data.set(t,e,new i),this._data.get(t,e).set(s,r,a)}get(t,e,i,s){return this._data.get(t,e)?.get(i,s)}clear(){this._data.clear()}}},95(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.isChromeOS=e.isLinux=e.isWindows=e.isMac=e.isSafari=e.isLegacyEdge=e.isChrome=e.isFirefox=e.isNode=void 0,e.getZoomFactor=function(t){return 1},e.getSafariVersion=function(){if(!e.isSafari)return 0;const t=i.match(/Version\/(\d+)/);return null===t||t.length<2?0:parseInt(t[1],10)},e.isNode=!("undefined"==typeof process||!("title"in process)||"undefined"!=typeof navigator&&!navigator.userAgent.startsWith("Node.js/"));const i=e.isNode?"node":navigator.userAgent,s=e.isNode?"node":navigator.platform;e.isFirefox=i.includes("Firefox"),e.isChrome=i.includes("Chrome"),e.isLegacyEdge=i.includes("Edge"),e.isSafari=/^((?!chrome|android).)*safari/i.test(i),e.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(s),e.isWindows=["Windows","Win16","Win32","WinCE"].includes(s),e.isLinux=s.indexOf("Linux")>=0,e.isChromeOS=/\bCrOS\b/.test(i)},930(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.DebouncedIdleTask=e.IdleTaskQueue=e.PriorityTaskQueue=void 0;class i{constructor(t){this._tasks=[],this._i=0,this._logService=t}enqueue(t){this._tasks.push(t),this._start()}flush(){for(;this._ii)return r-e<-20&&this._logService.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-e))}ms`),void this._start();r=i}this.clear()}}class s extends i{_requestCallback(t){return setTimeout(()=>t(this._createDeadline(16)))}_cancelCallback(t){clearTimeout(t)}_createDeadline(t){const e=performance.now()+t;return{timeRemaining:()=>Math.max(0,e-performance.now())}}}e.PriorityTaskQueue=s,e.IdleTaskQueue="requestIdleCallback"in globalThis?class extends i{_requestCallback(t){return requestIdleCallback(t)}_cancelCallback(t){cancelIdleCallback(t)}}:s,e.DebouncedIdleTask=class{constructor(t){this._queue=new e.IdleTaskQueue(t)}set(t){this._queue.clear(),this._queue.enqueue(t)}flush(){this._queue.flush()}dispose(){this._queue.clear()}}},917(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.ExtendedAttrs=e.AttributeData=void 0;class i{constructor(){this.fg=0,this.bg=0,this.extended=new s}static toColorRGB(t){return[t>>>16&255,t>>>8&255,255&t]}static fromColorRGB(t){return(255&t[0])<<16|(255&t[1])<<8|255&t[2]}clone(){const t=new i;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)}isBgPalette(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?16777216==(50331648&this.extended.underlineColor)||33554432==(50331648&this.extended.underlineColor):this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}e.AttributeData=i;class s{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(t){this._ext&=-67108864,this._ext|=67108863&t}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){const t=(3758096384&this._ext)>>29;return t<0?4294967288^t:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}constructor(t=0,e=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=e}clone(){return new s(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}}e.ExtendedAttrs=s},721(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.CellData=void 0;const s=i(348),r=i(564),a=i(917);class o extends a.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new a.ExtendedAttrs,this.combinedData=""}static fromCharData(t){const e=new o;return e.setFromCharData(t),e}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,s.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(t){this.fg=t[r.CHAR_DATA_ATTR_INDEX],this.bg=0;let e=!1;if(t[r.CHAR_DATA_CHAR_INDEX].length>2)e=!0;else if(2===t[r.CHAR_DATA_CHAR_INDEX].length){const i=t[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=i&&i<=56319){const s=t[r.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=s&&s<=57343?this.content=1024*(i-55296)+s-56320+65536|t[r.CHAR_DATA_WIDTH_INDEX]<<22:e=!0}else e=!0}else this.content=t[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[r.CHAR_DATA_WIDTH_INDEX]<<22;e&&(this.combinedData=t[r.CHAR_DATA_CHAR_INDEX],this.content=2097152|t[r.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}attributesEquals(t){if(this.getFgColorMode()!==t.getFgColorMode()||this.getFgColor()!==t.getFgColor())return!1;if(this.getBgColorMode()!==t.getBgColorMode()||this.getBgColor()!==t.getBgColor())return!1;if(this.isInverse()!==t.isInverse())return!1;if(this.isBold()!==t.isBold())return!1;if(this.isUnderline()!==t.isUnderline())return!1;if(this.isUnderline()){if(this.getUnderlineStyle()!==t.getUnderlineStyle())return!1;const e=this.isUnderlineColorDefault(),i=t.isUnderlineColorDefault();if(!e||!i){if(e!==i)return!1;if(this.getUnderlineColor()!==t.getUnderlineColor())return!1;if(this.getUnderlineColorMode()!==t.getUnderlineColorMode())return!1}}return this.isOverline()===t.isOverline()&&this.isBlink()===t.isBlink()&&this.isInvisible()===t.isInvisible()&&this.isItalic()===t.isItalic()&&this.isDim()===t.isDim()&&this.isStrikethrough()===t.isStrikethrough()}}e.CellData=o},564(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.WHITESPACE_CELL_CODE=e.WHITESPACE_CELL_WIDTH=e.WHITESPACE_CELL_CHAR=e.NULL_CELL_CODE=e.NULL_CELL_WIDTH=e.NULL_CELL_CHAR=e.CHAR_DATA_CODE_INDEX=e.CHAR_DATA_WIDTH_INDEX=e.CHAR_DATA_CHAR_INDEX=e.CHAR_DATA_ATTR_INDEX=e.DEFAULT_EXT=e.DEFAULT_ATTR=e.DEFAULT_COLOR=void 0,e.DEFAULT_COLOR=0,e.DEFAULT_ATTR=e.DEFAULT_COLOR<<9|256,e.DEFAULT_EXT=0,e.CHAR_DATA_ATTR_INDEX=0,e.CHAR_DATA_CHAR_INDEX=1,e.CHAR_DATA_WIDTH_INDEX=2,e.CHAR_DATA_CODE_INDEX=3,e.NULL_CELL_CHAR="",e.NULL_CELL_WIDTH=1,e.NULL_CELL_CODE=0,e.WHITESPACE_CELL_CHAR=" ",e.WHITESPACE_CELL_WIDTH=1,e.WHITESPACE_CELL_CODE=32},348(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.Utf8ToUtf32=e.StringToUtf32=void 0,e.stringFromCodePoint=function(t){return t>65535?(t-=65536,String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):String.fromCharCode(t)},e.utf32ToString=function(t,e=0,i=t.length){let s="";for(let r=e;r65535?(e-=65536,s+=String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):s+=String.fromCharCode(e)}return s},e.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(t,e){const i=t.length;if(!i)return 0;let s=0,r=0;if(this._interim){const i=t.charCodeAt(r++);56320<=i&&i<=57343?e[s++]=1024*(this._interim-55296)+i-56320+65536:(e[s++]=this._interim,e[s++]=i),this._interim=0}for(let a=r;a=i)return this._interim=r,s;const o=t.charCodeAt(a);56320<=o&&o<=57343?e[s++]=1024*(r-55296)+o-56320+65536:(e[s++]=r,e[s++]=o);continue}65279!==r&&(e[s++]=r)}return s}},e.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(t,e){const i=t.length;if(!i)return 0;let s,r,a,o,n,L=0,h=0;if(this.interim[0]){let s=!1,r=this.interim[0];r&=192==(224&r)?31:224==(240&r)?15:7;let a,o=0;for(;(a=this.interim[++o])&&o<4;)r<<=6,r|=63&a;const n=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,T=n-o;for(;h=i)return 0;if(a=t[h++],128!=(192&a)){h--,s=!0;break}this.interim[o++]=a,r<<=6,r|=63&a}s||(2===n?r<128?h--:e[L++]=r:3===n?r<2048||r>=55296&&r<=57343||65279===r||(e[L++]=r):r<65536||r>1114111||(e[L++]=r)),this.interim.fill(0)}const T=i-4;let l=h;for(;l=i)return this.interim[0]=s,L;if(r=t[l++],128!=(192&r)){l--;continue}if(n=(31&s)<<6|63&r,n<128){l--;continue}e[L++]=n}else if(224==(240&s)){if(l>=i)return this.interim[0]=s,L;if(r=t[l++],128!=(192&r)){l--;continue}if(l>=i)return this.interim[0]=s,this.interim[1]=r,L;if(a=t[l++],128!=(192&a)){l--;continue}if(n=(15&s)<<12|(63&r)<<6|63&a,n<2048||n>=55296&&n<=57343||65279===n)continue;e[L++]=n}else if(240==(248&s)){if(l>=i)return this.interim[0]=s,L;if(r=t[l++],128!=(192&r)){l--;continue}if(l>=i)return this.interim[0]=s,this.interim[1]=r,L;if(a=t[l++],128!=(192&a)){l--;continue}if(l>=i)return this.interim[0]=s,this.interim[1]=r,this.interim[2]=a,L;if(o=t[l++],128!=(192&o)){l--;continue}if(n=(7&s)<<18|(63&r)<<12|(63&a)<<6|63&o,n<65536||n>1114111)continue;e[L++]=n}}return L}}},864(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.CellColorResolver=void 0;const s=i(564),r=i(993),a=i(959),o=i(915);let n,L=0,h=0,T=!1,l=!1,d=!1,c=0;e.CellColorResolver=class{constructor(t,e,i,s,r,a){this._terminal=t,this._optionService=e,this._selectionRenderModel=i,this._decorationService=s,this._coreBrowserService=r,this._themeService=a,this.result={fg:0,bg:0,ext:0}}resolve(t,e,i,_,Q){this.result.bg=t.bg,this.result.fg=t.fg,this.result.ext=268435456&t.bg?t.extended.ext:0,h=0,L=0,l=!1,T=!1,d=!1,n=this._themeService.colors,c=0;const u=t.getCode();if(u!==s.NULL_CELL_CODE&&4===t.extended.underlineStyle){const t=Math.max(1,Math.floor(this._optionService.rawOptions.fontSize*this._coreBrowserService.dpr/15));c=e*_%(2*Math.round(t))}if(0===c&&o.blockPatternCodepoints.has(u)&&(c=e*_%2*2+i*Q%2),this._decorationService.forEachDecorationAtCell(e,i,"bottom",t=>{t.backgroundColorRGB&&(h=t.backgroundColorRGB.rgba>>8&16777215,l=!0),t.foregroundColorRGB&&(L=t.foregroundColorRGB.rgba>>8&16777215,T=!0)}),d=this._selectionRenderModel.isCellSelected(this._terminal,e,i),d){if(67108864&this.result.fg||50331648&this.result.bg){if(67108864&this.result.fg)switch(50331648&this.result.fg){case 16777216:case 33554432:h=this._themeService.colors.ansi[255&this.result.fg].rgba;break;case 50331648:h=(16777215&this.result.fg)<<8|255;break;default:h=this._themeService.colors.foreground.rgba}else switch(50331648&this.result.bg){case 16777216:case 33554432:h=this._themeService.colors.ansi[255&this.result.bg].rgba;break;case 50331648:h=(16777215&this.result.bg)<<8|255}h=r.rgba.blend(h,4294967040&(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba|128)>>8&16777215}else h=(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba>>8&16777215;if(l=!0,n.selectionForeground&&(L=n.selectionForeground.rgba>>8&16777215,T=!0),(0,a.treatGlyphAsBackgroundColor)(t.getCode())){if(67108864&this.result.fg&&!(50331648&this.result.bg))L=(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba>>8&16777215;else{if(67108864&this.result.fg)switch(50331648&this.result.bg){case 16777216:case 33554432:L=this._themeService.colors.ansi[255&this.result.bg].rgba;break;case 50331648:L=(16777215&this.result.bg)<<8|255}else switch(50331648&this.result.fg){case 16777216:case 33554432:L=this._themeService.colors.ansi[255&this.result.fg].rgba;break;case 50331648:L=(16777215&this.result.fg)<<8|255;break;default:L=this._themeService.colors.foreground.rgba}L=r.rgba.blend(L,4294967040&(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba|128)>>8&16777215}T=!0}}this._decorationService.forEachDecorationAtCell(e,i,"top",t=>{t.backgroundColorRGB&&(h=t.backgroundColorRGB.rgba>>8&16777215,l=!0),t.foregroundColorRGB&&(L=t.foregroundColorRGB.rgba>>8&16777215,T=!0)}),l&&(h=d?-16777216&t.bg&-134217729|h|50331648:-16777216&t.bg|h|50331648),T&&(L=-16777216&t.fg&-67108865|L|50331648),67108864&this.result.fg&&(l&&!T&&(L=50331648&this.result.bg?-134217728&this.result.fg|67108863&this.result.bg:-134217728&this.result.fg|16777215&n.background.rgba>>8|50331648,T=!0),!l&&T&&(h=50331648&this.result.fg?-67108864&this.result.bg|67108863&this.result.fg:-67108864&this.result.bg|16777215&n.foreground.rgba>>8|50331648,l=!0)),n=void 0,this.result.bg=l?h:this.result.bg,this.result.fg=T?L:this.result.fg,this.result.ext&=536870911,this.result.ext|=c<<29&3758096384}}},670(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.acquireTextureAtlas=function(t,e,i,o,n,L,h,T,l,d=!0){const c=(0,r.generateConfig)(o,n,L,h,e,i,T,l,d);for(let e=0;e=0){if((0,r.configEquals)(i.config,c))return i.atlas;1===i.ownedBy.length?(i.atlas.dispose(),a.splice(e,1)):i.ownedBy.splice(s,1);break}}for(let e=0;e{this._renderCallback(),this._animationFrame=void 0})))}_restartInterval(t=600){this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout=this._coreBrowserService.window.setTimeout(()=>{if(this._animationTimeRestarted){const t=600-(Date.now()-this._animationTimeRestarted);if(this._animationTimeRestarted=void 0,t>0)return void this._restartInterval(t)}this.isCursorVisible=!1,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0}),this._blinkInterval=this._coreBrowserService.window.setInterval(()=>{if(this._animationTimeRestarted){const t=600-(Date.now()-this._animationTimeRestarted);return this._animationTimeRestarted=void 0,void this._restartInterval(t)}this.isCursorVisible=!this.isCursorVisible,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0})},600)},t)}pause(){this.isCursorVisible=!0,this._isIdlePaused=!1,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._idleTimeout&&(this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0)}resume(){this.pause(),this._animationTimeRestarted=void 0,this._restartInterval(),this._resetIdleTimer(),this.restartBlinkAnimation()}_resetIdleTimer(){this._isIdlePaused=!1,this._idleTimeout&&this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=this._coreBrowserService.window.setTimeout(()=>{this._stopBlinkingDueToIdle()},3e5)}_stopBlinkingDueToIdle(){this.isCursorVisible=!0,this._isIdlePaused=!0,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0,this._renderCallback()}}},697(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.observeDevicePixelDimensions=function(t,e,i){let r=new e.ResizeObserver(e=>{const s=e.find(e=>e.target===t);if(!s)return;if(!("devicePixelContentBoxSize"in s))return r?.disconnect(),void(r=void 0);const a=s.devicePixelContentBoxSize[0].inlineSize,o=s.devicePixelContentBoxSize[0].blockSize;a>0&&o>0&&i(a,o)});try{r.observe(t,{box:["device-pixel-content-box"]})}catch{r.disconnect(),r=void 0}return(0,s.toDisposable)(()=>r?.disconnect())};const s=i(426)},28(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.GlyphRenderer=void 0;const s=i(115),r=i(564),a=i(426),o=i(719),n=i(959);let L,h=0,T=0,l=0;class d extends a.Disposable{constructor(t,e,i,r,L){super(),this._terminal=t,this._gl=e,this._dimensions=i,this._optionsService=r,this._logService=L,this._activeBuffer=0,this._vertices={count:0,attributes:new Float32Array(0),attributesBuffers:[new Float32Array(0),new Float32Array(0)]};const h=this._gl;void 0===s.TextureAtlas.maxAtlasPages&&(s.TextureAtlas.maxAtlasPages=Math.min(32,(0,n.throwIfFalsy)(h.getParameter(h.MAX_TEXTURE_IMAGE_UNITS))),s.TextureAtlas.maxTextureSize=(0,n.throwIfFalsy)(h.getParameter(h.MAX_TEXTURE_SIZE))),this._program=(0,n.throwIfFalsy)((0,o.createProgram)(h,"#version 300 es\nlayout (location = 0) in vec2 a_unitquad;\nlayout (location = 1) in vec2 a_cellpos;\nlayout (location = 2) in vec2 a_offset;\nlayout (location = 3) in vec2 a_size;\nlayout (location = 4) in float a_texpage;\nlayout (location = 5) in vec2 a_texcoord;\nlayout (location = 6) in vec2 a_texsize;\n\nuniform mat4 u_projection;\nuniform vec2 u_resolution;\n\nout vec2 v_texcoord;\nflat out int v_texpage;\n\nvoid main() {\n vec2 zeroToOne = (a_offset / u_resolution) + a_cellpos + (a_unitquad * a_size);\n gl_Position = u_projection * vec4(zeroToOne, 0.0, 1.0);\n v_texpage = int(a_texpage);\n v_texcoord = a_texcoord + a_unitquad * a_texsize;\n}",function(t){let e="";for(let i=1;ih.deleteProgram(this._program))),this._projectionLocation=(0,n.throwIfFalsy)(h.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=(0,n.throwIfFalsy)(h.getUniformLocation(this._program,"u_resolution")),this._textureLocation=(0,n.throwIfFalsy)(h.getUniformLocation(this._program,"u_texture"));const T=this._vertexArrayObject=h.createVertexArray();this._register((0,a.toDisposable)(()=>h.deleteVertexArray(T))),h.bindVertexArray(T);const l=new Float32Array([0,0,1,0,0,1,1,1]),d=h.createBuffer();this._register((0,a.toDisposable)(()=>h.deleteBuffer(d))),h.bindBuffer(h.ARRAY_BUFFER,d),h.bufferData(h.ARRAY_BUFFER,l,h.STATIC_DRAW),h.enableVertexAttribArray(0),h.vertexAttribPointer(0,2,this._gl.FLOAT,!1,0,0);const c=new Uint8Array([0,1,2,3]),_=h.createBuffer();this._register((0,a.toDisposable)(()=>h.deleteBuffer(_))),h.bindBuffer(h.ELEMENT_ARRAY_BUFFER,_),h.bufferData(h.ELEMENT_ARRAY_BUFFER,c,h.STATIC_DRAW),this._attributesBuffer=(0,n.throwIfFalsy)(h.createBuffer()),this._register((0,a.toDisposable)(()=>h.deleteBuffer(this._attributesBuffer))),h.bindBuffer(h.ARRAY_BUFFER,this._attributesBuffer),h.enableVertexAttribArray(2),h.vertexAttribPointer(2,2,h.FLOAT,!1,44,0),h.vertexAttribDivisor(2,1),h.enableVertexAttribArray(3),h.vertexAttribPointer(3,2,h.FLOAT,!1,44,2*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(3,1),h.enableVertexAttribArray(4),h.vertexAttribPointer(4,1,h.FLOAT,!1,44,4*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(4,1),h.enableVertexAttribArray(5),h.vertexAttribPointer(5,2,h.FLOAT,!1,44,5*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(5,1),h.enableVertexAttribArray(6),h.vertexAttribPointer(6,2,h.FLOAT,!1,44,7*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(6,1),h.enableVertexAttribArray(1),h.vertexAttribPointer(1,2,h.FLOAT,!1,44,9*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(1,1),h.useProgram(this._program);const Q=new Int32Array(s.TextureAtlas.maxAtlasPages);for(let t=0;th.deleteTexture(e.texture))),h.activeTexture(h.TEXTURE0+t),h.bindTexture(h.TEXTURE_2D,e.texture),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texImage2D(h.TEXTURE_2D,0,h.RGBA,1,1,0,h.RGBA,h.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[t]=e}h.enable(h.BLEND),h.blendFunc(h.SRC_ALPHA,h.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){if(!this._atlas)return!0;const _g=this._atlas._clearModelGeneration||0;return this._lastSeenClearModelGeneration!==_g&&(this._lastSeenClearModelGeneration=_g,!0)}updateCell(t,e,i,s,r,a,o,n,L){this._updateCell(this._vertices.attributes,t,e,i,s,r,a,o,n,L)}_updateCell(t,e,i,s,a,o,d,c,_,Q){h=11*(i*this._terminal.cols+e),s!==r.NULL_CELL_CODE&&void 0!==s?this._atlas&&(L=c&&c.length>1?this._atlas.getRasterizedGlyphCombinedChar(c,a,o,d,!1,this._terminal.element):this._atlas.getRasterizedGlyph(s,a,o,d,!1,this._terminal.element),T=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),a!==Q&&L.offset.x>T?(l=L.offset.x-T,t[h]=-(L.offset.x-l)+this._dimensions.device.char.left,t[h+1]=-L.offset.y+this._dimensions.device.char.top,t[h+2]=(L.size.x-l)/this._dimensions.device.canvas.width,t[h+3]=L.size.y/this._dimensions.device.canvas.height,t[h+4]=L.texturePage,t[h+5]=L.texturePositionClipSpace.x+l/this._atlas.pages[L.texturePage].canvas.width,t[h+6]=L.texturePositionClipSpace.y,t[h+7]=L.sizeClipSpace.x-l/this._atlas.pages[L.texturePage].canvas.width,t[h+8]=L.sizeClipSpace.y):(t[h]=-L.offset.x+this._dimensions.device.char.left,t[h+1]=-L.offset.y+this._dimensions.device.char.top,t[h+2]=L.size.x/this._dimensions.device.canvas.width,t[h+3]=L.size.y/this._dimensions.device.canvas.height,t[h+4]=L.texturePage,t[h+5]=L.texturePositionClipSpace.x,t[h+6]=L.texturePositionClipSpace.y,t[h+7]=L.sizeClipSpace.x,t[h+8]=L.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&(0,n.allowRescaling)(s,_,L.size.x,this._dimensions.device.cell.width)&&(t[h+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width)):t.fill(0,h,h+11-1-2)}clear(){const t=this._terminal,e=t.cols*t.rows*11;this._vertices.count!==e?this._vertices.attributes=new Float32Array(e):this._vertices.attributes.fill(0);let i=0;for(;iT.deleteProgram(this._program))),this._projectionLocation=(0,a.throwIfFalsy)(T.getUniformLocation(this._program,"u_projection"));const l=this._vertexArrayObject=T.createVertexArray();this._register((0,s.toDisposable)(()=>T.deleteVertexArray(l))),T.bindVertexArray(l);const d=new Float32Array([0,0,1,0,0,1,1,1]),c=T.createBuffer();this._register((0,s.toDisposable)(()=>T.deleteBuffer(c))),T.bindBuffer(T.ARRAY_BUFFER,c),T.bufferData(T.ARRAY_BUFFER,d,T.STATIC_DRAW),T.enableVertexAttribArray(3),T.vertexAttribPointer(3,2,this._gl.FLOAT,!1,0,0);const _=new Uint8Array([0,1,2,3]),Q=T.createBuffer();this._register((0,s.toDisposable)(()=>T.deleteBuffer(Q))),T.bindBuffer(T.ELEMENT_ARRAY_BUFFER,Q),T.bufferData(T.ELEMENT_ARRAY_BUFFER,_,T.STATIC_DRAW),this._attributesBuffer=(0,a.throwIfFalsy)(T.createBuffer()),this._register((0,s.toDisposable)(()=>T.deleteBuffer(this._attributesBuffer))),T.bindBuffer(T.ARRAY_BUFFER,this._attributesBuffer),T.enableVertexAttribArray(0),T.vertexAttribPointer(0,2,T.FLOAT,!1,o,0),T.vertexAttribDivisor(0,1),T.enableVertexAttribArray(1),T.vertexAttribPointer(1,2,T.FLOAT,!1,o,2*Float32Array.BYTES_PER_ELEMENT),T.vertexAttribDivisor(1,1),T.enableVertexAttribArray(2),T.vertexAttribPointer(2,4,T.FLOAT,!1,o,4*Float32Array.BYTES_PER_ELEMENT),T.vertexAttribDivisor(2,1),this._updateCachedColors(L.colors),this._register(this._themeService.onChangeColors(t=>{this._updateCachedColors(t),this._updateViewportRectangle()}))}renderBackgrounds(){this._renderVertices(this._vertices)}renderCursor(){this._renderVertices(this._verticesCursor)}_renderVertices(t){const e=this._gl;e.useProgram(this._program),e.bindVertexArray(this._vertexArrayObject),e.uniformMatrix4fv(this._projectionLocation,!1,r.PROJECTION_MATRIX),e.bindBuffer(e.ARRAY_BUFFER,this._attributesBuffer),e.bufferData(e.ARRAY_BUFFER,t.attributes,e.DYNAMIC_DRAW),e.drawElementsInstanced(this._gl.TRIANGLE_STRIP,4,e.UNSIGNED_BYTE,0,t.count)}handleResize(){this._updateViewportRectangle()}setDimensions(t){this._dimensions=t}_updateCachedColors(t){this._bgFloat=this._colorToFloat32Array(t.background),this._cursorFloat=this._colorToFloat32Array(t.cursor)}_updateViewportRectangle(){this._addRectangleFloat(this._vertices.attributes,0,0,0,this._terminal.cols*this._dimensions.device.cell.width,this._terminal.rows*this._dimensions.device.cell.height,this._bgFloat)}updateBackgrounds(t){const e=this._terminal,i=this._vertices;let s,r,a,o,n,L,h,T,l,d,c,_=1;for(s=0;s>24&255)/255,d=(L>>16&255)/255,c=(L>>8&255)/255,_=1,this._addRectangle(t.attributes,e,h,T,(o-a)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,l,d,c,_)}_addRectangle(t,e,i,s,r,a,o,n,L,h){t[e]=i/this._dimensions.device.canvas.width,t[e+1]=s/this._dimensions.device.canvas.height,t[e+2]=r/this._dimensions.device.canvas.width,t[e+3]=a/this._dimensions.device.canvas.height,t[e+4]=o,t[e+5]=n,t[e+6]=L,t[e+7]=h}_addRectangleFloat(t,e,i,s,r,a,o){t[e]=i/this._dimensions.device.canvas.width,t[e+1]=s/this._dimensions.device.canvas.height,t[e+2]=r/this._dimensions.device.canvas.width,t[e+3]=a/this._dimensions.device.canvas.height,t[e+4]=o[0],t[e+5]=o[1],t[e+6]=o[2],t[e+7]=o[3]}_colorToFloat32Array(t){return new Float32Array([(t.rgba>>24&255)/255,(t.rgba>>16&255)/255,(t.rgba>>8&255)/255,(255&t.rgba)/255])}}e.RectangleRenderer=Q},208(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.RenderModel=e.COMBINED_CHAR_BIT_MASK=void 0;const s=i(948);e.COMBINED_CHAR_BIT_MASK=2147483648,e.RenderModel=class{constructor(){this.cells=new Uint32Array(0),this.lineLengths=new Uint32Array(0),this.selection=(0,s.createSelectionRenderModel)()}resize(t,e){const i=t*e*4;i!==this.cells.length&&(this.cells=new Uint32Array(i),this.lineLengths=new Uint32Array(e))}clear(){this.cells.fill(0,0),this.lineLengths.fill(0,0)}}},115(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.TextureAtlas=void 0;const s=i(0),r=i(183),a=i(959),o=i(993),n=i(836),L=i(930),h=i(917),T=i(564),l=i(414),d={texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},offset:{x:0,y:0},size:{x:0,y:0},sizeClipSpace:{x:0,y:0}};let c;class _{get pages(){return this._pages}constructor(t,e,i,s){this._document=t,this._config=e,this._unicodeService=i,this._logService=s,this._didWarmUp=!1,this._cacheMap=new n.FourKeyMap,this._cacheMapCombined=new n.FourKeyMap,this._pages=[],this._activePages=[],this._workBoundingBox={top:0,left:0,bottom:0,right:0},this._workAttributeData=new h.AttributeData,this._textureSize=512,this._onAddTextureAtlasCanvas=new l.Emitter,this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=new l.Emitter,this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._requestClearModel=!1,this._clearModelGeneration=0,this._createNewPage(),this._tmpCanvas=p(t,4*this._config.deviceCellWidth+4,this._config.deviceCellHeight+4),this._tmpCtx=(0,a.throwIfFalsy)(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:!0}))}dispose(){this._tmpCanvas.remove();for(const t of this.pages)t.canvas.remove();this._onAddTextureAtlasCanvas.dispose(),this._onRemoveTextureAtlasCanvas.dispose()}warmUp(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)}_doWarmUp(){const t=new L.IdleTaskQueue(this._logService);for(let e=33;e<126;e++)t.enqueue(()=>{if(!this._cacheMap.get(e,T.DEFAULT_COLOR,T.DEFAULT_COLOR,T.DEFAULT_EXT)){const t=this._drawToCache(e,T.DEFAULT_COLOR,T.DEFAULT_COLOR,T.DEFAULT_EXT,!1,void 0);this._cacheMap.set(e,T.DEFAULT_COLOR,T.DEFAULT_COLOR,T.DEFAULT_EXT,t)}})}beginFrame(){const t=this._requestClearModel;return this._requestClearModel=!1,t}clearTexture(){if(0!==this._pages[0].currentRow.x||0!==this._pages[0].currentRow.y){for(const t of this._pages)t.clear();this._cacheMap.clear(),this._cacheMapCombined.clear(),this._didWarmUp=!1,this._requestClearModel=!0,this._clearModelGeneration++}}_createNewPage(){if(_.maxAtlasPages&&this._pages.length>=Math.max(4,_.maxAtlasPages)){const t=this._pages.filter(t=>2*t.canvas.width<=(_.maxTextureSize||4096)).sort((t,e)=>e.canvas.width!==t.canvas.width?e.canvas.width-t.canvas.width:e.percentageUsed-t.percentageUsed);let e=-1,i=0;for(let s=0;st.canvas.width!==s[0].canvas.width)){const t=new Q(this._document,this._textureSize);return this._pages.push(t),this._activePages.push(t),this._onAddTextureAtlasCanvas.fire(t.canvas),t}const r=s.map(t=>t.glyphs[0].texturePage).sort((t,e)=>t-e),a=this.pages.length-s.length,o=this._mergePages(s,a);o.version=++Q.nextVersion;for(let t=r.length-1;t>=0;t--)this._deletePage(r[t]);this.pages.push(o),this._requestClearModel=!0,this._clearModelGeneration++,this._onAddTextureAtlasCanvas.fire(o.canvas)}const t=new Q(this._document,this._textureSize);return this._pages.push(t),this._activePages.push(t),this._onAddTextureAtlasCanvas.fire(t.canvas),t}_mergePages(t,e){const i=2*t[0].canvas.width,s=new Q(this._document,i,t);for(const[r,a]of t.entries()){const t=r*a.canvas.width%i,o=Math.floor(r/2)*a.canvas.height;s.ctx.drawImage(a.canvas,t,o);for(const s of a.glyphs)s.texturePage=e,s.sizeClipSpace.x=s.size.x/i,s.sizeClipSpace.y=s.size.y/i,s.texturePosition.x+=t,s.texturePosition.y+=o,s.texturePositionClipSpace.x=s.texturePosition.x/i,s.texturePositionClipSpace.y=s.texturePosition.y/i;this._onRemoveTextureAtlasCanvas.fire(a.canvas);const n=this._activePages.indexOf(a);-1!==n&&this._activePages.splice(n,1)}return s}_deletePage(t){this._pages.splice(t,1);for(let e=t;e=this._config.colors.ansi.length)throw new Error("No color found for idx "+t);return this._config.colors.ansi[t]}_getBackgroundColor(t,e,i,s){if(this._config.allowTransparency)return o.NULL_COLOR;let r;switch(t){case 16777216:case 33554432:r=this._getColorFromAnsiIndex(e);break;case 50331648:const t=h.AttributeData.toColorRGB(e);r=o.channels.toColor(t[0],t[1],t[2]);break;default:r=i?o.color.opaque(this._config.colors.foreground):this._config.colors.background}return this._config.allowTransparency||(r=o.color.opaque(r)),r}_getForegroundColor(t,e,i,r,a,n,L,T,l,d){const c=this._getMinimumContrastColor(t,e,i,r,a,n,L,l,T,d);if(c)return c;let _;switch(a){case 16777216:case 33554432:this._config.drawBoldTextInBrightColors&&l&&n<8&&(n+=8),_=this._getColorFromAnsiIndex(n);break;case 50331648:const t=h.AttributeData.toColorRGB(n);_=o.channels.toColor(t[0],t[1],t[2]);break;default:_=L?this._config.colors.background:this._config.colors.foreground}return this._config.allowTransparency&&(_=o.color.opaque(_)),T&&(_=o.color.multiplyOpacity(_,s.DIM_OPACITY)),_}_resolveBackgroundRgba(t,e,i){switch(t){case 16777216:case 33554432:return this._getColorFromAnsiIndex(e).rgba;case 50331648:return e<<8;default:return i?this._config.colors.foreground.rgba:this._config.colors.background.rgba}}_resolveForegroundRgba(t,e,i,s){switch(t){case 16777216:case 33554432:return this._config.drawBoldTextInBrightColors&&s&&e<8&&(e+=8),this._getColorFromAnsiIndex(e).rgba;case 50331648:return e<<8;default:return i?this._config.colors.background.rgba:this._config.colors.foreground.rgba}}_getMinimumContrastColor(t,e,i,s,r,a,n,L,h,T){if(1===this._config.minimumContrastRatio||T)return;const l=this._getContrastCache(h),d=l.getColor(t,s);if(void 0!==d)return d??void 0;const c=this._resolveBackgroundRgba(e,i,n),_=this._resolveForegroundRgba(r,a,n,L),Q=o.rgba.ensureContrastRatio(c,_,this._config.minimumContrastRatio/(h?2:1));if(!Q)return void l.setColor(t,s,null);const u=o.channels.toColor(Q>>24&255,Q>>16&255,Q>>8&255);return l.setColor(t,s,u),u}_getContrastCache(t){return t?this._config.colors.halfContrastCache:this._config.colors.contrastCache}_drawToCache(t,e,i,o,n,L){const T="number"==typeof t?String.fromCharCode(t):t;L&&this._tmpCanvas.parentElement!==L&&(this._tmpCanvas.style.display="none",L.append(this._tmpCanvas));const l=Math.min(this._config.deviceCellWidth*Math.max(T.length,2)+4,this._config.deviceMaxTextureSize);this._tmpCanvas.width=t?2*t-o:t-o;!1==!(o>=t)||0===_?(this._tmpCtx.setLineDash([Math.round(t),Math.round(t)]),this._tmpCtx.moveTo(h+_,s),this._tmpCtx.lineTo(T,s)):(this._tmpCtx.setLineDash([Math.round(t),Math.round(t)]),this._tmpCtx.moveTo(h,s),this._tmpCtx.lineTo(h+_,s),this._tmpCtx.moveTo(h+_+t,s),this._tmpCtx.lineTo(T,s)),o=(0,a.computeNextVariantOffset)(T-h,t,o);break;case 5:const Q=.6,u=.3,p=T-h,g=Math.floor(Q*p),M=Math.floor(u*p),y=p-g-M;this._tmpCtx.setLineDash([g,M,y]),this._tmpCtx.moveTo(h,s),this._tmpCtx.lineTo(T,s);break;default:this._tmpCtx.moveTo(h,s),this._tmpCtx.lineTo(T,s)}n||this._tmpCtx.stroke(),this._tmpCtx.restore()}if(this._tmpCtx.restore(),!O&&this._config.fontSize>=12&&!this._config.allowTransparency&&" "!==T){this._tmpCtx.save(),this._tmpCtx.textBaseline="alphabetic";const e=this._tmpCtx.measureText(T);if(this._tmpCtx.restore(),"actualBoundingBoxDescent"in e&&e.actualBoundingBoxDescent>0){this._tmpCtx.save();const e=new Path2D;e.rect(i,L-Math.ceil(t/2),this._config.deviceCellWidth*I,l-L+Math.ceil(t/2)),this._tmpCtx.clip(e),this._tmpCtx.lineWidth=3*this._config.devicePixelRatio,this._tmpCtx.strokeStyle=E.css,this._tmpCtx.strokeText(T,S,S+this._config.deviceCharHeight),this._tmpCtx.restore()}}}if(C){const t=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/15)),e=t%2==1?.5:0;this._tmpCtx.lineWidth=t,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(S,S+e),this._tmpCtx.lineTo(S+this._config.deviceCharWidth*I,S+e),this._tmpCtx.stroke()}if(O||this._tmpCtx.fillText(T,S,S+this._config.deviceCharHeight),"_"===T&&!this._config.allowTransparency){let t=u(this._tmpCtx.getImageData(S,S,this._config.deviceCellWidth,this._config.deviceCellHeight),E,D,W);if(t)for(let e=1;e<=5&&(this._tmpCtx.save(),this._tmpCtx.fillStyle=E.css,this._tmpCtx.fillRect(0,0,this._tmpCanvas.width,this._tmpCanvas.height),this._tmpCtx.restore(),this._tmpCtx.fillText(T,S,S+this._config.deviceCharHeight-e),t=u(this._tmpCtx.getImageData(S,S,this._config.deviceCellWidth,this._config.deviceCellHeight),E,D,W),t);e++);}if(f){const t=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/10)),e=this._tmpCtx.lineWidth%2==1?.5:0;this._tmpCtx.lineWidth=t,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(S,S+Math.floor(this._config.deviceCharHeight/2)-e),this._tmpCtx.lineTo(S+this._config.deviceCharWidth*I,S+Math.floor(this._config.deviceCharHeight/2)-e),this._tmpCtx.stroke()}this._tmpCtx.restore();const N=this._tmpCtx.getImageData(0,0,this._tmpCanvas.width,this._tmpCanvas.height);let P;if(P=this._config.allowTransparency?function(t){for(let e=0;e0)return!1;return!0}(N):u(N,E,D,W),P)return d;const B=this._findGlyphBoundingBox(N,this._workBoundingBox,l,Z,O,S);let $,F;for(;;){if(0===this._activePages.length){const t=this._createNewPage();$=t,F=t.currentRow,F.height=B.size.y;break}$=this._activePages[this._activePages.length-1],F=$.currentRow;for(const t of this._activePages)B.size.y<=t.currentRow.height&&($=t,F=t.currentRow);for(let t=this._activePages.length-1;t>=0;t--)for(const e of this._activePages[t].fixedRows)e.height<=F.height&&B.size.y<=e.height&&($=this._activePages[t],F=e);if(B.size.x>this._textureSize){this._overflowSizePage||(this._overflowSizePage=new Q(this._document,this._config.deviceMaxTextureSize),this.pages.push(this._overflowSizePage),this._requestClearModel=!0,this._clearModelGeneration++,this._onAddTextureAtlasCanvas.fire(this._overflowSizePage.canvas)),$=this._overflowSizePage,F=this._overflowSizePage.currentRow,F.x+B.size.x>=$.canvas.width&&(F.x=0,F.y+=F.height,F.height=0);break}if(F.y+B.size.y>=$.canvas.height||F.height>B.size.y+2){let t=!1;if($.currentRow.y+$.currentRow.height+B.size.y>=$.canvas.height){let e;for(const t of this._activePages)if(t.currentRow.y+t.currentRow.height+B.size.y=_.maxAtlasPages&&F.y+B.size.y<=$.canvas.height&&F.height>=B.size.y&&F.x+B.size.x<=$.canvas.width)t=!0;else{const e=this._createNewPage();$=e,F=e.currentRow,F.height=B.size.y,t=!0}}t||($.currentRow.height>0&&$.fixedRows.push($.currentRow),F={x:0,y:$.currentRow.y+$.currentRow.height,height:B.size.y},$.fixedRows.push(F),$.currentRow={x:0,y:F.y+F.height,height:0})}if(F.x+B.size.x<=$.canvas.width)break;F===$.currentRow?(F.x=0,F.y+=F.height,F.height=0):$.fixedRows.splice($.fixedRows.indexOf(F),1)}return B.texturePage=this._pages.indexOf($),B.texturePosition.x=F.x,B.texturePosition.y=F.y,B.texturePositionClipSpace.x=F.x/$.canvas.width,B.texturePositionClipSpace.y=F.y/$.canvas.height,B.sizeClipSpace.x/=$.canvas.width,B.sizeClipSpace.y/=$.canvas.height,F.height=Math.max(F.height,B.size.y),F.x+=B.size.x,$.ctx.putImageData(N,B.texturePosition.x-this._workBoundingBox.left,B.texturePosition.y-this._workBoundingBox.top,this._workBoundingBox.left,this._workBoundingBox.top,B.size.x,B.size.y),$.addGlyph(B),$.version=++Q.nextVersion,B}_findGlyphBoundingBox(t,e,i,s,r,a){e.top=0;const o=s?this._config.deviceCellHeight:this._tmpCanvas.height,n=s?this._config.deviceCellWidth:i;let L=!1;for(let i=0;i=a;i--){for(let s=0;s=0;i--){for(let s=0;s>>24,a=e.rgba>>>16&255,o=e.rgba>>>8&255,n=i.rgba>>>24,L=i.rgba>>>16&255,h=i.rgba>>>8&255,T=Math.floor((Math.abs(r-n)+Math.abs(a-L)+Math.abs(o-h))/12);let l=!0;for(let e=0;ethis._handleColorChange())),this._cellColorResolver=new s.CellColorResolver(this._terminal,this._optionsService,this._model.selection,this._decorationService,this._coreBrowserService,this._themeService),this._core=this._terminal._core,this._renderLayers=[new _.LinkRenderLayer(this._core.screenElement,2,this._terminal,this._core.linkifier,this._coreBrowserService,d,this._themeService)],this.dimensions=(0,g.createRenderDimensions)(),this._devicePixelRatio=this._coreBrowserService.dpr,this._updateDimensions(),this._updateCursorBlink(),this._register(d.onOptionChange(()=>this._handleOptionsChanged())),this._textBlinkStateManager=this._register(new T.TextBlinkStateManager(()=>this._requestRedrawViewport(),this._coreBrowserService,this._optionsService)),this._resetBlinkingRowState(),this._deviceMaxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._register((0,u.addDisposableListener)(this._canvas,"webglcontextlost",t=>{this._logService.debug("webglcontextlost event received"),t.preventDefault(),this._contextRestorationTimeout=setTimeout(()=>{this._contextRestorationTimeout=void 0,this._logService.warn("webgl context not restored; firing onContextLoss"),this._onContextLoss.fire(t)},3e3)})),this._register((0,u.addDisposableListener)(this._canvas,"webglcontextrestored",t=>{this._logService.warn("webglcontextrestored event received"),clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0,(0,r.removeTerminalFromCache)(this._terminal),this._initializeWebGLState(),this._requestRedrawViewport()})),this._observerDisposable.value=(0,o.observeDevicePixelDimensions)(this._canvas,this._coreBrowserService.window,(t,e)=>this._setCanvasDevicePixelDimensions(t,e)),this._register(this._coreBrowserService.onWindowChange(t=>{this._observerDisposable.value=(0,o.observeDevicePixelDimensions)(this._canvas,t,(t,e)=>this._setCanvasDevicePixelDimensions(t,e))})),this._register((0,u.addDisposableListener)(this._coreBrowserService.mainDocument,"mousedown",()=>this._cursorBlinkStateManager.value?.restartBlinkAnimation())),this._core.screenElement.appendChild(this._canvas),[this._rectangleRenderer.value,this._glyphRenderer.value]=this._initializeWebGLState(),this._isAttached=this._core.screenElement.isConnected,this._register((0,p.toDisposable)(()=>{clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0;for(const t of this._renderLayers)t.dispose();this._canvas.parentElement?.removeChild(this._canvas),(0,r.removeTerminalFromCache)(this._terminal)}))}get textureAtlas(){return this._charAtlas?.pages[0].canvas}_handleColorChange(){this._refreshCharAtlas(),this._clearModel(!0)}handleDevicePixelRatioChange(){this._devicePixelRatio!==this._coreBrowserService.dpr&&(this._devicePixelRatio=this._coreBrowserService.dpr,this.handleResize(this._terminal.cols,this._terminal.rows))}handleResize(t,e){this._updateDimensions(),this._model.resize(this._terminal.cols,this._terminal.rows),this._resetBlinkingRowState();for(const t of this._renderLayers)t.resize(this._terminal,this.dimensions);this._canvas.width=this.dimensions.device.canvas.width,this._canvas.height=this.dimensions.device.canvas.height,this._canvas.style.width=`${this.dimensions.css.canvas.width}px`,this._canvas.style.height=`${this.dimensions.css.canvas.height}px`,this._core.screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._core.screenElement.style.height=`${this.dimensions.css.canvas.height}px`,this._rectangleRenderer.value?.setDimensions(this.dimensions),this._rectangleRenderer.value?.handleResize(),this._glyphRenderer.value?.setDimensions(this.dimensions),this._glyphRenderer.value?.handleResize(),this._refreshCharAtlas(),this._clearModel(!1),this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1,sync:!0})}handleCharSizeChanged(){this.handleResize(this._terminal.cols,this._terminal.rows)}handleBlur(){for(const t of this._renderLayers)t.handleBlur(this._terminal);this._cursorBlinkStateManager.value?.pause(),this._requestRedrawViewport()}handleFocus(){for(const t of this._renderLayers)t.handleFocus(this._terminal);this._cursorBlinkStateManager.value?.resume(),this._requestRedrawViewport()}handleViewportVisibilityChange(t){this._textBlinkStateManager.setViewportVisible(t)}handleSelectionChanged(t,e,i){for(const s of this._renderLayers)s.handleSelectionChanged(this._terminal,t,e,i);this._model.selection.update(this._core,t,e,i),this._requestRedrawViewport()}handleCursorMove(){for(const t of this._renderLayers)t.handleCursorMove(this._terminal);this._cursorBlinkStateManager.value?.restartBlinkAnimation()}_handleOptionsChanged(){this._updateDimensions(),this._refreshCharAtlas(),this._updateCursorBlink()}_initializeWebGLState(){return this._rectangleRenderer.value=new d.RectangleRenderer(this._terminal,this._gl,this.dimensions,this._themeService,this._logService),this._glyphRenderer.value=new l.GlyphRenderer(this._terminal,this._gl,this.dimensions,this._optionsService,this._logService),this.handleCharSizeChanged(),[this._rectangleRenderer.value,this._glyphRenderer.value]}_refreshCharAtlas(){if(this.dimensions.device.char.width<=0&&this.dimensions.device.char.height<=0)return void(this._isAttached=!1);const t=(0,r.acquireTextureAtlas)(this._terminal,this._optionsService.rawOptions,this._themeService.colors,this.dimensions.device.cell.width,this.dimensions.device.cell.height,this.dimensions.device.char.width,this.dimensions.device.char.height,this._coreBrowserService.dpr,this._deviceMaxTextureSize,this._customGlyphs);this._charAtlas!==t&&(this._onChangeTextureAtlas.fire(t.pages[0].canvas),this._charAtlasDisposable.value=(0,p.combinedDisposable)(Q.EventUtils.forward(t.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas),Q.EventUtils.forward(t.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas))),this._charAtlas=t,this._charAtlas.warmUp(),this._glyphRenderer.value?.setAtlas(this._charAtlas)}_clearModel(t){this._model.clear(),t&&this._glyphRenderer.value?.clear()}clearTextureAtlas(){this._charAtlas?.clearTexture(),this._clearModel(!0),this._requestRedrawViewport()}clear(){this._clearModel(!0);for(const t of this._renderLayers)t.reset(this._terminal);this._resetBlinkingRowState(),this._textBlinkStateManager.setNeedsBlinkInViewport(!1),this._cursorBlinkStateManager.value?.restartBlinkAnimation(),this._updateCursorBlink()}renderRows(t,e){if(!this._isAttached){if(!(this._core.screenElement?.isConnected&&this._charSizeService.width&&this._charSizeService.height))return;this._updateDimensions(),this._refreshCharAtlas(),this._isAttached=!0}for(const i of this._renderLayers)i.handleGridChanged(this._terminal,t,e);if(!this._glyphRenderer.value||!this._rectangleRenderer.value)return;this._glyphRenderer.value.beginFrame()?(this._clearModel(!0),this._updateModel(0,this._terminal.rows-1)):this._updateModel(t,e);let i=!1,s=0;for(;this._charAtlas&&this._glyphRenderer.value.beginFrame()&&s++<32;)i=!0,this._clearModel(!0),this._updateModel(0,this._terminal.rows-1);i&&this._glyphRenderer.value.invalidateAtlasTextures(),this._rectangleRenderer.value.renderBackgrounds(),this._glyphRenderer.value.render(this._model),this._cursorBlinkStateManager.value&&!this._cursorBlinkStateManager.value.isCursorVisible||this._rectangleRenderer.value.renderCursor()}_updateCursorBlink(){this._coreService.decPrivateModes.cursorBlink??this._terminal.options.cursorBlink?this._cursorBlinkStateManager.value=new a.CursorBlinkStateManager(()=>{this._requestRedrawCursor()},this._coreBrowserService):this._cursorBlinkStateManager.clear(),this._requestRedrawCursor()}_updateModel(t,e){const i=this._core;let s,r,a,o,n,L,T,l,d,_,Q,u,p,g,M,f,C,m=this._workCell;t=v(t,i.rows-1,0),e=v(e,i.rows-1,0);const w=this._coreService.decPrivateModes.cursorStyle??i.options.cursorStyle??"block",x=this._terminal.buffer.active.baseY+this._terminal.buffer.active.cursorY,b=x-i.buffer.ydisp,E=Math.min(this._terminal.buffer.active.cursorX,i.cols-1);let R=-1;const k=this._coreService.isCursorInitialized&&!this._coreService.isCursorHidden&&(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible);this._model.cursor=void 0;let A=!1;for(r=t;r<=e;r++){a=r+i.buffer.ydisp;const t=i.buffer.lines.get(a);if(!t){for(this._model.lineLengths[r]=0,f=0;f=T,d=f,n.length>0&&f===n[0][0]&&l){_=n.shift();const t=this._model.selection.isCellSelected(this._terminal,_[0],a);for(M=_[0]+1;M<_[1];M++)l&&=t===this._model.selection.isCellSelected(this._terminal,M,a);l&&=!Q||E<_[0]||E>=_[1],l?(L=!0,m=new y(m,o.translateToString(!0,_[0],_[1]),_[1]-_[0]),d=_[1]-1):T=_[1]}if(u=m.getChars(),p=m.getCode(),M=4*(r*i.cols+f),!e&&m.isBlink()&&(e=!0),this._cellColorResolver.resolve(m,f,a,this.dimensions.device.cell.width,this.dimensions.device.cell.height),k&&a===x&&(f===E&&(this._model.cursor={x:E,y:b,width:m.getWidth(),style:this._coreBrowserService.isFocused?w:i.options.cursorInactiveStyle,cursorWidth:i.options.cursorWidth,dpr:this._devicePixelRatio},R=E+m.getWidth()-1),f>=E&&f<=R&&(this._coreBrowserService.isFocused&&"block"===w||!1===this._coreBrowserService.isFocused&&"block"===i.options.cursorInactiveStyle)&&(this._cellColorResolver.result.fg=50331648|this._themeService.colors.cursorAccent.rgba>>8&16777215,this._cellColorResolver.result.bg=50331648|this._themeService.colors.cursor.rgba>>8&16777215)),this._textBlinkStateManager.isEnabled&&!this._textBlinkStateManager.isBlinkOn&&m.isBlink()&&(this._cellColorResolver.result.fg|=1073741824),p!==h.NULL_CELL_CODE&&(this._model.lineLengths[r]=f+1),(this._model.cells[M]!==p||this._model.cells[M+1]!==this._cellColorResolver.result.bg||this._model.cells[M+2]!==this._cellColorResolver.result.fg||this._model.cells[M+3]!==this._cellColorResolver.result.ext)&&(A=!0,u.length>1&&(p|=c.COMBINED_CHAR_BIT_MASK),this._model.cells[M]=p,this._model.cells[M+1]=this._cellColorResolver.result.bg,this._model.cells[M+2]=this._cellColorResolver.result.fg,this._model.cells[M+3]=this._cellColorResolver.result.ext,g=m.getWidth(),this._glyphRenderer.value.updateCell(f,r,p,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext,u,g,s),L)){for(m=this._workCell,f++;f<=d;f++)C=4*(r*i.cols+f),this._nullModelCell(f,r,C,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext);f--}}this._setRowBlinkState(r,e)}A&&this._rectangleRenderer.value.updateBackgrounds(this._model),this._rectangleRenderer.value.updateCursor(this._model),this._updateTextBlinkState()}_nullModelCell(t,e,i,s,r,a){this._glyphRenderer.value.updateCell(t,e,h.NULL_CELL_CODE,s,r,a,h.NULL_CELL_CHAR,0,0),this._model.cells[i]=h.NULL_CELL_CODE,this._model.cells[i+1]=s,this._model.cells[i+2]=r,this._model.cells[i+3]=a}_resetBlinkingRowState(){this._rowHasBlinkingCells=new Array(this._terminal.rows).fill(!1),this._rowHasBlinkingCellsCount=0}_setRowBlinkState(t,e){this._rowHasBlinkingCells[t]!==e&&(this._rowHasBlinkingCells[t]=e,this._rowHasBlinkingCellsCount+=e?1:-1)}_updateTextBlinkState(){this._textBlinkStateManager.setNeedsBlinkInViewport(this._rowHasBlinkingCellsCount>0)}_updateDimensions(){this._charSizeService.width&&this._charSizeService.height&&(this.dimensions.device.char.width=Math.floor(this._charSizeService.width*this._devicePixelRatio),this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*this._devicePixelRatio),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.top=1===this._optionsService.rawOptions.lineHeight?0:Math.round((this.dimensions.device.cell.height-this.dimensions.device.char.height)/2),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.char.left=Math.floor(this._optionsService.rawOptions.letterSpacing/2),this.dimensions.device.canvas.height=this._terminal.rows*this.dimensions.device.cell.height,this.dimensions.device.canvas.width=this._terminal.cols*this.dimensions.device.cell.width,this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/this._devicePixelRatio),this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/this._devicePixelRatio),this.dimensions.css.cell.height=this.dimensions.device.cell.height/this._devicePixelRatio,this.dimensions.css.cell.width=this.dimensions.device.cell.width/this._devicePixelRatio)}_setCanvasDevicePixelDimensions(t,e){this._canvas.width===t&&this._canvas.height===e||(this._canvas.width=t,this._canvas.height=e,this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1,sync:!0}))}_requestRedrawViewport(){this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1})}_requestRedrawCursor(){const t=this._terminal.buffer.active.cursorY;this._onRequestRedraw.fire({start:t,end:t})}}e.WebglRenderer=M;class y extends n.AttributeData{constructor(t,e,i){super(),this.content=0,this.combinedData="",this.fg=t.fg,this.bg=t.bg,this.combinedData=e,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(t){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}function v(t,e,i=0){return Math.max(Math.min(t,e),i)}e.JoinedCellData=y},719(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.GLTexture=e.PROJECTION_MATRIX=void 0,e.createProgram=function(t,e,i,a){const o=(0,s.throwIfFalsy)(t.createProgram());if(t.attachShader(o,(0,s.throwIfFalsy)(r(t,t.VERTEX_SHADER,e,a))),t.attachShader(o,(0,s.throwIfFalsy)(r(t,t.FRAGMENT_SHADER,i,a))),t.linkProgram(o),t.getProgramParameter(o,t.LINK_STATUS))return o;a.error(t.getProgramInfoLog(o)),t.deleteProgram(o)},e.createShader=r,e.expandFloat32Array=function(t,e){const i=Math.min(2*t.length,e),s=new Float32Array(i);for(let e=0;e{const e=[],i=[3/8,2/8,3/8],s=[0,3/8,5/8];for(let r=0;r<3;r++){const a=t>>2*r&1,o=t>>2*r+1&1;a&&o?e.push(`M0,${s[r]} L1,${s[r]} L1,${s[r]+i[r]} L0,${s[r]+i[r]} Z`):a?e.push(`M0,${s[r]} L0.5,${s[r]} L0.5,${s[r]+i[r]} L0,${s[r]+i[r]} Z`):o&&e.push(`M0.5,${s[r]} L1,${s[r]} L1,${s[r]+i[r]} L0.5,${s[r]+i[r]} Z`)}return e.join(" ")}}}function r(t){const e=[],i=.15,s=.015,r=.075,a=.0375,o=.95;if(64&t){const t=.175,a=.2125,n=.25,L=.2+s,h=o-i-s;e.push(`M${L},${a} L${L+r},${t} L${h-r},${t} L${h},${a} L${h-r},${n} L${L+r},${n} Z`)}if(32&t){const t=o-i,s=.875,r=o,n=.265,L=.485;e.push(`M${s},${n} L${r},${n+a} L${r},${L-a} L${s},${L} L${t},${L-a} L${t},${n+a} Z`)}if(16&t){const t=o-i,s=.875,r=o,n=.515,L=.735;e.push(`M${s},${n} L${r},${n+a} L${r},${L-a} L${s},${L} L${t},${L-a} L${t},${n+a} Z`)}if(8&t){const t=.75,a=.7875,n=.825,L=.2+s,h=o-i-s;e.push(`M${L},${a} L${L+r},${t} L${h-r},${t} L${h},${a} L${h-r},${n} L${L+r},${n} Z`)}if(4&t){const t=.05,i=.125,s=.2,r=.515,o=.735;e.push(`M${i},${r} L${s},${r+a} L${s},${o-a} L${i},${o} L${t},${o-a} L${t},${r+a} Z`)}if(2&t){const t=.05,i=.125,s=.2,r=.265,o=.485;e.push(`M${i},${r} L${s},${r+a} L${s},${o-a} L${i},${o} L${t},${o-a} L${t},${r+a} Z`)}if(1&t){const t=.4625,a=.5,n=.5375,L=.2+s,h=o-i-s;e.push(`M${L},${a} L${L+r},${t} L${h-r},${t} L${h},${a} L${h-r},${n} L${L+r},${n} Z`)}return e.join(" ")}Object.defineProperty(e,"__esModule",{value:!0}),e.blockPatternCodepoints=e.customGlyphDefinitions=void 0,function(t){t.LINE_H=Object.freeze({type:2,data:"M0,.5 L1,.5",strokeWidth:1}),t.LINE_V=Object.freeze({type:2,data:"M.5,0 L.5,1",strokeWidth:1}),t.FADE_RIGHT=Object.freeze({type:2,data:"M0,.5 L.28,.5 M.32,.5 L.52,.5 M.60,.5 L.72,.5 M.84,.5 L.90,.5",strokeWidth:1}),t.FADE_LEFT=Object.freeze({type:2,data:"M.10,.5 L.16,.5 M.28,.5 L.40,.5 M.48,.5 L.68,.5 M.72,.5 L1,.5",strokeWidth:1}),t.FADE_DOWN=Object.freeze({type:2,data:"M.5,0 L.5,.28 M.5,.32 L.5,.52 M.5,.60 L.5,.72 M.5,.84 L.5,.90",strokeWidth:1}),t.FADE_UP=Object.freeze({type:2,data:"M.5,.10 L.5,.16 M.5,.28 L.5,.40 M.5,.48 L.5,.68 M.5,.72 L.5,1",strokeWidth:1}),t.CURVE_DOWN_RIGHT=Object.freeze({type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,1,.5`,strokeWidth:1}),t.CURVE_DOWN_LEFT=Object.freeze({type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,0,.5`,strokeWidth:1}),t.CURVE_UP_RIGHT=Object.freeze({type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,1,.5`,strokeWidth:1}),t.CURVE_UP_LEFT=Object.freeze({type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,0,.5`,strokeWidth:1}),t.NODE_FILL=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5"}),t.NODE_STROKE=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5",strokeWidth:1}),t.NODE_LINE_RIGHT=Object.freeze({type:3,data:"M1,.5 L.85,.5",strokeWidth:1}),t.NODE_LINE_LEFT=Object.freeze({type:3,data:"M0,.5 L.15,.5",strokeWidth:1}),t.NODE_LINE_DOWN=Object.freeze({type:3,data:"M.5,1 L.5,.7",strokeWidth:1}),t.NODE_LINE_UP=Object.freeze({type:3,data:"M.5,0 L.5,.3",strokeWidth:1})}(i||(i={})),e.customGlyphDefinitions={"─":{type:2,data:"M0,.5 L1,.5",strokeWidth:1},"━":{type:2,data:"M0,.5 L1,.5",strokeWidth:3},"│":{type:2,data:"M.5,0 L.5,1",strokeWidth:1},"┃":{type:2,data:"M.5,0 L.5,1",strokeWidth:3},"┄":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:1},"┅":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:3},"┆":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:1},"┇":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:3},"┈":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:1},"┉":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:3},"┊":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:1},"┋":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:3},"┌":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},"┍":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┎":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┏":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3},"┐":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},"┑":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┒":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┓":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3},"└":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},"┕":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┖":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┗":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3},"┘":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},"┙":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┚":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┛":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3},"├":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},"┝":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┞":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┟":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┠":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"┡":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"┢":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"┣":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3},"┤":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},"┥":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┦":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┧":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┨":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"┩":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"┪":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"┫":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3},"┬":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},"┭":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┮":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┯":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"┰":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┱":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"┲":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"┳":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3},"┴":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:1},"┵":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┶":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┷":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"┸":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┹":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"┺":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"┻":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:3},"┼":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:1},"┽":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┾":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┿":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"╀":[{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"╁":[{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"╂":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"╃":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"╄":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"╅":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"╆":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"╇":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:3}],"╈":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3}],"╉":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3}],"╊":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3}],"╋":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:3},"╌":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:1},"╍":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:3},"╎":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:1},"╏":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:3},"═":{type:2,data:(t,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"║":{type:2,data:(t,e)=>`M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1`,strokeWidth:1},"╒":{type:2,data:(t,e)=>`M.5,1 L.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"╓":{type:2,data:(t,e)=>`M${.5-t},1 L${.5-t},.5 L1,.5 M${.5+t},.5 L${.5+t},1`,strokeWidth:1},"╔":{type:2,data:(t,e)=>`M1,${.5-e} L${.5-t},${.5-e} L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1`,strokeWidth:1},"╕":{type:2,data:(t,e)=>`M0,${.5-e} L.5,${.5-e} L.5,1 M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"╖":{type:2,data:(t,e)=>`M${.5+t},1 L${.5+t},.5 L0,.5 M${.5-t},.5 L${.5-t},1`,strokeWidth:1},"╗":{type:2,data:(t,e)=>`M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M0,${.5-e} L${.5+t},${.5-e} L${.5+t},1`,strokeWidth:1},"╘":{type:2,data:(t,e)=>`M.5,0 L.5,${.5+e} L1,${.5+e} M.5,${.5-e} L1,${.5-e}`,strokeWidth:1},"╙":{type:2,data:(t,e)=>`M1,.5 L${.5-t},.5 L${.5-t},0 M${.5+t},.5 L${.5+t},0`,strokeWidth:1},"╚":{type:2,data:(t,e)=>`M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0 M1,${.5+e} L${.5-t},${.5+e} L${.5-t},0`,strokeWidth:1},"╛":{type:2,data:(t,e)=>`M0,${.5+e} L.5,${.5+e} L.5,0 M0,${.5-e} L.5,${.5-e}`,strokeWidth:1},"╜":{type:2,data:(t,e)=>`M0,.5 L${.5+t},.5 L${.5+t},0 M${.5-t},.5 L${.5-t},0`,strokeWidth:1},"╝":{type:2,data:(t,e)=>`M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0 M0,${.5+e} L${.5+t},${.5+e} L${.5+t},0`,strokeWidth:1},"╞":{type:2,data:(t,e)=>`M.5,0 L.5,1 M.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"╟":{type:2,data:(t,e)=>`M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1 M${.5+t},.5 L1,.5`,strokeWidth:1},"╠":{type:2,data:(t,e)=>`M${.5-t},0 L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1 M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0`,strokeWidth:1},"╡":{type:2,data:(t,e)=>`M.5,0 L.5,1 M0,${.5-e} L.5,${.5-e} M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"╢":{type:2,data:(t,e)=>`M0,.5 L${.5-t},.5 M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1`,strokeWidth:1},"╣":{type:2,data:(t,e)=>`M${.5+t},0 L${.5+t},1 M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0`,strokeWidth:1},"╤":{type:2,data:(t,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e} M.5,${.5+e} L.5,1`,strokeWidth:1},"╥":{type:2,data:(t,e)=>`M0,.5 L1,.5 M${.5-t},.5 L${.5-t},1 M${.5+t},.5 L${.5+t},1`,strokeWidth:1},"╦":{type:2,data:(t,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1`,strokeWidth:1},"╧":{type:2,data:(t,e)=>`M.5,0 L.5,${.5-e} M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"╨":{type:2,data:(t,e)=>`M0,.5 L1,.5 M${.5-t},.5 L${.5-t},0 M${.5+t},.5 L${.5+t},0`,strokeWidth:1},"╩":{type:2,data:(t,e)=>`M0,${.5+e} L1,${.5+e} M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0 M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0`,strokeWidth:1},"╪":{type:2,data:(t,e)=>`M.5,0 L.5,1 M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"╫":{type:2,data:(t,e)=>`M0,.5 L1,.5 M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1`,strokeWidth:1},"╬":{type:2,data:(t,e)=>`M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1 M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0 M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0`,strokeWidth:1},"╭":{type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"╮":{type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"╯":{type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"╰":{type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"╱":{type:2,data:"M1,0 L0,1",strokeWidth:1},"╲":{type:2,data:"M0,0 L1,1",strokeWidth:1},"╳":{type:2,data:"M1,0 L0,1 M0,0 L1,1",strokeWidth:1},"╴":{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},"╵":{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},"╶":{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},"╷":{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},"╸":{type:2,data:"M.5,.5 L0,.5",strokeWidth:3},"╹":{type:2,data:"M.5,.5 L.5,0",strokeWidth:3},"╺":{type:2,data:"M.5,.5 L1,.5",strokeWidth:3},"╻":{type:2,data:"M.5,.5 L.5,1",strokeWidth:3},"╼":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"╽":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"╾":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"╿":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"▀":{type:0,data:[{x:0,y:0,w:8,h:4}]},"▁":{type:0,data:[{x:0,y:7,w:8,h:1}]},"▂":{type:0,data:[{x:0,y:6,w:8,h:2}]},"▃":{type:0,data:[{x:0,y:5,w:8,h:3}]},"▄":{type:0,data:[{x:0,y:4,w:8,h:4}]},"▅":{type:0,data:[{x:0,y:3,w:8,h:5}]},"▆":{type:0,data:[{x:0,y:2,w:8,h:6}]},"▇":{type:0,data:[{x:0,y:1,w:8,h:7}]},"█":{type:0,data:[{x:0,y:0,w:8,h:8}]},"▉":{type:0,data:[{x:0,y:0,w:7,h:8}]},"▊":{type:0,data:[{x:0,y:0,w:6,h:8}]},"▋":{type:0,data:[{x:0,y:0,w:5,h:8}]},"▌":{type:0,data:[{x:0,y:0,w:4,h:8}]},"▍":{type:0,data:[{x:0,y:0,w:3,h:8}]},"▎":{type:0,data:[{x:0,y:0,w:2,h:8}]},"▏":{type:0,data:[{x:0,y:0,w:1,h:8}]},"▐":{type:0,data:[{x:4,y:0,w:4,h:8}]},"░":{type:1,data:[[1,0],[0,0]]},"▒":{type:1,data:[[1,0],[0,1]]},"▓":{type:1,data:[[1,1],[1,0]]},"▔":{type:0,data:[{x:0,y:0,w:8,h:1}]},"▕":{type:0,data:[{x:7,y:0,w:1,h:8}]},"▖":{type:0,data:[{x:0,y:4,w:4,h:4}]},"▗":{type:0,data:[{x:4,y:4,w:4,h:4}]},"▘":{type:0,data:[{x:0,y:0,w:4,h:4}]},"▙":{type:0,data:[{x:0,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"▚":{type:0,data:[{x:0,y:0,w:4,h:4},{x:4,y:4,w:4,h:4}]},"▛":{type:0,data:[{x:0,y:0,w:4,h:8},{x:4,y:0,w:4,h:4}]},"▜":{type:0,data:[{x:0,y:0,w:8,h:4},{x:4,y:0,w:4,h:8}]},"▝":{type:0,data:[{x:4,y:0,w:4,h:4}]},"▞":{type:0,data:[{x:4,y:0,w:4,h:4},{x:0,y:4,w:4,h:4}]},"▟":{type:0,data:[{x:4,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"":{type:5,data:{d:"M.3,1 L.03,1 L.03,.88 C.03,.82,.06,.78,.11,.73 C.15,.7,.2,.68,.28,.65 L.43,.6 C.49,.58,.53,.56,.56,.53 C.59,.5,.6,.47,.6,.43 L.6,.27 L.4,.27 L.69,.1 L.98,.27 L.78,.27 L.78,.46 C.78,.52,.76,.56,.72,.61 C.68,.66,.63,.67,.56,.7 L.48,.72 C.42,.74,.38,.76,.35,.78 C.32,.8,.31,.84,.31,.88 L.31,1 M.3,.5 L.03,.59 L.03,.09 L.3,.09 L.3,.655",type:0}},"":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.355,.03 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"":{type:5,data:{d:"M.25,.94 C.16,.94,.11,.92,.11,.87 L.11,.53 C.11,.48,.15,.455,.23,.45 L.23,.3 C.23,.25,.26,.22,.31,.19 C.36,.16,.43,.15,.51,.15 C.59,.15,.66,.16,.71,.19 C.77,.22,.79,.26,.79,.3 L.79,.45 C.87,.45,.91,.48,.91,.53 L.91,.87 C.91,.92,.86,.94,.77,.94 L.24,.94 M.53,.2 C.49,.2,.45,.21,.42,.23 C.39,.25,.38,.27,.38,.3 L.38,.45 L.68,.45 L.68,.3 C.68,.27,.67,.25,.64,.23 C.61,.21,.58,.2,.53,.2 M.58,.82 L.58,.66 C.63,.65,.65,.63,.65,.6 C.65,.58,.64,.57,.61,.56 C.58,.55,.56,.54,.52,.54 C.48,.54,.46,.55,.43,.56 C.4,.57,.39,.59,.39,.6 C.39,.63,.41,.64,.46,.66 L.46,.82 L.57,.82",type:0}},"":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.7,.03 L.7,.1 L.355,.1 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"":{type:5,data:{d:"M0,0 L1,.5 L0,1",type:0,rightPadding:2}},"":{type:5,data:{d:"M-1,-.5 L1,.5 L-1,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M1,0 L0,.5 L1,1",type:0,leftPadding:2}},"":{type:5,data:{d:"M2,-.5 L0,.5 L2,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M0,0 L0,1 C0.552,1,1,0.776,1,.5 C1,0.224,0.552,0,0,0",type:0,rightPadding:1}},"":{type:5,data:{d:"M.2,1 C.422,1,.8,.826,.78,.5 C.8,.174,0.422,0,.2,0",type:1,rightPadding:1}},"":{type:5,data:{d:"M1,0 L1,1 C0.448,1,0,0.776,0,.5 C0,0.224,0.448,0,1,0",type:0,leftPadding:1}},"":{type:5,data:{d:"M.8,1 C0.578,1,0.2,.826,.22,.5 C0.2,0.174,0.578,0,0.8,0",type:1,leftPadding:1}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L-.5,1.5",type:0}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L1.5,1.5",type:0}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L-.5,-.5",type:0}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L1.5,-.5",type:0}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M0.8069,0.6075 Q0.7991,0.612,0.7815,0.6218 T0.7542,0.6369 T0.7282,0.6508 T0.7016,0.6644 T0.6778,0.6758 T0.6551,0.6854 T0.637,0.6911 T0.622,0.6936 Q0.6186,0.6936,0.6128,0.6942 T0.6018,0.6952 T0.5894,0.6956 T0.5757,0.6952 T0.561,0.693 T0.5451,0.6879 Q0.5342,0.6834,0.5193,0.6756 T0.4925,0.6614 T0.4673,0.6485 T0.4436,0.6389 T0.4239,0.6363 T0.4089,0.6422 Q0.4045,0.6467,0.3958,0.6554 T0.3843,0.6669 T0.3748,0.6746 T0.3613,0.683 T0.3442,0.6903 L0.3499,0.6956 Q0.3584,0.7042,0.3679,0.7177 T0.3836,0.7403 T0.4019,0.7583 T0.4295,0.7703 Q0.4688,0.7785,0.5203,0.7605 Q0.4902,0.7817,0.449,0.7911 T0.3696,0.8001 Q0.3567,0.7997,0.341,0.7942 T0.3111,0.7813 T0.2805,0.766 T0.2493,0.753 T0.218,0.7472 T0.187,0.754 Q0.1762,0.7589,0.1653,0.7681 T0.1453,0.7895 T0.1308,0.818 T0.1264,0.8507 L0.1264,0.858 Q0.1453,0.8462,0.1607,0.8433 T0.1899,0.8452 T0.2226,0.8625 Q0.2344,0.8707,0.2485,0.8752 T0.2813,0.8831 T0.3089,0.889 Q0.2981,0.8915,0.2846,0.8956 T0.2603,0.9037 T0.2368,0.9115 T0.2129,0.9174 T0.1894,0.9194 T0.1653,0.9155 Q0.1504,0.9115,0.1328,0.9196 T0.0986,0.9421 T0.0655,0.9708 T0.0317,0.9943 T0,1 Q0.001,0.94,0.0017,0.6508 T0.0024,0.2322 Q0.002,0.2109,0.0007,0.1379 T0,0.0249 Q0.0058,0.0253,0.009,0.0257 T0.0156,0.0288 T0.0203,0.0333 T0.0264,0.0422 T0.0349,0.0539 Q0.044,0.0657,0.0542,0.072 T0.0752,0.0789 T0.096,0.0775 T0.1175,0.0694 T0.1379,0.0573 T0.1579,0.0432 Q0.2141,0,0.2673,0.0318 Q0.2588,0.0318,0.2517,0.033 T0.239,0.0361 T0.2276,0.0424 T0.218,0.0504 T0.2085,0.0612 T0.1997,0.0732 T0.1899,0.0875 T0.1795,0.1028 Q0.1748,0.1093,0.1507,0.1234 T0.1186,0.1448 Q0.0999,0.1612,0.1108,0.1783 Q0.1162,0.1877,0.1238,0.1928 T0.1404,0.1979 T0.158,0.1967 T0.1775,0.1895 T0.1963,0.1791 T0.2151,0.1663 T0.2314,0.1534 T0.2458,0.141 T0.2561,0.1322 Q0.2815,0.1106,0.3017,0.101 T0.344,0.0926 T0.3919,0.1077 Q0.4099,0.1175,0.4265,0.1206 T0.4588,0.1202 T0.488,0.1098 T0.5176,0.0914 Q0.5071,0.1032,0.4963,0.1122 T0.4722,0.1285 T0.4497,0.1401 T0.4223,0.1518 T0.3943,0.1636 Q0.374,0.1726,0.3623,0.1863 T0.3482,0.2162 Q0.3445,0.2403,0.3608,0.2605 T0.4072,0.2876 Q0.4194,0.2909,0.4326,0.2899 T0.457,0.2856 T0.4805,0.2764 T0.5032,0.264 T0.5256,0.2497 T0.5478,0.2352 T0.5698,0.2222 T0.5921,0.2118 Q0.6982,0.173,0.81,0.2436 Q0.833,0.2583,0.8496,0.2674 T0.887,0.2846 T0.925,0.294 T0.9617,0.2911 T1,0.2746 Q0.9817,0.2946,0.96,0.3056 T0.9175,0.3191 T0.8731,0.3209 T0.8277,0.3164 T0.7818,0.3109 T0.7359,0.3101 T0.6907,0.3197 T0.647,0.3448 Q0.6443,0.3472,0.6333,0.3562 T0.6194,0.3674 T0.6076,0.3766 T0.594,0.386 T0.5815,0.3931 T0.5661,0.4007 T0.5501,0.4064 L0.5556,0.4121 Q0.5627,0.4198,0.5722,0.4251 T0.5926,0.4337 T0.6131,0.439 T0.6343,0.4431 T0.6521,0.4468 Q0.6762,0.4529,0.7056,0.4463 Q0.6772,0.4623,0.6543,0.471 T0.604,0.4814 Q0.5962,0.4818,0.5815,0.4825 T0.5591,0.4835 T0.5393,0.4857 T0.519,0.4908 T0.5007,0.4996 T0.4812,0.5141 T0.4627,0.5353 L0.4549,0.5451 L0.4661,0.543 Q0.4759,0.541,0.4909,0.55 T0.5315,0.5796 T0.5684,0.6083 Q0.5799,0.6161,0.5915,0.6212 T0.6181,0.6308 L0.6331,0.6353 Q0.6514,0.6418,0.7004,0.633 T0.8069,0.6075 Z",type:0}},"":{type:5,data:{d:"M0.011,0.0469 Q0.0152,0.0412,0.02,0.0361 T0.0292,0.0281 T0.0365,0.0253 Q0.0426,0.0257,0.0461,0.0263 T0.0534,0.03 T0.0582,0.0345 T0.0645,0.0434 T0.0723,0.0546 Q0.0807,0.0653,0.0897,0.0712 T0.1081,0.0775 T0.1255,0.0765 T0.1438,0.0695 T0.1605,0.0593 T0.1772,0.0473 Q0.2388,0,0.2927,0.0326 L0.2614,0.0767 L0.2581,0.0767 Q0.2494,0.0767,0.2444,0.0773 T0.2359,0.0789 T0.2291,0.0842 T0.2233,0.0922 T0.2146,0.1054 T0.2026,0.1236 Q0.1943,0.1354,0.1843,0.1444 T0.1675,0.1574 T0.1526,0.1654 T0.1429,0.1701 Q0.1436,0.1717,0.1446,0.1733 Q0.1504,0.1823,0.1581,0.1866 T0.1733,0.1915 T0.1909,0.1884 T0.2085,0.1809 T0.2265,0.169 T0.2427,0.1564 T0.2575,0.1436 T0.2688,0.1338 Q0.2969,0.1101,0.3195,0.0995 T0.3643,0.0901 T0.4114,0.1048 Q0.4279,0.1138,0.4426,0.1168 T0.4705,0.117 T0.4945,0.1089 T0.5186,0.0942 L0.5211,0.0926 L0.5289,0.0922 Q0.5411,0.095,0.5189,0.1203 Q0.505,0.1358,0.4913,0.1474 T0.4634,0.167 T0.4389,0.1796 T0.4121,0.1909 T0.3866,0.2011 Q0.3782,0.2047,0.3727,0.2092 Q0.3717,0.2117,0.3714,0.2141 Q0.3695,0.2263,0.3751,0.2388 T0.394,0.2616 T0.4253,0.2761 Q0.4398,0.2785,0.4513,0.2779 T0.4756,0.2724 T0.4987,0.2616 T0.5216,0.2476 T0.5453,0.2321 T0.5703,0.217 T0.5976,0.2043 Q0.7015,0.166,0.8099,0.2345 Q0.8361,0.2512,0.8572,0.2616 T0.9006,0.2779 T0.9432,0.281 T0.9819,0.2663 L0.9887,0.2671 Q1,0.272,0.9768,0.2969 Q0.9558,0.3193,0.9319,0.333 T0.8858,0.3513 T0.8391,0.3569 T0.793,0.3546 T0.7485,0.3497 T0.7065,0.3473 T0.6681,0.3522 T0.6344,0.3699 Q0.5963,0.4005,0.5847,0.4082 Q0.595,0.4139,0.6079,0.4174 T0.6367,0.4237 T0.6586,0.4278 Q0.6793,0.4331,0.7044,0.4278 Q0.7057,0.4278,0.707,0.4274 Q0.7067,0.429,0.7062,0.4313 T0.7036,0.4398 T0.6993,0.4513 T0.6931,0.4619 T0.6851,0.4698 Q0.6573,0.4857,0.6336,0.4947 T0.5831,0.5053 Q0.577,0.5057,0.5615,0.5065 T0.5394,0.508 T0.5221,0.51 T0.5042,0.5139 T0.4905,0.5204 Q0.5008,0.5232,0.515,0.5328 T0.549,0.5585 T0.5799,0.5824 Q0.5905,0.5897,0.6013,0.5946 T0.6262,0.6036 T0.6409,0.6081 Q0.6567,0.6134,0.7035,0.605 T0.8028,0.5816 L0.7974,0.5922 T0.7867,0.6134 L0.7812,0.624 Q0.7799,0.6248,0.7786,0.6252 Q0.7709,0.6297,0.7573,0.6372 T0.7346,0.6499 T0.7123,0.6621 T0.6897,0.6741 T0.6686,0.6847 T0.648,0.6941 T0.6297,0.7013 T0.6129,0.7062 T0.5995,0.7076 Q0.5992,0.7076,0.5831,0.7092 T0.5529,0.7092 T0.525,0.7019 Q0.5105,0.6958,0.4824,0.6811 T0.4356,0.6586 T0.4079,0.6533 Q0.3872,0.6741,0.3827,0.6782 Q0.3872,0.6835,0.3934,0.6929 T0.4037,0.7078 T0.4142,0.7198 T0.4284,0.7304 T0.4466,0.7365 Q0.4824,0.7443,0.5292,0.728 L0.5292,0.7294 T0.529,0.7333 T0.5284,0.7392 T0.5266,0.7463 T0.5236,0.7539 T0.5186,0.7612 T0.5111,0.7679 Q0.5086,0.77,0.5056,0.7716 Q0.4466,0.8104,0.3591,0.8091 Q0.344,0.8091,0.3246,0.802 T0.2893,0.7863 T0.2543,0.77 T0.2206,0.76 T0.1894,0.7643 Q0.1804,0.7684,0.1733,0.7753 Q0.1591,0.7892,0.1601,0.8169 Q0.1784,0.8067,0.1938,0.8053 T0.2212,0.8087 T0.2507,0.825 Q0.2614,0.8324,0.2744,0.8365 T0.3053,0.844 T0.332,0.8499 L0.303,0.894 L0.2998,0.8948 Q0.2904,0.8968,0.278,0.9009 T0.2554,0.9086 T0.233,0.9158 T0.2099,0.9213 T0.1868,0.9229 T0.1633,0.9192 Q0.1517,0.916,0.1367,0.9241 T0.1065,0.9462 T0.0753,0.9737 T0.041,0.9955 T0.0061,1 Q0,0.9984,0.0068,0.9845 Q0.009,0.9804,0.0123,0.9755 Q0.0187,0.9666,0.0261,0.9606 T0.0374,0.9555 Q0.0481,0.958,0.0629,0.949 T0.0931,0.9262 T0.1247,0.8987 T0.1597,0.8777 T0.1949,0.8752 Q0.213,0.8805,0.2343,0.8772 Q0.2249,0.8736,0.2172,0.8683 Q0.1914,0.8511,0.1738,0.8497 T0.1349,0.8617 Q0.1304,0.865,0.1273,0.8646 T0.1242,0.8605 L0.1239,0.8536 Q0.1226,0.8295,0.1354,0.8016 T0.1723,0.7496 Q0.1914,0.7308,0.2104,0.7219 Q0.2259,0.7145,0.2425,0.7141 T0.273,0.7182 T0.3022,0.7296 T0.3301,0.7439 T0.3569,0.7571 T0.3821,0.7643 Q0.373,0.7561,0.3598,0.7367 T0.3382,0.7088 L0.3327,0.7035 Q0.3282,0.699,0.3353,0.6884 T0.3517,0.6692 L0.3611,0.6607 Q0.3711,0.657,0.3751,0.6554 T0.3837,0.6507 T0.3898,0.6458 T0.3979,0.637 T0.4111,0.6236 Q0.4172,0.6175,0.4234,0.6138 Q0.4327,0.6081,0.4439,0.6077 T0.4655,0.6105 T0.4884,0.6201 T0.5113,0.633 T0.5347,0.6468 T0.5573,0.6578 Q0.5705,0.6635,0.5833,0.665 T0.6112,0.665 T0.6286,0.6635 Q0.6421,0.6631,0.6718,0.6501 Q0.626,0.6578,0.6089,0.6517 Q0.6063,0.6509,0.6002,0.6491 T0.5884,0.6454 T0.5757,0.6409 T0.561,0.6344 T0.5466,0.6256 Q0.536,0.6183,0.5108,0.5989 T0.4722,0.5712 T0.4527,0.564 L0.4418,0.5661 Q0.4308,0.5681,0.4366,0.5563 Q0.4401,0.5485,0.4476,0.5392 L0.455,0.5298 Q0.4631,0.5188,0.4714,0.51 T0.4866,0.4947 T0.5021,0.4831 T0.516,0.4749 T0.53,0.4694 T0.5428,0.4657 T0.5558,0.4637 T0.5674,0.4629 T0.5795,0.4625 Q0.5489,0.4543,0.534,0.4384 L0.5286,0.4327 Q0.5244,0.4282,0.5318,0.4174 T0.5486,0.398 L0.5579,0.3899 Q0.567,0.387,0.5749,0.3834 T0.5878,0.3772 T0.6012,0.3687 T0.6126,0.3603 T0.6268,0.3487 T0.6421,0.3361 Q0.6567,0.3242,0.6712,0.3159 T0.7009,0.3034 T0.7277,0.2973 T0.7556,0.2961 T0.7809,0.2977 T0.8074,0.301 Q0.8096,0.3014,0.8109,0.3016 T0.8143,0.302 T0.818,0.3026 Q0.8012,0.2936,0.7767,0.2781 Q0.6718,0.2117,0.5744,0.2476 Q0.5637,0.2516,0.5492,0.2604 T0.5218,0.2779 T0.4923,0.2965 T0.461,0.3124 T0.4282,0.3216 T0.394,0.3206 Q0.3637,0.3136,0.3474,0.2936 T0.3353,0.2459 Q0.3385,0.2247,0.355,0.2023 Q0.3646,0.1892,0.3763,0.179 Q0.3898,0.1672,0.4063,0.1595 Q0.3927,0.1562,0.3785,0.1485 Q0.3604,0.1387,0.3453,0.1354 T0.3161,0.1354 T0.2899,0.1458 T0.2627,0.166 Q0.262,0.1664,0.254,0.1733 T0.2414,0.1841 T0.2267,0.196 T0.2094,0.2086 T0.1915,0.2196 T0.1725,0.2288 T0.1546,0.2337 T0.1373,0.2343 T0.1223,0.228 T0.1097,0.2145 Q0.0962,0.1929,0.1258,0.1582 Q0.131,0.1517,0.1371,0.1464 Q0.1462,0.1387,0.156,0.1321 T0.1752,0.1205 T0.1878,0.1134 Q0.1891,0.1117,0.1947,0.103 T0.2035,0.0899 T0.2125,0.0781 T0.2243,0.064 Q0.1949,0.0616,0.1672,0.0828 Q0.153,0.0934,0.1412,0.1009 T0.1146,0.1146 T0.0873,0.1213 T0.0616,0.116 T0.0374,0.0962 Q0.0339,0.0909,0.0295,0.0846 T0.024,0.0767 T0.0202,0.0728 T0.0148,0.0704 T0.0068,0.0697 Q0.0003,0.0693,0.0058,0.0567 Q0.0077,0.0522,0.011,0.0469 Z",type:0}},"":{type:5,data:{d:"M0.1934,0.6075 Q0.2012,0.612,0.2188,0.6218 T0.2459,0.6369 T0.2718,0.6508 T0.2983,0.6644 T0.322,0.6758 T0.3447,0.6854 T0.363,0.6911 T0.3783,0.6936 Q0.3796,0.6936,0.396,0.6952 T0.4265,0.6952 T0.4548,0.6879 Q0.4656,0.6834,0.4805,0.6756 T0.5073,0.6614 T0.5327,0.6485 T0.5564,0.6389 T0.5759,0.6363 T0.5909,0.6422 Q0.5953,0.6467,0.604,0.6554 T0.6155,0.6669 T0.6251,0.6746 T0.6387,0.683 T0.6556,0.6903 L0.6498,0.6956 Q0.6414,0.7042,0.6319,0.7177 T0.6162,0.7403 T0.5979,0.7583 T0.5703,0.7703 Q0.5313,0.7785,0.4799,0.7605 Q0.5097,0.7817,0.5508,0.7911 T0.6302,0.8001 Q0.6431,0.7997,0.659,0.7942 T0.6888,0.7813 T0.7194,0.766 T0.7506,0.753 T0.7819,0.7472 T0.8131,0.754 Q0.8239,0.7589,0.8346,0.7681 T0.8544,0.7895 T0.8689,0.818 T0.8737,0.8507 L0.8733,0.858 Q0.8591,0.849,0.8474,0.845 T0.8242,0.8421 T0.8021,0.8482 T0.7772,0.8625 Q0.7653,0.8707,0.7513,0.8752 T0.7184,0.8831 T0.6908,0.889 Q0.7017,0.8915,0.7152,0.8956 T0.7396,0.9037 T0.7633,0.9115 T0.7872,0.9174 T0.8107,0.9194 T0.8347,0.9155 Q0.8493,0.9115,0.8671,0.9196 T0.9015,0.9421 T0.9345,0.9708 T0.9682,0.9943 T0.9997,1 Q0.999,0.94,0.9983,0.6508 T0.9976,0.2322 Q0.9976,0.2109,0.9992,0.1379 T1,0.0249 Q0.9949,0.0249,0.9917,0.0257 T0.9863,0.0273 T0.9817,0.0308 T0.9776,0.0357 T0.9721,0.0437 T0.9651,0.0539 Q0.956,0.0657,0.9456,0.072 T0.9247,0.0789 T0.904,0.0775 T0.8823,0.0694 T0.862,0.0573 T0.8422,0.0432 Q0.7856,0,0.7328,0.0318 Q0.7392,0.0318,0.7452,0.0324 T0.756,0.0345 T0.7657,0.0386 T0.7741,0.0437 T0.7821,0.0506 T0.7894,0.0588 T0.7966,0.0683 T0.8039,0.0787 T0.8119,0.0904 T0.8202,0.1028 Q0.8249,0.1093,0.849,0.1234 T0.8811,0.1448 Q0.8998,0.1612,0.8893,0.1783 Q0.8835,0.1877,0.8759,0.1928 T0.8593,0.1979 T0.8417,0.1967 T0.8222,0.1895 T0.8034,0.1791 T0.7848,0.1663 T0.7687,0.1534 T0.7543,0.141 T0.744,0.1322 Q0.7186,0.1106,0.6984,0.101 T0.6559,0.0926 T0.6082,0.1077 Q0.5899,0.1175,0.5733,0.1206 T0.5411,0.1202 T0.5122,0.1098 T0.4822,0.0914 Q0.4927,0.1032,0.5036,0.1122 T0.5276,0.1285 T0.5503,0.1401 T0.5777,0.1518 T0.6055,0.1636 Q0.6258,0.1726,0.6375,0.1863 T0.6519,0.2162 Q0.6556,0.2403,0.6392,0.2605 T0.5926,0.2876 Q0.5804,0.2909,0.5672,0.2899 T0.5428,0.2856 T0.5193,0.2764 T0.4966,0.264 T0.4744,0.2497 T0.4523,0.2352 T0.4301,0.2222 T0.4077,0.2118 Q0.3021,0.173,0.1903,0.2436 Q0.1669,0.2583,0.1504,0.2674 T0.1129,0.2846 T0.075,0.294 T0.0384,0.2911 T0,0.2746 Q0.021,0.297,0.0459,0.3082 T0.0953,0.3207 T0.146,0.3193 T0.1988,0.3131 T0.2508,0.3095 T0.3029,0.3176 T0.3529,0.3448 Q0.3566,0.348,0.3652,0.355 T0.3771,0.3645 T0.3877,0.3731 T0.3993,0.3815 T0.4103,0.3884 T0.4226,0.3953 T0.4352,0.4009 T0.4497,0.4064 L0.4443,0.4121 Q0.4372,0.4198,0.4277,0.4251 T0.4072,0.4337 T0.3867,0.439 T0.3656,0.4431 T0.3481,0.4468 Q0.3241,0.4529,0.2943,0.4463 Q0.3227,0.4623,0.3458,0.471 T0.3959,0.4814 Q0.404,0.4818,0.4187,0.4825 T0.4409,0.4835 T0.4605,0.4857 T0.4809,0.4908 T0.4992,0.4996 T0.5186,0.5141 T0.5371,0.5353 L0.5449,0.5451 L0.5337,0.543 Q0.5242,0.541,0.5091,0.55 T0.4683,0.5796 T0.4314,0.6083 Q0.4203,0.6161,0.4086,0.6212 T0.382,0.6308 T0.3667,0.6353 Q0.3485,0.6418,0.2995,0.633 T0.1934,0.6075 Z",type:0}},"":{type:5,data:{d:"M0.989,0.0469 Q0.9829,0.0379,0.9753,0.0316 T0.9635,0.0253 Q0.9574,0.0257,0.9539,0.0263 T0.9466,0.03 T0.9418,0.0345 T0.9355,0.0434 T0.9277,0.0546 Q0.9193,0.0653,0.9103,0.0712 T0.8919,0.0775 T0.8745,0.0765 T0.8564,0.0695 T0.8396,0.0593 T0.8228,0.0473 Q0.7612,0,0.7073,0.0326 L0.7386,0.0767 L0.7419,0.0767 Q0.7506,0.0767,0.7556,0.0773 T0.7641,0.0789 T0.7709,0.0842 T0.7767,0.0922 T0.7854,0.1054 T0.7974,0.1236 Q0.8057,0.1354,0.8157,0.1444 T0.8325,0.1574 T0.8474,0.1654 T0.8571,0.1701 Q0.8564,0.1717,0.8554,0.1733 Q0.8503,0.1815,0.844,0.186 T0.8301,0.1909 T0.8153,0.1903 T0.7993,0.1845 T0.7836,0.1758 T0.768,0.1648 T0.754,0.1535 T0.741,0.1425 T0.7312,0.1338 Q0.7031,0.1101,0.6805,0.0995 T0.6357,0.0901 T0.5886,0.1048 Q0.5721,0.1138,0.5574,0.1168 T0.5295,0.117 T0.5055,0.1089 T0.4814,0.0942 L0.4789,0.0926 L0.4711,0.0922 Q0.4589,0.095,0.4811,0.1203 Q0.495,0.1358,0.5087,0.1474 T0.5366,0.167 T0.5611,0.1796 T0.5879,0.1909 T0.6134,0.2011 Q0.6218,0.2047,0.6273,0.2092 Q0.6283,0.2117,0.6286,0.2141 Q0.6305,0.2263,0.6249,0.2388 T0.606,0.2616 T0.5747,0.2761 Q0.5602,0.2785,0.5487,0.2779 T0.5245,0.2724 T0.5015,0.2616 T0.4784,0.2476 T0.4547,0.2321 T0.4297,0.217 T0.4024,0.2043 Q0.2985,0.166,0.1901,0.2345 Q0.1694,0.248,0.1523,0.2569 T0.1165,0.2726 T0.0818,0.2812 T0.0494,0.2796 T0.0181,0.2663 L0.0116,0.2671 Q0,0.272,0.0232,0.2969 Q0.0468,0.3222,0.0742,0.3365 T0.1278,0.3542 T0.1807,0.3564 T0.233,0.352 T0.2815,0.3473 T0.3269,0.3509 T0.3656,0.3699 Q0.4037,0.4005,0.4153,0.4082 Q0.405,0.4139,0.3921,0.4174 T0.3633,0.4237 T0.3414,0.4278 Q0.3207,0.4331,0.2956,0.4278 Q0.2943,0.4278,0.293,0.4274 Q0.2933,0.429,0.2938,0.4313 T0.2964,0.4398 T0.3007,0.4513 T0.3069,0.4619 T0.3149,0.4698 Q0.3427,0.4857,0.3664,0.4947 T0.4169,0.5053 Q0.423,0.5057,0.4385,0.5065 T0.4606,0.508 T0.4779,0.51 T0.4958,0.5139 T0.5095,0.5204 Q0.4992,0.5232,0.485,0.5328 T0.451,0.5585 T0.4201,0.5824 Q0.4095,0.5897,0.3987,0.5946 T0.3738,0.6036 T0.3591,0.6081 Q0.3433,0.6134,0.2965,0.605 T0.1972,0.5816 L0.2026,0.5922 T0.2133,0.6134 L0.2188,0.624 Q0.2201,0.6248,0.2214,0.6252 Q0.2291,0.6297,0.2486,0.6405 T0.2786,0.657 T0.3066,0.6721 T0.3353,0.6866 T0.3598,0.6972 T0.383,0.7051 T0.4005,0.7076 Q0.4008,0.7076,0.4169,0.7092 T0.4471,0.7092 T0.475,0.7019 Q0.4895,0.6958,0.5176,0.6811 T0.5644,0.6586 T0.5921,0.6533 Q0.6128,0.6741,0.6173,0.6782 Q0.6131,0.6835,0.6068,0.6929 T0.5963,0.7078 T0.5858,0.7198 T0.5716,0.7304 T0.5534,0.7365 Q0.5179,0.7443,0.4708,0.728 L0.4708,0.7294 T0.471,0.7333 T0.4716,0.7392 T0.4734,0.7463 T0.4764,0.7539 T0.4814,0.7612 T0.4889,0.7679 Q0.4914,0.77,0.4944,0.7716 Q0.5534,0.8104,0.6409,0.8091 Q0.6521,0.8091,0.6654,0.8053 T0.6907,0.7959 T0.7157,0.7838 T0.741,0.772 T0.7652,0.7631 T0.7888,0.7594 T0.8106,0.7643 Q0.8196,0.7684,0.8267,0.7753 Q0.8409,0.7892,0.8399,0.8169 Q0.8216,0.8067,0.8062,0.8053 T0.7788,0.8087 T0.7493,0.825 Q0.7386,0.8324,0.7256,0.8365 T0.6947,0.844 T0.668,0.8499 L0.697,0.894 L0.7002,0.8948 Q0.7099,0.8968,0.7222,0.9009 T0.7446,0.9086 T0.767,0.9158 T0.7901,0.9213 T0.8132,0.9229 T0.8367,0.9192 Q0.8483,0.916,0.8633,0.9241 T0.8937,0.9462 T0.9248,0.9737 T0.959,0.9955 T0.9939,1 Q1,0.9984,0.9932,0.9845 Q0.991,0.9804,0.9877,0.9755 Q0.9813,0.9666,0.9739,0.9606 T0.9626,0.9555 Q0.9519,0.958,0.9372,0.949 T0.9071,0.9262 T0.8753,0.8987 T0.8403,0.8777 T0.8051,0.8752 Q0.787,0.8805,0.7657,0.8772 Q0.7751,0.8736,0.7828,0.8683 Q0.8086,0.8511,0.8262,0.8497 T0.8651,0.8617 Q0.8696,0.865,0.8727,0.8646 T0.8758,0.8605 L0.8761,0.8536 Q0.8774,0.8295,0.8646,0.8016 T0.8277,0.7496 Q0.8086,0.7308,0.7896,0.7219 Q0.7741,0.7145,0.7575,0.7141 T0.727,0.7182 T0.6978,0.7296 T0.6699,0.7439 T0.6433,0.7571 T0.6179,0.7643 Q0.627,0.7561,0.6402,0.7367 T0.6618,0.7088 L0.6673,0.7035 Q0.6718,0.699,0.6647,0.6884 T0.6483,0.6692 L0.6389,0.6607 Q0.6289,0.657,0.6249,0.6554 T0.6163,0.6507 T0.6102,0.6458 T0.6021,0.637 T0.5889,0.6236 Q0.5828,0.6175,0.5766,0.6138 Q0.5673,0.6081,0.5561,0.6077 T0.5345,0.6105 T0.5116,0.6201 T0.4887,0.633 T0.4653,0.6468 T0.4427,0.6578 Q0.4295,0.6635,0.4167,0.665 T0.3888,0.665 T0.3714,0.6635 Q0.3579,0.6631,0.3282,0.6501 Q0.374,0.6578,0.3911,0.6517 Q0.3937,0.6509,0.4024,0.6482 T0.4179,0.6434 T0.4348,0.6364 T0.4534,0.6256 Q0.464,0.6183,0.4892,0.5989 T0.5278,0.5712 T0.5476,0.564 L0.5582,0.5661 Q0.5692,0.5681,0.5634,0.5563 Q0.5599,0.5485,0.5524,0.5392 L0.545,0.5298 Q0.5369,0.5188,0.5286,0.51 T0.5134,0.4947 T0.4979,0.4831 T0.484,0.4749 T0.47,0.4694 T0.4572,0.4657 T0.4442,0.4637 T0.4326,0.4629 T0.4205,0.4625 Q0.4511,0.4543,0.466,0.4384 L0.4714,0.4327 Q0.4795,0.4237,0.4469,0.394 L0.4421,0.3899 Q0.433,0.387,0.4251,0.3834 T0.4122,0.3772 T0.3988,0.3687 T0.3874,0.3603 T0.3732,0.3487 T0.3579,0.3361 Q0.3433,0.3242,0.3288,0.3159 T0.2993,0.3034 T0.2725,0.2973 T0.2446,0.2961 T0.2193,0.2977 T0.1926,0.301 Q0.1855,0.3022,0.182,0.3026 Q0.1991,0.2936,0.2233,0.2781 Q0.3282,0.2117,0.4256,0.2476 Q0.4363,0.2516,0.451,0.2604 T0.4784,0.2779 T0.5077,0.2965 T0.539,0.3124 T0.5718,0.3216 T0.606,0.3206 Q0.6363,0.3136,0.6526,0.2936 T0.6647,0.2459 Q0.6615,0.2247,0.645,0.2023 Q0.6354,0.1892,0.6237,0.179 Q0.6102,0.1672,0.5937,0.1595 Q0.6073,0.1562,0.6215,0.1485 Q0.6396,0.1387,0.6547,0.1354 T0.6839,0.1354 T0.7101,0.1458 T0.7373,0.166 Q0.738,0.1664,0.746,0.1733 T0.7586,0.1841 T0.7733,0.196 T0.7907,0.2086 T0.8086,0.2196 T0.8275,0.2288 T0.8454,0.2337 T0.8627,0.2343 T0.8777,0.228 T0.8903,0.2145 Q0.9038,0.1929,0.8742,0.1582 Q0.869,0.1517,0.8629,0.1464 Q0.8538,0.1387,0.844,0.1321 T0.8248,0.1205 T0.8122,0.1134 Q0.8109,0.1117,0.8053,0.103 T0.7965,0.0899 T0.7875,0.0781 T0.7757,0.064 Q0.8051,0.0616,0.8328,0.0828 Q0.847,0.0934,0.8588,0.1009 T0.8854,0.1146 T0.9127,0.1213 T0.9384,0.116 T0.9626,0.0962 Q0.9664,0.0909,0.9706,0.0846 T0.976,0.0767 T0.9798,0.0728 T0.9852,0.0704 T0.9932,0.0697 Q0.9997,0.0693,0.9942,0.0567 Q0.9923,0.0522,0.989,0.0469 Z",type:0}},"":{type:5,data:{d:"M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0.9099,0.1158 L0.9099,0.1888 L0.9951,0.1888 L0.9951,0.1158 L0.9099,0.1158 Z M0.9075,0.1116 L0.9976,0.1116 Q1,0.1116,1,0.1137 L1,0.1909 Q1,0.193,0.9976,0.193 L0.9075,0.193 Q0.905,0.193,0.905,0.1909 L0.905,0.1137 Q0.905,0.1116,0.9075,0.1116 Z M0.7852,0.6086 L0.7852,0.682 L0.8704,0.682 L0.8704,0.6086 L0.7852,0.6086 Z M0.7828,0.6044 L0.8729,0.6044 Q0.8753,0.6044,0.8753,0.6065 L0.8753,0.6841 Q0.8753,0.6862,0.8729,0.6862 L0.7828,0.6862 Q0.7803,0.6862,0.7803,0.6841 L0.7803,0.6065 Q0.7803,0.6044,0.7828,0.6044 Z M0.66,0.1137 L0.7501,0.1137 L0.7501,0.1909 L0.66,0.1909 L0.66,0.1137 Z M0.6624,0.4102 L0.6624,0.4836 L0.7477,0.4836 L0.7477,0.4102 L0.6624,0.4102 Z M0.66,0.406 L0.7501,0.406 Q0.7526,0.406,0.7526,0.4081 L0.7526,0.4857 Q0.7526,0.4878,0.7501,0.4878 L0.66,0.4878 Q0.6576,0.4878,0.6576,0.4857 L0.6576,0.4081 Q0.6576,0.406,0.66,0.406 Z M0.6624,0.7131 L0.6624,0.7865 L0.7477,0.7865 L0.7477,0.7131 L0.6624,0.7131 Z M0.66,0.7089 L0.7501,0.7089 Q0.7526,0.7089,0.7526,0.711 L0.7526,0.7886 Q0.7526,0.7907,0.7501,0.7907 L0.66,0.7907 Q0.6576,0.7907,0.6576,0.7886 L0.6576,0.711 Q0.6576,0.7089,0.66,0.7089 Z M0.5407,0.2227 L0.5407,0.2836 L0.6113,0.2836 L0.6113,0.2227 L0.5407,0.2227 Z M0.5309,0.206 L0.621,0.206 Q0.623,0.206,0.6249,0.2068 T0.6281,0.2089 T0.6301,0.2116 T0.6308,0.2143 L0.6308,0.2919 Q0.6308,0.2957,0.6276,0.298 T0.621,0.3003 L0.5309,0.3003 Q0.5265,0.3003,0.5239,0.2976 T0.5212,0.2919 L0.5212,0.2143 Q0.5212,0.211,0.5244,0.2085 T0.5309,0.206 Z M0.5407,0.3184 L0.5407,0.3792 L0.6113,0.3792 L0.6113,0.3184 L0.5407,0.3184 Z M0.5309,0.3016 L0.621,0.3016 Q0.6254,0.3016,0.6281,0.3043 T0.6308,0.31 L0.6308,0.3876 Q0.6308,0.3914,0.6276,0.3937 T0.621,0.396 L0.5309,0.396 Q0.5265,0.396,0.5239,0.3932 T0.5212,0.3876 L0.5212,0.31 Q0.5212,0.3062,0.5244,0.3039 T0.5309,0.3016 Z M0.5309,0.4081 L0.621,0.4081 L0.621,0.4857 L0.5309,0.4857 L0.5309,0.4081 Z M0.5309,0.5059 L0.621,0.5059 L0.621,0.5835 L0.5309,0.5835 L0.5309,0.5059 Z M0.5407,0.6149 L0.5407,0.6758 L0.6113,0.6758 L0.6113,0.6149 L0.5407,0.6149 Z M0.5309,0.5982 L0.621,0.5982 Q0.6254,0.5982,0.6281,0.6009 T0.6308,0.6065 L0.6308,0.6841 Q0.6308,0.6879,0.6276,0.6902 T0.621,0.6925 L0.5309,0.6925 Q0.5265,0.6925,0.5239,0.6898 T0.5212,0.6841 L0.5212,0.6065 Q0.5212,0.6028,0.5244,0.6005 T0.5309,0.5982 Z M0.4062,0.1137 L0.4963,0.1137 L0.4963,0.1909 L0.4062,0.1909 L0.4062,0.1137 Z M0.4062,0.2143 L0.4963,0.2143 L0.4963,0.2919 L0.4062,0.2919 L0.4062,0.2143 Z M0.4184,0.4186 L0.4184,0.4753 L0.4842,0.4753 L0.4842,0.4186 L0.4184,0.4186 Z M0.4062,0.3977 L0.4963,0.3977 Q0.5017,0.3977,0.5051,0.401 T0.5085,0.4081 L0.5085,0.4857 Q0.5085,0.4904,0.5046,0.4933 T0.4963,0.4962 L0.4062,0.4962 Q0.4009,0.4962,0.3975,0.4929 T0.3941,0.4857 L0.3941,0.4081 Q0.3941,0.4035,0.398,0.4006 T0.4062,0.3977 Z M0.4062,0.5059 L0.4963,0.5059 L0.4963,0.5835 L0.4062,0.5835 L0.4062,0.5059 Z M0.4087,0.7131 L0.4087,0.7865 L0.4939,0.7865 L0.4939,0.7131 L0.4087,0.7131 Z M0.4062,0.7089 L0.4963,0.7089 Q0.4988,0.7089,0.4988,0.711 L0.4988,0.7886 Q0.4988,0.7907,0.4963,0.7907 L0.4062,0.7907 Q0.4038,0.7907,0.4038,0.7886 L0.4038,0.711 Q0.4038,0.7089,0.4062,0.7089 Z M0.2689,0.1137 L0.359,0.1137 L0.359,0.1909 L0.2689,0.1909 L0.2689,0.1137 Z M0.2689,0.2143 L0.359,0.2143 L0.359,0.2919 L0.2689,0.2919 L0.2689,0.2143 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.31 L0.359,0.31 L0.359,0.3876 L0.2689,0.3876 L0.2689,0.31 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.4081 L0.359,0.4081 L0.359,0.4857 L0.2689,0.4857 L0.2689,0.4081 Z M0.2689,0.5059 L0.359,0.5059 L0.359,0.5835 L0.2689,0.5835 L0.2689,0.5059 Z M0.2689,0.711 L0.359,0.711 L0.359,0.7886 L0.2689,0.7886 L0.2689,0.711 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.1374,0.1137 L0.2275,0.1137 L0.2275,0.1909 L0.1374,0.1909 L0.1374,0.1137 Z M0.1374,0.2143 L0.2275,0.2143 L0.2275,0.2919 L0.1374,0.2919 L0.1374,0.2143 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.31 L0.2275,0.31 L0.2275,0.3876 L0.1374,0.3876 L0.1374,0.31 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.4081 L0.2275,0.4081 L0.2275,0.4857 L0.1374,0.4857 L0.1374,0.4081 Z M0.1374,0.5059 L0.2275,0.5059 L0.2275,0.5835 L0.1374,0.5835 L0.1374,0.5059 Z M0.1374,0.6065 L0.2275,0.6065 L0.2275,0.6841 L0.1374,0.6841 L0.1374,0.6065 Z M0.1374,0.711 L0.2275,0.711 L0.2275,0.7886 L0.1374,0.7886 L0.1374,0.711 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0,0.1137 L0.0901,0.1137 L0.0901,0.1909 L0,0.1909 L0,0.1137 Z M0,0.2143 L0.0901,0.2143 L0.0901,0.2919 L0,0.2919 L0,0.2143 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.31 L0.0901,0.31 L0.0901,0.3876 L0,0.3876 L0,0.31 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.4081 L0.0901,0.4081 L0.0901,0.4857 L0,0.4857 L0,0.4081 Z M0,0.5059 L0.0901,0.5059 L0.0901,0.5835 L0,0.5835 L0,0.5059 Z M0,0.6065 L0.0901,0.6065 L0.0901,0.6841 L0,0.6841 L0,0.6065 Z M0,0.711 L0.0901,0.711 L0.0901,0.7886 L0,0.7886 L0,0.711 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z",type:0}},"":{type:5,data:{d:"M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M0.0901,0.1158 L0.0901,0.1888 L0.0049,0.1888 L0.0049,0.1158 L0.0901,0.1158 Z M0.0925,0.1116 L0.0024,0.1116 Q0,0.1116,0,0.1137 L0,0.1909 Q0,0.193,0.0024,0.193 L0.0925,0.193 Q0.095,0.193,0.095,0.1909 L0.095,0.1137 Q0.095,0.1116,0.0925,0.1116 Z M0.2148,0.6086 L0.2148,0.682 L0.1296,0.682 L0.1296,0.6086 L0.2148,0.6086 Z M0.2172,0.6044 L0.1271,0.6044 Q0.1247,0.6044,0.1247,0.6065 L0.1247,0.6841 Q0.1247,0.6862,0.1271,0.6862 L0.2172,0.6862 Q0.2197,0.6862,0.2197,0.6841 L0.2197,0.6065 Q0.2197,0.6044,0.2172,0.6044 Z M0.34,0.1137 L0.2499,0.1137 L0.2499,0.1909 L0.34,0.1909 L0.34,0.1137 Z M0.3376,0.4102 L0.3376,0.4836 L0.2523,0.4836 L0.2523,0.4102 L0.3376,0.4102 Z M0.34,0.406 L0.2499,0.406 Q0.2474,0.406,0.2474,0.4081 L0.2474,0.4857 Q0.2474,0.4878,0.2499,0.4878 L0.34,0.4878 Q0.3424,0.4878,0.3424,0.4857 L0.3424,0.4081 Q0.3424,0.406,0.34,0.406 Z M0.3376,0.7131 L0.3376,0.7865 L0.2523,0.7865 L0.2523,0.7131 L0.3376,0.7131 Z M0.34,0.7089 L0.2499,0.7089 Q0.2474,0.7089,0.2474,0.711 L0.2474,0.7886 Q0.2474,0.7907,0.2499,0.7907 L0.34,0.7907 Q0.3424,0.7907,0.3424,0.7886 L0.3424,0.711 Q0.3424,0.7089,0.34,0.7089 Z M0.4593,0.2227 L0.4593,0.2836 L0.3887,0.2836 L0.3887,0.2227 L0.4593,0.2227 Z M0.4691,0.206 L0.379,0.206 Q0.3746,0.206,0.3719,0.2087 T0.3692,0.2143 L0.3692,0.2919 Q0.3692,0.2957,0.3724,0.298 T0.379,0.3003 L0.4691,0.3003 Q0.4735,0.3003,0.4761,0.2976 T0.4788,0.2919 L0.4788,0.2143 Q0.4788,0.211,0.4756,0.2085 T0.4691,0.206 Z M0.4593,0.3184 L0.4593,0.3792 L0.3887,0.3792 L0.3887,0.3184 L0.4593,0.3184 Z M0.4691,0.3016 L0.379,0.3016 Q0.3746,0.3016,0.3719,0.3043 T0.3692,0.31 L0.3692,0.3876 Q0.3692,0.3914,0.3724,0.3937 T0.379,0.396 L0.4691,0.396 Q0.4735,0.396,0.4761,0.3932 T0.4788,0.3876 L0.4788,0.31 Q0.4788,0.3062,0.4756,0.3039 T0.4691,0.3016 Z M0.4691,0.4081 L0.379,0.4081 L0.379,0.4857 L0.4691,0.4857 L0.4691,0.4081 Z M0.4691,0.5059 L0.379,0.5059 L0.379,0.5835 L0.4691,0.5835 L0.4691,0.5059 Z M0.4593,0.6149 L0.4593,0.6758 L0.3887,0.6758 L0.3887,0.6149 L0.4593,0.6149 Z M0.4691,0.5982 L0.379,0.5982 Q0.3746,0.5982,0.3719,0.6009 T0.3692,0.6065 L0.3692,0.6841 Q0.3692,0.6879,0.3724,0.6902 T0.379,0.6925 L0.4691,0.6925 Q0.4735,0.6925,0.4761,0.6898 T0.4788,0.6841 L0.4788,0.6065 Q0.4788,0.6028,0.4756,0.6005 T0.4691,0.5982 Z M0.5938,0.1137 L0.5037,0.1137 L0.5037,0.1909 L0.5938,0.1909 L0.5938,0.1137 Z M0.5938,0.2143 L0.5037,0.2143 L0.5037,0.2919 L0.5938,0.2919 L0.5938,0.2143 Z M0.5816,0.4186 L0.5816,0.4753 L0.5158,0.4753 L0.5158,0.4186 L0.5816,0.4186 Z M0.5938,0.3977 L0.5037,0.3977 Q0.4983,0.3977,0.4949,0.401 T0.4915,0.4081 L0.4915,0.4857 Q0.4915,0.4904,0.4954,0.4933 T0.5037,0.4962 L0.5938,0.4962 Q0.5991,0.4962,0.6025,0.4929 T0.6059,0.4857 L0.6059,0.4081 Q0.6059,0.4035,0.602,0.4006 T0.5938,0.3977 Z M0.5938,0.5059 L0.5037,0.5059 L0.5037,0.5835 L0.5938,0.5835 L0.5938,0.5059 Z M0.5913,0.7131 L0.5913,0.7865 L0.5061,0.7865 L0.5061,0.7131 L0.5913,0.7131 Z M0.5938,0.7089 L0.5037,0.7089 Q0.5012,0.7089,0.5012,0.711 L0.5012,0.7886 Q0.5012,0.7907,0.5037,0.7907 L0.5938,0.7907 Q0.5962,0.7907,0.5962,0.7886 L0.5962,0.711 Q0.5962,0.7089,0.5938,0.7089 Z M0.7311,0.1137 L0.641,0.1137 L0.641,0.1909 L0.7311,0.1909 L0.7311,0.1137 Z M0.7311,0.2143 L0.641,0.2143 L0.641,0.2919 L0.7311,0.2919 L0.7311,0.2143 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.31 L0.641,0.31 L0.641,0.3876 L0.7311,0.3876 L0.7311,0.31 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.4081 L0.641,0.4081 L0.641,0.4857 L0.7311,0.4857 L0.7311,0.4081 Z M0.7311,0.5059 L0.641,0.5059 L0.641,0.5835 L0.7311,0.5835 L0.7311,0.5059 Z M0.7311,0.711 L0.641,0.711 L0.641,0.7886 L0.7311,0.7886 L0.7311,0.711 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.8626,0.1137 L0.7725,0.1137 L0.7725,0.1909 L0.8626,0.1909 L0.8626,0.1137 Z M0.8626,0.2143 L0.7725,0.2143 L0.7725,0.2919 L0.8626,0.2919 L0.8626,0.2143 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.31 L0.7725,0.31 L0.7725,0.3876 L0.8626,0.3876 L0.8626,0.31 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.4081 L0.7725,0.4081 L0.7725,0.4857 L0.8626,0.4857 L0.8626,0.4081 Z M0.8626,0.5059 L0.7725,0.5059 L0.7725,0.5835 L0.8626,0.5835 L0.8626,0.5059 Z M0.8626,0.6065 L0.7725,0.6065 L0.7725,0.6841 L0.8626,0.6841 L0.8626,0.6065 Z M0.8626,0.711 L0.7725,0.711 L0.7725,0.7886 L0.8626,0.7886 L0.8626,0.711 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M1,0.1137 L0.9099,0.1137 L0.9099,0.1909 L1,0.1909 L1,0.1137 Z M1,0.2143 L0.9099,0.2143 L0.9099,0.2919 L1,0.2919 L1,0.2143 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.31 L0.9099,0.31 L0.9099,0.3876 L1,0.3876 L1,0.31 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.4081 L0.9099,0.4081 L0.9099,0.4857 L1,0.4857 L1,0.4081 Z M1,0.5059 L0.9099,0.5059 L0.9099,0.5835 L1,0.5835 L1,0.5059 Z M1,0.6065 L0.9099,0.6065 L0.9099,0.6841 L1,0.6841 L1,0.6065 Z M1,0.711 L0.9099,0.711 L0.9099,0.7886 L1,0.7886 L1,0.711 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z",type:0}},"":{type:5,data:{d:"M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0.8574,0.3217 L0.8574,0.4098 L0.9691,0.4098 L0.9691,0.3217 L0.8574,0.3217 Z M0.8419,0.2978 L0.9846,0.2978 Q0.9892,0.2978,0.9928,0.2997 T0.9982,0.3043 T1,0.31 L1,0.4216 Q1,0.427,0.9951,0.4304 T0.9846,0.4337 L0.8419,0.4337 Q0.8352,0.4337,0.8308,0.4299 T0.8265,0.4216 L0.8265,0.31 Q0.8265,0.3062,0.829,0.3035 T0.835,0.2993 T0.8419,0.2978 Z M0.8574,0.888 L0.8574,0.9757 L0.9691,0.9757 L0.9691,0.888 L0.8574,0.888 Z M0.8419,0.8637 L0.9846,0.8637 Q0.9892,0.8637,0.9928,0.8658 T0.9982,0.8706 T1,0.8758 L1,0.9878 Q1,0.9929,0.9951,0.9964 T0.9846,1 L0.8419,1 Q0.8352,1,0.8308,0.996 T0.8265,0.9878 L0.8265,0.8758 Q0.8265,0.8708,0.8314,0.8672 T0.8419,0.8637 Z M0.6509,0.169 L0.6509,0.2706 L0.7806,0.2706 L0.7806,0.169 L0.6509,0.169 Z M0.6442,0.159 L0.7868,0.159 Q0.7899,0.159,0.7917,0.1604 T0.7935,0.164 L0.7935,0.2756 Q0.7935,0.2781,0.7915,0.2796 T0.7868,0.281 L0.6442,0.281 Q0.6416,0.281,0.6395,0.2794 T0.6375,0.2756 L0.6375,0.164 Q0.6375,0.1619,0.6398,0.1604 T0.6442,0.159 Z M0.6632,0.6044 L0.6632,0.6858 L0.7678,0.6858 L0.7678,0.6044 L0.6632,0.6044 Z M0.6442,0.5742 L0.7868,0.5742 Q0.7951,0.5742,0.8007,0.5791 T0.8064,0.5893 L0.8064,0.7013 Q0.8064,0.7076,0.8002,0.712 T0.7868,0.7164 L0.6442,0.7164 Q0.6359,0.7164,0.6305,0.7114 T0.6251,0.7013 L0.6251,0.5893 Q0.6251,0.5847,0.6282,0.5812 T0.6357,0.5759 T0.6442,0.5742 Z M0.4264,0.164 L0.5695,0.164 L0.5695,0.2756 L0.4264,0.2756 L0.4264,0.164 Z M0.4325,0.315 L0.4325,0.4165 L0.5628,0.4165 L0.5628,0.315 L0.4325,0.315 Z M0.4264,0.3049 L0.5695,0.3049 Q0.5721,0.3049,0.5739,0.3064 T0.5757,0.31 L0.5757,0.4216 Q0.5757,0.4237,0.5736,0.4251 T0.5695,0.4266 L0.4264,0.4266 Q0.4238,0.4266,0.422,0.4251 T0.4202,0.4216 L0.4202,0.31 Q0.4202,0.3087,0.4207,0.3077 T0.4222,0.306 T0.4243,0.3052 T0.4264,0.3049 Z M0.4264,0.4476 L0.5695,0.4476 L0.5695,0.5596 L0.4264,0.5596 L0.4264,0.4476 Z M0.4392,0.7408 L0.4392,0.8326 L0.5561,0.8326 L0.5561,0.7408 L0.4392,0.7408 Z M0.4264,0.7206 L0.5695,0.7206 Q0.5747,0.7206,0.5783,0.724 T0.5819,0.7307 L0.5819,0.8427 Q0.5819,0.8469,0.5778,0.8498 T0.5695,0.8528 L0.4264,0.8528 Q0.4207,0.8528,0.4171,0.8496 T0.4135,0.8427 L0.4135,0.7307 Q0.4135,0.7265,0.4176,0.7236 T0.4264,0.7206 Z M0.2178,0.164 L0.3605,0.164 L0.3605,0.2756 L0.2178,0.2756 L0.2178,0.164 Z M0.2178,0.31 L0.3605,0.31 L0.3605,0.4216 L0.2178,0.4216 L0.2178,0.31 Z M0.2178,0.5893 L0.3605,0.5893 L0.3605,0.7013 L0.2178,0.7013 L0.2178,0.5893 Z M0.2178,0.7307 L0.3605,0.7307 L0.3605,0.8427 L0.2178,0.8427 L0.2178,0.7307 Z M0.2178,0.8758 L0.3605,0.8758 L0.3605,0.9878 L0.2178,0.9878 L0.2178,0.8758 Z M0,0.164 L0.1432,0.164 L0.1432,0.2756 L0,0.2756 L0,0.164 Z M0,0.31 L0.1432,0.31 L0.1432,0.4216 L0,0.4216 L0,0.31 Z M0,0.4476 L0.1432,0.4476 L0.1432,0.5596 L0,0.5596 L0,0.4476 Z M0,0.5893 L0.1432,0.5893 L0.1432,0.7013 L0,0.7013 L0,0.5893 Z M0,0.7307 L0.1432,0.7307 L0.1432,0.8427 L0,0.8427 L0,0.7307 Z M0,0.8758 L0.1432,0.8758 L0.1432,0.9878 L0,0.9878 L0,0.8758 Z",type:0}},"":{type:5,data:{d:"M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M0.1432,0.3217 L0.1432,0.4098 L0.0309,0.4098 L0.0309,0.3217 L0.1432,0.3217 Z M0.1586,0.2978 L0.0154,0.2978 Q0.0088,0.2978,0.0044,0.3016 T0,0.31 L0,0.4216 Q0,0.427,0.0049,0.4304 T0.0154,0.4337 L0.1586,0.4337 Q0.1648,0.4337,0.1694,0.4299 T0.174,0.4216 L0.174,0.31 Q0.174,0.3062,0.1715,0.3035 T0.1653,0.2993 T0.1586,0.2978 Z M0.1432,0.888 L0.1432,0.9757 L0.0309,0.9757 L0.0309,0.888 L0.1432,0.888 Z M0.1586,0.8637 L0.0154,0.8637 Q0.0108,0.8637,0.0072,0.8658 T0.0018,0.8706 T0,0.8758 L0,0.9878 Q0,0.9929,0.0049,0.9964 T0.0154,1 L0.1586,1 Q0.1648,1,0.1694,0.996 T0.174,0.9878 L0.174,0.8758 Q0.174,0.8725,0.1715,0.8695 T0.1653,0.8651 T0.1586,0.8637 Z M0.3496,0.169 L0.3496,0.2706 L0.2194,0.2706 L0.2194,0.169 L0.3496,0.169 Z M0.3563,0.159 L0.2132,0.159 Q0.2106,0.159,0.2088,0.1604 T0.207,0.164 L0.207,0.2756 Q0.207,0.2781,0.2091,0.2796 T0.2132,0.281 L0.3563,0.281 Q0.3589,0.281,0.3607,0.2794 T0.3625,0.2756 L0.3625,0.164 Q0.3625,0.1619,0.3605,0.1604 T0.3563,0.159 Z M0.3368,0.6044 L0.3368,0.6858 L0.2327,0.6858 L0.2327,0.6044 L0.3368,0.6044 Z M0.3563,0.5742 L0.2132,0.5742 Q0.2049,0.5742,0.1993,0.5791 T0.1936,0.5893 L0.1936,0.7013 Q0.1936,0.7076,0.2001,0.712 T0.2132,0.7164 L0.3563,0.7164 Q0.3641,0.7164,0.3697,0.7114 T0.3754,0.7013 L0.3754,0.5893 Q0.3754,0.5847,0.3723,0.5812 T0.3648,0.5759 T0.3563,0.5742 Z M0.5736,0.164 L0.431,0.164 L0.431,0.2756 L0.5736,0.2756 L0.5736,0.164 Z M0.5675,0.315 L0.5675,0.4165 L0.4377,0.4165 L0.4377,0.315 L0.5675,0.315 Z M0.5736,0.3049 L0.431,0.3049 Q0.4284,0.3049,0.4264,0.3064 T0.4243,0.31 L0.4243,0.4216 Q0.4243,0.4237,0.4266,0.4251 T0.431,0.4266 L0.5736,0.4266 Q0.5767,0.4266,0.5785,0.4251 T0.5803,0.4216 L0.5803,0.31 Q0.5803,0.3087,0.5798,0.3077 T0.5783,0.306 T0.5762,0.3052 T0.5736,0.3049 Z M0.5736,0.4476 L0.431,0.4476 L0.431,0.5596 L0.5736,0.5596 L0.5736,0.4476 Z M0.5613,0.7408 L0.5613,0.8326 L0.4439,0.8326 L0.4439,0.7408 L0.5613,0.7408 Z M0.5736,0.7206 L0.431,0.7206 Q0.4253,0.7206,0.4217,0.724 T0.4181,0.7307 L0.4181,0.8427 Q0.4181,0.8469,0.4222,0.8498 T0.431,0.8528 L0.5736,0.8528 Q0.5778,0.8528,0.5808,0.8511 T0.5855,0.8471 T0.587,0.8427 L0.587,0.7307 Q0.587,0.7265,0.5826,0.7236 T0.5736,0.7206 Z M0.7827,0.164 L0.6395,0.164 L0.6395,0.2756 L0.7827,0.2756 L0.7827,0.164 Z M0.7827,0.31 L0.6395,0.31 L0.6395,0.4216 L0.7827,0.4216 L0.7827,0.31 Z M0.7827,0.5893 L0.6395,0.5893 L0.6395,0.7013 L0.7827,0.7013 L0.7827,0.5893 Z M0.7827,0.7307 L0.6395,0.7307 L0.6395,0.8427 L0.7827,0.8427 L0.7827,0.7307 Z M0.7827,0.8758 L0.6395,0.8758 L0.6395,0.9878 L0.7827,0.9878 L0.7827,0.8758 Z M1,0.164 L0.8574,0.164 L0.8574,0.2756 L1,0.2756 L1,0.164 Z M1,0.31 L0.8574,0.31 L0.8574,0.4216 L1,0.4216 L1,0.31 Z M1,0.4476 L0.8574,0.4476 L0.8574,0.5596 L1,0.5596 L1,0.4476 Z M1,0.5893 L0.8574,0.5893 L0.8574,0.7013 L1,0.7013 L1,0.5893 Z M1,0.7307 L0.8574,0.7307 L0.8574,0.8427 L1,0.8427 L1,0.7307 Z M1,0.8758 L0.8574,0.8758 L0.8574,0.9878 L1,0.9878 L1,0.8758 Z",type:0}},"":{type:5,data:{d:"M0.0008,0.9979 Q0.0008,1,0.0032,1 Q0.0482,1,0.0602,0.9975 Q0.0667,0.9963,0.0847,0.9917 T0.1084,0.9859 Q0.1124,0.9851,0.1221,0.9851 L0.1253,0.9851 L0.1285,0.9851 Q0.1518,0.9851,0.1655,0.9809 Q0.1695,0.9801,0.1731,0.9788 T0.1791,0.9766 T0.1839,0.9747 T0.1888,0.9732 L0.1936,0.972 T0.1988,0.9712 T0.2048,0.971 L0.2096,0.971 Q0.2201,0.9714,0.2233,0.9714 T0.2345,0.9693 Q0.2386,0.9685,0.2502,0.9674 T0.2715,0.966 L0.2811,0.9656 Q0.2916,0.9647,0.2916,0.9573 Q0.2916,0.954,0.2892,0.9515 T0.2819,0.9486 Q0.2755,0.9482,0.2683,0.9482 Q0.2643,0.9482,0.2582,0.9484 T0.2498,0.9486 Q0.2426,0.9486,0.2402,0.9473 Q0.2386,0.9469,0.2317,0.943 T0.2161,0.937 Q0.2104,0.9357,0.1992,0.933 T0.1831,0.9291 Q0.1807,0.9287,0.1783,0.9285 T0.1739,0.928 T0.1703,0.9276 T0.1675,0.9272 T0.1655,0.9266 T0.1639,0.9253 Q0.1598,0.9216,0.1462,0.9216 L0.143,0.9216 L0.1398,0.9216 L0.1365,0.9216 Q0.1197,0.9195,0.1197,0.9154 L0.1197,0.9154 Q0.1205,0.9121,0.1373,0.9088 T0.1703,0.9054 Q0.1791,0.9054,0.1863,0.904 T0.1984,0.9011 T0.2064,0.8992 Q0.2402,0.8967,0.2506,0.8934 Q0.2538,0.8926,0.2602,0.8899 T0.2707,0.8872 Q0.2715,0.8872,0.2731,0.8876 Q0.2795,0.8884,0.2884,0.8884 Q0.3068,0.8884,0.3092,0.8826 L0.3092,0.8797 Q0.3092,0.8772,0.3076,0.8747 T0.3044,0.8706 T0.3028,0.8681 Q0.3076,0.8656,0.3237,0.8656 Q0.3317,0.8656,0.3622,0.8623 Q0.3655,0.8623,0.3867,0.8617 T0.4217,0.8602 Q0.4241,0.8598,0.4289,0.8598 L0.4345,0.8598 L0.441,0.8598 Q0.4578,0.8598,0.4667,0.8586 Q0.4739,0.8573,0.4851,0.8567 T0.5004,0.8552 Q0.5012,0.8552,0.5108,0.855 T0.5269,0.853 T0.5333,0.8461 Q0.5333,0.8445,0.5325,0.8432 T0.5309,0.8409 T0.5289,0.8391 T0.5261,0.8378 L0.5229,0.837 T0.5185,0.8362 T0.5133,0.8355 T0.5076,0.8349 T0.502,0.8341 Q0.4932,0.8324,0.4859,0.8324 Q0.4827,0.8324,0.4787,0.8328 T0.4731,0.8333 Q0.4707,0.8333,0.4683,0.8324 Q0.4482,0.825,0.4394,0.825 Q0.4369,0.825,0.4345,0.8254 Q0.4225,0.827,0.4153,0.827 Q0.4088,0.827,0.4064,0.8258 Q0.3976,0.8204,0.3751,0.8204 Q0.3703,0.8204,0.3667,0.8214 T0.3622,0.8225 Q0.3598,0.8225,0.3558,0.82 Q0.351,0.8175,0.3402,0.8167 T0.3177,0.8156 T0.3028,0.8146 L0.2956,0.8121 T0.2871,0.8094 T0.2771,0.8073 T0.2635,0.8063 Q0.261,0.8063,0.2586,0.8067 Q0.2378,0.8071,0.2273,0.8071 Q0.2072,0.8071,0.2024,0.8051 Q0.1976,0.8034,0.1932,0.8026 T0.1867,0.8013 T0.1847,0.8001 L0.1847,0.7993 Q0.1855,0.7984,0.1855,0.7978 T0.1859,0.7966 T0.1867,0.7959 T0.188,0.7955 T0.1896,0.7951 T0.1916,0.7949 T0.1944,0.7945 T0.1984,0.7941 T0.2032,0.7939 Q0.212,0.7926,0.2325,0.7918 T0.2562,0.7905 Q0.2691,0.7893,0.2787,0.7847 Q0.2835,0.7827,0.2968,0.7791 T0.3149,0.7756 Q0.3189,0.7756,0.3305,0.7733 T0.3446,0.771 L0.3454,0.771 Q0.3462,0.771,0.3498,0.7721 T0.3574,0.774 T0.3655,0.7748 Q0.3703,0.7748,0.3743,0.7731 T0.3823,0.7708 T0.3916,0.77 T0.3992,0.7694 Q0.4008,0.7694,0.4076,0.7688 T0.4205,0.7675 L0.4305,0.7665 Q0.4345,0.7657,0.4402,0.7617 T0.4458,0.7545 Q0.4458,0.7503,0.4353,0.7487 Q0.4297,0.7478,0.4209,0.7462 T0.4044,0.7433 T0.3904,0.7416 L0.3847,0.7416 Q0.3807,0.7416,0.3747,0.7422 T0.3663,0.7428 T0.3606,0.7424 Q0.3582,0.742,0.3562,0.7418 T0.3522,0.7412 T0.3482,0.7406 T0.3446,0.7401 T0.341,0.7397 T0.3373,0.7393 T0.3341,0.7391 L0.3293,0.7391 Q0.3277,0.7395,0.3253,0.7395 Q0.3205,0.7395,0.3052,0.7387 T0.2835,0.7379 Q0.2755,0.7379,0.253,0.7325 Q0.2506,0.7316,0.2462,0.731 T0.2382,0.7296 T0.2305,0.7271 T0.2181,0.7234 T0.2048,0.7196 T0.2,0.7155 Q0.2,0.7142,0.2016,0.713 Q0.208,0.7059,0.2285,0.6978 T0.2618,0.6898 Q0.2739,0.6898,0.2831,0.6848 T0.2956,0.6794 Q0.3028,0.6786,0.3289,0.6765 T0.3566,0.674 Q0.3582,0.674,0.3855,0.6723 T0.4406,0.6688 T0.4755,0.6653 Q0.5004,0.6607,0.5124,0.6599 L0.5165,0.6599 Q0.5213,0.6599,0.5277,0.6605 T0.5373,0.6611 Q0.543,0.6611,0.5494,0.6599 Q0.592,0.6524,0.6,0.6524 Q0.6064,0.6524,0.61,0.6499 T0.6161,0.6474 Q0.6177,0.6474,0.6261,0.6495 T0.6418,0.6516 L0.6482,0.6516 Q0.653,0.6512,0.6651,0.6506 T0.6876,0.6493 T0.7084,0.6477 T0.7229,0.645 Q0.7269,0.6437,0.7333,0.6437 Q0.7373,0.6437,0.7458,0.6443 T0.7574,0.645 Q0.7614,0.645,0.7631,0.6445 T0.7655,0.6441 Q0.7671,0.6441,0.7723,0.6448 T0.7823,0.6454 Q0.788,0.6454,0.7952,0.6445 Q0.8233,0.6408,0.8723,0.6367 Q0.9012,0.6342,0.9092,0.6342 L0.9165,0.6342 L0.9205,0.6342 Q0.9277,0.6342,0.9382,0.6323 T0.9526,0.6304 Q0.9534,0.6304,0.9594,0.6307 T0.9695,0.6309 Q0.9976,0.6309,0.9992,0.6234 Q1,0.6201,1,0.618 Q1,0.6089,0.9775,0.608 Q0.9703,0.6076,0.9582,0.6076 Q0.9518,0.6076,0.9394,0.6078 T0.9213,0.608 Q0.9036,0.608,0.8972,0.6072 Q0.894,0.6068,0.8871,0.6058 T0.8751,0.6039 T0.8627,0.6024 T0.8506,0.6018 L0.8474,0.6018 Q0.841,0.6022,0.8281,0.6041 T0.8112,0.606 Q0.8096,0.606,0.808,0.6056 Q0.7783,0.6002,0.7647,0.6002 Q0.7598,0.6002,0.7454,0.6006 T0.7261,0.601 Q0.7221,0.601,0.7145,0.6022 T0.7036,0.6035 Q0.6996,0.6035,0.6964,0.6022 Q0.6723,0.5902,0.6442,0.5902 Q0.6426,0.5902,0.6386,0.5904 T0.6337,0.5906 Q0.6273,0.5906,0.6249,0.5894 L0.6177,0.5856 T0.6116,0.5838 T0.6016,0.5825 T0.5855,0.5823 Q0.5719,0.5823,0.5574,0.5798 T0.5373,0.5774 L0.5341,0.5774 Q0.5293,0.5778,0.5213,0.5786 T0.51,0.5794 Q0.5036,0.5794,0.4988,0.5769 Q0.4932,0.574,0.4771,0.574 Q0.4723,0.574,0.4631,0.5745 T0.4498,0.5749 Q0.4418,0.5749,0.4394,0.5736 Q0.4353,0.5724,0.4305,0.5715 T0.4225,0.5707 T0.4145,0.5705 T0.4056,0.5699 Q0.4008,0.5691,0.398,0.5689 T0.394,0.5689 T0.3908,0.5686 T0.3855,0.5674 Q0.3831,0.567,0.3811,0.5662 T0.3779,0.5645 T0.3743,0.563 T0.3695,0.5624 Q0.3655,0.5624,0.3594,0.5635 T0.3494,0.5645 T0.3406,0.5635 T0.3325,0.5624 Q0.3309,0.5624,0.3301,0.5628 L0.3141,0.5628 Q0.2635,0.5628,0.2506,0.5612 Q0.2474,0.5608,0.2434,0.5608 Q0.2402,0.5608,0.2349,0.561 T0.2273,0.5612 Q0.2209,0.5612,0.2177,0.5595 Q0.2145,0.557,0.2145,0.5558 Q0.2169,0.5537,0.2345,0.5521 Q0.2876,0.5475,0.3028,0.5425 Q0.3068,0.5413,0.3149,0.5396 T0.3309,0.5367 T0.3478,0.5338 T0.3606,0.5309 Q0.3631,0.5305,0.3755,0.5259 T0.3968,0.5214 Q0.3992,0.5214,0.4024,0.5218 T0.4096,0.5222 Q0.4161,0.5222,0.4213,0.5209 T0.4313,0.5185 T0.4402,0.5172 Q0.4418,0.5168,0.447,0.5168 L0.4558,0.5168 T0.4639,0.5162 T0.4707,0.5141 T0.4731,0.5102 Q0.4731,0.5089,0.4723,0.5081 Q0.4699,0.5019,0.4627,0.4994 T0.4369,0.4965 Q0.4273,0.4961,0.4193,0.4946 T0.4048,0.4915 T0.3952,0.4894 Q0.392,0.4886,0.388,0.4886 Q0.3847,0.4886,0.3775,0.4892 T0.3647,0.4898 Q0.3598,0.4898,0.355,0.4894 Q0.3165,0.4861,0.3141,0.4853 Q0.2779,0.4774,0.2715,0.4774 Q0.2699,0.4774,0.2683,0.4776 T0.2627,0.4778 Q0.2498,0.4778,0.2281,0.4762 Q0.2241,0.4749,0.2233,0.4737 Q0.2249,0.472,0.2321,0.4708 Q0.2402,0.4695,0.2554,0.4695 L0.2675,0.4695 L0.2795,0.4695 Q0.294,0.4695,0.2996,0.4679 Q0.3141,0.4629,0.3373,0.4616 Q0.3414,0.4612,0.3466,0.4606 T0.3582,0.4589 T0.3687,0.4562 T0.3727,0.4525 Q0.3727,0.4509,0.3703,0.4492 Q0.3639,0.4455,0.3474,0.4419 T0.3213,0.4384 L0.3157,0.4384 L0.31,0.4384 Q0.294,0.4384,0.2859,0.4363 Q0.2795,0.4347,0.2691,0.4347 L0.2618,0.4347 L0.2546,0.4347 Q0.2458,0.4347,0.2394,0.4338 Q0.2257,0.4318,0.2193,0.4303 T0.2092,0.4266 T0.2052,0.4224 T0.2024,0.4154 T0.196,0.4052 Q0.1912,0.3994,0.1867,0.3949 T0.1807,0.3884 T0.1791,0.3849 Q0.1791,0.3824,0.1839,0.3745 Q0.1871,0.3687,0.1944,0.3637 T0.2072,0.3561 T0.2221,0.3501 T0.2321,0.3463 Q0.2353,0.3455,0.241,0.3445 T0.2522,0.3428 T0.2639,0.3411 T0.2731,0.3384 T0.2956,0.3351 T0.3197,0.3326 Q0.3213,0.3322,0.3237,0.3322 T0.3325,0.3331 T0.3414,0.3339 Q0.3478,0.3339,0.3518,0.3314 Q0.3606,0.3264,0.3703,0.3264 Q0.3775,0.3264,0.3847,0.3293 Q0.3888,0.331,0.396,0.331 Q0.4024,0.331,0.4116,0.3295 T0.4265,0.3266 T0.4414,0.3227 T0.4514,0.3202 Q0.4578,0.3181,0.4839,0.3152 T0.5112,0.3123 T0.5177,0.3119 T0.5285,0.3111 T0.5398,0.3096 T0.549,0.3065 T0.5526,0.3015 Q0.5526,0.2999,0.5518,0.2982 Q0.547,0.2903,0.5386,0.2883 T0.5165,0.2862 Q0.5116,0.2862,0.5056,0.2866 T0.4972,0.287 Q0.4884,0.287,0.4787,0.2833 Q0.4594,0.2758,0.4265,0.2758 Q0.4169,0.2758,0.4129,0.2766 Q0.4112,0.2771,0.4104,0.2771 Q0.4088,0.2771,0.4056,0.2748 T0.3968,0.2721 Q0.3695,0.2696,0.359,0.2659 Q0.355,0.2646,0.351,0.2646 T0.3426,0.2661 T0.3365,0.2675 T0.3333,0.2659 Q0.3277,0.2605,0.3116,0.2553 T0.2859,0.2501 L0.2843,0.2501 L0.2819,0.2501 Q0.2779,0.2501,0.2723,0.2493 T0.2586,0.2472 T0.2474,0.2455 Q0.1799,0.236,0.1719,0.236 Q0.1663,0.236,0.1606,0.235 T0.1502,0.2316 T0.1454,0.2265 Q0.1454,0.2223,0.1558,0.2173 Q0.1679,0.2115,0.1859,0.2092 T0.2185,0.207 T0.2353,0.2057 Q0.2369,0.2049,0.2502,0.2041 T0.2799,0.2022 T0.302,0.2007 Q0.3084,0.1999,0.3245,0.1954 T0.347,0.1908 Q0.3502,0.1908,0.3534,0.1916 Q0.3663,0.197,0.388,0.197 Q0.404,0.197,0.4088,0.1929 Q0.4096,0.192,0.4108,0.192 T0.4177,0.1945 T0.4277,0.197 T0.4369,0.1949 Q0.4442,0.1908,0.4843,0.1875 Q0.4892,0.1871,0.4968,0.1839 T0.5084,0.1808 L0.5108,0.1808 Q0.5213,0.1825,0.5454,0.1825 Q0.5823,0.1825,0.5992,0.1779 Q0.6096,0.1746,0.6217,0.1746 Q0.6249,0.1746,0.6309,0.1748 T0.6394,0.175 Q0.6434,0.175,0.6466,0.1746 Q0.6474,0.1746,0.6594,0.1738 T0.6787,0.1713 T0.6892,0.1659 Q0.6924,0.1634,0.6924,0.1593 Q0.6924,0.1547,0.6888,0.151 T0.6795,0.1472 Q0.6779,0.1472,0.6763,0.1477 Q0.6699,0.1493,0.6667,0.1493 Q0.661,0.1493,0.6506,0.1456 Q0.6329,0.1394,0.6129,0.1394 Q0.6048,0.1394,0.5992,0.1377 T0.5888,0.136 T0.5803,0.1377 T0.5751,0.1394 Q0.5711,0.1394,0.5639,0.1369 Q0.5365,0.1273,0.5116,0.1273 Q0.4876,0.1273,0.4667,0.1253 Q0.4627,0.1248,0.4542,0.1211 T0.4337,0.1174 L0.4305,0.1174 Q0.4217,0.1178,0.4153,0.119 T0.408,0.1203 Q0.4056,0.1203,0.4,0.117 Q0.3976,0.1153,0.396,0.1136 T0.3932,0.1112 T0.39,0.1099 T0.3847,0.1095 Q0.3799,0.1095,0.3687,0.1103 Q0.355,0.1112,0.3434,0.1141 T0.3301,0.117 Q0.3261,0.117,0.3229,0.1145 Q0.3181,0.1116,0.3052,0.1087 T0.2787,0.1043 T0.2546,0.1029 Q0.2506,0.1029,0.2474,0.1033 Q0.2418,0.1037,0.2349,0.1054 T0.2249,0.107 Q0.2225,0.107,0.2193,0.1066 Q0.2024,0.1024,0.1863,0.1024 Q0.1823,0.1024,0.1562,0.0971 T0.1269,0.0917 T0.1161,0.0896 T0.106,0.0854 Q0.1076,0.0846,0.11,0.0842 Q0.1173,0.0821,0.1261,0.0821 Q0.1301,0.0821,0.1369,0.0825 T0.1462,0.083 Q0.1494,0.083,0.151,0.0825 T0.1831,0.0813 T0.2201,0.0784 T0.243,0.074 T0.2667,0.0718 Q0.2707,0.0718,0.2755,0.0724 T0.2843,0.073 T0.2936,0.0724 T0.3024,0.0705 T0.3072,0.068 T0.3092,0.0657 T0.3108,0.0647 Q0.3116,0.0643,0.3133,0.0643 L0.3157,0.0643 L0.3181,0.0643 Q0.3446,0.0643,0.3446,0.0556 T0.3205,0.0469 L0.3189,0.0469 Q0.3157,0.0469,0.3157,0.0465 Q0.3084,0.0427,0.2835,0.0386 Q0.2739,0.0369,0.2675,0.0342 T0.2538,0.0299 Q0.249,0.029,0.245,0.029 T0.2378,0.0303 T0.2321,0.0315 Q0.2305,0.0315,0.2273,0.0307 Q0.2201,0.0286,0.2004,0.0272 T0.1775,0.0245 Q0.1735,0.0228,0.1663,0.0226 T0.1522,0.0197 T0.1345,0.0145 T0.1124,0.0079 Q0.0996,0.0033,0.0671,0.0044 T0.0297,0.0041 Q0.0169,0,0.0024,0.0017 Q0,0.0021,0,0.0037 Z M0.0064,0.9954 L0.0056,0.0058 Q0.0177,0.005,0.0281,0.0083 Q0.0345,0.01,0.0675,0.0089 T0.1108,0.012 Q0.1221,0.0162,0.1329,0.0187 T0.1498,0.0236 T0.1606,0.0268 T0.1691,0.0274 T0.1759,0.0286 Q0.1807,0.0303,0.2,0.0315 T0.2257,0.0348 Q0.2305,0.0361,0.2337,0.0361 Q0.2361,0.0361,0.2398,0.0348 T0.2466,0.0336 Q0.249,0.0336,0.2522,0.034 Q0.2586,0.0353,0.2655,0.0382 T0.2827,0.0427 Q0.3068,0.0469,0.3124,0.0502 Q0.3157,0.0523,0.3237,0.0523 L0.3277,0.0523 L0.3309,0.0523 Q0.3398,0.0523,0.3398,0.0556 Q0.3398,0.0581,0.3341,0.0587 T0.3205,0.0593 T0.3092,0.0603 T0.3036,0.0643 T0.2932,0.068 Q0.2884,0.0684,0.2843,0.0684 Q0.2811,0.0684,0.2763,0.0678 T0.2667,0.0672 Q0.2586,0.0672,0.2422,0.0697 T0.2177,0.0747 Q0.2137,0.0759,0.1831,0.0767 T0.1494,0.0784 L0.1474,0.0784 T0.1398,0.078 T0.1285,0.0776 Q0.1173,0.0776,0.1084,0.08 Q0.1004,0.0817,0.1004,0.0846 Q0.1004,0.0867,0.104,0.0888 T0.1124,0.0923 T0.1213,0.0948 T0.1269,0.0958 T0.155,0.1014 T0.1863,0.107 Q0.2016,0.107,0.2185,0.1107 Q0.2217,0.1116,0.2257,0.1116 Q0.2289,0.1116,0.2365,0.1099 T0.2482,0.1074 L0.2538,0.1074 Q0.2683,0.1074,0.2912,0.1107 T0.3197,0.1182 Q0.3245,0.1215,0.3301,0.1215 Q0.3333,0.1215,0.3454,0.1184 T0.3687,0.1145 Q0.3735,0.1141,0.3779,0.1139 T0.3843,0.1134 T0.3871,0.1132 Q0.3896,0.1132,0.39,0.1136 T0.392,0.1161 T0.3968,0.1203 Q0.404,0.1248,0.408,0.1248 Q0.4096,0.1248,0.4165,0.1234 T0.4305,0.1215 L0.4337,0.1215 Q0.4442,0.1215,0.4518,0.1251 T0.4659,0.1294 Q0.4876,0.1319,0.5116,0.1319 T0.5622,0.141 Q0.5703,0.1439,0.5751,0.1439 Q0.5791,0.1439,0.5831,0.1423 T0.5888,0.1406 Q0.592,0.1406,0.5944,0.1412 T0.6012,0.1427 T0.6129,0.1435 Q0.6313,0.1435,0.649,0.1497 Q0.6602,0.1535,0.6667,0.1535 Q0.6715,0.1535,0.6779,0.1522 Q0.6787,0.1518,0.6795,0.1518 Q0.6827,0.1518,0.6847,0.1541 T0.6867,0.1593 Q0.6867,0.1618,0.6851,0.1634 Q0.6835,0.1655,0.6775,0.1667 T0.6598,0.169 T0.6458,0.1705 T0.6402,0.1709 Q0.6378,0.1709,0.6321,0.1705 T0.6225,0.1701 Q0.6096,0.1701,0.5968,0.1738 Q0.5823,0.1779,0.5446,0.1779 Q0.5205,0.1779,0.5116,0.1767 Q0.51,0.1763,0.5084,0.1763 Q0.5028,0.1763,0.4944,0.1796 T0.4835,0.1829 L0.4771,0.1833 T0.4659,0.1844 L0.4546,0.1858 T0.443,0.1881 T0.4337,0.1912 Q0.4321,0.1916,0.4305,0.1916 Q0.4273,0.1916,0.4209,0.1895 T0.412,0.1875 Q0.408,0.1875,0.4056,0.19 Q0.4024,0.1925,0.388,0.1925 Q0.3663,0.1925,0.3558,0.1879 Q0.3518,0.1862,0.3462,0.1862 Q0.3373,0.1862,0.3213,0.191 T0.3012,0.1962 Q0.2964,0.1966,0.2799,0.1976 T0.2494,0.1997 T0.2313,0.2024 L0.2313,0.2024 L0.2293,0.2024 L0.2261,0.2024 L0.2217,0.2024 Q0.204,0.2024,0.1851,0.2047 T0.1526,0.2136 Q0.1406,0.2198,0.1406,0.226 Q0.1406,0.2319,0.1518,0.2362 T0.1719,0.2406 Q0.1791,0.2406,0.2466,0.2497 Q0.2498,0.2501,0.2574,0.2516 T0.2711,0.2538 T0.2819,0.2547 L0.2851,0.2547 Q0.2851,0.2543,0.2859,0.2543 Q0.294,0.2543,0.3096,0.2592 T0.3285,0.2684 Q0.3317,0.2721,0.3373,0.2721 Q0.3406,0.2721,0.3462,0.2708 T0.3542,0.2696 Q0.3558,0.2696,0.3574,0.27 Q0.3679,0.2737,0.3968,0.2762 Q0.3984,0.2766,0.4004,0.2779 L0.4044,0.2804 T0.4096,0.2816 Q0.412,0.2816,0.4145,0.2808 Q0.4177,0.2804,0.4249,0.2804 Q0.4586,0.2804,0.4763,0.287 Q0.4867,0.2912,0.4972,0.2912 Q0.5004,0.2912,0.5064,0.2908 T0.5165,0.2903 Q0.5293,0.2903,0.5361,0.2922 T0.547,0.3003 L0.547,0.3011 Q0.547,0.3036,0.5414,0.3049 T0.5249,0.3067 T0.51,0.3082 Q0.5092,0.3082,0.4831,0.3111 T0.4498,0.3161 Q0.408,0.3264,0.3952,0.3264 Q0.3896,0.3264,0.3863,0.3252 Q0.3783,0.3223,0.3703,0.3223 Q0.359,0.3223,0.3494,0.3277 Q0.347,0.3293,0.343,0.3293 Q0.3414,0.3293,0.3353,0.3285 T0.3253,0.3277 T0.3181,0.3285 Q0.3149,0.3289,0.2952,0.3306 T0.2699,0.3347 Q0.2675,0.3364,0.2598,0.3372 T0.2434,0.3395 T0.2297,0.3426 L0.2205,0.3461 T0.2048,0.3523 T0.1908,0.3606 T0.1791,0.3725 Q0.1743,0.3803,0.1743,0.3845 Q0.1743,0.3874,0.1763,0.3901 T0.1827,0.3976 T0.1912,0.4073 T0.198,0.4189 T0.2032,0.4276 T0.2137,0.4326 T0.2386,0.438 Q0.2458,0.4392,0.2562,0.4392 L0.2639,0.4392 L0.2699,0.4392 Q0.2795,0.4392,0.2843,0.4405 Q0.2932,0.443,0.3092,0.443 L0.3157,0.443 L0.3213,0.443 Q0.3293,0.443,0.3458,0.4463 T0.3671,0.4525 Q0.3598,0.4558,0.3373,0.4571 Q0.3124,0.4587,0.298,0.4637 Q0.294,0.465,0.2811,0.465 L0.2703,0.465 L0.2586,0.465 Q0.241,0.465,0.2305,0.4666 Q0.2185,0.4687,0.2185,0.4728 Q0.2185,0.4745,0.2205,0.4764 T0.2241,0.4791 L0.2265,0.4803 L0.2273,0.4803 Q0.2506,0.4824,0.261,0.4824 Q0.2675,0.4824,0.2699,0.482 Q0.2699,0.4815,0.2707,0.4815 Q0.2771,0.4815,0.3124,0.4898 Q0.3173,0.4907,0.3229,0.4913 T0.3386,0.4925 T0.3542,0.4936 T0.3663,0.494 Q0.3711,0.494,0.3787,0.4936 T0.3888,0.4932 Q0.392,0.4932,0.3944,0.4936 T0.4032,0.4959 T0.4181,0.499 T0.4369,0.5006 Q0.449,0.501,0.455,0.5021 T0.4639,0.5048 T0.4675,0.5093 L0.4675,0.5097 Q0.4675,0.5106,0.4663,0.511 T0.4622,0.5116 L0.4566,0.512 T0.4486,0.5124 T0.4402,0.5127 Q0.4345,0.5131,0.4257,0.5153 T0.4096,0.5176 Q0.4064,0.5176,0.4024,0.5172 L0.3968,0.5172 Q0.3863,0.5172,0.3731,0.522 T0.359,0.5268 Q0.355,0.528,0.3317,0.5321 T0.3004,0.5388 Q0.2867,0.5433,0.2337,0.5479 Q0.2096,0.55,0.2096,0.5562 Q0.2096,0.5591,0.2145,0.5628 Q0.2193,0.5662,0.2289,0.5662 Q0.2313,0.5662,0.2373,0.5657 T0.2458,0.5653 L0.2498,0.5653 Q0.2635,0.5674,0.3124,0.5674 Q0.3261,0.5674,0.3301,0.567 L0.3317,0.567 Q0.3341,0.567,0.3394,0.568 T0.3486,0.5691 Q0.3542,0.5691,0.3606,0.5678 T0.3699,0.5666 T0.3759,0.5686 T0.3839,0.5718 T0.3908,0.573 T0.3964,0.5734 T0.4048,0.5742 T0.4165,0.5751 T0.4277,0.5757 T0.4369,0.5778 Q0.4426,0.5794,0.4538,0.5794 Q0.4586,0.5794,0.4679,0.5792 T0.4811,0.579 Q0.4924,0.579,0.4956,0.5807 Q0.502,0.584,0.5108,0.584 L0.5137,0.584 T0.5173,0.5838 L0.5205,0.5834 L0.5237,0.583 L0.5269,0.5825 T0.5305,0.5821 T0.5341,0.5819 L0.5365,0.5819 Q0.5414,0.5819,0.5562,0.5842 T0.5855,0.5865 Q0.5912,0.5865,0.5948,0.5867 T0.6012,0.5869 T0.6064,0.5873 T0.61,0.5877 T0.6133,0.5886 T0.6157,0.5896 L0.6185,0.591 T0.6217,0.5931 Q0.6265,0.5952,0.6369,0.5952 L0.6418,0.5952 L0.6466,0.5952 Q0.6723,0.5952,0.6932,0.606 Q0.698,0.608,0.7044,0.608 Q0.7084,0.608,0.7161,0.6068 T0.7261,0.6056 Q0.7309,0.6056,0.7454,0.6051 T0.7647,0.6047 Q0.7775,0.6047,0.8072,0.6101 Q0.8096,0.6105,0.812,0.6105 Q0.8177,0.6105,0.8297,0.6085 T0.8474,0.606 L0.8506,0.606 Q0.8562,0.606,0.8647,0.607 T0.8831,0.6095 T0.8964,0.6118 Q0.9036,0.6122,0.9221,0.6122 L0.9406,0.6122 L0.959,0.6122 L0.9767,0.6122 Q0.9952,0.613,0.9952,0.6172 Q0.9952,0.6176,0.9944,0.6221 Q0.9936,0.6259,0.9574,0.6259 L0.955,0.6259 L0.9526,0.6259 Q0.9478,0.6259,0.9373,0.628 T0.9205,0.63 L0.9173,0.63 Q0.9133,0.6296,0.9084,0.6296 Q0.9004,0.6296,0.8715,0.6321 Q0.8233,0.6367,0.7944,0.64 Q0.7888,0.6408,0.7839,0.6408 T0.7739,0.6402 T0.7671,0.6396 Q0.7639,0.6396,0.7622,0.64 Q0.7614,0.6404,0.759,0.6404 Q0.7574,0.6404,0.749,0.6398 T0.7357,0.6392 Q0.7261,0.6392,0.7213,0.6412 Q0.7173,0.6425,0.7032,0.6437 T0.6711,0.6458 T0.6474,0.647 Q0.645,0.6474,0.6418,0.6474 Q0.6353,0.6474,0.6277,0.6454 T0.6161,0.6433 Q0.6104,0.6433,0.6072,0.6456 T0.6,0.6479 Q0.5912,0.6479,0.5486,0.6557 Q0.5422,0.657,0.5373,0.657 Q0.5349,0.657,0.5289,0.6564 T0.5173,0.6557 L0.5124,0.6557 Q0.4996,0.6562,0.4739,0.6611 Q0.4675,0.6624,0.4398,0.6645 T0.3851,0.668 T0.3558,0.6698 Q0.355,0.6698,0.3285,0.6721 T0.2948,0.6752 Q0.2892,0.6761,0.2843,0.6786 T0.2747,0.6831 T0.2618,0.6852 Q0.253,0.6852,0.2394,0.6893 T0.2141,0.6993 T0.1968,0.7105 Q0.1944,0.713,0.1944,0.7155 Q0.1944,0.7196,0.2012,0.7229 T0.2177,0.7285 T0.2281,0.7308 Q0.2321,0.7329,0.2365,0.7339 T0.245,0.7356 T0.2514,0.7366 Q0.2522,0.737,0.2554,0.7379 T0.2614,0.7393 T0.2679,0.7406 T0.2755,0.7416 T0.2835,0.742 Q0.29,0.742,0.3048,0.7428 T0.3253,0.7437 L0.3301,0.7437 L0.3333,0.7437 Q0.3341,0.7437,0.3598,0.7466 Q0.3639,0.7474,0.3671,0.7474 T0.3759,0.7466 T0.3855,0.7457 Q0.388,0.7457,0.3904,0.7462 Q0.3984,0.7466,0.4137,0.7495 T0.4349,0.7532 T0.441,0.7557 Q0.441,0.7599,0.4289,0.7619 Q0.4257,0.7628,0.4197,0.7634 T0.4072,0.7644 T0.3984,0.7652 Q0.3968,0.7652,0.3912,0.7655 T0.3811,0.7665 T0.3719,0.7694 Q0.3695,0.7702,0.3655,0.7702 T0.3546,0.7686 T0.3462,0.7665 L0.3446,0.7665 Q0.3406,0.7665,0.3293,0.769 T0.3149,0.7715 Q0.3084,0.7715,0.2952,0.7748 T0.2763,0.781 Q0.2675,0.7847,0.2554,0.7864 Q0.253,0.7864,0.2325,0.7874 T0.2024,0.7893 Q0.2008,0.7893,0.1984,0.7897 T0.1948,0.7901 T0.1916,0.7903 T0.1888,0.7908 T0.1867,0.7914 T0.1847,0.7922 L0.1831,0.793 T0.1819,0.7943 L0.1811,0.7959 T0.1799,0.7976 Q0.1791,0.7993,0.1791,0.8001 Q0.1791,0.8034,0.1831,0.8051 T0.1932,0.8078 T0.2,0.8092 Q0.2072,0.8117,0.2257,0.8117 Q0.2337,0.8117,0.2586,0.8109 L0.2635,0.8109 Q0.2707,0.8109,0.2767,0.8117 T0.2859,0.8136 T0.2936,0.8163 T0.3012,0.8187 Q0.3068,0.82,0.3277,0.8206 T0.3526,0.8237 Q0.3582,0.8266,0.3622,0.8266 Q0.3647,0.8266,0.3687,0.8258 T0.3751,0.825 Q0.396,0.825,0.404,0.8291 Q0.408,0.8316,0.4161,0.8316 Q0.4217,0.8316,0.4353,0.8295 L0.4394,0.8295 Q0.4466,0.8295,0.4659,0.8366 Q0.4699,0.8378,0.4747,0.8378 Q0.4763,0.8378,0.4807,0.8374 T0.4884,0.837 Q0.494,0.837,0.5004,0.8382 Q0.5052,0.8391,0.5124,0.8399 Q0.5221,0.8411,0.5249,0.8422 T0.5277,0.8461 Q0.5277,0.8482,0.5233,0.849 T0.5112,0.8501 T0.4996,0.8511 Q0.4964,0.8519,0.4851,0.8523 T0.4659,0.8544 Q0.4578,0.8557,0.4402,0.8557 L0.4349,0.8557 L0.4297,0.8557 L0.4209,0.8557 Q0.408,0.8565,0.3867,0.8571 T0.3614,0.8582 Q0.3317,0.8611,0.3237,0.8611 L0.3225,0.8611 L0.3213,0.8611 Q0.2972,0.8611,0.2972,0.8681 Q0.2972,0.8714,0.3008,0.8747 T0.3044,0.8805 Q0.3044,0.881,0.3036,0.8814 Q0.3012,0.8839,0.2851,0.8839 Q0.2779,0.8839,0.2739,0.883 Q0.2723,0.8826,0.2699,0.8826 T0.2643,0.8835 T0.259,0.8853 T0.2542,0.8876 T0.249,0.8893 Q0.2386,0.8922,0.2056,0.8946 Q0.2016,0.8951,0.1916,0.898 T0.1703,0.9009 Q0.1518,0.9009,0.1337,0.9044 T0.1149,0.9146 L0.1149,0.9158 Q0.1149,0.9175,0.1157,0.9187 T0.1173,0.921 T0.1201,0.9226 T0.1233,0.9237 T0.1269,0.9245 L0.1305,0.9251 T0.1337,0.9255 L0.1357,0.9258 Q0.139,0.9262,0.1446,0.9262 T0.1542,0.9266 T0.1598,0.9282 Q0.1614,0.9303,0.1647,0.9314 T0.1739,0.9328 T0.1815,0.9336 Q0.1863,0.9345,0.1976,0.9372 T0.2145,0.9415 Q0.2225,0.9432,0.2285,0.9467 T0.2378,0.9515 Q0.2426,0.9531,0.2514,0.9531 Q0.2538,0.9531,0.2602,0.9529 T0.2707,0.9527 Q0.2763,0.9527,0.2815,0.9531 T0.2867,0.9569 T0.2811,0.9614 Q0.2434,0.9627,0.2329,0.9652 Q0.2249,0.9672,0.2241,0.9672 L0.2096,0.9668 L0.2056,0.9668 Q0.2,0.9668,0.196,0.9672 T0.1884,0.9687 T0.1815,0.9708 T0.1731,0.9737 T0.1639,0.9772 Q0.1518,0.9805,0.1285,0.9805 L0.1253,0.9805 Q0.1124,0.9805,0.1076,0.9818 Q0.1012,0.983,0.0831,0.9876 T0.0594,0.9934 Q0.049,0.9954,0.0064,0.9954 Z M0.0032,0.9979 L0.0024,0.0037 Q0.0161,0.0021,0.0289,0.0062 Q0.0337,0.0075,0.0671,0.0066 T0.1116,0.01 T0.1337,0.0166 T0.151,0.022 Q0.1582,0.0249,0.1659,0.0251 T0.1767,0.0265 Q0.1807,0.0278,0.2,0.0292 T0.2265,0.0328 Q0.2305,0.034,0.2329,0.034 T0.239,0.0326 T0.2458,0.0311 T0.253,0.0319 Q0.2578,0.0332,0.2614,0.0342 T0.2667,0.0363 T0.2723,0.0384 T0.2827,0.0406 Q0.3084,0.0448,0.3141,0.0485 Q0.3149,0.0494,0.3225,0.0494 T0.3361,0.0504 T0.3422,0.0554 T0.3357,0.0606 T0.3205,0.0618 T0.31,0.0626 Q0.3092,0.0626,0.3056,0.0659 T0.2932,0.0701 Q0.2884,0.0709,0.2843,0.0709 Q0.2811,0.0709,0.2759,0.0701 T0.2667,0.0693 Q0.2586,0.0693,0.2422,0.0718 T0.2193,0.0763 Q0.2137,0.0784,0.1831,0.079 T0.1502,0.0805 Q0.1494,0.0809,0.147,0.0809 Q0.1454,0.0809,0.1386,0.0803 T0.1277,0.0796 Q0.1173,0.0796,0.1092,0.0821 Q0.1036,0.0834,0.1036,0.0854 Q0.1036,0.0879,0.1129,0.0908 T0.1269,0.0937 Q0.1293,0.0937,0.1558,0.0991 T0.1863,0.1045 Q0.2016,0.1045,0.2193,0.1087 Q0.2225,0.1091,0.2249,0.1091 Q0.2289,0.1091,0.2357,0.1076 T0.2482,0.1054 Q0.2506,0.1049,0.2546,0.1049 Q0.2699,0.1049,0.2924,0.1085 T0.3213,0.1165 Q0.3253,0.119,0.3301,0.119 Q0.3325,0.119,0.3446,0.1161 T0.3687,0.1124 Q0.3831,0.1112,0.3863,0.1112 T0.3908,0.1118 T0.3936,0.1145 T0.3984,0.1186 Q0.4048,0.1228,0.408,0.1228 Q0.4096,0.1228,0.4161,0.1213 T0.4305,0.1195 L0.4337,0.1195 Q0.4426,0.1195,0.4474,0.1211 T0.4566,0.1246 T0.4667,0.1273 Q0.4876,0.1298,0.5116,0.1298 Q0.5365,0.1298,0.5631,0.1389 Q0.5703,0.1414,0.5751,0.1414 Q0.5783,0.1414,0.5819,0.1398 T0.5888,0.1381 Q0.5928,0.1381,0.5984,0.1398 T0.6129,0.1414 Q0.6321,0.1414,0.6498,0.1477 Q0.661,0.1514,0.6667,0.1514 Q0.6707,0.1514,0.6771,0.1501 Q0.6787,0.1497,0.6795,0.1497 Q0.6835,0.1497,0.6863,0.1526 T0.6892,0.1593 Q0.6892,0.1626,0.6876,0.1647 Q0.6851,0.1672,0.6799,0.1686 T0.6695,0.1705 T0.6566,0.1715 T0.6458,0.1725 Q0.6434,0.173,0.6402,0.173 Q0.6378,0.173,0.6317,0.1727 T0.6225,0.1725 Q0.6096,0.1725,0.5984,0.1759 Q0.5823,0.1804,0.5454,0.1804 Q0.5205,0.1804,0.5116,0.1788 L0.5084,0.1788 Q0.5036,0.1788,0.4956,0.1819 T0.4843,0.185 Q0.4434,0.1887,0.4353,0.1929 Q0.4321,0.1945,0.4289,0.1945 T0.4197,0.1922 T0.4112,0.19 T0.4072,0.1912 Q0.4032,0.1949,0.388,0.1949 Q0.3663,0.1949,0.3542,0.19 Q0.351,0.1883,0.3462,0.1883 Q0.3406,0.1883,0.3321,0.1906 T0.3153,0.1954 T0.302,0.1983 Q0.2972,0.1991,0.2859,0.1997 T0.2643,0.201 T0.245,0.2024 T0.2337,0.2041 Q0.2321,0.2045,0.2181,0.2045 T0.1851,0.207 T0.1542,0.2157 Q0.143,0.2211,0.143,0.226 Q0.143,0.2314,0.153,0.2348 T0.1719,0.2381 Q0.1791,0.2381,0.2474,0.2476 Q0.2506,0.248,0.2558,0.2489 T0.2651,0.2505 T0.2739,0.252 T0.2819,0.2526 Q0.2835,0.2526,0.2851,0.2522 L0.2859,0.2522 Q0.2948,0.2522,0.3104,0.2574 T0.3309,0.2671 Q0.3333,0.2696,0.3365,0.2696 Q0.339,0.2696,0.3442,0.2684 T0.3526,0.2671 T0.3582,0.2679 Q0.3687,0.2717,0.3968,0.2742 Q0.4,0.2746,0.4036,0.2771 T0.4096,0.2796 Q0.4112,0.2796,0.4137,0.2787 Q0.4169,0.2779,0.4257,0.2779 Q0.4594,0.2779,0.4779,0.2849 Q0.4876,0.2891,0.4972,0.2891 Q0.4996,0.2891,0.506,0.2887 T0.5165,0.2883 Q0.5253,0.2883,0.5305,0.2889 T0.541,0.292 T0.5494,0.299 L0.5494,0.3015 Q0.5494,0.3036,0.5466,0.3051 T0.5386,0.3073 T0.5285,0.3086 T0.5181,0.3094 T0.5108,0.3102 Q0.5068,0.3107,0.494,0.3121 L0.4683,0.315 T0.4506,0.3181 Q0.449,0.3181,0.4426,0.32 T0.4313,0.3229 T0.4197,0.3256 T0.4064,0.3281 T0.3952,0.3289 Q0.3888,0.3289,0.3855,0.3273 Q0.3783,0.3243,0.3703,0.3243 Q0.3598,0.3243,0.351,0.3297 Q0.3478,0.3314,0.3422,0.3314 Q0.3398,0.3314,0.3337,0.3306 T0.3245,0.3297 T0.3189,0.3306 Q0.3149,0.3314,0.2956,0.3328 T0.2715,0.3368 Q0.2691,0.338,0.2635,0.3391 T0.2522,0.3407 T0.2406,0.3424 T0.2313,0.3447 Q0.2305,0.3447,0.2213,0.348 T0.206,0.354 T0.1924,0.3621 T0.1815,0.3733 Q0.1767,0.3816,0.1767,0.3849 Q0.1767,0.387,0.1783,0.3893 T0.1847,0.3961 T0.1936,0.4063 T0.2004,0.4181 T0.2052,0.4264 T0.2145,0.4309 T0.2386,0.4359 Q0.2458,0.4372,0.2554,0.4372 Q0.2578,0.4372,0.2627,0.437 T0.2699,0.4367 Q0.2795,0.4367,0.2851,0.4384 Q0.294,0.4409,0.3092,0.4409 Q0.3116,0.4409,0.3157,0.4407 T0.3213,0.4405 Q0.3301,0.4405,0.3466,0.444 T0.3687,0.4509 Q0.3703,0.4517,0.3703,0.4525 Q0.3703,0.4575,0.3373,0.4596 Q0.3133,0.4608,0.2988,0.4658 Q0.294,0.4674,0.2803,0.4674 Q0.2763,0.4674,0.2687,0.4672 T0.257,0.467 Q0.2402,0.467,0.2313,0.4687 Q0.2209,0.4708,0.2209,0.4737 Q0.2209,0.4741,0.2213,0.4749 T0.2229,0.4764 L0.2249,0.4774 T0.2265,0.4778 L0.2273,0.4782 Q0.2498,0.4803,0.2618,0.4803 Q0.2667,0.4803,0.2691,0.4799 Q0.2699,0.4795,0.2715,0.4795 Q0.2779,0.4795,0.3133,0.4873 Q0.3181,0.4886,0.3233,0.4892 T0.3386,0.4905 T0.3542,0.4915 T0.3655,0.4919 Q0.3703,0.4919,0.3779,0.4915 T0.3888,0.4911 T0.3952,0.4915 Q0.3976,0.4919,0.4008,0.4927 L0.4072,0.4944 T0.4149,0.4961 T0.4249,0.4975 T0.4369,0.4985 Q0.449,0.499,0.4554,0.5 T0.4651,0.5031 T0.4699,0.5085 Q0.4707,0.5093,0.4707,0.5097 Q0.4707,0.5114,0.4687,0.5124 T0.4631,0.5139 T0.4562,0.5145 T0.4478,0.5147 L0.4402,0.5147 Q0.4353,0.5151,0.4265,0.5174 T0.4096,0.5197 L0.4024,0.5197 Q0.4,0.5193,0.3968,0.5193 Q0.3896,0.5193,0.3831,0.5209 T0.3703,0.5253 T0.3598,0.5288 Q0.3558,0.5301,0.3321,0.5342 T0.302,0.5409 Q0.2876,0.5454,0.2337,0.55 Q0.2112,0.5521,0.2112,0.5558 Q0.2112,0.5574,0.2161,0.5612 Q0.2201,0.5637,0.2281,0.5637 Q0.2305,0.5637,0.2361,0.5633 T0.2442,0.5628 Q0.2474,0.5628,0.2498,0.5633 Q0.2635,0.5653,0.3133,0.5653 Q0.3261,0.5653,0.3301,0.5649 L0.3325,0.5649 Q0.3349,0.5649,0.3402,0.5657 T0.3494,0.5666 Q0.3542,0.5666,0.3598,0.5657 Q0.3663,0.5645,0.3695,0.5645 Q0.3735,0.5645,0.3775,0.5666 T0.3847,0.5695 Q0.3888,0.5707,0.3912,0.5709 T0.3968,0.5711 T0.4048,0.572 Q0.4096,0.5724,0.4165,0.5726 T0.4281,0.5734 T0.4378,0.5757 Q0.4418,0.5774,0.4522,0.5774 Q0.4562,0.5774,0.4655,0.5769 T0.4795,0.5765 Q0.4932,0.5765,0.4972,0.579 Q0.5028,0.5819,0.51,0.5819 Q0.5141,0.5819,0.5221,0.5809 T0.5341,0.5798 L0.5373,0.5798 Q0.5422,0.5798,0.557,0.5821 T0.5855,0.5844 L0.5936,0.5844 L0.5992,0.5844 T0.604,0.5848 T0.6076,0.5852 T0.6108,0.5859 T0.6137,0.5865 T0.6161,0.5873 T0.6181,0.5881 T0.6209,0.5896 L0.6233,0.591 Q0.6265,0.5927,0.6353,0.5927 L0.6402,0.5927 L0.645,0.5927 Q0.6723,0.5927,0.6948,0.6039 Q0.6988,0.606,0.7036,0.606 Q0.7076,0.606,0.7153,0.6045 T0.7261,0.6031 Q0.7309,0.6031,0.7454,0.6027 T0.7647,0.6022 Q0.7783,0.6022,0.808,0.608 L0.812,0.608 Q0.8169,0.608,0.8293,0.6062 T0.8474,0.6039 L0.8506,0.6039 Q0.857,0.6039,0.8655,0.6049 T0.8835,0.6074 T0.8972,0.6093 Q0.9036,0.6101,0.9213,0.6101 L0.9398,0.6101 L0.959,0.6101 L0.9767,0.6101 Q0.9976,0.6109,0.9976,0.6176 Q0.9976,0.6188,0.9968,0.6226 Q0.9952,0.6284,0.9671,0.6284 L0.959,0.6284 L0.9526,0.6284 Q0.9486,0.6284,0.9382,0.6302 T0.9205,0.6321 L0.9173,0.6321 Q0.9133,0.6317,0.9092,0.6317 Q0.9012,0.6317,0.8715,0.6346 Q0.8233,0.6387,0.7944,0.6421 Q0.7888,0.6429,0.7831,0.6429 Q0.7783,0.6429,0.7731,0.6425 T0.7663,0.6421 L0.7622,0.6421 Q0.7614,0.6425,0.7586,0.6425 T0.7474,0.6421 T0.7349,0.6416 Q0.7261,0.6416,0.7221,0.6429 Q0.7173,0.645,0.7032,0.646 T0.6711,0.6479 T0.6482,0.6491 Q0.645,0.6495,0.6418,0.6495 Q0.6353,0.6495,0.6273,0.6474 T0.6161,0.6454 Q0.612,0.6454,0.6088,0.6477 T0.6,0.6499 Q0.5912,0.6499,0.5494,0.6578 Q0.5422,0.6591,0.5373,0.6591 Q0.5341,0.6591,0.5281,0.6584 T0.5173,0.6578 L0.5124,0.6578 Q0.5004,0.6582,0.4747,0.6632 Q0.4675,0.6649,0.4398,0.6667 T0.3851,0.6703 T0.3566,0.6719 Q0.3534,0.6723,0.3406,0.6734 T0.3141,0.6757 T0.2948,0.6773 Q0.2908,0.6781,0.2819,0.6829 T0.2618,0.6877 Q0.2482,0.6877,0.2273,0.6958 T0.1992,0.7117 Q0.1976,0.7138,0.1976,0.7155 Q0.1976,0.7188,0.2032,0.7213 T0.2181,0.7258 T0.2289,0.7292 Q0.2337,0.7308,0.2378,0.7316 L0.2458,0.7333 T0.2522,0.7345 Q0.2747,0.7399,0.2835,0.7399 Q0.29,0.7399,0.3048,0.7408 T0.3253,0.7416 Q0.3277,0.7416,0.3297,0.7414 T0.3341,0.7412 L0.3598,0.7445 Q0.3639,0.7449,0.3663,0.7449 Q0.3695,0.7449,0.3751,0.7443 T0.3855,0.7437 L0.3904,0.7437 Q0.3984,0.7441,0.4141,0.7472 T0.4353,0.7507 Q0.4434,0.752,0.4434,0.7553 Q0.4434,0.7578,0.439,0.7605 T0.4297,0.764 Q0.4257,0.7648,0.4201,0.7655 T0.4076,0.7665 T0.3984,0.7673 Q0.3968,0.7673,0.3912,0.7677 T0.3815,0.7688 T0.3735,0.771 T0.3655,0.7727 Q0.3606,0.7727,0.3534,0.7708 T0.3458,0.769 L0.3446,0.769 Q0.3414,0.769,0.3297,0.7713 T0.3149,0.7735 Q0.3092,0.7735,0.296,0.7771 T0.2771,0.7831 Q0.2683,0.7872,0.2554,0.7885 Q0.253,0.7889,0.2325,0.7897 T0.2032,0.7914 Q0.2008,0.7918,0.198,0.792 T0.194,0.7924 T0.1912,0.7928 T0.1888,0.793 T0.1867,0.7934 T0.1851,0.7943 T0.1843,0.7953 T0.1835,0.7968 T0.1823,0.7984 T0.1815,0.8001 Q0.1815,0.8022,0.1847,0.8032 T0.1932,0.8053 T0.2008,0.8071 Q0.2072,0.8092,0.2265,0.8092 Q0.2361,0.8092,0.2586,0.8088 L0.2635,0.8088 Q0.2731,0.8088,0.2795,0.8098 T0.2928,0.8134 T0.302,0.8167 Q0.306,0.8179,0.3277,0.8183 T0.3542,0.8221 Q0.359,0.8246,0.3622,0.8246 Q0.3639,0.8246,0.3675,0.8237 T0.3751,0.8229 Q0.3968,0.8229,0.4048,0.8275 Q0.4088,0.8291,0.4161,0.8291 Q0.4225,0.8291,0.4353,0.8275 Q0.4369,0.827,0.4394,0.827 Q0.4474,0.827,0.4675,0.8345 Q0.4707,0.8358,0.4739,0.8358 Q0.4755,0.8358,0.4799,0.8353 T0.4876,0.8349 Q0.494,0.8349,0.5012,0.8362 L0.5076,0.837 T0.5133,0.8376 T0.5181,0.8382 T0.5221,0.8391 L0.5253,0.8399 T0.5277,0.8409 L0.5293,0.8422 T0.5301,0.8438 L0.5301,0.8461 Q0.5301,0.8499,0.5249,0.8511 T0.5112,0.8526 T0.5004,0.8532 Q0.4964,0.854,0.4851,0.8546 T0.4667,0.8565 Q0.4578,0.8577,0.441,0.8577 L0.4345,0.8577 L0.4289,0.8577 L0.4209,0.8577 Q0.4153,0.8582,0.4088,0.8586 T0.3968,0.8592 T0.3855,0.8594 T0.3755,0.8596 T0.3675,0.86 T0.3622,0.8602 Q0.3317,0.8635,0.3237,0.8635 Q0.2996,0.8635,0.2996,0.8681 Q0.2996,0.8698,0.3032,0.8733 T0.3068,0.8797 L0.3068,0.8822 Q0.3052,0.8859,0.2859,0.8859 Q0.2787,0.8859,0.2739,0.8851 L0.2699,0.8851 Q0.2659,0.8851,0.259,0.888 T0.2498,0.8913 Q0.2394,0.8946,0.2056,0.8971 Q0.2032,0.8971,0.1928,0.9002 T0.1703,0.9034 Q0.1526,0.9034,0.1353,0.9067 T0.1173,0.915 L0.1173,0.9158 Q0.1173,0.9166,0.1177,0.9175 T0.1189,0.9191 T0.1205,0.9204 T0.1229,0.9212 T0.1257,0.922 T0.1285,0.9226 T0.1309,0.9231 T0.1337,0.9235 T0.1365,0.9237 L0.1446,0.9237 T0.1554,0.9243 T0.1614,0.9268 T0.1659,0.9293 T0.1743,0.9303 T0.1823,0.9316 Q0.1863,0.932,0.1912,0.9332 T0.2028,0.9361 T0.2153,0.939 Q0.2233,0.9411,0.2297,0.9448 T0.2386,0.9494 Q0.2426,0.9506,0.2506,0.9506 Q0.253,0.9506,0.2594,0.9504 T0.2699,0.9502 Q0.2763,0.9502,0.2819,0.9511 Q0.2851,0.9511,0.2871,0.9529 T0.2892,0.9573 Q0.2892,0.9627,0.2811,0.9635 Q0.2434,0.9652,0.2337,0.9672 Q0.2257,0.9693,0.2241,0.9693 Q0.2217,0.9693,0.2096,0.9689 L0.2056,0.9689 Q0.1976,0.9689,0.1924,0.9699 T0.1787,0.9741 L0.1647,0.9793 Q0.1518,0.983,0.1285,0.983 L0.1261,0.983 L0.1237,0.983 Q0.1124,0.983,0.1076,0.9838 Q0.102,0.9851,0.0839,0.9896 T0.0602,0.9954 T0.0406,0.9971 T0.0153,0.9979 L0.0032,0.9979 Z",type:0}},"":{type:5,data:{d:"M0.9992,0.998 Q0.9992,1,0.9968,1 Q0.9521,1,0.9392,0.998 Q0.9335,0.997,0.9152,0.9921 T0.8913,0.9862 Q0.8873,0.9852,0.8783,0.9852 L0.8747,0.9852 L0.871,0.9852 Q0.8483,0.9852,0.8345,0.9812 Q0.8289,0.9792,0.8228,0.9773 T0.8135,0.9743 T0.8054,0.9723 T0.7948,0.9713 L0.7908,0.9713 L0.777,0.9713 T0.7656,0.9693 Q0.7616,0.9683,0.7498,0.9674 T0.7283,0.9664 L0.7186,0.9654 Q0.708,0.9644,0.708,0.9575 Q0.708,0.9545,0.7109,0.952 T0.7178,0.9486 L0.7315,0.9486 L0.7417,0.9486 L0.7502,0.9486 Q0.7575,0.9486,0.7599,0.9476 Q0.7616,0.9466,0.7685,0.9426 T0.7843,0.9377 Q0.7899,0.9357,0.8009,0.9332 T0.8175,0.9298 Q0.82,0.9288,0.8228,0.9283 T0.8277,0.9278 T0.8313,0.9273 T0.8341,0.9263 T0.8362,0.9258 Q0.8402,0.9219,0.854,0.9219 L0.8569,0.9219 L0.8597,0.9219 L0.8637,0.9219 Q0.88,0.9199,0.88,0.9159 L0.88,0.9149 Q0.88,0.913,0.8719,0.911 T0.852,0.9075 T0.8297,0.906 Q0.8224,0.906,0.8167,0.905 T0.8074,0.9031 T0.8001,0.9006 T0.794,0.8991 Q0.7599,0.8971,0.7494,0.8942 Q0.7461,0.8932,0.7397,0.8902 T0.7299,0.8872 L0.7267,0.8872 Q0.721,0.8882,0.7121,0.8882 Q0.6926,0.8882,0.691,0.8833 L0.691,0.8803 Q0.691,0.8773,0.6922,0.8749 T0.6955,0.8704 L0.6975,0.8684 Q0.6926,0.8655,0.6764,0.8655 Q0.6683,0.8655,0.6375,0.8625 Q0.6358,0.8625,0.629,0.862 T0.6148,0.8615 T0.5973,0.861 T0.5791,0.8605 L0.5718,0.8605 L0.5661,0.8605 L0.5596,0.8605 Q0.5426,0.8605,0.5337,0.8586 Q0.5264,0.8576,0.515,0.8571 T0.4996,0.8556 Q0.498,0.8556,0.4947,0.8551 T0.4882,0.8546 T0.4809,0.8541 T0.474,0.8531 T0.4692,0.8506 T0.4672,0.8467 Q0.4672,0.8437,0.468,0.8422 T0.4704,0.8398 T0.4736,0.8383 T0.4781,0.8368 T0.4838,0.8358 T0.4911,0.8353 T0.4988,0.8338 Q0.5069,0.8328,0.5142,0.8328 Q0.5174,0.8328,0.5215,0.8333 T0.5264,0.8338 Q0.5296,0.8338,0.532,0.8328 Q0.5523,0.8249,0.5604,0.8249 L0.5653,0.8249 Q0.5775,0.8269,0.5848,0.8269 Q0.5912,0.8269,0.5937,0.8259 Q0.6026,0.821,0.6253,0.821 Q0.6294,0.821,0.6334,0.822 T0.6383,0.8229 Q0.6399,0.8229,0.644,0.82 Q0.6504,0.817,0.6723,0.816 T0.6975,0.814 Q0.6999,0.814,0.7048,0.8121 T0.7129,0.8091 T0.7226,0.8071 T0.7372,0.8061 L0.7421,0.8061 Q0.7624,0.8071,0.7721,0.8071 Q0.7924,0.8071,0.7981,0.8051 Q0.8021,0.8032,0.807,0.8027 T0.8135,0.8017 T0.8151,0.8002 L0.8151,0.7992 Q0.8143,0.7962,0.8127,0.7957 T0.8045,0.7943 Q0.7997,0.7943,0.7964,0.7933 Q0.7883,0.7933,0.7676,0.7923 T0.7437,0.7903 Q0.7307,0.7893,0.7218,0.7844 Q0.7194,0.7834,0.7141,0.7819 L0.7036,0.7789 T0.693,0.7765 T0.6853,0.7755 Q0.6805,0.7755,0.6691,0.773 T0.6553,0.7705 Q0.6545,0.7705,0.6545,0.7715 Q0.6537,0.7715,0.65,0.7725 T0.6423,0.774 T0.635,0.7745 Q0.6294,0.7745,0.6257,0.773 T0.618,0.771 T0.6083,0.77 T0.601,0.7695 Q0.5985,0.7695,0.5921,0.769 T0.5795,0.7676 T0.5702,0.7666 Q0.5653,0.7656,0.5596,0.7616 T0.5539,0.7547 Q0.5539,0.7498,0.5645,0.7488 Q0.5693,0.7478,0.5852,0.7448 T0.6099,0.7418 L0.6148,0.7418 Q0.6196,0.7418,0.6253,0.7423 T0.6338,0.7428 L0.6399,0.7428 Q0.6431,0.7418,0.6488,0.7409 T0.6586,0.7394 T0.6659,0.7389 L0.6707,0.7389 Q0.6723,0.7399,0.6748,0.7399 Q0.6796,0.7399,0.6946,0.7389 T0.7161,0.7379 Q0.7251,0.7379,0.7478,0.7319 Q0.7494,0.7319,0.7539,0.7315 T0.762,0.73 T0.7697,0.727 T0.7818,0.723 T0.7948,0.7196 T0.7997,0.7151 Q0.7997,0.7141,0.7989,0.7132 Q0.7924,0.7062,0.7717,0.6978 T0.738,0.6894 Q0.7267,0.6894,0.717,0.6845 T0.7048,0.6795 Q0.6975,0.6785,0.6711,0.6766 T0.6431,0.6746 Q0.6415,0.6736,0.6144,0.6721 T0.5596,0.6686 T0.5247,0.6657 Q0.4996,0.6607,0.4874,0.6597 L0.4834,0.6597 Q0.4785,0.6597,0.4724,0.6607 T0.4631,0.6617 Q0.4574,0.6617,0.4501,0.6597 Q0.4088,0.6518,0.4006,0.6518 Q0.3933,0.6518,0.3901,0.6499 T0.3844,0.6479 T0.3739,0.6499 T0.3585,0.6518 L0.352,0.6518 Q0.3471,0.6508,0.335,0.6503 T0.3122,0.6494 T0.2912,0.6479 T0.2766,0.6449 Q0.2733,0.6439,0.2668,0.6439 Q0.2628,0.6439,0.2543,0.6444 T0.2425,0.6449 T0.2368,0.6439 L0.2344,0.6439 Q0.2336,0.6439,0.2283,0.6444 T0.2182,0.6449 Q0.2117,0.6449,0.2052,0.6439 Q0.1768,0.6409,0.1281,0.637 Q0.0989,0.634,0.0916,0.634 L0.0835,0.634 L0.0795,0.634 Q0.0722,0.634,0.0616,0.632 T0.0479,0.6301 Q0.0462,0.6301,0.0406,0.6306 T0.0308,0.6311 Q0.0032,0.6311,0.0008,0.6231 Q0,0.6202,0,0.6182 Q0,0.6083,0.0227,0.6083 Q0.03,0.6073,0.0422,0.6073 Q0.0487,0.6073,0.0608,0.6078 T0.0787,0.6083 Q0.0973,0.6083,0.103,0.6073 Q0.1062,0.6063,0.1131,0.6053 T0.1253,0.6039 T0.1375,0.6024 T0.1492,0.6014 L0.1533,0.6014 Q0.1598,0.6024,0.1723,0.6044 T0.189,0.6063 Q0.1906,0.6063,0.1922,0.6053 Q0.2214,0.6004,0.236,0.6004 Q0.2409,0.6004,0.2551,0.6009 T0.2741,0.6014 Q0.2782,0.6014,0.2859,0.6024 T0.2968,0.6034 Q0.3009,0.6034,0.3041,0.6024 Q0.3277,0.5905,0.356,0.5905 L0.3613,0.5905 L0.3666,0.5905 Q0.3731,0.5905,0.3755,0.5895 Q0.382,0.5856,0.3844,0.5846 T0.3938,0.5831 T0.4144,0.5826 T0.4428,0.5801 T0.4631,0.5776 L0.4663,0.5776 Q0.4704,0.5776,0.4785,0.5786 T0.4899,0.5796 Q0.4964,0.5796,0.5012,0.5767 Q0.5069,0.5737,0.5223,0.5737 Q0.5272,0.5737,0.5369,0.5742 T0.5499,0.5747 Q0.558,0.5747,0.5612,0.5737 Q0.5661,0.5717,0.5714,0.5712 T0.5835,0.5702 T0.5945,0.5692 T0.6018,0.5687 L0.6062,0.5687 T0.6095,0.5682 T0.6148,0.5678 Q0.6172,0.5668,0.6196,0.5653 T0.6245,0.5633 T0.631,0.5628 T0.6407,0.5638 T0.6504,0.5648 T0.6594,0.5638 T0.6675,0.5628 L0.6707,0.5628 L0.6861,0.5628 Q0.7364,0.5628,0.7494,0.5608 L0.7567,0.5608 L0.7652,0.5608 L0.7729,0.5608 Q0.7794,0.5608,0.7818,0.5589 Q0.7851,0.5569,0.7859,0.5559 Q0.7835,0.5539,0.7656,0.5519 Q0.7121,0.547,0.6975,0.543 Q0.6934,0.541,0.6853,0.5396 L0.6691,0.5366 T0.6525,0.5336 T0.6391,0.5312 Q0.6367,0.5302,0.6245,0.5257 T0.6034,0.5213 L0.5977,0.5213 Q0.5945,0.5223,0.5904,0.5223 Q0.5839,0.5223,0.5787,0.5208 T0.5685,0.5183 T0.5596,0.5173 Q0.558,0.5173,0.5552,0.5168 T0.5495,0.5163 L0.5434,0.5163 T0.5373,0.5158 T0.532,0.5148 T0.5284,0.5129 T0.5272,0.5104 L0.5272,0.5074 Q0.5304,0.5015,0.5377,0.499 T0.5629,0.4965 Q0.5734,0.4955,0.5811,0.4946 T0.5953,0.4916 T0.605,0.4896 Q0.6083,0.4886,0.6123,0.4886 Q0.6148,0.4886,0.6225,0.4891 T0.635,0.4896 L0.6456,0.4896 Q0.6837,0.4857,0.6861,0.4857 Q0.7226,0.4768,0.7283,0.4768 Q0.7307,0.4768,0.732,0.4773 T0.7372,0.4777 Q0.7502,0.4777,0.7721,0.4758 Q0.7753,0.4748,0.777,0.4738 Q0.7745,0.4718,0.768,0.4708 Q0.7599,0.4688,0.7445,0.4688 Q0.7405,0.4688,0.7324,0.4693 T0.721,0.4698 Q0.7056,0.4698,0.6999,0.4679 Q0.6861,0.4629,0.6626,0.4619 Q0.6586,0.4609,0.6533,0.4604 T0.6419,0.459 T0.6314,0.456 T0.6269,0.452 Q0.6269,0.451,0.6302,0.4491 Q0.6358,0.4451,0.6525,0.4416 T0.6788,0.4382 L0.6845,0.4382 L0.6902,0.4382 Q0.7064,0.4382,0.7145,0.4362 Q0.7202,0.4342,0.7307,0.4342 L0.7356,0.4342 L0.7409,0.4342 L0.7453,0.4342 Q0.7543,0.4342,0.7607,0.4332 Q0.7778,0.4313,0.7847,0.4288 T0.7932,0.4248 T0.7972,0.4169 T0.8045,0.4045 L0.8094,0.3986 T0.8135,0.3942 L0.8167,0.3912 T0.8191,0.3887 T0.8204,0.3867 T0.8208,0.3848 Q0.8208,0.3818,0.8167,0.3739 Q0.8127,0.3689,0.8054,0.3635 T0.7924,0.3556 T0.7778,0.3497 T0.768,0.3462 Q0.764,0.3442,0.7478,0.3427 T0.7267,0.3383 Q0.7234,0.3363,0.7044,0.3348 T0.6805,0.3323 L0.6764,0.3323 T0.6679,0.3328 T0.6586,0.3333 Q0.6521,0.3333,0.648,0.3314 Q0.6391,0.3264,0.6294,0.3264 Q0.6229,0.3264,0.6156,0.3294 Q0.6115,0.3304,0.6042,0.3304 Q0.5977,0.3304,0.5888,0.3289 T0.5738,0.3264 T0.5584,0.3225 L0.5491,0.3195 Q0.5418,0.3185,0.5162,0.3155 T0.4895,0.3121 T0.4826,0.3116 T0.4716,0.3111 T0.4607,0.3096 T0.4513,0.3066 T0.4477,0.3017 Q0.4477,0.2997,0.4485,0.2977 Q0.4526,0.2898,0.4611,0.2878 T0.4842,0.2859 Q0.4882,0.2859,0.4943,0.2864 T0.5028,0.2868 Q0.5118,0.2868,0.5215,0.2829 Q0.5401,0.276,0.5734,0.276 Q0.5831,0.276,0.5872,0.277 L0.5904,0.277 T0.5949,0.2745 T0.6034,0.272 Q0.631,0.269,0.6407,0.2661 Q0.6448,0.2641,0.6488,0.2641 T0.6573,0.2656 T0.6634,0.2671 Q0.6659,0.2671,0.6675,0.2651 Q0.6723,0.2601,0.6886,0.2552 T0.7137,0.2502 L0.7153,0.2502 L0.7178,0.2502 Q0.7218,0.2502,0.7279,0.2493 T0.7417,0.2468 T0.7526,0.2453 Q0.8208,0.2354,0.8281,0.2354 Q0.8337,0.2354,0.8394,0.2344 T0.8496,0.2315 T0.854,0.2265 Q0.854,0.2216,0.8443,0.2176 Q0.8354,0.2127,0.8216,0.2102 T0.7972,0.2072 T0.777,0.2067 T0.7648,0.2057 Q0.7632,0.2047,0.7498,0.2038 T0.7202,0.2018 T0.6983,0.1998 Q0.6918,0.1998,0.676,0.1949 T0.6537,0.1899 Q0.6496,0.1899,0.6472,0.1919 Q0.6342,0.1968,0.6123,0.1968 Q0.5961,0.1968,0.5912,0.1929 Q0.5904,0.1919,0.5892,0.1919 T0.5823,0.1944 T0.5722,0.1968 T0.5637,0.1949 Q0.5556,0.1909,0.5158,0.1869 Q0.5109,0.1869,0.5032,0.1835 T0.4915,0.18 Q0.4907,0.18,0.4891,0.181 Q0.4793,0.182,0.455,0.182 Q0.4177,0.182,0.4015,0.1771 Q0.3901,0.1741,0.3779,0.1741 Q0.3747,0.1741,0.369,0.1746 T0.3609,0.1751 Q0.3569,0.1751,0.3536,0.1741 Q0.3512,0.1741,0.3459,0.1736 T0.3358,0.1726 T0.3256,0.1716 T0.3167,0.1696 T0.3106,0.1662 Q0.3082,0.1632,0.3082,0.1592 Q0.3082,0.1543,0.3114,0.1508 T0.3204,0.1474 L0.3236,0.1474 Q0.3301,0.1494,0.3333,0.1494 Q0.339,0.1494,0.3496,0.1454 Q0.3674,0.1385,0.3869,0.1385 Q0.395,0.1385,0.4011,0.137 T0.4116,0.1355 T0.4197,0.1375 T0.425,0.1395 Q0.429,0.1395,0.4355,0.1365 Q0.4631,0.1266,0.4882,0.1266 Q0.5126,0.1266,0.5337,0.1246 Q0.5369,0.1246,0.5458,0.1207 T0.5661,0.1167 L0.5693,0.1167 Q0.5791,0.1177,0.5852,0.1187 T0.5921,0.1197 Q0.5945,0.1197,0.6002,0.1167 Q0.6026,0.1147,0.605,0.1123 T0.6091,0.1093 T0.6156,0.1088 T0.6318,0.1098 Q0.6456,0.1108,0.6569,0.1137 T0.6707,0.1167 Q0.674,0.1167,0.6772,0.1147 Q0.6821,0.1108,0.6946,0.1083 T0.721,0.1044 T0.7453,0.1029 L0.7526,0.1029 Q0.7583,0.1039,0.7652,0.1053 T0.7753,0.1068 Q0.7778,0.1068,0.7802,0.1058 Q0.7981,0.1019,0.8143,0.1019 Q0.8175,0.1019,0.8439,0.0964 T0.8735,0.091 Q0.8759,0.091,0.8836,0.089 T0.8938,0.0851 Q0.8929,0.0841,0.8905,0.0841 Q0.8832,0.0821,0.8735,0.0821 Q0.8694,0.0821,0.8629,0.0826 T0.854,0.0831 Q0.8508,0.0831,0.8491,0.0821 Q0.8475,0.0821,0.8171,0.0811 T0.7802,0.0781 T0.7571,0.0737 T0.7332,0.0712 Q0.7299,0.0712,0.7247,0.0717 T0.7161,0.0722 L0.7064,0.0722 Q0.7032,0.0712,0.7003,0.0707 T0.6959,0.0692 T0.693,0.0678 T0.6914,0.0663 T0.6902,0.0648 T0.689,0.0643 L0.6869,0.0643 L0.6845,0.0643 L0.6821,0.0643 Q0.6553,0.0643,0.6553,0.0554 T0.6796,0.0465 L0.6813,0.0465 L0.6845,0.0465 Q0.6918,0.0425,0.717,0.0376 Q0.7226,0.0366,0.7267,0.0356 T0.7324,0.0336 T0.7376,0.0317 T0.747,0.0297 Q0.7518,0.0287,0.7551,0.0287 T0.762,0.0297 T0.768,0.0307 L0.7729,0.0307 Q0.7802,0.0277,0.7997,0.0267 T0.8224,0.0237 Q0.8273,0.0227,0.8341,0.0223 T0.8475,0.0193 T0.8654,0.0143 T0.8873,0.0079 Q0.9002,0.003,0.9331,0.004 T0.97,0.004 Q0.9838,0,0.9976,0.001 Q1,0.001,1,0.003 Z M0.9935,0.996 L0.9951,0.0049 Q0.9822,0.0049,0.9716,0.0079 Q0.9659,0.0099,0.9327,0.0089 T0.8897,0.0119 Q0.8775,0.0158,0.8666,0.0183 T0.85,0.0237 Q0.8418,0.0267,0.8341,0.0272 T0.8248,0.0277 Q0.82,0.0297,0.8001,0.0312 T0.7745,0.0346 Q0.7697,0.0356,0.7664,0.0356 Q0.764,0.0356,0.7603,0.0341 T0.7534,0.0326 Q0.751,0.0326,0.7478,0.0336 Q0.7429,0.0346,0.7397,0.0356 T0.7344,0.0376 T0.7283,0.0401 T0.7178,0.0425 Q0.6926,0.0465,0.6878,0.0495 Q0.6845,0.0514,0.6764,0.0514 L0.6723,0.0514 L0.6691,0.0514 Q0.6602,0.0514,0.6602,0.0554 Q0.6602,0.0574,0.6659,0.0579 T0.6796,0.0589 T0.691,0.0603 T0.6967,0.0643 T0.7072,0.0673 Q0.7121,0.0682,0.7153,0.0682 T0.7238,0.0678 T0.7332,0.0673 Q0.7413,0.0673,0.7579,0.0692 T0.7818,0.0742 Q0.7867,0.0752,0.8171,0.0762 T0.8508,0.0781 L0.852,0.0781 T0.8601,0.0776 T0.8719,0.0772 Q0.8832,0.0772,0.8921,0.0791 Q0.8994,0.0811,0.8994,0.0841 T0.8933,0.0895 T0.8812,0.094 T0.8735,0.0959 T0.8451,0.1014 T0.8143,0.1068 Q0.7989,0.1068,0.7818,0.1098 Q0.7778,0.1108,0.7745,0.1108 T0.768,0.1103 T0.7603,0.1088 T0.7518,0.1068 L0.7461,0.1068 Q0.7315,0.1068,0.7088,0.1103 T0.6805,0.1177 Q0.6756,0.1207,0.6699,0.1207 Q0.6667,0.1207,0.6545,0.1177 T0.631,0.1147 Q0.6269,0.1137,0.6225,0.1133 T0.616,0.1128 L0.6123,0.1128 T0.6103,0.1133 L0.6083,0.1157 T0.6034,0.1197 Q0.5961,0.1246,0.5921,0.1246 Q0.5904,0.1246,0.5835,0.1231 T0.5693,0.1217 L0.5661,0.1217 Q0.558,0.1217,0.5535,0.1231 T0.5446,0.1266 T0.5345,0.1296 Q0.5126,0.1316,0.4882,0.1316 T0.438,0.1405 Q0.4298,0.1434,0.425,0.1434 Q0.4209,0.1434,0.4173,0.1419 T0.4112,0.1405 T0.4027,0.1419 T0.3869,0.1434 Q0.3682,0.1434,0.3512,0.1494 Q0.3398,0.1533,0.3333,0.1533 Q0.3285,0.1533,0.3228,0.1513 L0.3212,0.1513 Q0.3179,0.1513,0.3155,0.1538 T0.3131,0.1592 Q0.3131,0.1612,0.3147,0.1632 Q0.3171,0.1652,0.3232,0.1667 T0.3406,0.1691 T0.3544,0.1701 L0.3601,0.1701 L0.3678,0.1701 L0.3771,0.1701 Q0.3909,0.1701,0.4031,0.1731 Q0.4177,0.178,0.4558,0.178 Q0.4793,0.178,0.4882,0.1761 L0.4915,0.1761 Q0.498,0.1761,0.5061,0.179 T0.5158,0.183 Q0.5166,0.183,0.5231,0.1835 T0.5341,0.1845 T0.545,0.1855 T0.5572,0.1874 T0.5661,0.1909 Q0.5677,0.1919,0.5702,0.1919 T0.5791,0.1894 T0.588,0.1869 Q0.5921,0.1869,0.5945,0.1899 Q0.5977,0.1919,0.6123,0.1919 Q0.6334,0.1919,0.6448,0.1879 Q0.6488,0.186,0.6537,0.186 Q0.6626,0.186,0.6784,0.1909 T0.6983,0.1958 Q0.704,0.1968,0.7206,0.1973 T0.7506,0.1993 T0.7689,0.2018 L0.7705,0.2018 L0.7741,0.2018 L0.7786,0.2018 Q0.8248,0.2018,0.8475,0.2136 Q0.8597,0.2196,0.8597,0.2255 T0.8483,0.2359 T0.8281,0.2404 Q0.8208,0.2404,0.7534,0.2493 Q0.7502,0.2502,0.7425,0.2512 T0.7287,0.2532 T0.7178,0.2542 L0.7153,0.2542 L0.7137,0.2542 Q0.7064,0.2542,0.6906,0.2591 T0.6715,0.2681 T0.6626,0.272 Q0.6594,0.272,0.6541,0.2705 T0.6464,0.269 T0.6431,0.27 Q0.6318,0.273,0.6034,0.276 Q0.6018,0.276,0.5998,0.2774 T0.5957,0.2799 T0.5904,0.2809 L0.5856,0.2809 Q0.5823,0.2799,0.575,0.2799 Q0.541,0.2799,0.5239,0.2868 Q0.5134,0.2908,0.5028,0.2908 Q0.4996,0.2908,0.4935,0.2903 T0.4842,0.2898 Q0.4704,0.2898,0.4635,0.2918 T0.4534,0.2997 L0.4534,0.3007 Q0.4534,0.3037,0.459,0.3046 T0.4753,0.3066 T0.4899,0.3076 Q0.4907,0.3076,0.5166,0.3106 T0.5507,0.3155 Q0.5921,0.3264,0.605,0.3264 Q0.6107,0.3264,0.6131,0.3254 Q0.6212,0.3225,0.6294,0.3225 Q0.6407,0.3225,0.6513,0.3274 Q0.6529,0.3294,0.6569,0.3294 Q0.6594,0.3294,0.665,0.3284 T0.6748,0.3274 T0.6821,0.3284 Q0.6861,0.3294,0.6967,0.3299 T0.7165,0.3314 T0.7299,0.3343 Q0.7324,0.3363,0.7486,0.3383 T0.7697,0.3422 Q0.7713,0.3432,0.7774,0.3452 T0.7887,0.3492 T0.8005,0.3546 T0.8127,0.3625 T0.8208,0.3719 Q0.8256,0.3798,0.8256,0.3848 Q0.8256,0.3877,0.8236,0.3902 T0.8171,0.3976 T0.809,0.4075 T0.8021,0.4189 T0.7968,0.4273 T0.7867,0.4322 T0.7616,0.4382 Q0.7543,0.4392,0.7437,0.4392 L0.7364,0.4392 L0.7299,0.4392 Q0.7202,0.4392,0.7161,0.4402 Q0.7072,0.4431,0.691,0.4431 L0.6845,0.4431 L0.6788,0.4431 Q0.6707,0.4431,0.6545,0.4461 T0.6334,0.452 Q0.6399,0.456,0.6626,0.457 Q0.6878,0.458,0.7024,0.4639 Q0.7064,0.4649,0.7186,0.4649 L0.7295,0.4649 L0.7413,0.4649 Q0.7591,0.4649,0.7697,0.4669 Q0.7818,0.4688,0.7818,0.4728 Q0.7818,0.4748,0.7798,0.4763 T0.7753,0.4787 L0.7737,0.4797 L0.7729,0.4797 Q0.7494,0.4827,0.7388,0.4827 Q0.7332,0.4827,0.7307,0.4817 L0.7291,0.4817 Q0.7226,0.4817,0.6878,0.4896 Q0.6829,0.4906,0.6772,0.4911 T0.6618,0.4921 T0.646,0.4931 T0.6342,0.4936 T0.6212,0.4931 T0.6115,0.4926 Q0.6083,0.4926,0.6058,0.4931 T0.5969,0.4955 T0.5819,0.499 T0.5629,0.5005 Q0.5572,0.5005,0.5527,0.501 T0.545,0.502 T0.5397,0.503 T0.5361,0.5045 T0.5337,0.5064 T0.5328,0.5094 L0.532,0.5094 Q0.532,0.5104,0.5337,0.5109 T0.5381,0.5114 T0.5438,0.5119 T0.5515,0.5124 L0.5604,0.5124 Q0.5661,0.5134,0.5746,0.5153 T0.5912,0.5173 L0.5977,0.5173 L0.6026,0.5173 Q0.6139,0.5173,0.6273,0.5218 T0.6407,0.5272 Q0.6448,0.5282,0.6683,0.5321 T0.6991,0.5381 Q0.7137,0.543,0.7664,0.548 Q0.7908,0.55,0.7908,0.5559 Q0.7908,0.5589,0.7859,0.5628 Q0.781,0.5658,0.7713,0.5658 Q0.7689,0.5658,0.7628,0.5653 T0.7543,0.5648 T0.7502,0.5658 Q0.7364,0.5678,0.6878,0.5678 Q0.674,0.5678,0.6699,0.5668 L0.6683,0.5668 Q0.6659,0.5668,0.6606,0.5678 T0.6513,0.5687 Q0.6464,0.5687,0.6391,0.5678 Q0.6334,0.5668,0.6302,0.5668 T0.6241,0.5687 T0.6164,0.5717 Q0.6123,0.5727,0.6099,0.5727 L0.6062,0.5727 T0.6022,0.5732 T0.5953,0.5737 Q0.5904,0.5747,0.5839,0.5747 T0.5726,0.5752 T0.5629,0.5776 T0.5458,0.5796 Q0.5418,0.5796,0.5324,0.5791 T0.5191,0.5786 Q0.5077,0.5786,0.5045,0.5806 Q0.498,0.5836,0.4899,0.5836 Q0.4858,0.5836,0.4777,0.5826 T0.4655,0.5816 L0.4631,0.5816 Q0.4582,0.5816,0.4436,0.5841 T0.4144,0.5865 L0.4051,0.5865 L0.3986,0.5865 T0.3933,0.587 T0.3897,0.5875 T0.3869,0.5885 T0.3844,0.5895 T0.3812,0.591 T0.3779,0.5925 Q0.3739,0.5955,0.3633,0.5955 L0.3585,0.5955 L0.3536,0.5955 Q0.3277,0.5955,0.3066,0.6053 Q0.3017,0.6083,0.296,0.6083 Q0.2912,0.6083,0.2839,0.6068 T0.2741,0.6053 Q0.2693,0.6053,0.2547,0.6048 T0.236,0.6044 Q0.2222,0.6044,0.193,0.6103 L0.1882,0.6103 Q0.1825,0.6103,0.1703,0.6083 T0.1525,0.6063 L0.15,0.6063 Q0.1436,0.6063,0.135,0.6073 T0.1168,0.6098 T0.1038,0.6113 Q0.0973,0.6123,0.0787,0.6123 L0.06,0.6123 L0.0414,0.6123 L0.0235,0.6123 Q0.0049,0.6133,0.0049,0.6172 L0.0057,0.6222 Q0.0073,0.6261,0.043,0.6261 L0.0454,0.6261 L0.0479,0.6261 Q0.0527,0.6261,0.0633,0.6281 T0.0803,0.6301 L0.0835,0.6301 L0.0916,0.6301 Q0.0998,0.6301,0.129,0.632 Q0.1768,0.636,0.206,0.64 Q0.2117,0.6409,0.2165,0.6409 Q0.2206,0.6409,0.2263,0.6405 T0.2336,0.64 L0.2384,0.64 L0.2409,0.64 T0.251,0.6395 T0.2644,0.639 Q0.2741,0.639,0.279,0.6409 Q0.283,0.6429,0.2972,0.6439 T0.3293,0.6459 T0.3528,0.6469 L0.3577,0.6469 Q0.3642,0.6469,0.3723,0.6449 T0.3844,0.6429 Q0.3901,0.6429,0.3933,0.6454 T0.4006,0.6479 Q0.4088,0.6479,0.4517,0.6558 Q0.4582,0.6568,0.4623,0.6568 Q0.4655,0.6568,0.4716,0.6563 T0.4826,0.6558 L0.4882,0.6558 Q0.5004,0.6558,0.5255,0.6607 Q0.5328,0.6627,0.5604,0.6647 T0.6152,0.6682 T0.644,0.6696 T0.6719,0.6721 T0.7056,0.6756 Q0.7113,0.6756,0.7198,0.6805 T0.738,0.6855 Q0.7453,0.6855,0.7551,0.6879 T0.7741,0.6939 T0.7912,0.7018 T0.8029,0.7102 Q0.8054,0.7132,0.8054,0.7151 Q0.8054,0.7191,0.8009,0.7216 T0.7908,0.7255 T0.779,0.7285 T0.7721,0.731 Q0.7672,0.7329,0.7632,0.7339 T0.7551,0.7354 T0.7486,0.7369 Q0.7478,0.7369,0.7445,0.7379 T0.7388,0.7394 T0.7324,0.7404 L0.7242,0.7413 T0.7161,0.7418 Q0.7105,0.7418,0.6955,0.7428 T0.6748,0.7438 L0.6699,0.7438 L0.6667,0.7438 Q0.6659,0.7438,0.6407,0.7468 Q0.6367,0.7478,0.6334,0.7478 T0.6245,0.7468 T0.6148,0.7458 L0.6099,0.7458 Q0.6018,0.7468,0.5864,0.7498 T0.5653,0.7532 T0.5596,0.7557 Q0.5596,0.7596,0.571,0.7616 Q0.5742,0.7626,0.5803,0.7631 T0.5929,0.7641 T0.6018,0.7656 L0.6087,0.7656 T0.6192,0.7666 T0.6277,0.7695 Q0.631,0.7705,0.6342,0.7705 Q0.6383,0.7705,0.6452,0.7685 T0.6537,0.7666 L0.6553,0.7666 Q0.6602,0.7666,0.6711,0.769 T0.6853,0.7715 Q0.691,0.7715,0.7048,0.775 T0.7242,0.7814 Q0.7324,0.7854,0.7445,0.7864 Q0.7478,0.7864,0.768,0.7873 T0.7972,0.7893 Q0.7989,0.7893,0.8017,0.7898 T0.8054,0.7903 L0.8082,0.7903 T0.811,0.7908 T0.8131,0.7913 T0.8151,0.7918 L0.8167,0.7928 T0.8179,0.7943 T0.8191,0.7957 T0.8204,0.7977 T0.8208,0.8002 Q0.8208,0.8032,0.8171,0.8051 T0.8074,0.8081 T0.7997,0.8091 Q0.7932,0.8121,0.7737,0.8121 Q0.7664,0.8121,0.7413,0.8111 L0.7364,0.8111 Q0.7275,0.8111,0.7214,0.8121 T0.7084,0.8155 T0.6991,0.819 Q0.6934,0.82,0.6723,0.8205 T0.6472,0.8239 Q0.6423,0.8269,0.6375,0.8269 Q0.6358,0.8269,0.6338,0.8264 T0.6294,0.8254 T0.6253,0.8249 Q0.6042,0.8249,0.5961,0.8289 Q0.5921,0.8318,0.5839,0.8318 Q0.5783,0.8318,0.5645,0.8299 L0.5604,0.8299 Q0.5531,0.8299,0.5337,0.8368 Q0.5296,0.8378,0.5255,0.8378 Q0.5239,0.8378,0.5195,0.8373 T0.5118,0.8368 Q0.5061,0.8368,0.4996,0.8388 Q0.4947,0.8388,0.4882,0.8398 Q0.4777,0.8417,0.4753,0.8427 T0.4728,0.8467 Q0.4728,0.8487,0.4769,0.8492 T0.4886,0.8501 T0.5004,0.8516 Q0.5036,0.8516,0.515,0.8521 T0.5345,0.8546 Q0.5426,0.8556,0.5596,0.8556 L0.5649,0.8556 L0.5702,0.8556 L0.5791,0.8556 Q0.5921,0.8566,0.6135,0.8571 T0.6383,0.8586 Q0.6683,0.8615,0.6764,0.8615 L0.6776,0.8615 L0.6788,0.8615 Q0.7032,0.8615,0.7032,0.8684 Q0.7032,0.8714,0.6995,0.8749 T0.6959,0.8803 L0.6959,0.8813 Q0.6991,0.8843,0.7153,0.8843 Q0.7218,0.8843,0.7259,0.8833 L0.7299,0.8833 Q0.7324,0.8833,0.7348,0.8838 T0.7393,0.8848 T0.7433,0.8863 L0.7474,0.8882 T0.751,0.8892 Q0.7616,0.8922,0.7948,0.8952 Q0.7981,0.8952,0.8082,0.8981 T0.8297,0.9011 T0.8528,0.9026 T0.8747,0.907 T0.8856,0.9149 L0.8856,0.9159 Q0.8856,0.9179,0.8848,0.9189 T0.8828,0.9209 T0.88,0.9228 T0.8767,0.9243 T0.8731,0.9248 T0.8698,0.9253 T0.8666,0.9258 L0.8646,0.9258 Q0.8621,0.9258,0.8577,0.9263 T0.85,0.9268 T0.8439,0.9273 T0.8402,0.9278 Q0.8386,0.9298,0.8358,0.9308 T0.8305,0.9322 T0.8244,0.9332 T0.8183,0.9337 Q0.8135,0.9347,0.8025,0.9372 T0.7859,0.9416 Q0.7778,0.9436,0.7717,0.9471 T0.7624,0.9515 Q0.7575,0.9535,0.7486,0.9535 Q0.7461,0.9535,0.7397,0.953 T0.7291,0.9525 Q0.7234,0.9525,0.7186,0.953 T0.7137,0.957 T0.7194,0.9614 Q0.7567,0.9634,0.7664,0.9654 Q0.7745,0.9674,0.7762,0.9674 L0.7908,0.9674 Q0.7924,0.9664,0.7948,0.9664 Q0.8029,0.9664,0.8082,0.9679 T0.8224,0.9723 T0.8362,0.9773 Q0.8483,0.9812,0.871,0.9812 L0.8751,0.9812 Q0.8873,0.9812,0.8929,0.9822 T0.9165,0.9876 T0.9408,0.9931 Q0.9513,0.996,0.9935,0.996 Z M0.9968,0.998 L0.9976,0.003 Q0.9838,0.002,0.9708,0.0059 Q0.9659,0.0069,0.9327,0.0059 T0.8881,0.0099 Q0.8767,0.0138,0.8658,0.0163 T0.8491,0.0218 Q0.8418,0.0247,0.8341,0.0247 T0.8232,0.0257 Q0.8191,0.0277,0.7997,0.0292 T0.7737,0.0326 Q0.7697,0.0336,0.7672,0.0336 T0.7612,0.0321 T0.7543,0.0307 T0.747,0.0317 Q0.7397,0.0326,0.7336,0.0356 T0.717,0.0406 Q0.6918,0.0445,0.6861,0.0475 Q0.6845,0.0485,0.6772,0.0485 T0.6638,0.05 T0.6577,0.0549 T0.6642,0.0598 T0.6796,0.0613 T0.6902,0.0623 Q0.691,0.0623,0.6946,0.0658 T0.7064,0.0702 L0.7161,0.0702 Q0.7194,0.0702,0.7242,0.0697 T0.7332,0.0692 Q0.7413,0.0692,0.7579,0.0717 T0.781,0.0762 Q0.7867,0.0781,0.8171,0.0786 T0.85,0.0801 L0.8532,0.0801 Q0.8548,0.0801,0.8613,0.0796 T0.8727,0.0791 Q0.8832,0.0791,0.8913,0.0811 Q0.897,0.0831,0.897,0.0851 Q0.897,0.088,0.8873,0.0905 T0.8735,0.093 Q0.871,0.093,0.8447,0.0984 T0.8143,0.1039 Q0.7981,0.1039,0.781,0.1078 Q0.7778,0.1088,0.7745,0.1088 T0.7644,0.1073 T0.7518,0.1048 L0.7453,0.1048 Q0.7299,0.1048,0.7076,0.1083 T0.6788,0.1157 Q0.6748,0.1187,0.6699,0.1187 Q0.6675,0.1187,0.6557,0.1157 T0.6318,0.1118 Q0.6164,0.1108,0.6135,0.1108 T0.6095,0.1113 T0.6067,0.1142 T0.6018,0.1187 Q0.5953,0.1227,0.5921,0.1227 Q0.5904,0.1227,0.5839,0.1212 T0.5693,0.1187 L0.5661,0.1187 Q0.558,0.1187,0.5527,0.1207 T0.5434,0.1246 T0.5337,0.1266 Q0.5126,0.1296,0.4882,0.1296 T0.4371,0.1385 Q0.4298,0.1414,0.425,0.1414 Q0.4225,0.1414,0.4189,0.1395 T0.4112,0.1375 Q0.4079,0.1375,0.4019,0.1395 T0.3869,0.1414 Q0.3682,0.1414,0.3504,0.1474 Q0.3398,0.1513,0.3333,0.1513 Q0.3293,0.1513,0.3228,0.1494 L0.3204,0.1494 Q0.3179,0.1494,0.3155,0.1508 T0.3118,0.1543 T0.3106,0.1592 T0.3127,0.1642 T0.32,0.1677 T0.3305,0.1701 T0.3435,0.1716 T0.3544,0.1721 Q0.3569,0.1731,0.3601,0.1731 Q0.3625,0.1731,0.3686,0.1726 T0.3779,0.1721 Q0.3901,0.1721,0.4023,0.1751 Q0.4177,0.18,0.455,0.18 Q0.4793,0.18,0.4882,0.178 L0.4915,0.178 Q0.4964,0.178,0.5045,0.1815 T0.5158,0.185 Q0.5564,0.1889,0.5645,0.1929 Q0.5677,0.1939,0.571,0.1939 Q0.575,0.1939,0.5807,0.1919 T0.5888,0.1899 T0.5929,0.1909 Q0.5969,0.1949,0.6123,0.1949 Q0.6334,0.1949,0.6456,0.1899 Q0.6488,0.1879,0.6537,0.1879 Q0.661,0.1879,0.6772,0.1929 T0.6983,0.1978 Q0.704,0.1988,0.7206,0.1998 T0.7502,0.2018 T0.7664,0.2038 Q0.7672,0.2038,0.7818,0.2043 T0.8151,0.2067 T0.8459,0.2156 Q0.8573,0.2206,0.8573,0.2255 Q0.8573,0.2295,0.8516,0.2324 T0.8394,0.2369 T0.8281,0.2384 Q0.8208,0.2384,0.7526,0.2473 Q0.7494,0.2483,0.7421,0.2493 T0.7287,0.2512 T0.7178,0.2522 L0.7153,0.2522 L0.7137,0.2522 Q0.7056,0.2522,0.6898,0.2572 T0.6691,0.2671 Q0.6667,0.269,0.6634,0.269 Q0.661,0.269,0.6557,0.2681 T0.6472,0.2671 Q0.6448,0.2671,0.6415,0.2681 Q0.631,0.271,0.6034,0.274 Q0.5994,0.274,0.5961,0.2765 T0.5904,0.2789 L0.5864,0.2789 Q0.5831,0.2779,0.5742,0.2779 Q0.541,0.2779,0.5223,0.2849 Q0.5126,0.2888,0.5028,0.2888 Q0.5004,0.2888,0.4943,0.2883 T0.4842,0.2878 Q0.4704,0.2878,0.4627,0.2898 T0.4509,0.2987 Q0.4501,0.2997,0.4501,0.3007 Q0.4501,0.3046,0.4574,0.3066 T0.4765,0.3091 T0.4899,0.3096 Q0.4931,0.3106,0.5061,0.3121 T0.5316,0.315 T0.5499,0.3175 Q0.5507,0.3175,0.5572,0.3195 T0.5685,0.3225 T0.5803,0.3254 T0.5933,0.3279 T0.605,0.3284 T0.6148,0.3274 Q0.6221,0.3244,0.6294,0.3244 Q0.6399,0.3244,0.6496,0.3294 Q0.6529,0.3314,0.6577,0.3314 Q0.6602,0.3314,0.6663,0.3304 T0.6756,0.3294 T0.6813,0.3304 Q0.6837,0.3304,0.6873,0.3309 L0.6946,0.3318 T0.7024,0.3323 T0.7105,0.3328 T0.7178,0.3338 T0.7238,0.3348 T0.7283,0.3363 Q0.7324,0.3383,0.7482,0.3403 T0.7689,0.3442 Q0.7697,0.3442,0.779,0.3477 T0.794,0.3536 T0.8074,0.3615 T0.8183,0.3729 Q0.8232,0.3808,0.8232,0.3848 Q0.8232,0.3867,0.8216,0.3892 T0.8151,0.3961 T0.8062,0.406 T0.7997,0.4179 T0.7952,0.4263 T0.7855,0.4308 T0.7616,0.4362 Q0.7543,0.4372,0.7445,0.4372 L0.7372,0.4372 L0.7307,0.4372 Q0.7202,0.4372,0.7153,0.4382 Q0.7064,0.4402,0.691,0.4402 L0.6845,0.4402 L0.6788,0.4402 Q0.6699,0.4402,0.6533,0.4436 T0.6318,0.451 Q0.6302,0.451,0.6302,0.452 Q0.6302,0.457,0.6626,0.459 Q0.6869,0.4609,0.7015,0.4659 Q0.7064,0.4669,0.7202,0.4669 L0.7311,0.4669 L0.7429,0.4669 Q0.7599,0.4669,0.7689,0.4688 Q0.7794,0.4708,0.7794,0.4738 L0.7786,0.4748 T0.777,0.4763 T0.7749,0.4773 L0.7737,0.4777 L0.7729,0.4777 Q0.7502,0.4797,0.738,0.4797 L0.7315,0.4797 L0.7291,0.4797 Q0.7226,0.4797,0.6869,0.4876 Q0.6821,0.4886,0.6768,0.4891 T0.6614,0.4901 T0.6456,0.4916 L0.6342,0.4916 Q0.6294,0.4916,0.6217,0.4911 T0.6115,0.4906 Q0.6083,0.4906,0.6054,0.4911 T0.5961,0.4936 T0.5815,0.4965 T0.5629,0.4985 Q0.5507,0.4985,0.5442,0.4995 T0.5345,0.5025 T0.5304,0.5084 L0.5296,0.5094 Q0.5296,0.5114,0.5316,0.5124 T0.5373,0.5138 T0.5442,0.5143 L0.5523,0.5143 L0.5604,0.5143 Q0.5637,0.5153,0.5677,0.5158 T0.5742,0.5173 T0.5811,0.5188 T0.5904,0.5193 L0.5977,0.5193 L0.6026,0.5193 Q0.6107,0.5193,0.6168,0.5208 T0.6294,0.5252 T0.6399,0.5292 Q0.6448,0.5302,0.6679,0.5341 T0.6983,0.541 Q0.7129,0.545,0.7664,0.55 Q0.7883,0.5519,0.7883,0.5559 Q0.7883,0.5579,0.7843,0.5608 T0.7721,0.5638 Q0.7697,0.5638,0.764,0.5633 T0.7559,0.5628 L0.7502,0.5628 Q0.7364,0.5648,0.6869,0.5648 L0.6699,0.5648 L0.6675,0.5648 Q0.665,0.5648,0.6602,0.5658 T0.6513,0.5668 Q0.6464,0.5668,0.6399,0.5658 Q0.6342,0.5648,0.6302,0.5648 T0.6225,0.5668 T0.6156,0.5697 Q0.6107,0.5707,0.6087,0.5707 T0.6034,0.5712 T0.5953,0.5717 Q0.5904,0.5727,0.5835,0.5727 T0.5718,0.5732 T0.562,0.5757 Q0.558,0.5767,0.5483,0.5767 L0.5349,0.5767 L0.5207,0.5767 Q0.5069,0.5767,0.5028,0.5786 Q0.4972,0.5816,0.4899,0.5816 Q0.4858,0.5816,0.4781,0.5806 T0.4663,0.5796 L0.4631,0.5796 Q0.4582,0.5796,0.4432,0.5821 T0.4144,0.5846 L0.4071,0.5846 L0.4011,0.5846 T0.3958,0.5851 T0.3921,0.5856 T0.3889,0.5861 T0.3865,0.5865 T0.384,0.5875 L0.382,0.5885 L0.3796,0.5895 L0.3771,0.5905 Q0.3731,0.5925,0.365,0.5925 L0.3601,0.5925 L0.3552,0.5925 Q0.3277,0.5925,0.3049,0.6044 Q0.3017,0.6053,0.296,0.6053 Q0.292,0.6053,0.2847,0.6044 T0.2741,0.6034 Q0.2693,0.6034,0.2547,0.6029 T0.236,0.6024 Q0.2222,0.6024,0.1922,0.6073 Q0.1906,0.6083,0.1882,0.6083 Q0.1833,0.6083,0.1711,0.6063 T0.1533,0.6044 Q0.1517,0.6034,0.1492,0.6034 Q0.1436,0.6034,0.135,0.6048 T0.1168,0.6078 T0.103,0.6093 Q0.0973,0.6103,0.0787,0.6103 L0.0604,0.6103 L0.0414,0.6103 L0.0235,0.6103 Q0.0024,0.6113,0.0024,0.6172 Q0.0024,0.6192,0.0032,0.6231 Q0.0049,0.6281,0.0333,0.6281 L0.0414,0.6281 L0.0479,0.6281 Q0.0519,0.6281,0.0624,0.6301 T0.0803,0.632 L0.0835,0.632 L0.0916,0.632 Q0.0989,0.632,0.1281,0.634 L0.206,0.6419 Q0.2117,0.6429,0.2174,0.6429 Q0.2214,0.6429,0.2271,0.6424 T0.2344,0.6419 L0.2376,0.6419 Q0.2393,0.6429,0.2417,0.6429 T0.2526,0.6419 T0.2652,0.6409 Q0.2741,0.6409,0.2782,0.6429 T0.2968,0.6459 T0.3293,0.6479 T0.352,0.6489 Q0.3552,0.6499,0.3585,0.6499 Q0.365,0.6499,0.3731,0.6474 T0.3844,0.6449 Q0.3885,0.6449,0.3917,0.6474 T0.4006,0.6499 Q0.4088,0.6499,0.4509,0.6578 Q0.4574,0.6588,0.4631,0.6588 Q0.4655,0.6588,0.4716,0.6583 T0.4834,0.6578 L0.4874,0.6578 Q0.5004,0.6588,0.5255,0.6637 Q0.532,0.6647,0.56,0.6667 T0.6148,0.6701 T0.644,0.6716 Q0.6464,0.6726,0.6594,0.6736 T0.6861,0.6756 T0.7048,0.6775 Q0.7097,0.6775,0.7186,0.6825 T0.738,0.6874 Q0.7518,0.6874,0.7729,0.6958 T0.8005,0.7122 Q0.8029,0.7141,0.8029,0.7151 Q0.8029,0.7191,0.7968,0.7216 T0.7818,0.726 T0.7705,0.729 L0.764,0.731 T0.7583,0.7324 T0.753,0.7334 T0.7486,0.7349 Q0.7251,0.7399,0.7161,0.7399 Q0.7097,0.7399,0.6951,0.7409 T0.6748,0.7418 L0.6703,0.7418 L0.6667,0.7418 Q0.6659,0.7418,0.6399,0.7448 L0.6334,0.7448 Q0.631,0.7448,0.6249,0.7443 T0.6148,0.7438 L0.6099,0.7438 Q0.601,0.7448,0.5856,0.7473 T0.5645,0.7507 Q0.5572,0.7517,0.5572,0.7547 T0.5616,0.7606 T0.5702,0.7646 Q0.5734,0.7646,0.5779,0.7651 T0.5864,0.7661 T0.5949,0.7671 T0.6018,0.7676 L0.6071,0.7676 T0.6135,0.7681 T0.62,0.769 T0.6269,0.771 T0.6342,0.7725 Q0.6391,0.7725,0.6464,0.7705 T0.6541,0.7685 L0.6553,0.7685 Q0.6586,0.7685,0.6699,0.771 T0.6853,0.7735 Q0.6902,0.7735,0.704,0.777 T0.7226,0.7834 Q0.7315,0.7873,0.7445,0.7883 Q0.747,0.7883,0.7676,0.7893 T0.7972,0.7913 Q0.7989,0.7913,0.8017,0.7918 T0.8058,0.7923 T0.809,0.7928 T0.8114,0.7933 T0.8131,0.7938 T0.8147,0.7943 T0.8159,0.7953 L0.8171,0.7967 T0.8175,0.7982 Q0.8183,0.7992,0.8183,0.8002 Q0.8183,0.8022,0.8155,0.8032 T0.807,0.8051 T0.7989,0.8071 Q0.7932,0.8091,0.7737,0.8091 L0.7413,0.8091 L0.7372,0.8091 Q0.7275,0.8091,0.721,0.8101 T0.7072,0.8136 T0.6983,0.817 Q0.6942,0.818,0.6825,0.818 T0.6602,0.819 T0.6456,0.822 Q0.6415,0.8249,0.6375,0.8249 Q0.6367,0.8249,0.6326,0.8239 T0.6253,0.8229 Q0.6034,0.8229,0.5953,0.8279 Q0.5912,0.8289,0.5848,0.8289 Q0.5775,0.8289,0.5645,0.8279 Q0.5629,0.8269,0.5604,0.8269 Q0.5523,0.8269,0.5328,0.8348 Q0.5296,0.8358,0.5264,0.8358 Q0.5247,0.8358,0.5203,0.8353 T0.5126,0.8348 Q0.5061,0.8348,0.4988,0.8358 Q0.4947,0.8368,0.4882,0.8378 Q0.4826,0.8388,0.4797,0.8388 T0.474,0.8398 T0.4704,0.8422 T0.4696,0.8462 T0.472,0.8501 T0.4781,0.8521 T0.4854,0.8526 L0.4935,0.8526 T0.4996,0.8536 Q0.5036,0.8536,0.515,0.8546 T0.5337,0.8566 Q0.5426,0.8576,0.5596,0.8576 L0.5657,0.8576 L0.571,0.8576 L0.5791,0.8576 Q0.5921,0.8586,0.6135,0.8591 T0.6383,0.8605 Q0.6683,0.8635,0.6764,0.8635 Q0.6999,0.8635,0.6999,0.8684 Q0.6999,0.8694,0.6967,0.8734 T0.6934,0.8803 L0.6934,0.8823 Q0.6951,0.8863,0.7137,0.8863 Q0.7218,0.8863,0.7267,0.8853 L0.7299,0.8853 Q0.734,0.8853,0.7409,0.8882 T0.7502,0.8912 Q0.7607,0.8942,0.794,0.8971 Q0.7972,0.8971,0.8078,0.9001 T0.8297,0.9031 Q0.8475,0.9031,0.8646,0.9065 T0.8824,0.9149 L0.8824,0.9159 Q0.8824,0.9169,0.882,0.9179 T0.8808,0.9194 L0.8792,0.9204 T0.8767,0.9214 T0.8743,0.9224 T0.8715,0.9228 L0.8686,0.9228 T0.8662,0.9233 T0.8637,0.9238 L0.8556,0.9238 T0.8447,0.9243 T0.8386,0.9268 Q0.837,0.9278,0.835,0.9288 T0.8305,0.9303 T0.8244,0.9308 T0.8175,0.9318 Q0.8127,0.9327,0.8017,0.9352 T0.7851,0.9397 Q0.777,0.9416,0.7705,0.9451 T0.7616,0.9496 Q0.7575,0.9505,0.7494,0.9505 L0.7405,0.9505 L0.7307,0.9505 Q0.7234,0.9505,0.7178,0.9515 Q0.7145,0.9515,0.7125,0.9535 T0.7105,0.9575 Q0.7105,0.9624,0.7194,0.9634 Q0.7567,0.9654,0.7664,0.9674 Q0.7745,0.9693,0.7762,0.9693 L0.7908,0.9693 L0.7948,0.9693 Q0.8005,0.9693,0.8058,0.9698 T0.8143,0.9718 T0.824,0.9753 T0.8354,0.9792 Q0.8483,0.9832,0.871,0.9832 L0.8739,0.9832 L0.8767,0.9832 Q0.8873,0.9832,0.8921,0.9842 Q0.8978,0.9852,0.9157,0.9896 T0.94,0.996 Q0.9424,0.996,0.9469,0.9965 T0.9566,0.997 T0.9676,0.9975 T0.9781,0.998 L0.9874,0.998 L0.9943,0.998 L0.9968,0.998 Z",type:0}},"":{type:5,data:{d:"M1,0.5071 L0.8623,0.7102 L0.5865,0.7102 L0.4489,0.5071 L0.5865,0.3045 L0.8623,0.3045 Z M0.4135,0.7974 L0.2758,1 L0,1 L0,0.5944 L0.2758,0.5944 Z M0.4135,0.2026 L0.2758,0.4056 L0,0.4056 L0,0 L0.2758,0 Z",type:0}},"":{type:5,data:{d:"M0.9726,0.5071 L0.8451,0.3184 L0.59,0.3184 L0.4624,0.5071 L0.59,0.6955 L0.8451,0.6955 Z M1,0.5071 L0.8588,0.716 L0.5768,0.716 L0.4355,0.5071 L0.5768,0.2982 L0.8588,0.2982 Z M0.401,0.7911 L0.2735,0.6028 L0.0236,0.6028 L0.0236,0.9799 L0.2735,0.9799 Z M0.4284,0.7911 L0.2872,1 L0,1 L0,0.5826 L0.2872,0.5826 Z M0.401,0.2089 L0.2735,0.0201 L0.0236,0.0201 L0.0236,0.3972 L0.2735,0.3972 Z M0.4284,0.2089 L0.2872,0.4174 L0,0.4174 L0,0 L0.2872,0 Z",type:0}},"":{type:5,data:{d:"M1,0.4996 Q1,0.5365,0.9924,0.568 T0.9718,0.6177 T0.9433,0.6363 L0.9425,0.6367 Q0.9355,0.6367,0.9285,0.6326 L0.9308,0.6326 Q0.9129,0.6195,0.9013,0.587 T0.8871,0.5164 T0.8943,0.4373 T0.9254,0.3687 L0.9254,0.3691 Q0.9339,0.3628,0.9425,0.3628 Q0.9584,0.3628,0.9716,0.3811 T0.9924,0.431 T1,0.4996 Z M0.9234,0.6321 L0.8776,0.7169 Q0.8791,0.732,0.8791,0.7441 Q0.8791,0.781,0.8716,0.8123 T0.8508,0.862 T0.8224,0.8809 L0.8216,0.8809 Q0.8154,0.8809,0.8092,0.8775 L0.8088,0.8775 Q0.7905,0.8633,0.7792,0.8297 T0.766,0.7571 T0.775,0.6768 T0.8088,0.6086 L0.7431,0.6065 Q0.719,0.6313,0.7072,0.6705 T0.6965,0.7487 T0.7097,0.823 T0.7423,0.8763 L0.7913,0.8775 L0.7314,0.9895 L0.4648,0.5038 L0.7299,0.0176 L0.7882,0.1229 L0.7404,0.1212 Q0.7244,0.138,0.7136,0.1617 T0.6982,0.2108 T0.6943,0.2632 T0.7003,0.3144 T0.7159,0.3586 T0.7396,0.3909 L0.8072,0.3926 Q0.7894,0.3796,0.7777,0.3479 T0.7635,0.2789 T0.7697,0.2011 T0.7987,0.1326 Q0.8092,0.1225,0.8204,0.1225 Q0.8321,0.1225,0.8426,0.1332 T0.8609,0.1623 T0.8731,0.2062 T0.8776,0.2592 Q0.8776,0.268,0.8768,0.2815 L0.9219,0.3628 L0.8644,0.3612 Q0.8403,0.3855,0.8284,0.4247 T0.8177,0.5029 T0.8309,0.5772 T0.8632,0.6305 Z M0.6759,0.6384 Q0.6576,0.625,0.6457,0.5914 T0.6319,0.5185 T0.6407,0.4375 T0.6751,0.3691 L0.609,0.367 Q0.5849,0.3918,0.5731,0.431 T0.5626,0.509 T0.5758,0.5833 T0.6082,0.6367 Z M0.6459,0.0025 L0.391,0.4551 L0.0035,0.4551 L0.246,0 Z M0.6553,1 L0.2421,1 L0,0.5449 L0.3875,0.5449 Z",type:0}},"":{type:5,data:{d:"M0.4996,0 Q0.5562,0,0.5961,0.0166 T0.6364,0.0566 L0.6368,0.0575 Q0.6368,0.0646,0.6324,0.0713 L0.6324,0.0692 Q0.6196,0.0868,0.5872,0.0986 T0.5166,0.1128 T0.4373,0.1057 T0.3689,0.0747 L0.3694,0.0747 Q0.3627,0.0663,0.3627,0.0575 Q0.3627,0.0336,0.4028,0.0168 T0.4996,0 Z M0.6324,0.0768 L0.717,0.1225 Q0.7321,0.1212,0.744,0.1212 Q0.8007,0.1212,0.8406,0.1378 T0.8809,0.1779 L0.8813,0.1783 Q0.8813,0.1846,0.8778,0.1909 Q0.8636,0.2093,0.8299,0.2208 T0.7573,0.2343 T0.6769,0.2253 T0.6089,0.1913 L0.6067,0.2567 Q0.6315,0.281,0.6707,0.2928 T0.7489,0.3035 T0.8231,0.2903 T0.8764,0.258 L0.8778,0.2085 L0.9898,0.2685 L0.504,0.5352 L0.0177,0.2701 L0.1227,0.2118 L0.1213,0.2596 Q0.1457,0.2836,0.1851,0.2955 T0.2635,0.3062 T0.3377,0.293 T0.3911,0.2605 L0.3928,0.193 Q0.38,0.2106,0.3483,0.2221 T0.2792,0.2364 T0.2013,0.2303 T0.1324,0.2013 Q0.1222,0.1909,0.1222,0.1795 Q0.1222,0.156,0.1623,0.1393 T0.2591,0.1225 Q0.2679,0.1225,0.2817,0.1233 L0.3627,0.078 L0.3609,0.1359 Q0.3857,0.1598,0.4249,0.1718 T0.5031,0.1825 T0.5773,0.1693 T0.6306,0.1367 Z M0.6386,0.3242 Q0.6253,0.3427,0.5917,0.3544 T0.5186,0.3683 T0.4376,0.3595 T0.3689,0.3251 L0.3671,0.3909 Q0.3915,0.4148,0.4309,0.4268 T0.5093,0.4375 T0.5835,0.4243 T0.6368,0.3918 Z M0.0027,0.354 L0.4553,0.6091 L0.4553,0.9962 L0,0.7542 Z M1,0.3448 L1,0.7576 L0.5447,1 L0.5447,0.6128 Z",type:0}},"":{type:5,data:{d:"M0,0.7699 Q0,0.7172,0.0277,0.6731 T0.103,0.6032 T0.2066,0.5774 Q0.2487,0.5774,0.2865,0.5922 T0.3526,0.6339 L0.3935,0.6715 Q0.4218,0.6984,0.438,0.7336 T0.4541,0.8075 Q0.4541,0.8602,0.4264,0.9046 T0.3511,0.9745 T0.2475,1 Q0.2054,1,0.1676,0.9852 T0.1016,0.9435 L0.0606,0.9059 Q0.0317,0.879,0.0159,0.8438 T0,0.7699 Z M0.5459,0.7699 Q0.5459,0.7172,0.5736,0.6731 T0.6489,0.6032 T0.7525,0.5774 Q0.7946,0.5774,0.8324,0.5922 T0.8984,0.6339 L0.9394,0.6715 Q0.9579,0.6892,0.9714,0.7105 T0.9925,0.7567 T1,0.8075 Q1,0.8602,0.9723,0.9046 T0.897,0.9745 T0.7934,1 Q0.7513,1,0.7135,0.9852 T0.6474,0.9435 L0.6065,0.9059 Q0.5776,0.879,0.5617,0.8438 T0.5459,0.7699 Z M0,0.1925 Q0,0.1398,0.0277,0.0957 T0.103,0.0258 T0.2066,0 Q0.2487,0,0.2865,0.0148 T0.3526,0.0565 L0.3935,0.0941 Q0.4218,0.121,0.438,0.1562 T0.4541,0.2301 Q0.4541,0.2828,0.4264,0.3269 T0.3511,0.3968 T0.2475,0.4226 Q0.2054,0.4226,0.1676,0.4078 T0.1016,0.3661 L0.0606,0.3285 Q0.0317,0.3016,0.0159,0.2664 T0,0.1925 Z M0.5459,0.1925 Q0.5459,0.1398,0.5736,0.0957 T0.6489,0.0258 T0.7525,0 Q0.7946,0,0.8324,0.0148 T0.8984,0.0565 L0.9394,0.0941 Q0.9677,0.121,0.9838,0.1562 T1,0.2301 Q1,0.2828,0.9723,0.3269 T0.897,0.3968 T0.7934,0.4226 Q0.7513,0.4226,0.7135,0.4078 T0.6474,0.3661 L0.6065,0.3285 Q0.5874,0.3108,0.5741,0.2895 T0.5534,0.2433 T0.5459,0.1925 Z M0.3301,0.6403 Q0.3306,0.6403,0.3312,0.6409 L0.3272,0.6371 L0.3272,0.6371 Z M0.8759,0.6403 Q0.8765,0.6403,0.8771,0.6409 Q0.8748,0.6387,0.8725,0.6371 L0.8731,0.6371 Z M0.3301,0.0629 Q0.3306,0.0629,0.3312,0.0634 L0.3272,0.0597 L0.3272,0.0602 Z M0.8759,0.0629 Q0.8765,0.0629,0.8771,0.0634 Q0.8748,0.0613,0.8725,0.0597 Q0.8731,0.0597,0.8731,0.0602 Z M0.779,0.4113 L0.7501,0.3849 Q0.7046,0.3844,0.6636,0.3661 Q0.7132,0.407,0.779,0.4113 Z M0.7957,0.4118 Q0.8477,0.4113,0.8918,0.3874 T0.9619,0.3223 T0.9885,0.2323 L0.9585,0.2048 Q0.9538,0.2769,0.8987,0.3282 T0.7657,0.3844 Z M0.9879,0.2167 Q0.9827,0.1554,0.9388,0.1097 Q0.9585,0.1478,0.959,0.1898 Z M0.2331,0.4113 L0.2043,0.3849 Q0.1587,0.3844,0.1177,0.3661 Q0.1673,0.407,0.2331,0.4113 Z M0.2499,0.4118 Q0.2885,0.4118,0.324,0.3973 T0.3852,0.3589 T0.4264,0.3019 T0.4426,0.2323 L0.4126,0.2048 Q0.408,0.2769,0.3529,0.3282 T0.2198,0.3844 Z M0.442,0.2167 Q0.4368,0.1554,0.393,0.1097 Q0.4126,0.1478,0.4132,0.1903 Z M0.779,0.9887 L0.7501,0.9624 Q0.7046,0.9618,0.6636,0.9435 Q0.7132,0.9844,0.779,0.9887 Z M0.7957,0.9892 Q0.8477,0.9887,0.8918,0.9648 T0.9619,0.8997 T0.9885,0.8097 L0.9585,0.7823 Q0.9538,0.8543,0.8987,0.9056 T0.7657,0.9618 Z M0.9879,0.7941 Q0.9827,0.7328,0.9388,0.6871 Q0.9585,0.7253,0.959,0.7672 Z M0.2331,0.9887 L0.2043,0.9624 Q0.1587,0.9618,0.1177,0.9435 Q0.1673,0.9844,0.2331,0.9887 Z M0.2499,0.9892 Q0.3018,0.9887,0.3459,0.9648 T0.416,0.8997 T0.4426,0.8102 L0.4126,0.7823 Q0.408,0.8543,0.3529,0.9056 T0.2198,0.9618 Z M0.442,0.7941 Q0.4368,0.7328,0.393,0.6871 Q0.4126,0.7253,0.4132,0.7672 Z M0.3191,0.6452 Q0.2943,0.622,0.2643,0.6091 T0.2066,0.5962 Q0.1795,0.5962,0.1497,0.6091 T0.0949,0.6441 T0.0537,0.6995 T0.0375,0.7699 Q0.0375,0.8419,0.0941,0.8941 Q0.1189,0.9172,0.1489,0.9304 T0.2066,0.9435 Q0.2337,0.9435,0.2634,0.9304 T0.3182,0.8952 T0.3595,0.8398 T0.3756,0.7699 Q0.3756,0.6978,0.3191,0.6452 Z M0.026,0.7731 L0.026,0.7699 Q0.026,0.6935,0.0854,0.6376 Q0.0658,0.6538,0.0514,0.6739 T0.0289,0.718 T0.0202,0.7677 Z M0.0271,0.7892 L0.0208,0.7833 Q0.0254,0.8419,0.0681,0.886 Q0.0664,0.8828,0.0646,0.879 Q0.0329,0.8382,0.0271,0.7892 Z M0.3866,0.7823 Q0.382,0.8511,0.3278,0.9016 Q0.3843,0.8565,0.3918,0.7871 Z M0.3872,0.7677 L0.393,0.7726 L0.393,0.7699 Q0.393,0.7349,0.3791,0.7038 Q0.3739,0.6973,0.3681,0.6914 Q0.3866,0.7274,0.3872,0.7677 Z M0.865,0.6452 Q0.8402,0.622,0.8102,0.6091 T0.7525,0.5962 Q0.7305,0.5962,0.7072,0.6043 T0.6619,0.628 T0.6223,0.6642 T0.5941,0.7124 T0.5834,0.7699 Q0.5834,0.8419,0.6399,0.8941 Q0.6561,0.9097,0.6757,0.9207 T0.7149,0.9376 T0.7525,0.9435 Q0.7796,0.9435,0.8093,0.9304 T0.8641,0.8952 T0.9054,0.8398 T0.9215,0.7699 Q0.9215,0.6978,0.865,0.6452 Z M0.5718,0.7731 L0.5718,0.7699 Q0.5718,0.6935,0.6313,0.6376 Q0.6013,0.6618,0.584,0.6954 T0.5661,0.7677 Z M0.573,0.7892 L0.5666,0.7833 Q0.5713,0.8419,0.614,0.886 Q0.6122,0.8828,0.6105,0.879 Q0.5788,0.8382,0.573,0.7892 Z M0.9325,0.7823 Q0.9279,0.8511,0.8736,0.9016 Q0.9308,0.8565,0.9377,0.7871 Z M0.9331,0.7672 L0.9388,0.7726 L0.9388,0.7699 Q0.9388,0.7349,0.925,0.7038 Q0.9198,0.6973,0.914,0.6914 Q0.9325,0.7274,0.9331,0.7672 Z M0.3191,0.0677 Q0.2943,0.0446,0.2643,0.0317 T0.2066,0.0188 Q0.1795,0.0188,0.1497,0.0317 T0.0949,0.0667 T0.0537,0.122 T0.0375,0.1925 Q0.0375,0.2645,0.0941,0.3167 Q0.1189,0.3398,0.1489,0.353 T0.2066,0.3661 Q0.2337,0.3661,0.2634,0.353 T0.3182,0.3177 T0.3595,0.2624 T0.3756,0.1925 Q0.3756,0.1204,0.3191,0.0677 Z M0.026,0.1957 L0.026,0.1925 Q0.026,0.1161,0.0854,0.0602 Q0.0554,0.0844,0.0381,0.118 T0.0202,0.1903 Z M0.0271,0.2118 L0.0208,0.2059 Q0.0254,0.2645,0.0681,0.3086 Q0.0664,0.3054,0.0646,0.3016 Q0.0329,0.2608,0.0271,0.2118 Z M0.3866,0.2048 Q0.382,0.2737,0.3278,0.3242 Q0.3849,0.279,0.3918,0.2097 Z M0.3872,0.1903 L0.393,0.1952 L0.393,0.1925 Q0.393,0.1581,0.3791,0.1263 Q0.3739,0.1199,0.3681,0.114 Q0.3866,0.15,0.3872,0.1903 Z M0.865,0.0677 Q0.8402,0.0446,0.8102,0.0317 T0.7525,0.0188 Q0.7253,0.0188,0.6956,0.0317 T0.6408,0.0667 T0.5995,0.122 T0.5834,0.1925 Q0.5834,0.2645,0.6399,0.3167 Q0.6647,0.3398,0.6947,0.353 T0.7525,0.3661 Q0.7796,0.3661,0.8093,0.353 T0.8641,0.3177 T0.9054,0.2624 T0.9215,0.1925 Q0.9215,0.1204,0.865,0.0677 Z M0.5718,0.1957 L0.5718,0.1925 Q0.5718,0.1161,0.6313,0.0602 Q0.6013,0.0844,0.584,0.118 T0.5661,0.1903 Z M0.573,0.2118 L0.5666,0.2059 Q0.5713,0.2645,0.614,0.3086 Q0.6122,0.3054,0.6105,0.3016 Q0.5788,0.2608,0.573,0.2118 Z M0.9325,0.2048 Q0.9279,0.2737,0.8736,0.3242 Q0.9308,0.279,0.9377,0.2097 Z M0.9331,0.1898 L0.9388,0.1952 L0.9388,0.1925 Q0.9388,0.1575,0.925,0.1263 Q0.9198,0.1199,0.914,0.114 Q0.9325,0.15,0.9331,0.1898 Z",type:0}},"":{type:5,data:{d:"M0.7639,0.1974 L0.9593,0.1974 L0.9593,0.1443 L0.7639,0.1443 L0.7639,0.1974 Z M0.7586,0.109 L0.9727,0.109 Q0.9839,0.109,0.992,0.1153 T1,0.1291 L1,0.382 Q1,0.3906,0.9912,0.3964 T0.9727,0.4021 L0.7586,0.4021 Q0.7468,0.4021,0.739,0.3956 T0.7313,0.382 L0.7313,0.1291 Q0.7313,0.1246,0.7339,0.1207 T0.7406,0.1143 T0.7495,0.1104 T0.7586,0.109 Z M0.7639,0.6575 L0.9593,0.6575 L0.9593,0.6044 L0.7639,0.6044 L0.7639,0.6575 Z M0.7313,0.8347 L0.7313,0.5843 Q0.7313,0.5757,0.7401,0.5699 T0.7586,0.5641 L0.9706,0.5641 Q0.9818,0.5641,0.9898,0.5705 T0.9979,0.5843 L0.9979,0.8347 Q0.9979,0.8433,0.989,0.8491 T0.9706,0.8549 L0.7586,0.8549 Q0.7468,0.8549,0.739,0.8483 T0.7313,0.8347 Z M0,1 L0,0 L0.7607,0 L0.7607,1 L0,1 Z",type:0}},"":{type:5,data:{d:"M0.9764,0.0029 L0.3179,0.4552 L0,0.4552 L0,0 Z M1,1 L0,1 L0,0.5448 L0.3091,0.5448 Z",type:0}},"":{type:5,data:{d:"M0.0236,0.0029 L0.6824,0.4552 L1,0.4552 L1,0 Z M0,1 L1,1 L1,0.5448 L0.6912,0.5448 Z",type:0}},"":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z"},"":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z"},"":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z"},"":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z M.25,.15 L1,.15 L1,.85 L.25,.85 Z"},"":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z M0,.15 L1,.15 L1,.85 L0,.85 Z"},"":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z M0,.15 L.75,.15 L.75,.85 L0,.85 Z"},"":{type:5,data:{d:"M0.6574,0.303 Q0.623,0.291,0.5852,0.285 T0.5082,0.279 T0.4311,0.285 T0.359,0.303 L0.3082,0.248 Q0.3525,0.232,0.4041,0.2235 T0.5082,0.215 T0.6123,0.2235 T0.7082,0.248 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.8557,0.582 L0.7656,0.551 Q0.7852,0.53,0.7951,0.507 T0.8049,0.46 Q0.8049,0.424,0.782,0.3905 T0.718,0.332 T0.6221,0.293 T0.5082,0.279 L0.5082,0.215 Q0.5607,0.215,0.6123,0.2235 T0.709,0.248 T0.7918,0.287 T0.8557,0.3375 T0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.582 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.5082,0.705 Q0.482,0.705,0.4557,0.703 T0.4049,0.697 L0.4311,0.635 Q0.4508,0.638,0.4697,0.6395 T0.5082,0.641 Q0.5672,0.641,0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 Q0.8049,0.436,0.7951,0.413 T0.7656,0.369 L0.8557,0.338 Q0.882,0.365,0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 L0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 T0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 L0.9098,0.46 Q0.9098,0.492,0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.338 L0.2508,0.369 Q0.2311,0.39,0.2213,0.413 T0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 Q0.5279,0.641,0.5467,0.6395 T0.5852,0.635 L0.6115,0.697 Q0.5869,0.701,0.5607,0.703 T0.5082,0.705 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.1607,0.582 Q0.1344,0.555,0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.3375 T0.2246,0.287 T0.3074,0.248 T0.4041,0.2235 T0.5082,0.215 L0.5082,0.279 Q0.4492,0.279,0.3943,0.293 T0.2984,0.332 T0.2344,0.3905 T0.2115,0.46 Q0.2115,0.484,0.2213,0.507 T0.2508,0.551 Z",type:0},scaleType:1},"":i.LINE_H,"":i.LINE_V,"":i.FADE_RIGHT,"":i.FADE_LEFT,"":i.FADE_DOWN,"":i.FADE_UP,"":i.CURVE_DOWN_RIGHT,"":i.CURVE_DOWN_LEFT,"":i.CURVE_UP_RIGHT,"":i.CURVE_UP_LEFT,"":[i.LINE_V,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_DOWN_RIGHT],"":[i.CURVE_DOWN_RIGHT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_UP_LEFT],"":[i.LINE_V,i.CURVE_DOWN_LEFT],"":[i.CURVE_DOWN_LEFT,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_DOWN_LEFT],"":[i.LINE_H,i.CURVE_DOWN_RIGHT],"":[i.CURVE_DOWN_LEFT,i.CURVE_DOWN_RIGHT],"":[i.LINE_H,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_UP_RIGHT],"":[i.CURVE_UP_LEFT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_UP_LEFT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_DOWN_LEFT,i.CURVE_DOWN_RIGHT],"":[i.LINE_H,i.CURVE_DOWN_LEFT,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_DOWN_RIGHT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_DOWN_RIGHT,i.CURVE_UP_LEFT],"":[i.LINE_V,i.CURVE_DOWN_LEFT,i.CURVE_UP_RIGHT],"":[i.LINE_H,i.CURVE_DOWN_RIGHT,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_DOWN_LEFT,i.CURVE_UP_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE],"":i.NODE_STROKE,"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN],"":[i.NODE_STROKE,i.NODE_LINE_DOWN],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP],"":[i.NODE_STROKE,i.NODE_LINE_UP],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_UP],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_UP],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"🬀":s(1),"🬁":s(2),"🬂":s(3),"🬃":s(4),"🬄":s(5),"🬅":s(6),"🬆":s(7),"🬇":s(8),"🬈":s(9),"🬉":s(10),"🬊":s(11),"🬋":s(12),"🬌":s(13),"🬍":s(14),"🬎":s(15),"🬏":s(16),"🬐":s(17),"🬑":s(18),"🬒":s(19),"🬓":s(20),"🬔":s(22),"🬕":s(23),"🬖":s(24),"🬗":s(25),"🬘":s(26),"🬙":s(27),"🬚":s(28),"🬛":s(29),"🬜":s(30),"🬝":s(31),"🬞":s(32),"🬟":s(33),"🬠":s(34),"🬡":s(35),"🬢":s(36),"🬣":s(37),"🬤":s(38),"🬥":s(39),"🬦":s(40),"🬧":s(41),"🬨":s(43),"🬩":s(44),"🬪":s(45),"🬫":s(46),"🬬":s(47),"🬭":s(48),"🬮":s(49),"🬯":s(50),"🬰":s(51),"🬱":s(52),"🬲":s(53),"🬳":s(54),"🬴":s(55),"🬵":s(56),"🬶":s(57),"🬷":s(58),"🬸":s(59),"🬹":s(60),"🬺":s(61),"🬻":s(62),"🬼":{type:3,data:"M0,0.6667 L0,1 L0.5,1 Z"},"🬽":{type:3,data:"M0,0.6667 L0,1 L1,1 Z"},"🬾":{type:3,data:"M0,0.3333 L0,1 L0.5,1 Z"},"🬿":{type:3,data:"M0,0.3333 L0,1 L1,1 Z"},"🭀":{type:3,data:"M0,0 L0,1 L0.5,1 Z"},"🭁":{type:3,data:"M0,0.3333 L0.5,0 L1,0 L1,1 L0,1 Z"},"🭂":{type:3,data:"M0,0.3333 L1,0 L1,1 L0,1 Z"},"🭃":{type:3,data:"M0,0.6667 L0.5,0 L1,0 L1,1 L0,1 Z"},"🭄":{type:3,data:"M0,0.6667 L1,0 L1,1 L0,1 Z"},"🭅":{type:3,data:"M0,1 L0.5,0 L1,0 L1,1 Z"},"🭆":{type:3,data:"M0,0.6667 L1,0.3333 L1,1 L0,1 Z"},"🭇":{type:3,data:"M0.5,1 L1,0.6667 L1,1 Z"},"🭈":{type:3,data:"M0,1 L1,0.6667 L1,1 Z"},"🭉":{type:3,data:"M0.5,1 L1,0.3333 L1,1 Z"},"🭊":{type:3,data:"M0,1 L1,0.3333 L1,1 Z"},"🭋":{type:3,data:"M0.5,1 L1,0 L1,1 Z"},"🭌":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.3333 Z"},"🭍":{type:3,data:"M0,0 L0,1 L1,1 L1,0.3333 Z"},"🭎":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.6667 Z"},"🭏":{type:3,data:"M0,0 L0,1 L1,1 L1,0.6667 Z"},"🭐":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 Z"},"🭑":{type:3,data:"M0,0.3333 L0,1 L1,1 L1,0.6667 Z"},"🭒":{type:3,data:"M0,0.6667 L0.5,1 L1,1 L1,0 L0,0 Z"},"🭓":{type:3,data:"M0,0.6667 L1,1 L1,0 L0,0 Z"},"🭔":{type:3,data:"M0,0.3333 L0.5,1 L1,1 L1,0 L0,0 Z"},"🭕":{type:3,data:"M0,0.3333 L1,1 L1,0 L0,0 Z"},"🭖":{type:3,data:"M0,0 L0.5,1 L1,1 L1,0 Z"},"🭗":{type:3,data:"M0,0.3333 L0,0 L0.5,0 Z"},"🭘":{type:3,data:"M0,0.3333 L0,0 L1,0 Z"},"🭙":{type:3,data:"M0,0.6667 L0,0 L0.5,0 Z"},"🭚":{type:3,data:"M0,0.6667 L0,0 L1,0 Z"},"🭛":{type:3,data:"M0,1 L0,0 L0.5,0 Z"},"🭜":{type:3,data:"M0,0.6667 L0,0 L1,0 L1,0.3333 Z"},"🭝":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.6667 Z"},"🭞":{type:3,data:"M0,1 L0,0 L1,0 L1,0.6667 Z"},"🭟":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.3333 Z"},"🭠":{type:3,data:"M0,1 L0,0 L1,0 L1,0.3333 Z"},"🭡":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 Z"},"🭢":{type:3,data:"M0.5,0 L1,0 L1,0.3333 Z"},"🭣":{type:3,data:"M0,0 L1,0 L1,0.3333 Z"},"🭤":{type:3,data:"M0.5,0 L1,0 L1,0.6667 Z"},"🭥":{type:3,data:"M0,0 L1,0 L1,0.6667 Z"},"🭦":{type:3,data:"M0.5,0 L1,0 L1,1 Z"},"🭧":{type:3,data:"M0,0.3333 L1,0.6667 L1,0 L0,0 Z"},"🭨":{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0.5,0.5 Z"},"🭩":{type:3,data:"M0,0 L0.5,0.5 L1,0 L1,1 L0,1 Z"},"🭪":{type:3,data:"M0,0 L1,0 L0.5,0.5 L1,1 L0,1 Z"},"🭫":{type:3,data:"M0,0 L1,0 L1,1 L0.5,0.5 L0,1 Z"},"🭬":{type:3,data:"M0,0 L0.5,0.5 L0,1 Z"},"🭭":{type:3,data:"M0,0 L1,0 L0.5,0.5 Z"},"🭮":{type:3,data:"M1,0 L1,1 L0.5,0.5 Z"},"🭯":{type:3,data:"M0,1 L1,1 L0.5,0.5 Z"},"🭰":{type:0,data:[{x:1,y:0,w:1,h:8}]},"🭱":{type:0,data:[{x:2,y:0,w:1,h:8}]},"🭲":{type:0,data:[{x:3,y:0,w:1,h:8}]},"🭳":{type:0,data:[{x:4,y:0,w:1,h:8}]},"🭴":{type:0,data:[{x:5,y:0,w:1,h:8}]},"🭵":{type:0,data:[{x:6,y:0,w:1,h:8}]},"🭶":{type:0,data:[{x:0,y:1,w:8,h:1}]},"🭷":{type:0,data:[{x:0,y:2,w:8,h:1}]},"🭸":{type:0,data:[{x:0,y:3,w:8,h:1}]},"🭹":{type:0,data:[{x:0,y:4,w:8,h:1}]},"🭺":{type:0,data:[{x:0,y:5,w:8,h:1}]},"🭻":{type:0,data:[{x:0,y:6,w:8,h:1}]},"🭼":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"🭽":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"🭾":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"🭿":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"🮀":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:7,w:8,h:1}]},"🮁":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:2,w:8,h:1},{x:0,y:4,w:8,h:1},{x:0,y:7,w:8,h:1}]},"🮂":{type:0,data:[{x:0,y:0,w:8,h:2}]},"🮃":{type:0,data:[{x:0,y:0,w:8,h:3}]},"🮄":{type:0,data:[{x:0,y:0,w:8,h:5}]},"🮅":{type:0,data:[{x:0,y:0,w:8,h:6}]},"🮆":{type:0,data:[{x:0,y:0,w:8,h:7}]},"🮇":{type:0,data:[{x:6,y:0,w:2,h:8}]},"🮈":{type:0,data:[{x:5,y:0,w:3,h:8}]},"🮉":{type:0,data:[{x:3,y:0,w:5,h:8}]},"🮊":{type:0,data:[{x:2,y:0,w:6,h:8}]},"🮋":{type:0,data:[{x:1,y:0,w:7,h:8}]},"🮌":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},"🮍":{type:1,data:[[1,0],[0,1]],clipPath:"M0.5,0 L1,0 L1,1 L0.5,1 Z"},"🮎":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},"🮏":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},"🮐":{type:1,data:[[0,1],[1,0]]},"🮑":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},{type:0,data:[{x:0,y:0,w:8,h:4}]}],"🮒":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},{type:0,data:[{x:0,y:4,w:8,h:4}]}],"🮔":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},{type:0,data:[{x:4,y:0,w:4,h:8}]}],"🮕":{type:0,data:[{x:0,y:0,w:2,h:2},{x:4,y:0,w:2,h:2},{x:2,y:2,w:2,h:2},{x:6,y:2,w:2,h:2},{x:0,y:4,w:2,h:2},{x:4,y:4,w:2,h:2},{x:2,y:6,w:2,h:2},{x:6,y:6,w:2,h:2}]},"🮖":{type:0,data:[{x:2,y:0,w:2,h:2},{x:6,y:0,w:2,h:2},{x:0,y:2,w:2,h:2},{x:4,y:2,w:2,h:2},{x:2,y:4,w:2,h:2},{x:6,y:4,w:2,h:2},{x:0,y:6,w:2,h:2},{x:4,y:6,w:2,h:2}]},"🮗":{type:0,data:[{x:0,y:2,w:8,h:2},{x:0,y:6,w:8,h:2}]},"🮘":{type:2,data:"M-0.25,-0.25 L1.25,1.25 M-0.25,0 L1,1.25 M-0.25,0.25 L0.75,1.25 M-0.25,0.5 L0.5,1.25 M0,-0.25 L1.25,1 M0.25,-0.25 L1.25,0.75 M0.5,-0.25 L1.25,0.5 M-0.25,0.75 L0.25,1.25 M0.75,-0.25 L1.25,0.25",strokeWidth:1},"🮙":{type:2,data:"M-0.25,0.5 L0.5,-0.25 M-0.25,0.75 L0.75,-0.25 M-0.25,1 L1,-0.25 M-0.25,1.25 L1.25,-0.25 M0,1.25 L1.25,0 M0.25,1.25 L1.25,0.25 M0.5,1.25 L1.25,0.5 M-0.25,0.25 L0.25,-0.25 M0.75,1.25 L1.25,0.75",strokeWidth:1},"🮚":{type:5,data:{d:"M0,0 L.5,.5 L0,1 L1,1 L.5,.5 L1,0",type:0}},"🮛":{type:5,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1",type:0}},"🮜":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L0,1 Z"},"🮝":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,1 Z"},"🮞":{type:1,data:[[1,0],[0,1]],clipPath:"M1,0 L1,1 L0,1 Z"},"🮟":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,1 L0,1 Z"},"🮠":{type:2,data:"M.5,0 L0,.5",strokeWidth:1},"🮡":{type:2,data:"M.5,0 L1,.5",strokeWidth:1},"🮢":{type:2,data:"M0,.5 L.5,1",strokeWidth:1},"🮣":{type:2,data:"M1,.5 L.5,1",strokeWidth:1},"🮤":{type:2,data:"M.5,0 L0,.5 L.5,1",strokeWidth:1},"🮥":{type:2,data:"M.5,0 L1,.5 L.5,1",strokeWidth:1},"🮦":{type:2,data:"M0,.5 L.5,1 L1,.5",strokeWidth:1},"🮧":{type:2,data:"M0,.5 L.5,0 L1,.5",strokeWidth:1},"🮨":{type:2,data:"M.5,0 L0,.5 M1,.5 L.5,1",strokeWidth:1},"🮩":{type:2,data:"M.5,0 L1,.5 M0,.5 L.5,1",strokeWidth:1},"🮪":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5",strokeWidth:1},"🮫":{type:2,data:"M.5,0 L0,.5 L.5,1 L1,.5",strokeWidth:1},"🮬":{type:2,data:"M0,.5 L.5,0 L1,.5 L.5,1",strokeWidth:1},"🮭":{type:2,data:"M1,.5 L.5,0 L0,.5 L.5,1",strokeWidth:1},"🮮":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5 Z",strokeWidth:1},"🮯":{type:2,data:"M0,.5 L1,.5 M.5,.35 L.5,.65",strokeWidth:1},"🮰":{type:3,data:"M0.1,0.2 L0.1,.8 L.4,.6 L.9,0.6 Z",scaleType:1},"🮱":{type:4,data:{d:"M.1,.525 L.35,.675 L.9,.35",type:1},scaleType:1},"🮲":{type:3,data:"M.29,.27 L0.13,.56 L.22,.59 L.35,0.35 L.67,.35 L.57,.57 L.71,.76 L.22,.76 L.42,1 L.53,.98 L.43,.86 L.9,.86 L.71,.6 L1,.6 L1,.52 L.83,.52 L.92,.36 L1,.36 L1,.27Z M.99,.13 A.12,.12,0,1,1,.75,.13 A.12,.12,0,1,1,.99,.13"},"🮳":{type:3,data:"M0,.27 L.3,.27 L.55,.12 L.63,.18 L.33,.36 L0,.36 M0,.52 L.33,.52 L.59,.89 L.73,.89 L.73,.98 L.53,.98 L.28,.6 L0,.6"},"🮴":{type:4,data:{d:"M.15,.55 L.5,.4 L.5,.45 L.65,.45 L.65,.35 L.85,.35 L.85,.625 L.5,.625 L.5,.7 Z",type:0},scaleType:1},"🮵":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.15,.5 L.5,.35 L.5,.425 L.85,.425 L.85,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"🮶":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.85,.5 L.5,.35 L.5,.425 L.15,.425 L.15,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"🮷":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.675 L.2,.5 L.35,.5 L.35,.325 L.65,.325 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"🮸":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.325 L.2,.5 L.35,.5 L.35,.675 L.65,.675 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"🮹":{type:5,data:{d:"M1,.89 L.11,.89 L.11,.37 L.36,.12 L.74,.12 L.96,.34 L1,.34 L1,.405 L.92,.405 L.69,.185 L.41,.185 L.21,.42 L.21,.825 L1,.825 Z",type:0}},"🮺":{type:5,data:{d:"M0,.89 L0,.825 L.78,.825 L.78,.53 L.7,.415 L0,.415 L0,.35 L.75,.35 L.88,.48 L.88,.89 Z",type:0}},"🮻":{type:5,data:{d:"M.31,.275 L.44,.275 L.44,.47 L.05,.47 L.05,.405 L.31,.405 Z M.56,.275 L.69,.275 L.69,.405 L.95,.405 L.95,.47 L.56,.47 Z M.05,.53 L.44,.53 L.44,.725 L.31,.725 L.31,.595 L.05,.595 Z M.56,.53 L.95,.53 L.95,.595 L.69,.595 L.69,.725 L.56,.725 Z",type:0},scaleType:1},"🮼":[{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0,.935 L.885,.935 L.885,.065 L0,.065 Z"},{type:3,data:"M.67,.5 A.17,.085,0,1,1,.33,.5 A.17,.085,0,1,1,.67,.5",scaleType:1}],"🮽":{type:4,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1 Z",type:1}},"🮾":{type:4,data:{d:"M1,.5 L.5,1",type:1}},"🮿":{type:4,data:{d:"M.5,0 L1,.5 L.5,1 L0,.5 Z",type:1}},"🯀":{type:3,data:"M.16,.445 A.02,.01,0,0,1,.39,.33 L.5,.375 L.61,.33 A.02,.01,0,0,1,.84,.445 L.75,.5 L.84,.555 A.02,.01,0,0,1,.61,.67 L.5,.625 L.39,.67 A.02,.01,0,0,1,.16,.555 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",scaleType:1},"🯁":{type:3,data:"M0.142308,0.924 Q0.130770,0.924,0.120193,0.922 T0.101924,0.916 T0.089424,0.9065 T0.084616,0.895 V0.025 Q0.084616,0.019,0.089424,0.0135 T0.101924,0.004 T0.120193,-0.002 T0.142308,-0.004 Q0.150000,-0.004,0.157693,-0.003 T0.173078,0.000 L0.430770,0.085 Q0.451924,0.059,0.494232,0.041 T0.587501,0.013 T0.692309,-0.0005 T0.800001,-0.004 H1 V0.055 H0.800001 Q0.771155,0.055,0.742309,0.056 T0.685578,0.060 T0.630770,0.0685 T0.580770,0.0825 T0.543270,0.1045 T0.528847,0.133 V0.647 H0.530770 Q0.596155,0.645,0.659616,0.638 T0.782693,0.6165 T0.893270,0.5805 T1,0.531 V0.623 Q0.934616,0.644,0.880770,0.6595 T0.769232,0.685 T0.650963,0.700 T0.528847,0.707 V0.787 Q0.528847,0.802,0.543270,0.8155 T0.580770,0.8375 T0.630770,0.8515 T0.685578,0.860 T0.742309,0.864 T0.800001,0.865 H1 V0.924 H0.800001 Q0.746155,0.924,0.692309,0.9205 T0.587501,0.907 T0.494232,0.879 T0.430770,0.835 L0.173078,0.920 Q0.165386,0.922,0.157693,0.923 T0.142308,0.924 Z M0.2,0.841 L0.415385,0.770 V0.150 L0.2,0.079 V0.841 Z M1,0.698 Q0.973077,0.694,0.969231,0.6885 T0.965385,0.677 Q0.965385,0.672,0.969231,0.6665 T1,0.657 V0.698 Z"},"🯂":{type:3,data:"M0,0.623 V0.531 Q0.044231,0.512,0.0625,0.4905 T0.092308,0.4465 T0.108654,0.4005 T0.113462,0.354 V0.351 Q0.113462,0.345,0.117308,0.3395 T0.129808,0.3305 T0.148846,0.3245 T0.171154,0.323 H0.501923 Q0.532692,0.323,0.563462,0.3185 T0.617308,0.303 T0.651923,0.2765 T0.663462,0.2435 V0.241 Q0.663462,0.219,0.657692,0.197 T0.639423,0.1545 T0.604808,0.115 T0.549615,0.082 T0.475577,0.0615 T0.392308,0.055 H0 V-0.004 H1 V0.055 H0.667308 Q0.694231,0.071,0.713462,0.09 T0.746154,0.129 T0.766346,0.1705 T0.775,0.213 H1 V0.316 Q0.971154,0.305,0.955769,0.2965 T0.920192,0.2825 T0.876923,0.2745 T0.830769,0.272 H0.773077 Q0.767308,0.297,0.743269,0.319 T0.680769,0.355 T0.595192,0.375 T0.501923,0.381 H0.227308 Q0.223462,0.415,0.211,0.4485 T0.172692,0.5135 T0.108269,0.573 T0,0.623 Z M0.611538,0.924 H0 V0.865 H0.611538 Q0.642308,0.865,0.673077,0.8605 T0.727885,0.845 T0.762308,0.8185 T0.773077,0.787 V0.785 Q0.773077,0.769,0.762308,0.7535 T0.727885,0.727 T0.673077,0.7115 T0.611538,0.707 H0.059615 Q0.048077,0.707,0.037115,0.7045 T0,0.694 V0.653 Q0.026923,0.648,0.037115,0.646 T0.059615,0.644 H0.722692 Q0.753462,0.644,0.784231,0.6395 T0.839038,0.624 T0.873846,0.5975 T0.884615,0.566 V0.564 Q0.884615,0.548,0.873846,0.532 T0.839038,0.5055 T0.784231,0.49 T0.722692,0.4855 H0.392308 Q0.380769,0.4855,0.370192,0.483 T0.351923,0.4765 T0.339423,0.467 T0.334615,0.4555 T0.339423,0.444 T0.351923,0.4345 T0.370192,0.428 T0.392308,0.4255 H0.832692 Q0.855769,0.4255,0.878846,0.4235 T0.922115,0.416 T0.957692,0.4015 T1,0.3815 V0.4685 Q0.975,0.4705,0.966346,0.4725 T0.95,0.4765 Q0.961538,0.4835,0.969231,0.4915 T1,0.5075 V0.6205 Q0.965385,0.6455,0.926923,0.665 T0.84,0.6935 Q0.866923,0.7115,0.877596,0.7345 T0.894231,0.7855 V0.787 Q0.894231,0.815,0.876923,0.8425 T0.820192,0.8895 T0.726923,0.916 T0.611538,0.924 Z"},"🯃":{type:3,data:"M0,0.473 V0.386 Q0.025490,0.378,0.028431,0.3695 T0.031373,0.352 V0.35 Q0.031373,0.342,0.028431,0.333 T0,0.316 V0.213 H0.652941 Q0.684314,0.213,0.715686,0.2085 T0.770588,0.193 T0.804902,0.1665 T0.815686,0.135 V0.133 Q0.815686,0.117,0.804902,0.101 T0.770588,0.0745 T0.715686,0.0595 T0.652941,0.055 H0 V-0.004 H0.652941 Q0.707843,-0.004,0.761765,0.004 T0.856863,0.031 T0.915686,0.0775 T0.933333,0.133 V0.135 Q0.933333,0.163,0.915686,0.1905 T0.856863,0.237 T0.761765,0.264 T0.652941,0.272 H0.109804 Q0.131373,0.29,0.140196,0.31 T0.149020,0.35 V0.352 Q0.149020,0.37,0.142157,0.388 T0.118627,0.4225 T0.076471,0.452 T0,0.473 Z M0,0.625 V0.513 Q0.029412,0.526,0.032353,0.54 T0.035294,0.568 V0.57 Q0.035294,0.584,0.032353,0.598 T0,0.625 Z"},"🯄":{type:3,data:"M0.019231,1.085 V-0.165 H0.980769 V1.085 H0.019231 Z M0.446154,0.527 H0.553846 Q0.553846,0.511,0.5625,0.495 T0.591346,0.466 T0.631731,0.4405 T0.666346,0.4135 T0.688462,0.3825 T0.696154,0.35 Q0.696154,0.33,0.682692,0.311 T0.641346,0.2785 T0.575,0.259 T0.498077,0.253 T0.421154,0.259 T0.356731,0.279 T0.315385,0.3125 T0.301923,0.352 V0.357 H0.409615 V0.354 Q0.409615,0.345,0.414423,0.335 T0.431731,0.318 T0.4625,0.3075 T0.498077,0.304 Q0.517308,0.304,0.534615,0.307 T0.564423,0.3165 T0.582692,0.332 T0.588462,0.35 Q0.588462,0.366,0.572115,0.3805 T0.535577,0.4075 T0.496154,0.4335 T0.465385,0.4625 T0.45,0.4945 T0.446154,0.527 Z M0.5,0.667 Q0.519231,0.667,0.5375,0.664 T0.569231,0.654 T0.588462,0.637 T0.594231,0.617 T0.588462,0.5975 T0.569231,0.581 T0.5375,0.571 T0.5,0.568 T0.4625,0.571 T0.430769,0.581 T0.411538,0.5975 T0.405769,0.617 T0.411538,0.637 T0.430769,0.654 T0.4625,0.664 T0.5,0.667 Z",scaleType:1},"🯅":{type:5,data:{d:"M.44,.425 L.44,.51 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.51 L.56,.425 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯆":{type:5,data:{d:"M.44,.425 L.44,.46 L.23,.385 L.19,.43 L.44,.51 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.61,.735 L.7,.71 L.56,.56 L.56,.51 L.81,.43 L.77,.385 L.56,.46 L.56,.425 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯇":{type:5,data:{d:"M.44,.425 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.425 Z M.18,.53 L.23,.575 L.81,.43 L.77,.385 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯈":{type:5,data:{d:"M.44,.425 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.62,.735 L.71,.71 L.56,.56 L.56,.425 Z M.23,.385 L.18,.43 L.77,.575 L.81,.53 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯉":{type:5,data:{d:"M.44,.425 L.45,.495 L.15,.645 L.34,.645 L.34,.7 L.44,.7 L.44,.645 L.56,.645 L.56,.7 L.66,.7 L.66,.645 L.84,.645 L.54,.495 L.56,.425 Z M.39,.6 L.5,.55 L.60,.6 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯊":{type:5,data:{d:"M.26,.375 L.5,.255 L.74,.375 L.74,.665 L.5,.55 L.26,.665 Z M.37,.395 L.37,.54 L.5,.475 L.63,.54 L.63,.395 L.5,.33 Z",type:0},scaleType:1},"🯋":{type:5,data:{d:"M.09,.41 L.32,.295 L.5,.375 L.68,.295 L.91,.41 L.75,.5 L.91,.59 L.68,.705 L.5,.625 L.32,.705 L.09,.59 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",type:0},scaleType:1},"🯌":{type:5,data:{d:"M.55,.305 L.88,.305 L.88,.355 L.65,.355 L.65,.47 L.88,.47 L.88,.52 L.55,.52 Z",type:0},scaleType:1},"🯍":{type:5,data:{d:"M.38,.39 L.5,.33 L.62,.39 L.62,.53 L.5,.47 L.38,.53 Z",type:0},scaleType:1},"🯎":{type:3,data:"M0,0 L0.6667,0 L0.6667,1 L0,1 Z"},"🯏":{type:3,data:"M0,0 L0.3333,0 L0.3333,1 L0,1 Z"},"🯐":{type:2,data:"M1,.5 L0,1",strokeWidth:1},"🯑":{type:2,data:"M1,0 L0,.5",strokeWidth:1},"🯒":{type:2,data:"M0,0 L1,.5",strokeWidth:1},"🯓":{type:2,data:"M0,.5 L1,1",strokeWidth:1},"🯔":{type:2,data:"M0,0 L.5,1",strokeWidth:1},"🯕":{type:2,data:"M.5,0 L1,1",strokeWidth:1},"🯖":{type:2,data:"M1,0 L.5,1",strokeWidth:1},"🯗":{type:2,data:"M.5,0 L0,1",strokeWidth:1},"🯘":{type:2,data:"M0,0 L.5,.5 L1,0",strokeWidth:1},"🯙":{type:2,data:"M1,0 L.5,.5 L1,1",strokeWidth:1},"🯚":{type:2,data:"M0,1 L.5,.5 L1,1",strokeWidth:1},"🯛":{type:2,data:"M0,0 L.5,.5 L0,1",strokeWidth:1},"🯜":{type:2,data:"M0,0 L.5,1 L1,0",strokeWidth:1},"🯝":{type:2,data:"M1,0 L0,.5 L1,1",strokeWidth:1},"🯞":{type:2,data:"M0,1 L.5,0 L1,1",strokeWidth:1},"🯟":{type:2,data:"M0,0 L1,.5 L0,1",strokeWidth:1},"🯠":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0",type:1}},"🯡":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1",type:1}},"🯢":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1",type:1}},"🯣":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1",type:1}},"🯤":{type:0,data:[{x:2,y:0,w:4,h:4}]},"🯥":{type:0,data:[{x:2,y:4,w:4,h:4}]},"🯦":{type:0,data:[{x:0,y:2,w:4,h:4}]},"🯧":{type:0,data:[{x:4,y:2,w:4,h:4}]},"🯨":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0 Z",type:0}},"🯩":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1 Z",type:0}},"🯪":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1 Z",type:0}},"🯫":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1 Z",type:0}},"🯬":{type:5,data:{d:"M1,0 L.5,0 C.5,.276,.724,.5,1,.5 Z",type:0}},"🯭":{type:5,data:{d:"M0,1 L.5,1 C.5,.724,.276,.5,0,.5 Z",type:0}},"🯮":{type:5,data:{d:"M1,1 L1,.5 C.724,.5,.5,.724,.5,1 Z",type:0}},"🯯":{type:5,data:{d:"M0,0 L0,.5 C.276,.5,.5,.276,.5,0 Z",type:0}},"🯰":{type:5,data:{d:r(126),type:0},scaleType:1},"🯱":{type:5,data:{d:r(48),type:0},scaleType:1},"🯲":{type:5,data:{d:r(109),type:0},scaleType:1},"🯳":{type:5,data:{d:r(121),type:0},scaleType:1},"🯴":{type:5,data:{d:r(51),type:0},scaleType:1},"🯵":{type:5,data:{d:r(91),type:0},scaleType:1},"🯶":{type:5,data:{d:r(95),type:0},scaleType:1},"🯷":{type:5,data:{d:r(114),type:0},scaleType:1},"🯸":{type:5,data:{d:r(127),type:0},scaleType:1},"🯹":{type:5,data:{d:r(123),type:0},scaleType:1},"🯺":{type:5,data:{d:"M.5,.175 C.2,.175,.15,.305,.15,.435 L.05,.63 L.35,.63 C.35,.682,.42,.76,.5,.76 C.58,.76,.65,.682,.65,.63 L.95,.63 L.85,.435 C.85,.305,.8,.175,.5,.175 Z",type:0},scaleType:1},...Object.fromEntries(Array.from({length:256},(t,e)=>[String.fromCodePoint(10240+e),{type:6,data:e}]))},e.blockPatternCodepoints=new Set([9617,9618,9619,129932,129933,129934,129935,129936,129937,129938,129940,129948,129949,129950,129951])},183(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.tryDrawCustomGlyph=function(t,e,i,s,o,n,L,h,T,l,d,c,_=0){const Q=r.customGlyphDefinitions[e];if(Q){const e=Array.isArray(Q)?Q:[Q];for(const r of e)a(t,r,i,s,o,n,L,h,T,l,d,c,_);return!0}return!1};const s=i(959),r=i(915);function a(t,e,i,r,a,h,d,c,_,Q,u,p,g=0){let M=a,y=h,v=i,f=r;switch(1===e.scaleType&&(M=d,y=c,v=i+(a-d)/2,f=r+(h-c)/2),e.clipPath&&(t.save(),function(t,e,i,s,r,a){t.beginPath();for(const o of e.split(" ")){const e=o[0];if("Z"===e){t.closePath();continue}const n=o.substring(1).split(",");if(!n[0]||!n[1])continue;const L=i+parseFloat(n[0])*r,h=s+parseFloat(n[1])*a;"M"===e?t.moveTo(L,h):"L"===e&&t.lineTo(L,h)}t.clip()}(t,e.clipPath,v,f,M,y)),e.type){case 0:!function(t,e,i,s,r,a){for(let o=0;o7&&parseInt(T.slice(7,9),16)||1;else{if(!T.startsWith("rgba"))throw new Error(`Unexpected fillStyle color format "${T}" when drawing pattern glyph`);[L,d,c,_]=T.substring(5,T.length-1).split(",").map(t=>parseFloat(t))}for(let t=0;t>1&1,c=1&n;0!==d||0!==c?l.setTransform((new DOMMatrix).translateSelf(-d,-c)):l.setTransform(new DOMMatrix),t.fillStyle=l,t.fillRect(i,r,a,o)}(t,e.data,v,f,M,y,g);break;case 2:!function(t,e,i,s,r,a,o,n,L){let h;t.save(),t.beginPath(),t.rect(i,s,r,a),t.clip(),t.beginPath(),h="function"==typeof e?e(.15,.15/a*r):e;const d={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(const e of h.split(" ")){const L=e[0];if("Z"===L){t.closePath(),d.lastCommand=L;continue}const h=T[L];if(!h){n.error(`Could not find drawing instructions for "${L}"`);continue}const c=e.substring(1).split(",");c[0]&&c[1]&&(h(t,l(c,r,a,i,s,!0,o,0,0,!1),d),d.lastCommand=L)}void 0!==L?(t.strokeStyle=t.fillStyle,t.lineWidth=o*L,t.stroke()):t.fill(),t.closePath(),t.restore()}(t,e.data,v,f,M,y,Q,u,e.strokeWidth);break;case 3:!function(t,e,i,s,r,a,o,L){const h="string"==typeof e?e:e(0,0);t.beginPath();let T=0,l=0,d=0,c=0,_="";for(const e of h.split(" ")){const o=e[0],L=e.substring(1).split(",");if("Z"===o){t.closePath(),_=o;continue}if("V"===o){const e=s+parseFloat(L[0])*a;t.lineTo(T,e),l=e,d=T,c=l,_=o;continue}if("H"===o){const e=i+parseFloat(L[0])*r;t.lineTo(e,l),T=e,d=T,c=l,_=o;continue}if(!L[0]||!L[1])continue;if("A"===o){const e=parseFloat(L[0])*r,o=parseFloat(L[1])*a,h=parseFloat(L[2])*Math.PI/180,d=parseInt(L[3],10),c=parseInt(L[4],10),_=i+parseFloat(L[5])*r,Q=s+parseFloat(L[6])*a;n(t,T,l,e,o,h,d,c,_,Q),T=_,l=Q;continue}const h=L.map((t,e)=>{const o=parseFloat(t);return e%2==0?i+o*r:s+o*a});if("M"===o)t.moveTo(h[0],h[1]),T=h[0],l=h[1],d=T,c=l;else if("L"===o)t.lineTo(h[0],h[1]),T=h[0],l=h[1],d=T,c=l;else if("Q"===o)t.quadraticCurveTo(h[0],h[1],h[2],h[3]),d=h[0],c=h[1],T=h[2],l=h[3];else if("T"===o){let e,i;"Q"===_||"T"===_?(e=2*T-d,i=2*l-c):(e=T,i=l),t.quadraticCurveTo(e,i,h[0],h[1]),d=e,c=i,T=h[0],l=h[1]}else"C"===o&&(t.bezierCurveTo(h[0],h[1],h[2],h[3],h[4],h[5]),d=h[2],c=h[3],T=h[4],l=h[5]);_=o}void 0!==L?(t.strokeStyle=t.fillStyle,t.lineWidth=o*L,t.stroke()):t.fill()}(t,e.data,v,f,M,y,Q,e.strokeWidth);break;case 4:!function(t,e,i,s,r,a,o,n){t.save(),t.fillRect(i,s,r,a),n&&(t.fillStyle=n,t.strokeStyle=n),t.lineWidth=o,t.lineCap="square",t.beginPath();for(const o of e.d.split(" ")){const e=o[0],n=o.substring(1).split(",");if(!n[0]||!n[1]){"Z"===e&&t.closePath();continue}const L=n.map((t,e)=>{const o=parseFloat(t);return e%2==0?i+o*r:s+o*a});"M"===e?t.moveTo(L[0],L[1]):"L"===e&&t.lineTo(L[0],L[1])}1===e.type?t.stroke():t.fill(),t.restore()}(t,e.data,v,f,M,y,Q,p);break;case 5:!function(t,e,i,s,r,a,o,n,L){const h=new Path2D;h.rect(i,s,r,a),t.clip(h),t.beginPath();const d=o/12;t.lineWidth=n*d;const c={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(const o of e.d.split(" ")){const h=o[0];if("Z"===h){t.closePath(),c.lastCommand=h;continue}const _=T[h];if(!_){L.error(`Could not find drawing instructions for "${h}"`);continue}const Q=o.substring(1).split(",");Q[0]&&Q[1]&&(_(t,l(Q,r,a,i,s,!1,n,(e.leftPadding??0)*(d/2),(e.rightPadding??0)*(d/2)),c),c.lastCommand=h)}1===e.type?(t.strokeStyle=t.fillStyle,t.stroke()):t.fill(),t.closePath()}(t,e.data,v,f,M,y,_,Q,u);break;case 6:!function(t,e,i,s,r,a){const n=r/8,L=.1*a,h=.8*a/8,T=Math.min(n,h);for(let r=0;r<8;r++)if(e&1<1){const t=Math.sqrt(y);u=(s*=t)*s,p=(r*=t)*r}let v=(u*p-u*M-p*g)/(u*M+p*g);v<0&&(v=0);const f=(o===n?-1:1)*Math.sqrt(v),C=f*(s*Q/r),m=f*(-r*_/s),w=T*C-l*m+(e+L)/2,x=l*C+T*m+(i+h)/2,b=(_-C)/s,E=(Q-m)/r,R=(-_-C)/s,k=(-Q-m)/r,A=Math.atan2(E,b);let Z=Math.atan2(k,R)-A;0===n&&Z>0?Z-=2*Math.PI:1===n&&Z<0&&(Z+=2*Math.PI);const D=A+Z;t.ellipse(w,x,s,r,a,A,D,0===n)}const L=new Map;function h(t,e,i=0){return Math.max(Math.min(t,e),i)}const T={C:(t,e,i)=>{t.bezierCurveTo(e[0],e[1],e[2],e[3],e[4],e[5]),i.lastControlX=e[2],i.lastControlY=e[3],i.currentX=e[4],i.currentY=e[5]},L:(t,e,i)=>{t.lineTo(e[0],e[1]),i.lastControlX=i.currentX=e[0],i.lastControlY=i.currentY=e[1]},M:(t,e,i)=>{t.moveTo(e[0],e[1]),i.lastControlX=i.currentX=e[0],i.lastControlY=i.currentY=e[1]},Q:(t,e,i)=>{t.quadraticCurveTo(e[0],e[1],e[2],e[3]),i.lastControlX=e[0],i.lastControlY=e[1],i.currentX=e[2],i.currentY=e[3]},T:(t,e,i)=>{let s,r;"Q"===i.lastCommand||"T"===i.lastCommand?(s=2*i.currentX-i.lastControlX,r=2*i.currentY-i.lastControlY):(s=i.currentX,r=i.currentY),t.quadraticCurveTo(s,r,e[0],e[1]),i.lastControlX=s,i.lastControlY=r,i.currentX=e[0],i.currentY=e[1]}};function l(t,e,i,s,r,a,o,n=0,L=0,T=!0){const l=t.map(t=>parseFloat(t)||parseInt(t));if(l.length<2)throw new Error("Too few arguments for instruction");for(let t=0;t{this._refreshCharAtlas(t,e),this.reset(t)})),this._register((0,r.toDisposable)(()=>{this._canvas.remove()}))}_initCanvas(){this._ctx=(0,a.throwIfFalsy)(this._canvas.getContext("2d",{alpha:this._alpha})),this._alpha||this._clearAll()}handleBlur(t){}handleFocus(t){}handleCursorMove(t){}handleGridChanged(t,e,i){}handleSelectionChanged(t,e,i,s=!1){}_setTransparency(t,e){if(e===this._alpha)return;const i=this._canvas;this._alpha=e,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,i),this._refreshCharAtlas(t,this._themeService.colors),this.handleGridChanged(t,0,t.rows-1)}_refreshCharAtlas(t,e){this._deviceCharWidth<=0&&this._deviceCharHeight<=0||(this._charAtlas=(0,s.acquireTextureAtlas)(t,this._optionsService.rawOptions,e,this._deviceCellWidth,this._deviceCellHeight,this._deviceCharWidth,this._deviceCharHeight,this._coreBrowserService.dpr,2048),this._charAtlas.warmUp())}resize(t,e){this._deviceCellWidth=e.device.cell.width,this._deviceCellHeight=e.device.cell.height,this._deviceCharWidth=e.device.char.width,this._deviceCharHeight=e.device.char.height,this._deviceCharLeft=e.device.char.left,this._deviceCharTop=e.device.char.top,this._canvas.width=e.device.canvas.width,this._canvas.height=e.device.canvas.height,this._canvas.style.width=`${e.css.canvas.width}px`,this._canvas.style.height=`${e.css.canvas.height}px`,this._alpha||this._clearAll(),this._refreshCharAtlas(t,this._themeService.colors)}_fillBottomLineAtCells(t,e,i=1){this._ctx.fillRect(t*this._deviceCellWidth,(e+1)*this._deviceCellHeight-this._coreBrowserService.dpr-1,i*this._deviceCellWidth,this._coreBrowserService.dpr)}_clearAll(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))}_clearCells(t,e,i,s){this._alpha?this._ctx.clearRect(t*this._deviceCellWidth,e*this._deviceCellHeight,i*this._deviceCellWidth,s*this._deviceCellHeight):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(t*this._deviceCellWidth,e*this._deviceCellHeight,i*this._deviceCellWidth,s*this._deviceCellHeight))}_fillCharTrueColor(t,e,i,s){this._ctx.font=this._getFont(t,!1,!1),this._ctx.textBaseline=o.TEXT_BASELINE,this._clipCell(i,s,e.getWidth()),this._ctx.fillText(e.getChars(),i*this._deviceCellWidth+this._deviceCharLeft,s*this._deviceCellHeight+this._deviceCharTop+this._deviceCharHeight)}_clipCell(t,e,i){this._ctx.beginPath(),this._ctx.rect(t*this._deviceCellWidth,e*this._deviceCellHeight,i*this._deviceCellWidth,this._deviceCellHeight),this._ctx.clip()}_getFont(t,e,i){return`${i?"italic":""} ${e?t.options.fontWeightBold:t.options.fontWeight} ${t.options.fontSize*this._coreBrowserService.dpr}px ${t.options.fontFamily}`}}e.BaseRenderLayer=n},306(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.LinkRenderLayer=void 0;const s=i(657),r=i(814),a=i(133);class o extends a.BaseRenderLayer{constructor(t,e,i,s,r,a,o){super(i,t,"link",e,!0,r,a,o),this._register(s.onShowLinkUnderline(t=>this._handleShowLinkUnderline(t))),this._register(s.onHideLinkUnderline(t=>this._handleHideLinkUnderline(t)))}resize(t,e){super.resize(t,e),this._state=void 0}reset(t){this._clearCurrentLink()}_clearCurrentLink(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);const t=this._state.y2-this._state.y1-1;t>0&&this._clearCells(0,this._state.y1+1,this._state.cols,t),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}}_handleShowLinkUnderline(t){if(t.fg===r.INVERTED_DEFAULT_COLOR?this._ctx.fillStyle=this._themeService.colors.background.css:void 0!==t.fg&&(0,s.is256Color)(t.fg)?this._ctx.fillStyle=this._themeService.colors.ansi[t.fg].css:this._ctx.fillStyle=this._themeService.colors.foreground.css,t.y1===t.y2)this._fillBottomLineAtCells(t.x1,t.y1,t.x2-t.x1);else{this._fillBottomLineAtCells(t.x1,t.y1,t.cols-t.x1);for(let e=t.y1+1;e{var t=s;Object.defineProperty(t,"__esModule",{value:!0}),t.WebglAddon=void 0;const e=i(426),r=i(95),a=i(399),o=i(414);class n extends e.Disposable{constructor(t){if(r.isSafari&&(0,r.getSafariVersion)()<16){const t={antialias:!1,depth:!1,preserveDrawingBuffer:!0};if(!document.createElement("canvas").getContext("webgl2",t))throw new Error("WebGL2 is only supported on Safari 16 and above")}super(),this._onChangeTextureAtlas=this._register(new o.Emitter),this.onChangeTextureAtlas=this._onChangeTextureAtlas.event,this._onAddTextureAtlasCanvas=this._register(new o.Emitter),this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=this._register(new o.Emitter),this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._onContextLoss=this._register(new o.Emitter),this.onContextLoss=this._onContextLoss.event,this._customGlyphs=t?.customGlyphs??!0,this._preserveDrawingBuffer=t?.preserveDrawingBuffer}activate(t){const i=t._core;if(!t.element)return void this._register(i.onWillOpen(()=>this.activate(t)));this._terminal=t;const s=i.coreService,r=i.optionsService,n=i,L=n._renderService,h=n._characterJoinerService,T=n._charSizeService,l=n._coreBrowserService,d=n._decorationService,c=n._logService,_=n._themeService;this._renderer=this._register(new a.WebglRenderer(t,h,T,l,s,d,c,r,_,this._customGlyphs,this._preserveDrawingBuffer)),this._register(o.EventUtils.forward(this._renderer.onContextLoss,this._onContextLoss)),this._register(o.EventUtils.forward(this._renderer.onChangeTextureAtlas,this._onChangeTextureAtlas)),this._register(o.EventUtils.forward(this._renderer.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas)),this._register(o.EventUtils.forward(this._renderer.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas)),L.setRenderer(this._renderer),this._register((0,e.toDisposable)(()=>{if(this._terminal._core._store._isDisposed)return;const e=this._terminal._core._renderService;e.setRenderer(this._terminal._core._createRenderer()),e.handleResize(t.cols,t.rows)}))}get textureAtlas(){return this._renderer?.textureAtlas}clearTextureAtlas(){this._renderer?.clearTextureAtlas()}}t.WebglAddon=n})(),s})()); ++!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.WebglAddon=e():t.WebglAddon=e()}(globalThis,()=>(()=>{"use strict";var t={105(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.WindowIntervalTimer=e.eventType=void 0,e.getWindow=r,e.addDisposableListener=o,e.addStandardDisposableListener=function(t,e,i,s){return o(t,e,i,s)},e.getDomNodePagePosition=function(t){const e=t.getBoundingClientRect(),i=r(t);return{left:e.left+i.scrollX,top:e.top+i.scrollY,width:e.width,height:e.height}},e.scheduleAtNextAnimationFrame=function(t,e,i=0){const s=h(t),r=new n(e,i);return s.next.push(r),s.animFrameRequested||(s.animFrameRequested=!0,t.requestAnimationFrame(()=>function(t){const e=h(t);for(e.animFrameRequested=!1,e.current=e.next,e.next=[],e.inAnimationFrameRunner=!0;e.current.length>0;)e.current.sort(n.sort),e.current.shift().execute();e.inAnimationFrameRunner=!1}(t))),r};const s=i(578);function r(t){const e=t;if(e?.ownerDocument?.defaultView)return e.ownerDocument.defaultView;const i=t;return i?.view?i.view:window}class a{constructor(t,e,i,s){this._node=t,this._type=e,this._handler=i,this._options=s,t.addEventListener(e,i,s)}dispose(){this._node&&this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}}function o(t,e,i,s){return new a(t,e,i,s)}e.eventType={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",KEY_DOWN:"keydown",KEY_UP:"keyup",INPUT:"input",BLUR:"blur",FOCUS:"focus",CHANGE:"change",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_UP:"pointerup",MOUSE_WHEEL:"wheel",WHEEL:"wheel"};class n{constructor(t,e){this._runner=t,this.priority=e,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(t){console.error(t)}}static sort(t,e){return e.priority-t.priority}}const L=new Map;function h(t){let e=L.get(t);return e||(e={next:[],current:[],animFrameRequested:!1,inAnimationFrameRunner:!1},L.set(t,e)),e}class T extends s.IntervalTimer{constructor(t){super(),this._defaultTarget=t?r(t):void 0}cancelAndSet(t,e,i){super.cancelAndSet(t,e,i??this._defaultTarget??window)}}e.WindowIntervalTimer=T},814(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.INVERTED_DEFAULT_COLOR=void 0,e.INVERTED_DEFAULT_COLOR=257},959(t,e){function i(t){return 57508<=t&&t<=57558}function s(t){return t>=128512&&t<=128591||t>=127744&&t<=128511||t>=128640&&t<=128767||t>=9728&&t<=9983||t>=9984&&t<=10175||t>=65024&&t<=65039||t>=129280&&t<=129535||t>=127462&&t<=127487}Object.defineProperty(e,"__esModule",{value:!0}),e.throwIfFalsy=function(t){if(!t)throw new Error("value must not be falsy");return t},e.isPowerlineGlyph=i,e.isRestrictedPowerlineGlyph=function(t){return 57520<=t&&t<=57527},e.isEmoji=s,e.allowRescaling=function(t,e,r,a){return 1===e&&r>Math.ceil(1.5*a)&&void 0!==t&&t>255&&!s(t)&&!i(t)&&!function(t){return 57344<=t&&t<=63743}(t)},e.treatGlyphAsBackgroundColor=function(t){return i(t)||function(t){return 9472<=t&&t<=9631}(t)},e.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},e.computeNextVariantOffset=function(t,e,i=0){return(t-(2*Math.round(e)-i))%(2*Math.round(e))}},948(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.createSelectionRenderModel=function(){return new i};class i{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(t,e,i,s=!1){if(this.selectionStart=e,this.selectionEnd=i,!e||!i||e[0]===i[0]&&e[1]===i[1])return void this.clear();const r=t.buffers.active.ydisp,a=e[1]-r,o=i[1]-r,n=Math.max(a,0),L=Math.min(o,t.rows-1);n>=t.rows||L<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=n,this.viewportCappedEndRow=L,this.startCol=e[0],this.endCol=i[0])}isCellSelected(t,e,i){return!!this.hasSelection&&(i-=t.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?e>=this.startCol&&i>=this.viewportCappedStartRow&&e=this.viewportCappedStartRow&&e>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&e=this.startCol)}}},536(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.TextBlinkStateManager=void 0;const s=i(426);class r extends s.Disposable{constructor(t,e,i){super(),this._renderCallback=t,this._coreBrowserService=e,this._optionsService=i,this._intervalDuration=0,this._blinkOn=!0,this._needsBlinkInViewport=!1,this._isViewportVisible=!0,this._register(this._optionsService.onSpecificOptionChange("blinkIntervalDuration",t=>{this.setIntervalDuration(t)})),this.setIntervalDuration(this._optionsService.rawOptions.blinkIntervalDuration),this._register((0,s.toDisposable)(()=>this._clearInterval()))}get isBlinkOn(){return this._blinkOn}get isEnabled(){return this._intervalDuration>0}setNeedsBlinkInViewport(t){this._needsBlinkInViewport!==t&&(this._needsBlinkInViewport=t,this._updateIntervalState())}setViewportVisible(t){this._isViewportVisible!==t&&(this._isViewportVisible=t,this._updateIntervalState())}setIntervalDuration(t){t!==this._intervalDuration&&(this._intervalDuration=t,this._clearInterval(),this._updateIntervalState())}_updateIntervalState(){if(this._intervalDuration>0&&this._needsBlinkInViewport&&this._isViewportVisible){if(void 0!==this._interval)return;const t=this._blinkOn;return this._blinkOn=!0,this._interval=this._coreBrowserService.window.setInterval(()=>{this._blinkOn=!this._blinkOn,this._renderCallback()},this._intervalDuration),void(t||this._renderCallback())}this._clearInterval(),this._blinkOn||(this._blinkOn=!0,this._renderCallback())}_clearInterval(){void 0!==this._interval&&(this._coreBrowserService.window.clearInterval(this._interval),this._interval=void 0)}}e.TextBlinkStateManager=r},578(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.IntervalTimer=e.MicrotaskTimer=e.TimeoutTimer=void 0,e.timeout=function(t){return new Promise(e=>setTimeout(e,t))},e.disposableTimeout=function(t,e=0,i){const r=setTimeout(()=>{t(),i&&a.dispose()},e),a=(0,s.toDisposable)(()=>{clearTimeout(r)});return i?.add(a),a};const s=i(426);e.TimeoutTimer=class{constructor(){this._token=-1,this._isDisposed=!1}dispose(){this.cancel(),this._isDisposed=!0}cancel(){-1!==this._token&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(t,e){if(this._isDisposed)throw new Error("Calling cancelAndSet on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,t()},e)}setIfNotSet(t,e){if(this._isDisposed)throw new Error("Calling setIfNotSet on a disposed TimeoutTimer");-1===this._token&&(this._token=setTimeout(()=>{this._token=-1,t()},e))}},e.MicrotaskTimer=class{constructor(){this._isScheduled=!1,this._isDisposed=!1}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._isScheduled=!1}set(t){if(this._isDisposed)throw new Error("Calling set on a disposed MicrotaskTimer");this._isScheduled||(this._isScheduled=!0,queueMicrotask(()=>{this._isScheduled&&(this._isScheduled=!1,t())}))}},e.IntervalTimer=class{constructor(){this._isDisposed=!1}cancel(){this._disposable?.dispose(),this._disposable=void 0}cancelAndSet(t,e,i=globalThis){if(this._isDisposed)throw new Error("Calling cancelAndSet on a disposed IntervalTimer");this.cancel();const s=i.setInterval(()=>{t()},e);this._disposable={dispose:()=>{i.clearInterval(s),this._disposable=void 0}}}dispose(){this.cancel(),this._isDisposed=!0}}},993(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.rgba=e.rgb=e.css=e.color=e.channels=e.NULL_COLOR=void 0,e.toPaddedHex=l,e.contrastRatio=d;let i=0,s=0,r=0,a=0;var o,n,L,h,T;function l(t){const e=t.toString(16);return e.length<2?"0"+e:e}function d(t,e){return t>>0},t.toColor=function(e,i,s,r){return{css:t.toCss(e,i,s,r),rgba:t.toRgba(e,i,s,r)}}}(o||(e.channels=o={})),function(t){function e(t,e){return a=Math.round(255*e),[i,s,r]=T.toChannels(t.rgba),{css:o.toCss(i,s,r,a),rgba:o.toRgba(i,s,r,a)}}t.blend=function(t,e){if(a=(255&e.rgba)/255,1===a)return{css:e.css,rgba:e.rgba};const n=e.rgba>>24&255,L=e.rgba>>16&255,h=e.rgba>>8&255,T=t.rgba>>24&255,l=t.rgba>>16&255,d=t.rgba>>8&255;return i=T+Math.round((n-T)*a),s=l+Math.round((L-l)*a),r=d+Math.round((h-d)*a),{css:o.toCss(i,s,r),rgba:o.toRgba(i,s,r)}},t.isOpaque=function(t){return!(255&~t.rgba)},t.ensureContrastRatio=function(t,e,i){const s=T.ensureContrastRatio(t.rgba,e.rgba,i);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},t.opaque=function(t){const e=(255|t.rgba)>>>0;return[i,s,r]=T.toChannels(e),{css:o.toCss(i,s,r),rgba:e}},t.opacity=e,t.multiplyOpacity=function(t,i){return a=255&t.rgba,e(t,a*i/255)},t.toColorRGB=function(t){return[t.rgba>>24&255,t.rgba>>16&255,t.rgba>>8&255]}}(n||(e.color=n={})),function(t){let e,n;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i=t.getContext("2d",{willReadFrequently:!0});i&&(e=i,e.globalCompositeOperation="copy",n=e.createLinearGradient(0,0,1,1))}catch{}t.toColor=function(t){if(t.match(/#[\da-f]{3,8}/i))switch(t.length){case 4:return i=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),r=parseInt(t.slice(3,4).repeat(2),16),o.toColor(i,s,r);case 5:return i=parseInt(t.slice(1,2).repeat(2),16),s=parseInt(t.slice(2,3).repeat(2),16),r=parseInt(t.slice(3,4).repeat(2),16),a=parseInt(t.slice(4,5).repeat(2),16),o.toColor(i,s,r,a);case 7:return{css:t,rgba:(parseInt(t.slice(1),16)<<8|255)>>>0};case 9:return{css:t,rgba:parseInt(t.slice(1),16)>>>0}}const L=t.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(L)return i=parseInt(L[1],10),s=parseInt(L[2],10),r=parseInt(L[3],10),a=Math.round(255*(void 0===L[5]?1:parseFloat(L[5]))),o.toColor(i,s,r,a);if("transparent"===t)return{css:"transparent",rgba:0};if(!e||!n)throw new Error("css.toColor: Unsupported css format");if(e.fillStyle=n,e.fillStyle=t,"string"!=typeof e.fillStyle)throw new Error("css.toColor: Unsupported css format");if(e.fillRect(0,0,1,1),[i,s,r,a]=e.getImageData(0,0,1,1).data,255!==a)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(i,s,r,a),css:t}}}(L||(e.css=L={})),function(t){function e(t,e,i){const s=t/255,r=e/255,a=i/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4))}t.relativeLuminance=function(t){return e(t>>16&255,t>>8&255,255&t)},t.relativeLuminance2=e}(h||(e.rgb=h={})),function(t){function e(t,e,i){const s=t>>24&255,r=t>>16&255,a=t>>8&255;let o=e>>24&255,n=e>>16&255,L=e>>8&255,T=d(h.relativeLuminance2(o,n,L),h.relativeLuminance2(s,r,a));for(;T0||n>0||L>0);)o-=Math.max(0,Math.ceil(.1*o)),n-=Math.max(0,Math.ceil(.1*n)),L-=Math.max(0,Math.ceil(.1*L)),T=d(h.relativeLuminance2(o,n,L),h.relativeLuminance2(s,r,a));return(o<<24|n<<16|L<<8|255)>>>0}function n(t,e,i){const s=t>>24&255,r=t>>16&255,a=t>>8&255;let o=e>>24&255,n=e>>16&255,L=e>>8&255,T=d(h.relativeLuminance2(o,n,L),h.relativeLuminance2(s,r,a));for(;T>>0}t.blend=function(t,e){if(a=(255&e)/255,1===a)return e;const n=e>>24&255,L=e>>16&255,h=e>>8&255,T=t>>24&255,l=t>>16&255,d=t>>8&255;return i=T+Math.round((n-T)*a),s=l+Math.round((L-l)*a),r=d+Math.round((h-d)*a),o.toRgba(i,s,r)},t.ensureContrastRatio=function(t,i,s){const r=h.relativeLuminance(t>>8),a=h.relativeLuminance(i>>8);if(d(r,a)>8));if(od(r,h.relativeLuminance(e>>8))?a:e}return a}const o=n(t,i,s),L=d(r,h.relativeLuminance(o>>8));if(Ld(r,h.relativeLuminance(a>>8))?o:a}return o}},t.reduceLuminance=e,t.increaseLuminance=n,t.toChannels=function(t){return[t>>24&255,t>>16&255,t>>8&255,255&t]}}(T||(e.rgba=T={}))},414(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.EventUtils=e.Emitter=void 0;const s=i(426);var r;e.Emitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=(t,e,i)=>{if(this._disposed)return(0,s.toDisposable)(()=>{});const r={fn:t,thisArgs:e};this._listeners.push(r);const a=(0,s.toDisposable)(()=>{const t=this._listeners.indexOf(r);-1!==t&&this._listeners.splice(t,1)});return i&&(Array.isArray(i)?i.push(a):i.add(a)),a}),this._event}fire(t){if(!this._disposed)switch(this._listeners.length){case 0:return;case 1:{const{fn:e,thisArgs:i}=this._listeners[0];return void e.call(i,t)}default:{const e=this._listeners.slice();for(const{fn:i,thisArgs:s}of e)i.call(s,t)}}}dispose(){this._disposed||(this._disposed=!0,this._listeners.length=0)}},function(t){t.forward=function(t,e){return t(t=>e.fire(t))},t.map=function(t,e){return(i,s,r)=>t(t=>i.call(s,e(t)),void 0,r)},t.any=function(...t){return(e,i,r)=>{const a=new s.DisposableStore;for(const s of t)a.add(s(t=>e.call(i,t)));return r&&(Array.isArray(r)?r.push(a):r.add(a)),a}},t.runAndSubscribe=function(t,e,i){return e(i),t(t=>e(t))}}(r||(e.EventUtils=r={}))},426(t,e){function i(t){return{dispose:t}}function s(t){if(!t)return t;if(Array.isArray(t)){for(const e of t)e.dispose();return[]}return t.dispose(),t}Object.defineProperty(e,"__esModule",{value:!0}),e.MutableDisposable=e.Disposable=e.DisposableStore=void 0,e.toDisposable=i,e.dispose=s,e.combinedDisposable=function(...t){return i(()=>s(t))};class r{constructor(){this._disposables=new Set,this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(t){return this._isDisposed?t.dispose():this._disposables.add(t),t}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(const t of this._disposables)t.dispose();this._disposables.clear()}}clear(){for(const t of this._disposables)t.dispose();this._disposables.clear()}}e.DisposableStore=r;class a{constructor(){this._store=new r}dispose(){this._store.dispose()}_register(t){return this._store.add(t)}}e.Disposable=a,a.None=Object.freeze({dispose(){}}),e.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(t){this._isDisposed||t===this._value||(this._value?.dispose(),this._value=t)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}}},836(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.FourKeyMap=e.TwoKeyMap=void 0;class i{constructor(){this._data={}}set(t,e,i){this._data[t]||(this._data[t]={}),this._data[t][e]=i}get(t,e){return this._data[t]?this._data[t][e]:void 0}clear(){this._data={}}}e.TwoKeyMap=i,e.FourKeyMap=class{constructor(){this._data=new i}set(t,e,s,r,a){this._data.get(t,e)||this._data.set(t,e,new i),this._data.get(t,e).set(s,r,a)}get(t,e,i,s){return this._data.get(t,e)?.get(i,s)}clear(){this._data.clear()}}},95(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.isChromeOS=e.isLinux=e.isWindows=e.isMac=e.isSafari=e.isLegacyEdge=e.isChrome=e.isFirefox=e.isNode=void 0,e.getZoomFactor=function(t){return 1},e.getSafariVersion=function(){if(!e.isSafari)return 0;const t=i.match(/Version\/(\d+)/);return null===t||t.length<2?0:parseInt(t[1],10)},e.isNode=!("undefined"==typeof process||!("title"in process)||"undefined"!=typeof navigator&&!navigator.userAgent.startsWith("Node.js/"));const i=e.isNode?"node":navigator.userAgent,s=e.isNode?"node":navigator.platform;e.isFirefox=i.includes("Firefox"),e.isChrome=i.includes("Chrome"),e.isLegacyEdge=i.includes("Edge"),e.isSafari=/^((?!chrome|android).)*safari/i.test(i),e.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(s),e.isWindows=["Windows","Win16","Win32","WinCE"].includes(s),e.isLinux=s.indexOf("Linux")>=0,e.isChromeOS=/\bCrOS\b/.test(i)},930(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.DebouncedIdleTask=e.IdleTaskQueue=e.PriorityTaskQueue=void 0;class i{constructor(t){this._tasks=[],this._i=0,this._logService=t}enqueue(t){this._tasks.push(t),this._start()}flush(){for(;this._ii)return r-e<-20&&this._logService.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-e))}ms`),void this._start();r=i}this.clear()}}class s extends i{_requestCallback(t){return setTimeout(()=>t(this._createDeadline(16)))}_cancelCallback(t){clearTimeout(t)}_createDeadline(t){const e=performance.now()+t;return{timeRemaining:()=>Math.max(0,e-performance.now())}}}e.PriorityTaskQueue=s,e.IdleTaskQueue="requestIdleCallback"in globalThis?class extends i{_requestCallback(t){return requestIdleCallback(t)}_cancelCallback(t){cancelIdleCallback(t)}}:s,e.DebouncedIdleTask=class{constructor(t){this._queue=new e.IdleTaskQueue(t)}set(t){this._queue.clear(),this._queue.enqueue(t)}flush(){this._queue.flush()}dispose(){this._queue.clear()}}},917(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.ExtendedAttrs=e.AttributeData=void 0;class i{constructor(){this.fg=0,this.bg=0,this.extended=new s}static toColorRGB(t){return[t>>>16&255,t>>>8&255,255&t]}static fromColorRGB(t){return(255&t[0])<<16|(255&t[1])<<8|255&t[2]}clone(){const t=new i;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)}isBgPalette(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?16777216==(50331648&this.extended.underlineColor)||33554432==(50331648&this.extended.underlineColor):this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}e.AttributeData=i;class s{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(t){this._ext&=-67108864,this._ext|=67108863&t}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){const t=(3758096384&this._ext)>>29;return t<0?4294967288^t:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}constructor(t=0,e=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=e}clone(){return new s(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}}e.ExtendedAttrs=s},721(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.CellData=void 0;const s=i(348),r=i(564),a=i(917);class o extends a.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new a.ExtendedAttrs,this.combinedData=""}static fromCharData(t){const e=new o;return e.setFromCharData(t),e}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,s.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(t){this.fg=t[r.CHAR_DATA_ATTR_INDEX],this.bg=0;let e=!1;if(t[r.CHAR_DATA_CHAR_INDEX].length>2)e=!0;else if(2===t[r.CHAR_DATA_CHAR_INDEX].length){const i=t[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=i&&i<=56319){const s=t[r.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=s&&s<=57343?this.content=1024*(i-55296)+s-56320+65536|t[r.CHAR_DATA_WIDTH_INDEX]<<22:e=!0}else e=!0}else this.content=t[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[r.CHAR_DATA_WIDTH_INDEX]<<22;e&&(this.combinedData=t[r.CHAR_DATA_CHAR_INDEX],this.content=2097152|t[r.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}attributesEquals(t){if(this.getFgColorMode()!==t.getFgColorMode()||this.getFgColor()!==t.getFgColor())return!1;if(this.getBgColorMode()!==t.getBgColorMode()||this.getBgColor()!==t.getBgColor())return!1;if(this.isInverse()!==t.isInverse())return!1;if(this.isBold()!==t.isBold())return!1;if(this.isUnderline()!==t.isUnderline())return!1;if(this.isUnderline()){if(this.getUnderlineStyle()!==t.getUnderlineStyle())return!1;const e=this.isUnderlineColorDefault(),i=t.isUnderlineColorDefault();if(!e||!i){if(e!==i)return!1;if(this.getUnderlineColor()!==t.getUnderlineColor())return!1;if(this.getUnderlineColorMode()!==t.getUnderlineColorMode())return!1}}return this.isOverline()===t.isOverline()&&this.isBlink()===t.isBlink()&&this.isInvisible()===t.isInvisible()&&this.isItalic()===t.isItalic()&&this.isDim()===t.isDim()&&this.isStrikethrough()===t.isStrikethrough()}}e.CellData=o},564(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.WHITESPACE_CELL_CODE=e.WHITESPACE_CELL_WIDTH=e.WHITESPACE_CELL_CHAR=e.NULL_CELL_CODE=e.NULL_CELL_WIDTH=e.NULL_CELL_CHAR=e.CHAR_DATA_CODE_INDEX=e.CHAR_DATA_WIDTH_INDEX=e.CHAR_DATA_CHAR_INDEX=e.CHAR_DATA_ATTR_INDEX=e.DEFAULT_EXT=e.DEFAULT_ATTR=e.DEFAULT_COLOR=void 0,e.DEFAULT_COLOR=0,e.DEFAULT_ATTR=e.DEFAULT_COLOR<<9|256,e.DEFAULT_EXT=0,e.CHAR_DATA_ATTR_INDEX=0,e.CHAR_DATA_CHAR_INDEX=1,e.CHAR_DATA_WIDTH_INDEX=2,e.CHAR_DATA_CODE_INDEX=3,e.NULL_CELL_CHAR="",e.NULL_CELL_WIDTH=1,e.NULL_CELL_CODE=0,e.WHITESPACE_CELL_CHAR=" ",e.WHITESPACE_CELL_WIDTH=1,e.WHITESPACE_CELL_CODE=32},348(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.Utf8ToUtf32=e.StringToUtf32=void 0,e.stringFromCodePoint=function(t){return t>65535?(t-=65536,String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):String.fromCharCode(t)},e.utf32ToString=function(t,e=0,i=t.length){let s="";for(let r=e;r65535?(e-=65536,s+=String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):s+=String.fromCharCode(e)}return s},e.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(t,e){const i=t.length;if(!i)return 0;let s=0,r=0;if(this._interim){const i=t.charCodeAt(r++);56320<=i&&i<=57343?e[s++]=1024*(this._interim-55296)+i-56320+65536:(e[s++]=this._interim,e[s++]=i),this._interim=0}for(let a=r;a=i)return this._interim=r,s;const o=t.charCodeAt(a);56320<=o&&o<=57343?e[s++]=1024*(r-55296)+o-56320+65536:(e[s++]=r,e[s++]=o);continue}65279!==r&&(e[s++]=r)}return s}},e.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(t,e){const i=t.length;if(!i)return 0;let s,r,a,o,n,L=0,h=0;if(this.interim[0]){let s=!1,r=this.interim[0];r&=192==(224&r)?31:224==(240&r)?15:7;let a,o=0;for(;(a=this.interim[++o])&&o<4;)r<<=6,r|=63&a;const n=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,T=n-o;for(;h=i)return 0;if(a=t[h++],128!=(192&a)){h--,s=!0;break}this.interim[o++]=a,r<<=6,r|=63&a}s||(2===n?r<128?h--:e[L++]=r:3===n?r<2048||r>=55296&&r<=57343||65279===r||(e[L++]=r):r<65536||r>1114111||(e[L++]=r)),this.interim.fill(0)}const T=i-4;let l=h;for(;l=i)return this.interim[0]=s,L;if(r=t[l++],128!=(192&r)){l--;continue}if(n=(31&s)<<6|63&r,n<128){l--;continue}e[L++]=n}else if(224==(240&s)){if(l>=i)return this.interim[0]=s,L;if(r=t[l++],128!=(192&r)){l--;continue}if(l>=i)return this.interim[0]=s,this.interim[1]=r,L;if(a=t[l++],128!=(192&a)){l--;continue}if(n=(15&s)<<12|(63&r)<<6|63&a,n<2048||n>=55296&&n<=57343||65279===n)continue;e[L++]=n}else if(240==(248&s)){if(l>=i)return this.interim[0]=s,L;if(r=t[l++],128!=(192&r)){l--;continue}if(l>=i)return this.interim[0]=s,this.interim[1]=r,L;if(a=t[l++],128!=(192&a)){l--;continue}if(l>=i)return this.interim[0]=s,this.interim[1]=r,this.interim[2]=a,L;if(o=t[l++],128!=(192&o)){l--;continue}if(n=(7&s)<<18|(63&r)<<12|(63&a)<<6|63&o,n<65536||n>1114111)continue;e[L++]=n}}return L}}},864(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.CellColorResolver=void 0;const s=i(564),r=i(993),a=i(959),o=i(915);let n,L=0,h=0,T=!1,l=!1,d=!1,c=0;e.CellColorResolver=class{constructor(t,e,i,s,r,a){this._terminal=t,this._optionService=e,this._selectionRenderModel=i,this._decorationService=s,this._coreBrowserService=r,this._themeService=a,this.result={fg:0,bg:0,ext:0}}resolve(t,e,i,_,Q){this.result.bg=t.bg,this.result.fg=t.fg,this.result.ext=268435456&t.bg?t.extended.ext:0,h=0,L=0,l=!1,T=!1,d=!1,n=this._themeService.colors,c=0;const u=t.getCode();if(u!==s.NULL_CELL_CODE&&4===t.extended.underlineStyle){const t=Math.max(1,Math.floor(this._optionService.rawOptions.fontSize*this._coreBrowserService.dpr/15));c=e*_%(2*Math.round(t))}if(0===c&&o.blockPatternCodepoints.has(u)&&(c=e*_%2*2+i*Q%2),this._decorationService.forEachDecorationAtCell(e,i,"bottom",t=>{t.backgroundColorRGB&&(h=t.backgroundColorRGB.rgba>>8&16777215,l=!0),t.foregroundColorRGB&&(L=t.foregroundColorRGB.rgba>>8&16777215,T=!0)}),d=this._selectionRenderModel.isCellSelected(this._terminal,e,i),d){if(67108864&this.result.fg||50331648&this.result.bg){if(67108864&this.result.fg)switch(50331648&this.result.fg){case 16777216:case 33554432:h=this._themeService.colors.ansi[255&this.result.fg].rgba;break;case 50331648:h=(16777215&this.result.fg)<<8|255;break;default:h=this._themeService.colors.foreground.rgba}else switch(50331648&this.result.bg){case 16777216:case 33554432:h=this._themeService.colors.ansi[255&this.result.bg].rgba;break;case 50331648:h=(16777215&this.result.bg)<<8|255}h=r.rgba.blend(h,4294967040&(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba|128)>>8&16777215}else h=(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba>>8&16777215;if(l=!0,n.selectionForeground&&(L=n.selectionForeground.rgba>>8&16777215,T=!0),(0,a.treatGlyphAsBackgroundColor)(t.getCode())){if(67108864&this.result.fg&&!(50331648&this.result.bg))L=(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba>>8&16777215;else{if(67108864&this.result.fg)switch(50331648&this.result.bg){case 16777216:case 33554432:L=this._themeService.colors.ansi[255&this.result.bg].rgba;break;case 50331648:L=(16777215&this.result.bg)<<8|255}else switch(50331648&this.result.fg){case 16777216:case 33554432:L=this._themeService.colors.ansi[255&this.result.fg].rgba;break;case 50331648:L=(16777215&this.result.fg)<<8|255;break;default:L=this._themeService.colors.foreground.rgba}L=r.rgba.blend(L,4294967040&(this._coreBrowserService.isFocused?n.selectionBackgroundOpaque:n.selectionInactiveBackgroundOpaque).rgba|128)>>8&16777215}T=!0}}this._decorationService.forEachDecorationAtCell(e,i,"top",t=>{t.backgroundColorRGB&&(h=t.backgroundColorRGB.rgba>>8&16777215,l=!0),t.foregroundColorRGB&&(L=t.foregroundColorRGB.rgba>>8&16777215,T=!0)}),l&&(h=d?-16777216&t.bg&-134217729|h|50331648:-16777216&t.bg|h|50331648),T&&(L=-16777216&t.fg&-67108865|L|50331648),67108864&this.result.fg&&(l&&!T&&(L=50331648&this.result.bg?-134217728&this.result.fg|67108863&this.result.bg:-134217728&this.result.fg|16777215&n.background.rgba>>8|50331648,T=!0),!l&&T&&(h=50331648&this.result.fg?-67108864&this.result.bg|67108863&this.result.fg:-67108864&this.result.bg|16777215&n.foreground.rgba>>8|50331648,l=!0)),n=void 0,this.result.bg=l?h:this.result.bg,this.result.fg=T?L:this.result.fg,this.result.ext&=536870911,this.result.ext|=c<<29&3758096384}}},670(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.acquireTextureAtlas=function(t,e,i,o,n,L,h,T,l,d=!0){const c=(0,r.generateConfig)(o,n,L,h,e,i,T,l,d);for(let e=0;e=0){if((0,r.configEquals)(i.config,c))return i.atlas;1===i.ownedBy.length?(i.atlas.dispose(),a.splice(e,1)):i.ownedBy.splice(s,1);break}}for(let e=0;e{this._renderCallback(),this._animationFrame=void 0})))}_restartInterval(t=600){this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout=this._coreBrowserService.window.setTimeout(()=>{if(this._animationTimeRestarted){const t=600-(Date.now()-this._animationTimeRestarted);if(this._animationTimeRestarted=void 0,t>0)return void this._restartInterval(t)}this.isCursorVisible=!1,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0}),this._blinkInterval=this._coreBrowserService.window.setInterval(()=>{if(this._animationTimeRestarted){const t=600-(Date.now()-this._animationTimeRestarted);return this._animationTimeRestarted=void 0,void this._restartInterval(t)}this.isCursorVisible=!this.isCursorVisible,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0})},600)},t)}pause(){this.isCursorVisible=!0,this._isIdlePaused=!1,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._idleTimeout&&(this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0)}resume(){this.pause(),this._animationTimeRestarted=void 0,this._restartInterval(),this._resetIdleTimer(),this.restartBlinkAnimation()}_resetIdleTimer(){this._isIdlePaused=!1,this._idleTimeout&&this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=this._coreBrowserService.window.setTimeout(()=>{this._stopBlinkingDueToIdle()},3e5)}_stopBlinkingDueToIdle(){this.isCursorVisible=!0,this._isIdlePaused=!0,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0,this._renderCallback()}}},697(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.observeDevicePixelDimensions=function(t,e,i){let r=new e.ResizeObserver(e=>{const s=e.find(e=>e.target===t);if(!s)return;if(!("devicePixelContentBoxSize"in s))return r?.disconnect(),void(r=void 0);const a=s.devicePixelContentBoxSize[0].inlineSize,o=s.devicePixelContentBoxSize[0].blockSize;a>0&&o>0&&i(a,o)});try{r.observe(t,{box:["device-pixel-content-box"]})}catch{r.disconnect(),r=void 0}return(0,s.toDisposable)(()=>r?.disconnect())};const s=i(426)},28(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.GlyphRenderer=void 0;const s=i(115),r=i(564),a=i(426),o=i(719),n=i(959);let L,h=0,T=0,l=0;class d extends a.Disposable{constructor(t,e,i,r,L){super(),this._terminal=t,this._gl=e,this._dimensions=i,this._optionsService=r,this._logService=L,this._activeBuffer=0,this._vertices={count:0,attributes:new Float32Array(0),attributesBuffers:[new Float32Array(0),new Float32Array(0)]};const h=this._gl;void 0===s.TextureAtlas.maxAtlasPages&&(s.TextureAtlas.maxAtlasPages=Math.min(32,(0,n.throwIfFalsy)(h.getParameter(h.MAX_TEXTURE_IMAGE_UNITS))),s.TextureAtlas.maxTextureSize=(0,n.throwIfFalsy)(h.getParameter(h.MAX_TEXTURE_SIZE))),this._program=(0,n.throwIfFalsy)((0,o.createProgram)(h,"#version 300 es\nlayout (location = 0) in vec2 a_unitquad;\nlayout (location = 1) in vec2 a_cellpos;\nlayout (location = 2) in vec2 a_offset;\nlayout (location = 3) in vec2 a_size;\nlayout (location = 4) in float a_texpage;\nlayout (location = 5) in vec2 a_texcoord;\nlayout (location = 6) in vec2 a_texsize;\n\nuniform mat4 u_projection;\nuniform vec2 u_resolution;\n\nout vec2 v_texcoord;\nflat out int v_texpage;\n\nvoid main() {\n vec2 zeroToOne = (a_offset / u_resolution) + a_cellpos + (a_unitquad * a_size);\n gl_Position = u_projection * vec4(zeroToOne, 0.0, 1.0);\n v_texpage = int(a_texpage);\n v_texcoord = a_texcoord + a_unitquad * a_texsize;\n}",function(t){let e="";for(let i=1;ih.deleteProgram(this._program))),this._projectionLocation=(0,n.throwIfFalsy)(h.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=(0,n.throwIfFalsy)(h.getUniformLocation(this._program,"u_resolution")),this._textureLocation=(0,n.throwIfFalsy)(h.getUniformLocation(this._program,"u_texture"));const T=this._vertexArrayObject=h.createVertexArray();this._register((0,a.toDisposable)(()=>h.deleteVertexArray(T))),h.bindVertexArray(T);const l=new Float32Array([0,0,1,0,0,1,1,1]),d=h.createBuffer();this._register((0,a.toDisposable)(()=>h.deleteBuffer(d))),h.bindBuffer(h.ARRAY_BUFFER,d),h.bufferData(h.ARRAY_BUFFER,l,h.STATIC_DRAW),h.enableVertexAttribArray(0),h.vertexAttribPointer(0,2,this._gl.FLOAT,!1,0,0);const c=new Uint8Array([0,1,2,3]),_=h.createBuffer();this._register((0,a.toDisposable)(()=>h.deleteBuffer(_))),h.bindBuffer(h.ELEMENT_ARRAY_BUFFER,_),h.bufferData(h.ELEMENT_ARRAY_BUFFER,c,h.STATIC_DRAW),this._attributesBuffer=(0,n.throwIfFalsy)(h.createBuffer()),this._register((0,a.toDisposable)(()=>h.deleteBuffer(this._attributesBuffer))),h.bindBuffer(h.ARRAY_BUFFER,this._attributesBuffer),h.enableVertexAttribArray(2),h.vertexAttribPointer(2,2,h.FLOAT,!1,44,0),h.vertexAttribDivisor(2,1),h.enableVertexAttribArray(3),h.vertexAttribPointer(3,2,h.FLOAT,!1,44,2*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(3,1),h.enableVertexAttribArray(4),h.vertexAttribPointer(4,1,h.FLOAT,!1,44,4*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(4,1),h.enableVertexAttribArray(5),h.vertexAttribPointer(5,2,h.FLOAT,!1,44,5*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(5,1),h.enableVertexAttribArray(6),h.vertexAttribPointer(6,2,h.FLOAT,!1,44,7*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(6,1),h.enableVertexAttribArray(1),h.vertexAttribPointer(1,2,h.FLOAT,!1,44,9*Float32Array.BYTES_PER_ELEMENT),h.vertexAttribDivisor(1,1),h.useProgram(this._program);const Q=new Int32Array(s.TextureAtlas.maxAtlasPages);for(let t=0;th.deleteTexture(e.texture))),h.activeTexture(h.TEXTURE0+t),h.bindTexture(h.TEXTURE_2D,e.texture),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texImage2D(h.TEXTURE_2D,0,h.RGBA,1,1,0,h.RGBA,h.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[t]=e}h.enable(h.BLEND),h.blendFunc(h.SRC_ALPHA,h.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){if(!this._atlas)return!0;const _g=this._atlas._clearModelGeneration||0;return this._lastSeenClearModelGeneration!==_g&&(this._lastSeenClearModelGeneration=_g,!0)}updateCell(t,e,i,s,r,a,o,n,L){this._updateCell(this._vertices.attributes,t,e,i,s,r,a,o,n,L)}_updateCell(t,e,i,s,a,o,d,c,_,Q){h=11*(i*this._terminal.cols+e),s!==r.NULL_CELL_CODE&&void 0!==s?this._atlas&&(L=c&&c.length>1?this._atlas.getRasterizedGlyphCombinedChar(c,a,o,d,!1,this._terminal.element):this._atlas.getRasterizedGlyph(s,a,o,d,!1,this._terminal.element),T=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),a!==Q&&L.offset.x>T?(l=L.offset.x-T,t[h]=-(L.offset.x-l)+this._dimensions.device.char.left,t[h+1]=-L.offset.y+this._dimensions.device.char.top,t[h+2]=(L.size.x-l)/this._dimensions.device.canvas.width,t[h+3]=L.size.y/this._dimensions.device.canvas.height,t[h+4]=L.texturePage,t[h+5]=L.texturePositionClipSpace.x+l/this._atlas.pages[L.texturePage].canvas.width,t[h+6]=L.texturePositionClipSpace.y,t[h+7]=L.sizeClipSpace.x-l/this._atlas.pages[L.texturePage].canvas.width,t[h+8]=L.sizeClipSpace.y):(t[h]=-L.offset.x+this._dimensions.device.char.left,t[h+1]=-L.offset.y+this._dimensions.device.char.top,t[h+2]=L.size.x/this._dimensions.device.canvas.width,t[h+3]=L.size.y/this._dimensions.device.canvas.height,t[h+4]=L.texturePage,t[h+5]=L.texturePositionClipSpace.x,t[h+6]=L.texturePositionClipSpace.y,t[h+7]=L.sizeClipSpace.x,t[h+8]=L.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&(0,n.allowRescaling)(s,_,L.size.x,this._dimensions.device.cell.width)&&(t[h+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width)):t.fill(0,h,h+11-1-2)}clear(){const t=this._terminal,e=t.cols*t.rows*11;this._vertices.count!==e?this._vertices.attributes=new Float32Array(e):this._vertices.attributes.fill(0);let i=0;for(;iT.deleteProgram(this._program))),this._projectionLocation=(0,a.throwIfFalsy)(T.getUniformLocation(this._program,"u_projection"));const l=this._vertexArrayObject=T.createVertexArray();this._register((0,s.toDisposable)(()=>T.deleteVertexArray(l))),T.bindVertexArray(l);const d=new Float32Array([0,0,1,0,0,1,1,1]),c=T.createBuffer();this._register((0,s.toDisposable)(()=>T.deleteBuffer(c))),T.bindBuffer(T.ARRAY_BUFFER,c),T.bufferData(T.ARRAY_BUFFER,d,T.STATIC_DRAW),T.enableVertexAttribArray(3),T.vertexAttribPointer(3,2,this._gl.FLOAT,!1,0,0);const _=new Uint8Array([0,1,2,3]),Q=T.createBuffer();this._register((0,s.toDisposable)(()=>T.deleteBuffer(Q))),T.bindBuffer(T.ELEMENT_ARRAY_BUFFER,Q),T.bufferData(T.ELEMENT_ARRAY_BUFFER,_,T.STATIC_DRAW),this._attributesBuffer=(0,a.throwIfFalsy)(T.createBuffer()),this._register((0,s.toDisposable)(()=>T.deleteBuffer(this._attributesBuffer))),T.bindBuffer(T.ARRAY_BUFFER,this._attributesBuffer),T.enableVertexAttribArray(0),T.vertexAttribPointer(0,2,T.FLOAT,!1,o,0),T.vertexAttribDivisor(0,1),T.enableVertexAttribArray(1),T.vertexAttribPointer(1,2,T.FLOAT,!1,o,2*Float32Array.BYTES_PER_ELEMENT),T.vertexAttribDivisor(1,1),T.enableVertexAttribArray(2),T.vertexAttribPointer(2,4,T.FLOAT,!1,o,4*Float32Array.BYTES_PER_ELEMENT),T.vertexAttribDivisor(2,1),this._updateCachedColors(L.colors),this._register(this._themeService.onChangeColors(t=>{this._updateCachedColors(t),this._updateViewportRectangle()}))}renderBackgrounds(){this._renderVertices(this._vertices)}renderCursor(){this._renderVertices(this._verticesCursor)}_renderVertices(t){const e=this._gl;e.useProgram(this._program),e.bindVertexArray(this._vertexArrayObject),e.uniformMatrix4fv(this._projectionLocation,!1,r.PROJECTION_MATRIX),e.bindBuffer(e.ARRAY_BUFFER,this._attributesBuffer),e.bufferData(e.ARRAY_BUFFER,t.attributes,e.DYNAMIC_DRAW),e.drawElementsInstanced(this._gl.TRIANGLE_STRIP,4,e.UNSIGNED_BYTE,0,t.count)}handleResize(){this._updateViewportRectangle()}setDimensions(t){this._dimensions=t}_updateCachedColors(t){this._bgFloat=this._colorToFloat32Array(t.background),this._cursorFloat=this._colorToFloat32Array(t.cursor)}_updateViewportRectangle(){this._addRectangleFloat(this._vertices.attributes,0,0,0,this._terminal.cols*this._dimensions.device.cell.width,this._terminal.rows*this._dimensions.device.cell.height,this._bgFloat)}updateBackgrounds(t){const e=this._terminal,i=this._vertices;let s,r,a,o,n,L,h,T,l,d,c,_=1;for(s=0;s>24&255)/255,d=(L>>16&255)/255,c=(L>>8&255)/255,_=1,this._addRectangle(t.attributes,e,h,T,(o-a)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,l,d,c,_)}_addRectangle(t,e,i,s,r,a,o,n,L,h){t[e]=i/this._dimensions.device.canvas.width,t[e+1]=s/this._dimensions.device.canvas.height,t[e+2]=r/this._dimensions.device.canvas.width,t[e+3]=a/this._dimensions.device.canvas.height,t[e+4]=o,t[e+5]=n,t[e+6]=L,t[e+7]=h}_addRectangleFloat(t,e,i,s,r,a,o){t[e]=i/this._dimensions.device.canvas.width,t[e+1]=s/this._dimensions.device.canvas.height,t[e+2]=r/this._dimensions.device.canvas.width,t[e+3]=a/this._dimensions.device.canvas.height,t[e+4]=o[0],t[e+5]=o[1],t[e+6]=o[2],t[e+7]=o[3]}_colorToFloat32Array(t){return new Float32Array([(t.rgba>>24&255)/255,(t.rgba>>16&255)/255,(t.rgba>>8&255)/255,(255&t.rgba)/255])}}e.RectangleRenderer=Q},208(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.RenderModel=e.COMBINED_CHAR_BIT_MASK=void 0;const s=i(948);e.COMBINED_CHAR_BIT_MASK=2147483648,e.RenderModel=class{constructor(){this.cells=new Uint32Array(0),this.lineLengths=new Uint32Array(0),this.selection=(0,s.createSelectionRenderModel)()}resize(t,e){const i=t*e*4;i!==this.cells.length&&(this.cells=new Uint32Array(i),this.lineLengths=new Uint32Array(e))}clear(){this.cells.fill(0,0),this.lineLengths.fill(0,0)}}},115(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.TextureAtlas=void 0;const s=i(0),r=i(183),a=i(959),o=i(993),n=i(836),L=i(930),h=i(917),T=i(564),l=i(414),d={texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},offset:{x:0,y:0},size:{x:0,y:0},sizeClipSpace:{x:0,y:0}};let c;class _{get pages(){return this._pages}constructor(t,e,i,s){this._document=t,this._config=e,this._unicodeService=i,this._logService=s,this._didWarmUp=!1,this._cacheMap=new n.FourKeyMap,this._cacheMapCombined=new n.FourKeyMap,this._pages=[],this._activePages=[],this._workBoundingBox={top:0,left:0,bottom:0,right:0},this._workAttributeData=new h.AttributeData,this._textureSize=512,this._onAddTextureAtlasCanvas=new l.Emitter,this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=new l.Emitter,this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._requestClearModel=!1,this._clearModelGeneration=0,this._createNewPage(),this._tmpCanvas=p(t,4*this._config.deviceCellWidth+4,this._config.deviceCellHeight+4),this._tmpCtx=(0,a.throwIfFalsy)(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:!0}))}dispose(){this._tmpCanvas.remove();for(const t of this.pages)t.canvas.remove();this._onAddTextureAtlasCanvas.dispose(),this._onRemoveTextureAtlasCanvas.dispose()}warmUp(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)}_doWarmUp(){const t=new L.IdleTaskQueue(this._logService);for(let e=33;e<126;e++)t.enqueue(()=>{if(!this._cacheMap.get(e,T.DEFAULT_COLOR,T.DEFAULT_COLOR,T.DEFAULT_EXT)){const t=this._drawToCache(e,T.DEFAULT_COLOR,T.DEFAULT_COLOR,T.DEFAULT_EXT,!1,void 0);this._cacheMap.set(e,T.DEFAULT_COLOR,T.DEFAULT_COLOR,T.DEFAULT_EXT,t)}})}beginFrame(){const t=this._requestClearModel;return this._requestClearModel=!1,t}clearTexture(){if(this._pages.some(t=>t._glyphs.length>0||0!==t.currentRow.x||0!==t.currentRow.y)){for(const t of this._pages)t.clear();this._activePages.length=0;for(const t of this._pages)t!==this._overflowSizePage&&this._activePages.push(t);this._cacheMap.clear(),this._cacheMapCombined.clear(),this._didWarmUp=!1,this._requestClearModel=!0,this._clearModelGeneration++}}_createNewPage(){if(_.maxAtlasPages&&this._pages.length>=Math.max(4,_.maxAtlasPages)){const t=this._pages.filter(t=>2*t.canvas.width<=(_.maxTextureSize||4096)).sort((t,e)=>e.canvas.width!==t.canvas.width?e.canvas.width-t.canvas.width:e.percentageUsed-t.percentageUsed);let e=-1,i=0;for(let s=0;st.canvas.width!==s[0].canvas.width)){const t=new Q(this._document,this._textureSize);return this._pages.push(t),this._activePages.push(t),this._onAddTextureAtlasCanvas.fire(t.canvas),t}const r=s.map(t=>t.glyphs[0].texturePage).sort((t,e)=>t-e),a=this.pages.length-s.length,o=this._mergePages(s,a);o.version=++Q.nextVersion;for(let t=r.length-1;t>=0;t--)this._deletePage(r[t]);this.pages.push(o),this._requestClearModel=!0,this._clearModelGeneration++,this._onAddTextureAtlasCanvas.fire(o.canvas)}const t=new Q(this._document,this._textureSize);return this._pages.push(t),this._activePages.push(t),this._onAddTextureAtlasCanvas.fire(t.canvas),t}_mergePages(t,e){const i=2*t[0].canvas.width,s=new Q(this._document,i,t);for(const[r,a]of t.entries()){const t=r*a.canvas.width%i,o=Math.floor(r/2)*a.canvas.height;s.ctx.drawImage(a.canvas,t,o);for(const s of a.glyphs)s.texturePage=e,s.sizeClipSpace.x=s.size.x/i,s.sizeClipSpace.y=s.size.y/i,s.texturePosition.x+=t,s.texturePosition.y+=o,s.texturePositionClipSpace.x=s.texturePosition.x/i,s.texturePositionClipSpace.y=s.texturePosition.y/i;this._onRemoveTextureAtlasCanvas.fire(a.canvas);const n=this._activePages.indexOf(a);-1!==n&&this._activePages.splice(n,1)}return s}_deletePage(t){this._pages.splice(t,1);for(let e=t;e=this._config.colors.ansi.length)throw new Error("No color found for idx "+t);return this._config.colors.ansi[t]}_getBackgroundColor(t,e,i,s){if(this._config.allowTransparency)return o.NULL_COLOR;let r;switch(t){case 16777216:case 33554432:r=this._getColorFromAnsiIndex(e);break;case 50331648:const t=h.AttributeData.toColorRGB(e);r=o.channels.toColor(t[0],t[1],t[2]);break;default:r=i?o.color.opaque(this._config.colors.foreground):this._config.colors.background}return this._config.allowTransparency||(r=o.color.opaque(r)),r}_getForegroundColor(t,e,i,r,a,n,L,T,l,d){const c=this._getMinimumContrastColor(t,e,i,r,a,n,L,l,T,d);if(c)return c;let _;switch(a){case 16777216:case 33554432:this._config.drawBoldTextInBrightColors&&l&&n<8&&(n+=8),_=this._getColorFromAnsiIndex(n);break;case 50331648:const t=h.AttributeData.toColorRGB(n);_=o.channels.toColor(t[0],t[1],t[2]);break;default:_=L?this._config.colors.background:this._config.colors.foreground}return this._config.allowTransparency&&(_=o.color.opaque(_)),T&&(_=o.color.multiplyOpacity(_,s.DIM_OPACITY)),_}_resolveBackgroundRgba(t,e,i){switch(t){case 16777216:case 33554432:return this._getColorFromAnsiIndex(e).rgba;case 50331648:return e<<8;default:return i?this._config.colors.foreground.rgba:this._config.colors.background.rgba}}_resolveForegroundRgba(t,e,i,s){switch(t){case 16777216:case 33554432:return this._config.drawBoldTextInBrightColors&&s&&e<8&&(e+=8),this._getColorFromAnsiIndex(e).rgba;case 50331648:return e<<8;default:return i?this._config.colors.background.rgba:this._config.colors.foreground.rgba}}_getMinimumContrastColor(t,e,i,s,r,a,n,L,h,T){if(1===this._config.minimumContrastRatio||T)return;const l=this._getContrastCache(h),d=l.getColor(t,s);if(void 0!==d)return d??void 0;const c=this._resolveBackgroundRgba(e,i,n),_=this._resolveForegroundRgba(r,a,n,L),Q=o.rgba.ensureContrastRatio(c,_,this._config.minimumContrastRatio/(h?2:1));if(!Q)return void l.setColor(t,s,null);const u=o.channels.toColor(Q>>24&255,Q>>16&255,Q>>8&255);return l.setColor(t,s,u),u}_getContrastCache(t){return t?this._config.colors.halfContrastCache:this._config.colors.contrastCache}_drawToCache(t,e,i,o,n,L){const T="number"==typeof t?String.fromCharCode(t):t;L&&this._tmpCanvas.parentElement!==L&&(this._tmpCanvas.style.display="none",L.append(this._tmpCanvas));const l=Math.min(this._config.deviceCellWidth*Math.max(T.length,2)+4,this._config.deviceMaxTextureSize);this._tmpCanvas.width=t?2*t-o:t-o;!1==!(o>=t)||0===_?(this._tmpCtx.setLineDash([Math.round(t),Math.round(t)]),this._tmpCtx.moveTo(h+_,s),this._tmpCtx.lineTo(T,s)):(this._tmpCtx.setLineDash([Math.round(t),Math.round(t)]),this._tmpCtx.moveTo(h,s),this._tmpCtx.lineTo(h+_,s),this._tmpCtx.moveTo(h+_+t,s),this._tmpCtx.lineTo(T,s)),o=(0,a.computeNextVariantOffset)(T-h,t,o);break;case 5:const Q=.6,u=.3,p=T-h,g=Math.floor(Q*p),M=Math.floor(u*p),y=p-g-M;this._tmpCtx.setLineDash([g,M,y]),this._tmpCtx.moveTo(h,s),this._tmpCtx.lineTo(T,s);break;default:this._tmpCtx.moveTo(h,s),this._tmpCtx.lineTo(T,s)}n||this._tmpCtx.stroke(),this._tmpCtx.restore()}if(this._tmpCtx.restore(),!O&&this._config.fontSize>=12&&!this._config.allowTransparency&&" "!==T){this._tmpCtx.save(),this._tmpCtx.textBaseline="alphabetic";const e=this._tmpCtx.measureText(T);if(this._tmpCtx.restore(),"actualBoundingBoxDescent"in e&&e.actualBoundingBoxDescent>0){this._tmpCtx.save();const e=new Path2D;e.rect(i,L-Math.ceil(t/2),this._config.deviceCellWidth*I,l-L+Math.ceil(t/2)),this._tmpCtx.clip(e),this._tmpCtx.lineWidth=3*this._config.devicePixelRatio,this._tmpCtx.strokeStyle=E.css,this._tmpCtx.strokeText(T,S,S+this._config.deviceCharHeight),this._tmpCtx.restore()}}}if(C){const t=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/15)),e=t%2==1?.5:0;this._tmpCtx.lineWidth=t,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(S,S+e),this._tmpCtx.lineTo(S+this._config.deviceCharWidth*I,S+e),this._tmpCtx.stroke()}if(O||this._tmpCtx.fillText(T,S,S+this._config.deviceCharHeight),"_"===T&&!this._config.allowTransparency){let t=u(this._tmpCtx.getImageData(S,S,this._config.deviceCellWidth,this._config.deviceCellHeight),E,D,W);if(t)for(let e=1;e<=5&&(this._tmpCtx.save(),this._tmpCtx.fillStyle=E.css,this._tmpCtx.fillRect(0,0,this._tmpCanvas.width,this._tmpCanvas.height),this._tmpCtx.restore(),this._tmpCtx.fillText(T,S,S+this._config.deviceCharHeight-e),t=u(this._tmpCtx.getImageData(S,S,this._config.deviceCellWidth,this._config.deviceCellHeight),E,D,W),t);e++);}if(f){const t=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/10)),e=this._tmpCtx.lineWidth%2==1?.5:0;this._tmpCtx.lineWidth=t,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(S,S+Math.floor(this._config.deviceCharHeight/2)-e),this._tmpCtx.lineTo(S+this._config.deviceCharWidth*I,S+Math.floor(this._config.deviceCharHeight/2)-e),this._tmpCtx.stroke()}this._tmpCtx.restore();const N=this._tmpCtx.getImageData(0,0,this._tmpCanvas.width,this._tmpCanvas.height);let P;if(P=this._config.allowTransparency?function(t){for(let e=0;e0)return!1;return!0}(N):u(N,E,D,W),P)return d;const B=this._findGlyphBoundingBox(N,this._workBoundingBox,l,Z,O,S);let $,F;for(;;){if(0===this._activePages.length){const t=this._createNewPage();$=t,F=t.currentRow,F.height=B.size.y;break}$=this._activePages[this._activePages.length-1],F=$.currentRow;for(const t of this._activePages)B.size.y<=t.currentRow.height&&($=t,F=t.currentRow);for(let t=this._activePages.length-1;t>=0;t--)for(const e of this._activePages[t].fixedRows)e.height<=F.height&&B.size.y<=e.height&&($=this._activePages[t],F=e);if(B.size.x>this._textureSize){this._overflowSizePage||(this._overflowSizePage=new Q(this._document,this._config.deviceMaxTextureSize),this.pages.push(this._overflowSizePage),this._requestClearModel=!0,this._clearModelGeneration++,this._onAddTextureAtlasCanvas.fire(this._overflowSizePage.canvas)),$=this._overflowSizePage,F=this._overflowSizePage.currentRow,F.x+B.size.x>=$.canvas.width&&(F.x=0,F.y+=F.height,F.height=0);break}if(F.y+B.size.y>=$.canvas.height||F.height>B.size.y+2){let t=!1;if($.currentRow.y+$.currentRow.height+B.size.y>=$.canvas.height){let e;for(const t of this._activePages)if(t.currentRow.y+t.currentRow.height+B.size.y=_.maxAtlasPages&&F.y+B.size.y<=$.canvas.height&&F.height>=B.size.y&&F.x+B.size.x<=$.canvas.width)t=!0;else{const e=this._createNewPage();$=e,F=e.currentRow,F.height=B.size.y,t=!0}}t||($.currentRow.height>0&&$.fixedRows.push($.currentRow),F={x:0,y:$.currentRow.y+$.currentRow.height,height:B.size.y},$.fixedRows.push(F),$.currentRow={x:0,y:F.y+F.height,height:0})}if(F.x+B.size.x<=$.canvas.width)break;F===$.currentRow?(F.x=0,F.y+=F.height,F.height=0):$.fixedRows.splice($.fixedRows.indexOf(F),1)}return B.texturePage=this._pages.indexOf($),B.texturePosition.x=F.x,B.texturePosition.y=F.y,B.texturePositionClipSpace.x=F.x/$.canvas.width,B.texturePositionClipSpace.y=F.y/$.canvas.height,B.sizeClipSpace.x/=$.canvas.width,B.sizeClipSpace.y/=$.canvas.height,F.height=Math.max(F.height,B.size.y),F.x+=B.size.x,$.ctx.putImageData(N,B.texturePosition.x-this._workBoundingBox.left,B.texturePosition.y-this._workBoundingBox.top,this._workBoundingBox.left,this._workBoundingBox.top,B.size.x,B.size.y),$.addGlyph(B),$.version=++Q.nextVersion,B}_findGlyphBoundingBox(t,e,i,s,r,a){e.top=0;const o=s?this._config.deviceCellHeight:this._tmpCanvas.height,n=s?this._config.deviceCellWidth:i;let L=!1;for(let i=0;i=a;i--){for(let s=0;s=0;i--){for(let s=0;s>>24,a=e.rgba>>>16&255,o=e.rgba>>>8&255,n=i.rgba>>>24,L=i.rgba>>>16&255,h=i.rgba>>>8&255,T=Math.floor((Math.abs(r-n)+Math.abs(a-L)+Math.abs(o-h))/12);let l=!0;for(let e=0;ethis._handleColorChange())),this._cellColorResolver=new s.CellColorResolver(this._terminal,this._optionsService,this._model.selection,this._decorationService,this._coreBrowserService,this._themeService),this._core=this._terminal._core,this._renderLayers=[new _.LinkRenderLayer(this._core.screenElement,2,this._terminal,this._core.linkifier,this._coreBrowserService,d,this._themeService)],this.dimensions=(0,g.createRenderDimensions)(),this._devicePixelRatio=this._coreBrowserService.dpr,this._updateDimensions(),this._updateCursorBlink(),this._register(d.onOptionChange(()=>this._handleOptionsChanged())),this._textBlinkStateManager=this._register(new T.TextBlinkStateManager(()=>this._requestRedrawViewport(),this._coreBrowserService,this._optionsService)),this._resetBlinkingRowState(),this._deviceMaxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._register((0,u.addDisposableListener)(this._canvas,"webglcontextlost",t=>{this._logService.debug("webglcontextlost event received"),t.preventDefault(),this._contextRestorationTimeout=setTimeout(()=>{this._contextRestorationTimeout=void 0,this._logService.warn("webgl context not restored; firing onContextLoss"),this._onContextLoss.fire(t)},3e3)})),this._register((0,u.addDisposableListener)(this._canvas,"webglcontextrestored",t=>{this._logService.warn("webglcontextrestored event received"),clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0,(0,r.removeTerminalFromCache)(this._terminal),this._initializeWebGLState(),this._requestRedrawViewport()})),this._observerDisposable.value=(0,o.observeDevicePixelDimensions)(this._canvas,this._coreBrowserService.window,(t,e)=>this._setCanvasDevicePixelDimensions(t,e)),this._register(this._coreBrowserService.onWindowChange(t=>{this._observerDisposable.value=(0,o.observeDevicePixelDimensions)(this._canvas,t,(t,e)=>this._setCanvasDevicePixelDimensions(t,e))})),this._register((0,u.addDisposableListener)(this._coreBrowserService.mainDocument,"mousedown",()=>this._cursorBlinkStateManager.value?.restartBlinkAnimation())),this._core.screenElement.appendChild(this._canvas),[this._rectangleRenderer.value,this._glyphRenderer.value]=this._initializeWebGLState(),this._isAttached=this._core.screenElement.isConnected,this._register((0,p.toDisposable)(()=>{clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0;for(const t of this._renderLayers)t.dispose();this._canvas.parentElement?.removeChild(this._canvas),(0,r.removeTerminalFromCache)(this._terminal)}))}get textureAtlas(){return this._charAtlas?.pages[0].canvas}_handleColorChange(){this._refreshCharAtlas(),this._clearModel(!0)}handleDevicePixelRatioChange(){this._devicePixelRatio!==this._coreBrowserService.dpr&&(this._devicePixelRatio=this._coreBrowserService.dpr,this.handleResize(this._terminal.cols,this._terminal.rows))}handleResize(t,e){this._updateDimensions(),this._model.resize(this._terminal.cols,this._terminal.rows),this._resetBlinkingRowState();for(const t of this._renderLayers)t.resize(this._terminal,this.dimensions);this._canvas.width=this.dimensions.device.canvas.width,this._canvas.height=this.dimensions.device.canvas.height,this._canvas.style.width=`${this.dimensions.css.canvas.width}px`,this._canvas.style.height=`${this.dimensions.css.canvas.height}px`,this._core.screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._core.screenElement.style.height=`${this.dimensions.css.canvas.height}px`,this._rectangleRenderer.value?.setDimensions(this.dimensions),this._rectangleRenderer.value?.handleResize(),this._glyphRenderer.value?.setDimensions(this.dimensions),this._glyphRenderer.value?.handleResize(),this._refreshCharAtlas(),this._clearModel(!1),this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1,sync:!0})}handleCharSizeChanged(){this.handleResize(this._terminal.cols,this._terminal.rows)}handleBlur(){for(const t of this._renderLayers)t.handleBlur(this._terminal);this._cursorBlinkStateManager.value?.pause(),this._requestRedrawViewport()}handleFocus(){for(const t of this._renderLayers)t.handleFocus(this._terminal);this._cursorBlinkStateManager.value?.resume(),this._requestRedrawViewport()}handleViewportVisibilityChange(t){this._textBlinkStateManager.setViewportVisible(t)}handleSelectionChanged(t,e,i){for(const s of this._renderLayers)s.handleSelectionChanged(this._terminal,t,e,i);this._model.selection.update(this._core,t,e,i),this._requestRedrawViewport()}handleCursorMove(){for(const t of this._renderLayers)t.handleCursorMove(this._terminal);this._cursorBlinkStateManager.value?.restartBlinkAnimation()}_handleOptionsChanged(){this._updateDimensions(),this._refreshCharAtlas(),this._updateCursorBlink()}_initializeWebGLState(){return this._rectangleRenderer.value=new d.RectangleRenderer(this._terminal,this._gl,this.dimensions,this._themeService,this._logService),this._glyphRenderer.value=new l.GlyphRenderer(this._terminal,this._gl,this.dimensions,this._optionsService,this._logService),this.handleCharSizeChanged(),[this._rectangleRenderer.value,this._glyphRenderer.value]}_refreshCharAtlas(){if(this.dimensions.device.char.width<=0&&this.dimensions.device.char.height<=0)return void(this._isAttached=!1);const t=(0,r.acquireTextureAtlas)(this._terminal,this._optionsService.rawOptions,this._themeService.colors,this.dimensions.device.cell.width,this.dimensions.device.cell.height,this.dimensions.device.char.width,this.dimensions.device.char.height,this._coreBrowserService.dpr,this._deviceMaxTextureSize,this._customGlyphs);this._charAtlas!==t&&(this._onChangeTextureAtlas.fire(t.pages[0].canvas),this._charAtlasDisposable.value=(0,p.combinedDisposable)(Q.EventUtils.forward(t.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas),Q.EventUtils.forward(t.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas))),this._charAtlas=t,this._charAtlas.warmUp(),this._glyphRenderer.value?.setAtlas(this._charAtlas)}_clearModel(t){this._model.clear(),t&&this._glyphRenderer.value?.clear()}clearTextureAtlas(){this._charAtlas?.clearTexture(),this._clearModel(!0),this._requestRedrawViewport()}clear(){this._clearModel(!0);for(const t of this._renderLayers)t.reset(this._terminal);this._resetBlinkingRowState(),this._textBlinkStateManager.setNeedsBlinkInViewport(!1),this._cursorBlinkStateManager.value?.restartBlinkAnimation(),this._updateCursorBlink()}renderRows(t,e){if(!this._isAttached){if(!(this._core.screenElement?.isConnected&&this._charSizeService.width&&this._charSizeService.height))return;this._updateDimensions(),this._refreshCharAtlas(),this._isAttached=!0}for(const i of this._renderLayers)i.handleGridChanged(this._terminal,t,e);if(!this._glyphRenderer.value||!this._rectangleRenderer.value)return;this._glyphRenderer.value.beginFrame()?(this._clearModel(!0),this._updateModel(0,this._terminal.rows-1)):this._updateModel(t,e);let i=!1,s=0;for(;this._charAtlas&&s++<32&&this._glyphRenderer.value.beginFrame();)i=!0,this._clearModel(!0),this._updateModel(0,this._terminal.rows-1);i&&this._glyphRenderer.value.invalidateAtlasTextures(),this._rectangleRenderer.value.renderBackgrounds(),this._glyphRenderer.value.render(this._model),this._cursorBlinkStateManager.value&&!this._cursorBlinkStateManager.value.isCursorVisible||this._rectangleRenderer.value.renderCursor()}_updateCursorBlink(){this._coreService.decPrivateModes.cursorBlink??this._terminal.options.cursorBlink?this._cursorBlinkStateManager.value=new a.CursorBlinkStateManager(()=>{this._requestRedrawCursor()},this._coreBrowserService):this._cursorBlinkStateManager.clear(),this._requestRedrawCursor()}_updateModel(t,e){const i=this._core;let s,r,a,o,n,L,T,l,d,_,Q,u,p,g,M,f,C,m=this._workCell;t=v(t,i.rows-1,0),e=v(e,i.rows-1,0);const w=this._coreService.decPrivateModes.cursorStyle??i.options.cursorStyle??"block",x=this._terminal.buffer.active.baseY+this._terminal.buffer.active.cursorY,b=x-i.buffer.ydisp,E=Math.min(this._terminal.buffer.active.cursorX,i.cols-1);let R=-1;const k=this._coreService.isCursorInitialized&&!this._coreService.isCursorHidden&&(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible);this._model.cursor=void 0;let A=!1;for(r=t;r<=e;r++){a=r+i.buffer.ydisp;const t=i.buffer.lines.get(a);if(!t){for(this._model.lineLengths[r]=0,f=0;f=T,d=f,n.length>0&&f===n[0][0]&&l){_=n.shift();const t=this._model.selection.isCellSelected(this._terminal,_[0],a);for(M=_[0]+1;M<_[1];M++)l&&=t===this._model.selection.isCellSelected(this._terminal,M,a);l&&=!Q||E<_[0]||E>=_[1],l?(L=!0,m=new y(m,o.translateToString(!0,_[0],_[1]),_[1]-_[0]),d=_[1]-1):T=_[1]}if(u=m.getChars(),p=m.getCode(),M=4*(r*i.cols+f),!e&&m.isBlink()&&(e=!0),this._cellColorResolver.resolve(m,f,a,this.dimensions.device.cell.width,this.dimensions.device.cell.height),k&&a===x&&(f===E&&(this._model.cursor={x:E,y:b,width:m.getWidth(),style:this._coreBrowserService.isFocused?w:i.options.cursorInactiveStyle,cursorWidth:i.options.cursorWidth,dpr:this._devicePixelRatio},R=E+m.getWidth()-1),f>=E&&f<=R&&(this._coreBrowserService.isFocused&&"block"===w||!1===this._coreBrowserService.isFocused&&"block"===i.options.cursorInactiveStyle)&&(this._cellColorResolver.result.fg=50331648|this._themeService.colors.cursorAccent.rgba>>8&16777215,this._cellColorResolver.result.bg=50331648|this._themeService.colors.cursor.rgba>>8&16777215)),this._textBlinkStateManager.isEnabled&&!this._textBlinkStateManager.isBlinkOn&&m.isBlink()&&(this._cellColorResolver.result.fg|=1073741824),p!==h.NULL_CELL_CODE&&(this._model.lineLengths[r]=f+1),(this._model.cells[M]!==p||this._model.cells[M+1]!==this._cellColorResolver.result.bg||this._model.cells[M+2]!==this._cellColorResolver.result.fg||this._model.cells[M+3]!==this._cellColorResolver.result.ext)&&(A=!0,u.length>1&&(p|=c.COMBINED_CHAR_BIT_MASK),this._model.cells[M]=p,this._model.cells[M+1]=this._cellColorResolver.result.bg,this._model.cells[M+2]=this._cellColorResolver.result.fg,this._model.cells[M+3]=this._cellColorResolver.result.ext,g=m.getWidth(),this._glyphRenderer.value.updateCell(f,r,p,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext,u,g,s),L)){for(m=this._workCell,f++;f<=d;f++)C=4*(r*i.cols+f),this._nullModelCell(f,r,C,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext);f--}}this._setRowBlinkState(r,e)}A&&this._rectangleRenderer.value.updateBackgrounds(this._model),this._rectangleRenderer.value.updateCursor(this._model),this._updateTextBlinkState()}_nullModelCell(t,e,i,s,r,a){this._glyphRenderer.value.updateCell(t,e,h.NULL_CELL_CODE,s,r,a,h.NULL_CELL_CHAR,0,0),this._model.cells[i]=h.NULL_CELL_CODE,this._model.cells[i+1]=s,this._model.cells[i+2]=r,this._model.cells[i+3]=a}_resetBlinkingRowState(){this._rowHasBlinkingCells=new Array(this._terminal.rows).fill(!1),this._rowHasBlinkingCellsCount=0}_setRowBlinkState(t,e){this._rowHasBlinkingCells[t]!==e&&(this._rowHasBlinkingCells[t]=e,this._rowHasBlinkingCellsCount+=e?1:-1)}_updateTextBlinkState(){this._textBlinkStateManager.setNeedsBlinkInViewport(this._rowHasBlinkingCellsCount>0)}_updateDimensions(){this._charSizeService.width&&this._charSizeService.height&&(this.dimensions.device.char.width=Math.floor(this._charSizeService.width*this._devicePixelRatio),this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*this._devicePixelRatio),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.top=1===this._optionsService.rawOptions.lineHeight?0:Math.round((this.dimensions.device.cell.height-this.dimensions.device.char.height)/2),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.char.left=Math.floor(this._optionsService.rawOptions.letterSpacing/2),this.dimensions.device.canvas.height=this._terminal.rows*this.dimensions.device.cell.height,this.dimensions.device.canvas.width=this._terminal.cols*this.dimensions.device.cell.width,this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/this._devicePixelRatio),this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/this._devicePixelRatio),this.dimensions.css.cell.height=this.dimensions.device.cell.height/this._devicePixelRatio,this.dimensions.css.cell.width=this.dimensions.device.cell.width/this._devicePixelRatio)}_setCanvasDevicePixelDimensions(t,e){this._canvas.width===t&&this._canvas.height===e||(this._canvas.width=t,this._canvas.height=e,this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1,sync:!0}))}_requestRedrawViewport(){this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1})}_requestRedrawCursor(){const t=this._terminal.buffer.active.cursorY;this._onRequestRedraw.fire({start:t,end:t})}}e.WebglRenderer=M;class y extends n.AttributeData{constructor(t,e,i){super(),this.content=0,this.combinedData="",this.fg=t.fg,this.bg=t.bg,this.combinedData=e,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(t){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}function v(t,e,i=0){return Math.max(Math.min(t,e),i)}e.JoinedCellData=y},719(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.GLTexture=e.PROJECTION_MATRIX=void 0,e.createProgram=function(t,e,i,a){const o=(0,s.throwIfFalsy)(t.createProgram());if(t.attachShader(o,(0,s.throwIfFalsy)(r(t,t.VERTEX_SHADER,e,a))),t.attachShader(o,(0,s.throwIfFalsy)(r(t,t.FRAGMENT_SHADER,i,a))),t.linkProgram(o),t.getProgramParameter(o,t.LINK_STATUS))return o;a.error(t.getProgramInfoLog(o)),t.deleteProgram(o)},e.createShader=r,e.expandFloat32Array=function(t,e){const i=Math.min(2*t.length,e),s=new Float32Array(i);for(let e=0;e{const e=[],i=[3/8,2/8,3/8],s=[0,3/8,5/8];for(let r=0;r<3;r++){const a=t>>2*r&1,o=t>>2*r+1&1;a&&o?e.push(`M0,${s[r]} L1,${s[r]} L1,${s[r]+i[r]} L0,${s[r]+i[r]} Z`):a?e.push(`M0,${s[r]} L0.5,${s[r]} L0.5,${s[r]+i[r]} L0,${s[r]+i[r]} Z`):o&&e.push(`M0.5,${s[r]} L1,${s[r]} L1,${s[r]+i[r]} L0.5,${s[r]+i[r]} Z`)}return e.join(" ")}}}function r(t){const e=[],i=.15,s=.015,r=.075,a=.0375,o=.95;if(64&t){const t=.175,a=.2125,n=.25,L=.2+s,h=o-i-s;e.push(`M${L},${a} L${L+r},${t} L${h-r},${t} L${h},${a} L${h-r},${n} L${L+r},${n} Z`)}if(32&t){const t=o-i,s=.875,r=o,n=.265,L=.485;e.push(`M${s},${n} L${r},${n+a} L${r},${L-a} L${s},${L} L${t},${L-a} L${t},${n+a} Z`)}if(16&t){const t=o-i,s=.875,r=o,n=.515,L=.735;e.push(`M${s},${n} L${r},${n+a} L${r},${L-a} L${s},${L} L${t},${L-a} L${t},${n+a} Z`)}if(8&t){const t=.75,a=.7875,n=.825,L=.2+s,h=o-i-s;e.push(`M${L},${a} L${L+r},${t} L${h-r},${t} L${h},${a} L${h-r},${n} L${L+r},${n} Z`)}if(4&t){const t=.05,i=.125,s=.2,r=.515,o=.735;e.push(`M${i},${r} L${s},${r+a} L${s},${o-a} L${i},${o} L${t},${o-a} L${t},${r+a} Z`)}if(2&t){const t=.05,i=.125,s=.2,r=.265,o=.485;e.push(`M${i},${r} L${s},${r+a} L${s},${o-a} L${i},${o} L${t},${o-a} L${t},${r+a} Z`)}if(1&t){const t=.4625,a=.5,n=.5375,L=.2+s,h=o-i-s;e.push(`M${L},${a} L${L+r},${t} L${h-r},${t} L${h},${a} L${h-r},${n} L${L+r},${n} Z`)}return e.join(" ")}Object.defineProperty(e,"__esModule",{value:!0}),e.blockPatternCodepoints=e.customGlyphDefinitions=void 0,function(t){t.LINE_H=Object.freeze({type:2,data:"M0,.5 L1,.5",strokeWidth:1}),t.LINE_V=Object.freeze({type:2,data:"M.5,0 L.5,1",strokeWidth:1}),t.FADE_RIGHT=Object.freeze({type:2,data:"M0,.5 L.28,.5 M.32,.5 L.52,.5 M.60,.5 L.72,.5 M.84,.5 L.90,.5",strokeWidth:1}),t.FADE_LEFT=Object.freeze({type:2,data:"M.10,.5 L.16,.5 M.28,.5 L.40,.5 M.48,.5 L.68,.5 M.72,.5 L1,.5",strokeWidth:1}),t.FADE_DOWN=Object.freeze({type:2,data:"M.5,0 L.5,.28 M.5,.32 L.5,.52 M.5,.60 L.5,.72 M.5,.84 L.5,.90",strokeWidth:1}),t.FADE_UP=Object.freeze({type:2,data:"M.5,.10 L.5,.16 M.5,.28 L.5,.40 M.5,.48 L.5,.68 M.5,.72 L.5,1",strokeWidth:1}),t.CURVE_DOWN_RIGHT=Object.freeze({type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,1,.5`,strokeWidth:1}),t.CURVE_DOWN_LEFT=Object.freeze({type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,0,.5`,strokeWidth:1}),t.CURVE_UP_RIGHT=Object.freeze({type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,1,.5`,strokeWidth:1}),t.CURVE_UP_LEFT=Object.freeze({type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,0,.5`,strokeWidth:1}),t.NODE_FILL=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5"}),t.NODE_STROKE=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5",strokeWidth:1}),t.NODE_LINE_RIGHT=Object.freeze({type:3,data:"M1,.5 L.85,.5",strokeWidth:1}),t.NODE_LINE_LEFT=Object.freeze({type:3,data:"M0,.5 L.15,.5",strokeWidth:1}),t.NODE_LINE_DOWN=Object.freeze({type:3,data:"M.5,1 L.5,.7",strokeWidth:1}),t.NODE_LINE_UP=Object.freeze({type:3,data:"M.5,0 L.5,.3",strokeWidth:1})}(i||(i={})),e.customGlyphDefinitions={"─":{type:2,data:"M0,.5 L1,.5",strokeWidth:1},"━":{type:2,data:"M0,.5 L1,.5",strokeWidth:3},"│":{type:2,data:"M.5,0 L.5,1",strokeWidth:1},"┃":{type:2,data:"M.5,0 L.5,1",strokeWidth:3},"┄":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:1},"┅":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:3},"┆":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:1},"┇":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:3},"┈":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:1},"┉":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:3},"┊":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:1},"┋":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:3},"┌":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},"┍":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┎":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┏":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3},"┐":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},"┑":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┒":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┓":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3},"└":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},"┕":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┖":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┗":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3},"┘":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},"┙":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┚":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┛":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3},"├":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},"┝":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┞":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┟":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┠":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"┡":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"┢":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"┣":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3},"┤":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},"┥":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┦":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┧":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┨":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"┩":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"┪":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"┫":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3},"┬":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},"┭":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┮":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┯":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"┰":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"┱":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"┲":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"┳":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3},"┴":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:1},"┵":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┶":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┷":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"┸":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"┹":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"┺":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"┻":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:3},"┼":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:1},"┽":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"┾":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"┿":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"╀":[{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"╁":[{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"╂":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"╃":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"╄":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"╅":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"╆":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"╇":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:3}],"╈":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3}],"╉":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3}],"╊":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3}],"╋":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:3},"╌":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:1},"╍":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:3},"╎":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:1},"╏":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:3},"═":{type:2,data:(t,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"║":{type:2,data:(t,e)=>`M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1`,strokeWidth:1},"╒":{type:2,data:(t,e)=>`M.5,1 L.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"╓":{type:2,data:(t,e)=>`M${.5-t},1 L${.5-t},.5 L1,.5 M${.5+t},.5 L${.5+t},1`,strokeWidth:1},"╔":{type:2,data:(t,e)=>`M1,${.5-e} L${.5-t},${.5-e} L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1`,strokeWidth:1},"╕":{type:2,data:(t,e)=>`M0,${.5-e} L.5,${.5-e} L.5,1 M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"╖":{type:2,data:(t,e)=>`M${.5+t},1 L${.5+t},.5 L0,.5 M${.5-t},.5 L${.5-t},1`,strokeWidth:1},"╗":{type:2,data:(t,e)=>`M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M0,${.5-e} L${.5+t},${.5-e} L${.5+t},1`,strokeWidth:1},"╘":{type:2,data:(t,e)=>`M.5,0 L.5,${.5+e} L1,${.5+e} M.5,${.5-e} L1,${.5-e}`,strokeWidth:1},"╙":{type:2,data:(t,e)=>`M1,.5 L${.5-t},.5 L${.5-t},0 M${.5+t},.5 L${.5+t},0`,strokeWidth:1},"╚":{type:2,data:(t,e)=>`M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0 M1,${.5+e} L${.5-t},${.5+e} L${.5-t},0`,strokeWidth:1},"╛":{type:2,data:(t,e)=>`M0,${.5+e} L.5,${.5+e} L.5,0 M0,${.5-e} L.5,${.5-e}`,strokeWidth:1},"╜":{type:2,data:(t,e)=>`M0,.5 L${.5+t},.5 L${.5+t},0 M${.5-t},.5 L${.5-t},0`,strokeWidth:1},"╝":{type:2,data:(t,e)=>`M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0 M0,${.5+e} L${.5+t},${.5+e} L${.5+t},0`,strokeWidth:1},"╞":{type:2,data:(t,e)=>`M.5,0 L.5,1 M.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"╟":{type:2,data:(t,e)=>`M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1 M${.5+t},.5 L1,.5`,strokeWidth:1},"╠":{type:2,data:(t,e)=>`M${.5-t},0 L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1 M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0`,strokeWidth:1},"╡":{type:2,data:(t,e)=>`M.5,0 L.5,1 M0,${.5-e} L.5,${.5-e} M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"╢":{type:2,data:(t,e)=>`M0,.5 L${.5-t},.5 M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1`,strokeWidth:1},"╣":{type:2,data:(t,e)=>`M${.5+t},0 L${.5+t},1 M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0`,strokeWidth:1},"╤":{type:2,data:(t,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e} M.5,${.5+e} L.5,1`,strokeWidth:1},"╥":{type:2,data:(t,e)=>`M0,.5 L1,.5 M${.5-t},.5 L${.5-t},1 M${.5+t},.5 L${.5+t},1`,strokeWidth:1},"╦":{type:2,data:(t,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1`,strokeWidth:1},"╧":{type:2,data:(t,e)=>`M.5,0 L.5,${.5-e} M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"╨":{type:2,data:(t,e)=>`M0,.5 L1,.5 M${.5-t},.5 L${.5-t},0 M${.5+t},.5 L${.5+t},0`,strokeWidth:1},"╩":{type:2,data:(t,e)=>`M0,${.5+e} L1,${.5+e} M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0 M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0`,strokeWidth:1},"╪":{type:2,data:(t,e)=>`M.5,0 L.5,1 M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"╫":{type:2,data:(t,e)=>`M0,.5 L1,.5 M${.5-t},0 L${.5-t},1 M${.5+t},0 L${.5+t},1`,strokeWidth:1},"╬":{type:2,data:(t,e)=>`M0,${.5+e} L${.5-t},${.5+e} L${.5-t},1 M1,${.5+e} L${.5+t},${.5+e} L${.5+t},1 M0,${.5-e} L${.5-t},${.5-e} L${.5-t},0 M1,${.5-e} L${.5+t},${.5-e} L${.5+t},0`,strokeWidth:1},"╭":{type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"╮":{type:2,data:(t,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"╯":{type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"╰":{type:2,data:(t,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"╱":{type:2,data:"M1,0 L0,1",strokeWidth:1},"╲":{type:2,data:"M0,0 L1,1",strokeWidth:1},"╳":{type:2,data:"M1,0 L0,1 M0,0 L1,1",strokeWidth:1},"╴":{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},"╵":{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},"╶":{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},"╷":{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},"╸":{type:2,data:"M.5,.5 L0,.5",strokeWidth:3},"╹":{type:2,data:"M.5,.5 L.5,0",strokeWidth:3},"╺":{type:2,data:"M.5,.5 L1,.5",strokeWidth:3},"╻":{type:2,data:"M.5,.5 L.5,1",strokeWidth:3},"╼":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"╽":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"╾":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"╿":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"▀":{type:0,data:[{x:0,y:0,w:8,h:4}]},"▁":{type:0,data:[{x:0,y:7,w:8,h:1}]},"▂":{type:0,data:[{x:0,y:6,w:8,h:2}]},"▃":{type:0,data:[{x:0,y:5,w:8,h:3}]},"▄":{type:0,data:[{x:0,y:4,w:8,h:4}]},"▅":{type:0,data:[{x:0,y:3,w:8,h:5}]},"▆":{type:0,data:[{x:0,y:2,w:8,h:6}]},"▇":{type:0,data:[{x:0,y:1,w:8,h:7}]},"█":{type:0,data:[{x:0,y:0,w:8,h:8}]},"▉":{type:0,data:[{x:0,y:0,w:7,h:8}]},"▊":{type:0,data:[{x:0,y:0,w:6,h:8}]},"▋":{type:0,data:[{x:0,y:0,w:5,h:8}]},"▌":{type:0,data:[{x:0,y:0,w:4,h:8}]},"▍":{type:0,data:[{x:0,y:0,w:3,h:8}]},"▎":{type:0,data:[{x:0,y:0,w:2,h:8}]},"▏":{type:0,data:[{x:0,y:0,w:1,h:8}]},"▐":{type:0,data:[{x:4,y:0,w:4,h:8}]},"░":{type:1,data:[[1,0],[0,0]]},"▒":{type:1,data:[[1,0],[0,1]]},"▓":{type:1,data:[[1,1],[1,0]]},"▔":{type:0,data:[{x:0,y:0,w:8,h:1}]},"▕":{type:0,data:[{x:7,y:0,w:1,h:8}]},"▖":{type:0,data:[{x:0,y:4,w:4,h:4}]},"▗":{type:0,data:[{x:4,y:4,w:4,h:4}]},"▘":{type:0,data:[{x:0,y:0,w:4,h:4}]},"▙":{type:0,data:[{x:0,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"▚":{type:0,data:[{x:0,y:0,w:4,h:4},{x:4,y:4,w:4,h:4}]},"▛":{type:0,data:[{x:0,y:0,w:4,h:8},{x:4,y:0,w:4,h:4}]},"▜":{type:0,data:[{x:0,y:0,w:8,h:4},{x:4,y:0,w:4,h:8}]},"▝":{type:0,data:[{x:4,y:0,w:4,h:4}]},"▞":{type:0,data:[{x:4,y:0,w:4,h:4},{x:0,y:4,w:4,h:4}]},"▟":{type:0,data:[{x:4,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"":{type:5,data:{d:"M.3,1 L.03,1 L.03,.88 C.03,.82,.06,.78,.11,.73 C.15,.7,.2,.68,.28,.65 L.43,.6 C.49,.58,.53,.56,.56,.53 C.59,.5,.6,.47,.6,.43 L.6,.27 L.4,.27 L.69,.1 L.98,.27 L.78,.27 L.78,.46 C.78,.52,.76,.56,.72,.61 C.68,.66,.63,.67,.56,.7 L.48,.72 C.42,.74,.38,.76,.35,.78 C.32,.8,.31,.84,.31,.88 L.31,1 M.3,.5 L.03,.59 L.03,.09 L.3,.09 L.3,.655",type:0}},"":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.355,.03 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"":{type:5,data:{d:"M.25,.94 C.16,.94,.11,.92,.11,.87 L.11,.53 C.11,.48,.15,.455,.23,.45 L.23,.3 C.23,.25,.26,.22,.31,.19 C.36,.16,.43,.15,.51,.15 C.59,.15,.66,.16,.71,.19 C.77,.22,.79,.26,.79,.3 L.79,.45 C.87,.45,.91,.48,.91,.53 L.91,.87 C.91,.92,.86,.94,.77,.94 L.24,.94 M.53,.2 C.49,.2,.45,.21,.42,.23 C.39,.25,.38,.27,.38,.3 L.38,.45 L.68,.45 L.68,.3 C.68,.27,.67,.25,.64,.23 C.61,.21,.58,.2,.53,.2 M.58,.82 L.58,.66 C.63,.65,.65,.63,.65,.6 C.65,.58,.64,.57,.61,.56 C.58,.55,.56,.54,.52,.54 C.48,.54,.46,.55,.43,.56 C.4,.57,.39,.59,.39,.6 C.39,.63,.41,.64,.46,.66 L.46,.82 L.57,.82",type:0}},"":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.7,.03 L.7,.1 L.355,.1 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"":{type:5,data:{d:"M0,0 L1,.5 L0,1",type:0,rightPadding:2}},"":{type:5,data:{d:"M-1,-.5 L1,.5 L-1,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M1,0 L0,.5 L1,1",type:0,leftPadding:2}},"":{type:5,data:{d:"M2,-.5 L0,.5 L2,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M0,0 L0,1 C0.552,1,1,0.776,1,.5 C1,0.224,0.552,0,0,0",type:0,rightPadding:1}},"":{type:5,data:{d:"M.2,1 C.422,1,.8,.826,.78,.5 C.8,.174,0.422,0,.2,0",type:1,rightPadding:1}},"":{type:5,data:{d:"M1,0 L1,1 C0.448,1,0,0.776,0,.5 C0,0.224,0.448,0,1,0",type:0,leftPadding:1}},"":{type:5,data:{d:"M.8,1 C0.578,1,0.2,.826,.22,.5 C0.2,0.174,0.578,0,0.8,0",type:1,leftPadding:1}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L-.5,1.5",type:0}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L1.5,1.5",type:0}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L-.5,-.5",type:0}},"":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L1.5,-.5",type:0}},"":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"":{type:5,data:{d:"M0.8069,0.6075 Q0.7991,0.612,0.7815,0.6218 T0.7542,0.6369 T0.7282,0.6508 T0.7016,0.6644 T0.6778,0.6758 T0.6551,0.6854 T0.637,0.6911 T0.622,0.6936 Q0.6186,0.6936,0.6128,0.6942 T0.6018,0.6952 T0.5894,0.6956 T0.5757,0.6952 T0.561,0.693 T0.5451,0.6879 Q0.5342,0.6834,0.5193,0.6756 T0.4925,0.6614 T0.4673,0.6485 T0.4436,0.6389 T0.4239,0.6363 T0.4089,0.6422 Q0.4045,0.6467,0.3958,0.6554 T0.3843,0.6669 T0.3748,0.6746 T0.3613,0.683 T0.3442,0.6903 L0.3499,0.6956 Q0.3584,0.7042,0.3679,0.7177 T0.3836,0.7403 T0.4019,0.7583 T0.4295,0.7703 Q0.4688,0.7785,0.5203,0.7605 Q0.4902,0.7817,0.449,0.7911 T0.3696,0.8001 Q0.3567,0.7997,0.341,0.7942 T0.3111,0.7813 T0.2805,0.766 T0.2493,0.753 T0.218,0.7472 T0.187,0.754 Q0.1762,0.7589,0.1653,0.7681 T0.1453,0.7895 T0.1308,0.818 T0.1264,0.8507 L0.1264,0.858 Q0.1453,0.8462,0.1607,0.8433 T0.1899,0.8452 T0.2226,0.8625 Q0.2344,0.8707,0.2485,0.8752 T0.2813,0.8831 T0.3089,0.889 Q0.2981,0.8915,0.2846,0.8956 T0.2603,0.9037 T0.2368,0.9115 T0.2129,0.9174 T0.1894,0.9194 T0.1653,0.9155 Q0.1504,0.9115,0.1328,0.9196 T0.0986,0.9421 T0.0655,0.9708 T0.0317,0.9943 T0,1 Q0.001,0.94,0.0017,0.6508 T0.0024,0.2322 Q0.002,0.2109,0.0007,0.1379 T0,0.0249 Q0.0058,0.0253,0.009,0.0257 T0.0156,0.0288 T0.0203,0.0333 T0.0264,0.0422 T0.0349,0.0539 Q0.044,0.0657,0.0542,0.072 T0.0752,0.0789 T0.096,0.0775 T0.1175,0.0694 T0.1379,0.0573 T0.1579,0.0432 Q0.2141,0,0.2673,0.0318 Q0.2588,0.0318,0.2517,0.033 T0.239,0.0361 T0.2276,0.0424 T0.218,0.0504 T0.2085,0.0612 T0.1997,0.0732 T0.1899,0.0875 T0.1795,0.1028 Q0.1748,0.1093,0.1507,0.1234 T0.1186,0.1448 Q0.0999,0.1612,0.1108,0.1783 Q0.1162,0.1877,0.1238,0.1928 T0.1404,0.1979 T0.158,0.1967 T0.1775,0.1895 T0.1963,0.1791 T0.2151,0.1663 T0.2314,0.1534 T0.2458,0.141 T0.2561,0.1322 Q0.2815,0.1106,0.3017,0.101 T0.344,0.0926 T0.3919,0.1077 Q0.4099,0.1175,0.4265,0.1206 T0.4588,0.1202 T0.488,0.1098 T0.5176,0.0914 Q0.5071,0.1032,0.4963,0.1122 T0.4722,0.1285 T0.4497,0.1401 T0.4223,0.1518 T0.3943,0.1636 Q0.374,0.1726,0.3623,0.1863 T0.3482,0.2162 Q0.3445,0.2403,0.3608,0.2605 T0.4072,0.2876 Q0.4194,0.2909,0.4326,0.2899 T0.457,0.2856 T0.4805,0.2764 T0.5032,0.264 T0.5256,0.2497 T0.5478,0.2352 T0.5698,0.2222 T0.5921,0.2118 Q0.6982,0.173,0.81,0.2436 Q0.833,0.2583,0.8496,0.2674 T0.887,0.2846 T0.925,0.294 T0.9617,0.2911 T1,0.2746 Q0.9817,0.2946,0.96,0.3056 T0.9175,0.3191 T0.8731,0.3209 T0.8277,0.3164 T0.7818,0.3109 T0.7359,0.3101 T0.6907,0.3197 T0.647,0.3448 Q0.6443,0.3472,0.6333,0.3562 T0.6194,0.3674 T0.6076,0.3766 T0.594,0.386 T0.5815,0.3931 T0.5661,0.4007 T0.5501,0.4064 L0.5556,0.4121 Q0.5627,0.4198,0.5722,0.4251 T0.5926,0.4337 T0.6131,0.439 T0.6343,0.4431 T0.6521,0.4468 Q0.6762,0.4529,0.7056,0.4463 Q0.6772,0.4623,0.6543,0.471 T0.604,0.4814 Q0.5962,0.4818,0.5815,0.4825 T0.5591,0.4835 T0.5393,0.4857 T0.519,0.4908 T0.5007,0.4996 T0.4812,0.5141 T0.4627,0.5353 L0.4549,0.5451 L0.4661,0.543 Q0.4759,0.541,0.4909,0.55 T0.5315,0.5796 T0.5684,0.6083 Q0.5799,0.6161,0.5915,0.6212 T0.6181,0.6308 L0.6331,0.6353 Q0.6514,0.6418,0.7004,0.633 T0.8069,0.6075 Z",type:0}},"":{type:5,data:{d:"M0.011,0.0469 Q0.0152,0.0412,0.02,0.0361 T0.0292,0.0281 T0.0365,0.0253 Q0.0426,0.0257,0.0461,0.0263 T0.0534,0.03 T0.0582,0.0345 T0.0645,0.0434 T0.0723,0.0546 Q0.0807,0.0653,0.0897,0.0712 T0.1081,0.0775 T0.1255,0.0765 T0.1438,0.0695 T0.1605,0.0593 T0.1772,0.0473 Q0.2388,0,0.2927,0.0326 L0.2614,0.0767 L0.2581,0.0767 Q0.2494,0.0767,0.2444,0.0773 T0.2359,0.0789 T0.2291,0.0842 T0.2233,0.0922 T0.2146,0.1054 T0.2026,0.1236 Q0.1943,0.1354,0.1843,0.1444 T0.1675,0.1574 T0.1526,0.1654 T0.1429,0.1701 Q0.1436,0.1717,0.1446,0.1733 Q0.1504,0.1823,0.1581,0.1866 T0.1733,0.1915 T0.1909,0.1884 T0.2085,0.1809 T0.2265,0.169 T0.2427,0.1564 T0.2575,0.1436 T0.2688,0.1338 Q0.2969,0.1101,0.3195,0.0995 T0.3643,0.0901 T0.4114,0.1048 Q0.4279,0.1138,0.4426,0.1168 T0.4705,0.117 T0.4945,0.1089 T0.5186,0.0942 L0.5211,0.0926 L0.5289,0.0922 Q0.5411,0.095,0.5189,0.1203 Q0.505,0.1358,0.4913,0.1474 T0.4634,0.167 T0.4389,0.1796 T0.4121,0.1909 T0.3866,0.2011 Q0.3782,0.2047,0.3727,0.2092 Q0.3717,0.2117,0.3714,0.2141 Q0.3695,0.2263,0.3751,0.2388 T0.394,0.2616 T0.4253,0.2761 Q0.4398,0.2785,0.4513,0.2779 T0.4756,0.2724 T0.4987,0.2616 T0.5216,0.2476 T0.5453,0.2321 T0.5703,0.217 T0.5976,0.2043 Q0.7015,0.166,0.8099,0.2345 Q0.8361,0.2512,0.8572,0.2616 T0.9006,0.2779 T0.9432,0.281 T0.9819,0.2663 L0.9887,0.2671 Q1,0.272,0.9768,0.2969 Q0.9558,0.3193,0.9319,0.333 T0.8858,0.3513 T0.8391,0.3569 T0.793,0.3546 T0.7485,0.3497 T0.7065,0.3473 T0.6681,0.3522 T0.6344,0.3699 Q0.5963,0.4005,0.5847,0.4082 Q0.595,0.4139,0.6079,0.4174 T0.6367,0.4237 T0.6586,0.4278 Q0.6793,0.4331,0.7044,0.4278 Q0.7057,0.4278,0.707,0.4274 Q0.7067,0.429,0.7062,0.4313 T0.7036,0.4398 T0.6993,0.4513 T0.6931,0.4619 T0.6851,0.4698 Q0.6573,0.4857,0.6336,0.4947 T0.5831,0.5053 Q0.577,0.5057,0.5615,0.5065 T0.5394,0.508 T0.5221,0.51 T0.5042,0.5139 T0.4905,0.5204 Q0.5008,0.5232,0.515,0.5328 T0.549,0.5585 T0.5799,0.5824 Q0.5905,0.5897,0.6013,0.5946 T0.6262,0.6036 T0.6409,0.6081 Q0.6567,0.6134,0.7035,0.605 T0.8028,0.5816 L0.7974,0.5922 T0.7867,0.6134 L0.7812,0.624 Q0.7799,0.6248,0.7786,0.6252 Q0.7709,0.6297,0.7573,0.6372 T0.7346,0.6499 T0.7123,0.6621 T0.6897,0.6741 T0.6686,0.6847 T0.648,0.6941 T0.6297,0.7013 T0.6129,0.7062 T0.5995,0.7076 Q0.5992,0.7076,0.5831,0.7092 T0.5529,0.7092 T0.525,0.7019 Q0.5105,0.6958,0.4824,0.6811 T0.4356,0.6586 T0.4079,0.6533 Q0.3872,0.6741,0.3827,0.6782 Q0.3872,0.6835,0.3934,0.6929 T0.4037,0.7078 T0.4142,0.7198 T0.4284,0.7304 T0.4466,0.7365 Q0.4824,0.7443,0.5292,0.728 L0.5292,0.7294 T0.529,0.7333 T0.5284,0.7392 T0.5266,0.7463 T0.5236,0.7539 T0.5186,0.7612 T0.5111,0.7679 Q0.5086,0.77,0.5056,0.7716 Q0.4466,0.8104,0.3591,0.8091 Q0.344,0.8091,0.3246,0.802 T0.2893,0.7863 T0.2543,0.77 T0.2206,0.76 T0.1894,0.7643 Q0.1804,0.7684,0.1733,0.7753 Q0.1591,0.7892,0.1601,0.8169 Q0.1784,0.8067,0.1938,0.8053 T0.2212,0.8087 T0.2507,0.825 Q0.2614,0.8324,0.2744,0.8365 T0.3053,0.844 T0.332,0.8499 L0.303,0.894 L0.2998,0.8948 Q0.2904,0.8968,0.278,0.9009 T0.2554,0.9086 T0.233,0.9158 T0.2099,0.9213 T0.1868,0.9229 T0.1633,0.9192 Q0.1517,0.916,0.1367,0.9241 T0.1065,0.9462 T0.0753,0.9737 T0.041,0.9955 T0.0061,1 Q0,0.9984,0.0068,0.9845 Q0.009,0.9804,0.0123,0.9755 Q0.0187,0.9666,0.0261,0.9606 T0.0374,0.9555 Q0.0481,0.958,0.0629,0.949 T0.0931,0.9262 T0.1247,0.8987 T0.1597,0.8777 T0.1949,0.8752 Q0.213,0.8805,0.2343,0.8772 Q0.2249,0.8736,0.2172,0.8683 Q0.1914,0.8511,0.1738,0.8497 T0.1349,0.8617 Q0.1304,0.865,0.1273,0.8646 T0.1242,0.8605 L0.1239,0.8536 Q0.1226,0.8295,0.1354,0.8016 T0.1723,0.7496 Q0.1914,0.7308,0.2104,0.7219 Q0.2259,0.7145,0.2425,0.7141 T0.273,0.7182 T0.3022,0.7296 T0.3301,0.7439 T0.3569,0.7571 T0.3821,0.7643 Q0.373,0.7561,0.3598,0.7367 T0.3382,0.7088 L0.3327,0.7035 Q0.3282,0.699,0.3353,0.6884 T0.3517,0.6692 L0.3611,0.6607 Q0.3711,0.657,0.3751,0.6554 T0.3837,0.6507 T0.3898,0.6458 T0.3979,0.637 T0.4111,0.6236 Q0.4172,0.6175,0.4234,0.6138 Q0.4327,0.6081,0.4439,0.6077 T0.4655,0.6105 T0.4884,0.6201 T0.5113,0.633 T0.5347,0.6468 T0.5573,0.6578 Q0.5705,0.6635,0.5833,0.665 T0.6112,0.665 T0.6286,0.6635 Q0.6421,0.6631,0.6718,0.6501 Q0.626,0.6578,0.6089,0.6517 Q0.6063,0.6509,0.6002,0.6491 T0.5884,0.6454 T0.5757,0.6409 T0.561,0.6344 T0.5466,0.6256 Q0.536,0.6183,0.5108,0.5989 T0.4722,0.5712 T0.4527,0.564 L0.4418,0.5661 Q0.4308,0.5681,0.4366,0.5563 Q0.4401,0.5485,0.4476,0.5392 L0.455,0.5298 Q0.4631,0.5188,0.4714,0.51 T0.4866,0.4947 T0.5021,0.4831 T0.516,0.4749 T0.53,0.4694 T0.5428,0.4657 T0.5558,0.4637 T0.5674,0.4629 T0.5795,0.4625 Q0.5489,0.4543,0.534,0.4384 L0.5286,0.4327 Q0.5244,0.4282,0.5318,0.4174 T0.5486,0.398 L0.5579,0.3899 Q0.567,0.387,0.5749,0.3834 T0.5878,0.3772 T0.6012,0.3687 T0.6126,0.3603 T0.6268,0.3487 T0.6421,0.3361 Q0.6567,0.3242,0.6712,0.3159 T0.7009,0.3034 T0.7277,0.2973 T0.7556,0.2961 T0.7809,0.2977 T0.8074,0.301 Q0.8096,0.3014,0.8109,0.3016 T0.8143,0.302 T0.818,0.3026 Q0.8012,0.2936,0.7767,0.2781 Q0.6718,0.2117,0.5744,0.2476 Q0.5637,0.2516,0.5492,0.2604 T0.5218,0.2779 T0.4923,0.2965 T0.461,0.3124 T0.4282,0.3216 T0.394,0.3206 Q0.3637,0.3136,0.3474,0.2936 T0.3353,0.2459 Q0.3385,0.2247,0.355,0.2023 Q0.3646,0.1892,0.3763,0.179 Q0.3898,0.1672,0.4063,0.1595 Q0.3927,0.1562,0.3785,0.1485 Q0.3604,0.1387,0.3453,0.1354 T0.3161,0.1354 T0.2899,0.1458 T0.2627,0.166 Q0.262,0.1664,0.254,0.1733 T0.2414,0.1841 T0.2267,0.196 T0.2094,0.2086 T0.1915,0.2196 T0.1725,0.2288 T0.1546,0.2337 T0.1373,0.2343 T0.1223,0.228 T0.1097,0.2145 Q0.0962,0.1929,0.1258,0.1582 Q0.131,0.1517,0.1371,0.1464 Q0.1462,0.1387,0.156,0.1321 T0.1752,0.1205 T0.1878,0.1134 Q0.1891,0.1117,0.1947,0.103 T0.2035,0.0899 T0.2125,0.0781 T0.2243,0.064 Q0.1949,0.0616,0.1672,0.0828 Q0.153,0.0934,0.1412,0.1009 T0.1146,0.1146 T0.0873,0.1213 T0.0616,0.116 T0.0374,0.0962 Q0.0339,0.0909,0.0295,0.0846 T0.024,0.0767 T0.0202,0.0728 T0.0148,0.0704 T0.0068,0.0697 Q0.0003,0.0693,0.0058,0.0567 Q0.0077,0.0522,0.011,0.0469 Z",type:0}},"":{type:5,data:{d:"M0.1934,0.6075 Q0.2012,0.612,0.2188,0.6218 T0.2459,0.6369 T0.2718,0.6508 T0.2983,0.6644 T0.322,0.6758 T0.3447,0.6854 T0.363,0.6911 T0.3783,0.6936 Q0.3796,0.6936,0.396,0.6952 T0.4265,0.6952 T0.4548,0.6879 Q0.4656,0.6834,0.4805,0.6756 T0.5073,0.6614 T0.5327,0.6485 T0.5564,0.6389 T0.5759,0.6363 T0.5909,0.6422 Q0.5953,0.6467,0.604,0.6554 T0.6155,0.6669 T0.6251,0.6746 T0.6387,0.683 T0.6556,0.6903 L0.6498,0.6956 Q0.6414,0.7042,0.6319,0.7177 T0.6162,0.7403 T0.5979,0.7583 T0.5703,0.7703 Q0.5313,0.7785,0.4799,0.7605 Q0.5097,0.7817,0.5508,0.7911 T0.6302,0.8001 Q0.6431,0.7997,0.659,0.7942 T0.6888,0.7813 T0.7194,0.766 T0.7506,0.753 T0.7819,0.7472 T0.8131,0.754 Q0.8239,0.7589,0.8346,0.7681 T0.8544,0.7895 T0.8689,0.818 T0.8737,0.8507 L0.8733,0.858 Q0.8591,0.849,0.8474,0.845 T0.8242,0.8421 T0.8021,0.8482 T0.7772,0.8625 Q0.7653,0.8707,0.7513,0.8752 T0.7184,0.8831 T0.6908,0.889 Q0.7017,0.8915,0.7152,0.8956 T0.7396,0.9037 T0.7633,0.9115 T0.7872,0.9174 T0.8107,0.9194 T0.8347,0.9155 Q0.8493,0.9115,0.8671,0.9196 T0.9015,0.9421 T0.9345,0.9708 T0.9682,0.9943 T0.9997,1 Q0.999,0.94,0.9983,0.6508 T0.9976,0.2322 Q0.9976,0.2109,0.9992,0.1379 T1,0.0249 Q0.9949,0.0249,0.9917,0.0257 T0.9863,0.0273 T0.9817,0.0308 T0.9776,0.0357 T0.9721,0.0437 T0.9651,0.0539 Q0.956,0.0657,0.9456,0.072 T0.9247,0.0789 T0.904,0.0775 T0.8823,0.0694 T0.862,0.0573 T0.8422,0.0432 Q0.7856,0,0.7328,0.0318 Q0.7392,0.0318,0.7452,0.0324 T0.756,0.0345 T0.7657,0.0386 T0.7741,0.0437 T0.7821,0.0506 T0.7894,0.0588 T0.7966,0.0683 T0.8039,0.0787 T0.8119,0.0904 T0.8202,0.1028 Q0.8249,0.1093,0.849,0.1234 T0.8811,0.1448 Q0.8998,0.1612,0.8893,0.1783 Q0.8835,0.1877,0.8759,0.1928 T0.8593,0.1979 T0.8417,0.1967 T0.8222,0.1895 T0.8034,0.1791 T0.7848,0.1663 T0.7687,0.1534 T0.7543,0.141 T0.744,0.1322 Q0.7186,0.1106,0.6984,0.101 T0.6559,0.0926 T0.6082,0.1077 Q0.5899,0.1175,0.5733,0.1206 T0.5411,0.1202 T0.5122,0.1098 T0.4822,0.0914 Q0.4927,0.1032,0.5036,0.1122 T0.5276,0.1285 T0.5503,0.1401 T0.5777,0.1518 T0.6055,0.1636 Q0.6258,0.1726,0.6375,0.1863 T0.6519,0.2162 Q0.6556,0.2403,0.6392,0.2605 T0.5926,0.2876 Q0.5804,0.2909,0.5672,0.2899 T0.5428,0.2856 T0.5193,0.2764 T0.4966,0.264 T0.4744,0.2497 T0.4523,0.2352 T0.4301,0.2222 T0.4077,0.2118 Q0.3021,0.173,0.1903,0.2436 Q0.1669,0.2583,0.1504,0.2674 T0.1129,0.2846 T0.075,0.294 T0.0384,0.2911 T0,0.2746 Q0.021,0.297,0.0459,0.3082 T0.0953,0.3207 T0.146,0.3193 T0.1988,0.3131 T0.2508,0.3095 T0.3029,0.3176 T0.3529,0.3448 Q0.3566,0.348,0.3652,0.355 T0.3771,0.3645 T0.3877,0.3731 T0.3993,0.3815 T0.4103,0.3884 T0.4226,0.3953 T0.4352,0.4009 T0.4497,0.4064 L0.4443,0.4121 Q0.4372,0.4198,0.4277,0.4251 T0.4072,0.4337 T0.3867,0.439 T0.3656,0.4431 T0.3481,0.4468 Q0.3241,0.4529,0.2943,0.4463 Q0.3227,0.4623,0.3458,0.471 T0.3959,0.4814 Q0.404,0.4818,0.4187,0.4825 T0.4409,0.4835 T0.4605,0.4857 T0.4809,0.4908 T0.4992,0.4996 T0.5186,0.5141 T0.5371,0.5353 L0.5449,0.5451 L0.5337,0.543 Q0.5242,0.541,0.5091,0.55 T0.4683,0.5796 T0.4314,0.6083 Q0.4203,0.6161,0.4086,0.6212 T0.382,0.6308 T0.3667,0.6353 Q0.3485,0.6418,0.2995,0.633 T0.1934,0.6075 Z",type:0}},"":{type:5,data:{d:"M0.989,0.0469 Q0.9829,0.0379,0.9753,0.0316 T0.9635,0.0253 Q0.9574,0.0257,0.9539,0.0263 T0.9466,0.03 T0.9418,0.0345 T0.9355,0.0434 T0.9277,0.0546 Q0.9193,0.0653,0.9103,0.0712 T0.8919,0.0775 T0.8745,0.0765 T0.8564,0.0695 T0.8396,0.0593 T0.8228,0.0473 Q0.7612,0,0.7073,0.0326 L0.7386,0.0767 L0.7419,0.0767 Q0.7506,0.0767,0.7556,0.0773 T0.7641,0.0789 T0.7709,0.0842 T0.7767,0.0922 T0.7854,0.1054 T0.7974,0.1236 Q0.8057,0.1354,0.8157,0.1444 T0.8325,0.1574 T0.8474,0.1654 T0.8571,0.1701 Q0.8564,0.1717,0.8554,0.1733 Q0.8503,0.1815,0.844,0.186 T0.8301,0.1909 T0.8153,0.1903 T0.7993,0.1845 T0.7836,0.1758 T0.768,0.1648 T0.754,0.1535 T0.741,0.1425 T0.7312,0.1338 Q0.7031,0.1101,0.6805,0.0995 T0.6357,0.0901 T0.5886,0.1048 Q0.5721,0.1138,0.5574,0.1168 T0.5295,0.117 T0.5055,0.1089 T0.4814,0.0942 L0.4789,0.0926 L0.4711,0.0922 Q0.4589,0.095,0.4811,0.1203 Q0.495,0.1358,0.5087,0.1474 T0.5366,0.167 T0.5611,0.1796 T0.5879,0.1909 T0.6134,0.2011 Q0.6218,0.2047,0.6273,0.2092 Q0.6283,0.2117,0.6286,0.2141 Q0.6305,0.2263,0.6249,0.2388 T0.606,0.2616 T0.5747,0.2761 Q0.5602,0.2785,0.5487,0.2779 T0.5245,0.2724 T0.5015,0.2616 T0.4784,0.2476 T0.4547,0.2321 T0.4297,0.217 T0.4024,0.2043 Q0.2985,0.166,0.1901,0.2345 Q0.1694,0.248,0.1523,0.2569 T0.1165,0.2726 T0.0818,0.2812 T0.0494,0.2796 T0.0181,0.2663 L0.0116,0.2671 Q0,0.272,0.0232,0.2969 Q0.0468,0.3222,0.0742,0.3365 T0.1278,0.3542 T0.1807,0.3564 T0.233,0.352 T0.2815,0.3473 T0.3269,0.3509 T0.3656,0.3699 Q0.4037,0.4005,0.4153,0.4082 Q0.405,0.4139,0.3921,0.4174 T0.3633,0.4237 T0.3414,0.4278 Q0.3207,0.4331,0.2956,0.4278 Q0.2943,0.4278,0.293,0.4274 Q0.2933,0.429,0.2938,0.4313 T0.2964,0.4398 T0.3007,0.4513 T0.3069,0.4619 T0.3149,0.4698 Q0.3427,0.4857,0.3664,0.4947 T0.4169,0.5053 Q0.423,0.5057,0.4385,0.5065 T0.4606,0.508 T0.4779,0.51 T0.4958,0.5139 T0.5095,0.5204 Q0.4992,0.5232,0.485,0.5328 T0.451,0.5585 T0.4201,0.5824 Q0.4095,0.5897,0.3987,0.5946 T0.3738,0.6036 T0.3591,0.6081 Q0.3433,0.6134,0.2965,0.605 T0.1972,0.5816 L0.2026,0.5922 T0.2133,0.6134 L0.2188,0.624 Q0.2201,0.6248,0.2214,0.6252 Q0.2291,0.6297,0.2486,0.6405 T0.2786,0.657 T0.3066,0.6721 T0.3353,0.6866 T0.3598,0.6972 T0.383,0.7051 T0.4005,0.7076 Q0.4008,0.7076,0.4169,0.7092 T0.4471,0.7092 T0.475,0.7019 Q0.4895,0.6958,0.5176,0.6811 T0.5644,0.6586 T0.5921,0.6533 Q0.6128,0.6741,0.6173,0.6782 Q0.6131,0.6835,0.6068,0.6929 T0.5963,0.7078 T0.5858,0.7198 T0.5716,0.7304 T0.5534,0.7365 Q0.5179,0.7443,0.4708,0.728 L0.4708,0.7294 T0.471,0.7333 T0.4716,0.7392 T0.4734,0.7463 T0.4764,0.7539 T0.4814,0.7612 T0.4889,0.7679 Q0.4914,0.77,0.4944,0.7716 Q0.5534,0.8104,0.6409,0.8091 Q0.6521,0.8091,0.6654,0.8053 T0.6907,0.7959 T0.7157,0.7838 T0.741,0.772 T0.7652,0.7631 T0.7888,0.7594 T0.8106,0.7643 Q0.8196,0.7684,0.8267,0.7753 Q0.8409,0.7892,0.8399,0.8169 Q0.8216,0.8067,0.8062,0.8053 T0.7788,0.8087 T0.7493,0.825 Q0.7386,0.8324,0.7256,0.8365 T0.6947,0.844 T0.668,0.8499 L0.697,0.894 L0.7002,0.8948 Q0.7099,0.8968,0.7222,0.9009 T0.7446,0.9086 T0.767,0.9158 T0.7901,0.9213 T0.8132,0.9229 T0.8367,0.9192 Q0.8483,0.916,0.8633,0.9241 T0.8937,0.9462 T0.9248,0.9737 T0.959,0.9955 T0.9939,1 Q1,0.9984,0.9932,0.9845 Q0.991,0.9804,0.9877,0.9755 Q0.9813,0.9666,0.9739,0.9606 T0.9626,0.9555 Q0.9519,0.958,0.9372,0.949 T0.9071,0.9262 T0.8753,0.8987 T0.8403,0.8777 T0.8051,0.8752 Q0.787,0.8805,0.7657,0.8772 Q0.7751,0.8736,0.7828,0.8683 Q0.8086,0.8511,0.8262,0.8497 T0.8651,0.8617 Q0.8696,0.865,0.8727,0.8646 T0.8758,0.8605 L0.8761,0.8536 Q0.8774,0.8295,0.8646,0.8016 T0.8277,0.7496 Q0.8086,0.7308,0.7896,0.7219 Q0.7741,0.7145,0.7575,0.7141 T0.727,0.7182 T0.6978,0.7296 T0.6699,0.7439 T0.6433,0.7571 T0.6179,0.7643 Q0.627,0.7561,0.6402,0.7367 T0.6618,0.7088 L0.6673,0.7035 Q0.6718,0.699,0.6647,0.6884 T0.6483,0.6692 L0.6389,0.6607 Q0.6289,0.657,0.6249,0.6554 T0.6163,0.6507 T0.6102,0.6458 T0.6021,0.637 T0.5889,0.6236 Q0.5828,0.6175,0.5766,0.6138 Q0.5673,0.6081,0.5561,0.6077 T0.5345,0.6105 T0.5116,0.6201 T0.4887,0.633 T0.4653,0.6468 T0.4427,0.6578 Q0.4295,0.6635,0.4167,0.665 T0.3888,0.665 T0.3714,0.6635 Q0.3579,0.6631,0.3282,0.6501 Q0.374,0.6578,0.3911,0.6517 Q0.3937,0.6509,0.4024,0.6482 T0.4179,0.6434 T0.4348,0.6364 T0.4534,0.6256 Q0.464,0.6183,0.4892,0.5989 T0.5278,0.5712 T0.5476,0.564 L0.5582,0.5661 Q0.5692,0.5681,0.5634,0.5563 Q0.5599,0.5485,0.5524,0.5392 L0.545,0.5298 Q0.5369,0.5188,0.5286,0.51 T0.5134,0.4947 T0.4979,0.4831 T0.484,0.4749 T0.47,0.4694 T0.4572,0.4657 T0.4442,0.4637 T0.4326,0.4629 T0.4205,0.4625 Q0.4511,0.4543,0.466,0.4384 L0.4714,0.4327 Q0.4795,0.4237,0.4469,0.394 L0.4421,0.3899 Q0.433,0.387,0.4251,0.3834 T0.4122,0.3772 T0.3988,0.3687 T0.3874,0.3603 T0.3732,0.3487 T0.3579,0.3361 Q0.3433,0.3242,0.3288,0.3159 T0.2993,0.3034 T0.2725,0.2973 T0.2446,0.2961 T0.2193,0.2977 T0.1926,0.301 Q0.1855,0.3022,0.182,0.3026 Q0.1991,0.2936,0.2233,0.2781 Q0.3282,0.2117,0.4256,0.2476 Q0.4363,0.2516,0.451,0.2604 T0.4784,0.2779 T0.5077,0.2965 T0.539,0.3124 T0.5718,0.3216 T0.606,0.3206 Q0.6363,0.3136,0.6526,0.2936 T0.6647,0.2459 Q0.6615,0.2247,0.645,0.2023 Q0.6354,0.1892,0.6237,0.179 Q0.6102,0.1672,0.5937,0.1595 Q0.6073,0.1562,0.6215,0.1485 Q0.6396,0.1387,0.6547,0.1354 T0.6839,0.1354 T0.7101,0.1458 T0.7373,0.166 Q0.738,0.1664,0.746,0.1733 T0.7586,0.1841 T0.7733,0.196 T0.7907,0.2086 T0.8086,0.2196 T0.8275,0.2288 T0.8454,0.2337 T0.8627,0.2343 T0.8777,0.228 T0.8903,0.2145 Q0.9038,0.1929,0.8742,0.1582 Q0.869,0.1517,0.8629,0.1464 Q0.8538,0.1387,0.844,0.1321 T0.8248,0.1205 T0.8122,0.1134 Q0.8109,0.1117,0.8053,0.103 T0.7965,0.0899 T0.7875,0.0781 T0.7757,0.064 Q0.8051,0.0616,0.8328,0.0828 Q0.847,0.0934,0.8588,0.1009 T0.8854,0.1146 T0.9127,0.1213 T0.9384,0.116 T0.9626,0.0962 Q0.9664,0.0909,0.9706,0.0846 T0.976,0.0767 T0.9798,0.0728 T0.9852,0.0704 T0.9932,0.0697 Q0.9997,0.0693,0.9942,0.0567 Q0.9923,0.0522,0.989,0.0469 Z",type:0}},"":{type:5,data:{d:"M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0.9099,0.1158 L0.9099,0.1888 L0.9951,0.1888 L0.9951,0.1158 L0.9099,0.1158 Z M0.9075,0.1116 L0.9976,0.1116 Q1,0.1116,1,0.1137 L1,0.1909 Q1,0.193,0.9976,0.193 L0.9075,0.193 Q0.905,0.193,0.905,0.1909 L0.905,0.1137 Q0.905,0.1116,0.9075,0.1116 Z M0.7852,0.6086 L0.7852,0.682 L0.8704,0.682 L0.8704,0.6086 L0.7852,0.6086 Z M0.7828,0.6044 L0.8729,0.6044 Q0.8753,0.6044,0.8753,0.6065 L0.8753,0.6841 Q0.8753,0.6862,0.8729,0.6862 L0.7828,0.6862 Q0.7803,0.6862,0.7803,0.6841 L0.7803,0.6065 Q0.7803,0.6044,0.7828,0.6044 Z M0.66,0.1137 L0.7501,0.1137 L0.7501,0.1909 L0.66,0.1909 L0.66,0.1137 Z M0.6624,0.4102 L0.6624,0.4836 L0.7477,0.4836 L0.7477,0.4102 L0.6624,0.4102 Z M0.66,0.406 L0.7501,0.406 Q0.7526,0.406,0.7526,0.4081 L0.7526,0.4857 Q0.7526,0.4878,0.7501,0.4878 L0.66,0.4878 Q0.6576,0.4878,0.6576,0.4857 L0.6576,0.4081 Q0.6576,0.406,0.66,0.406 Z M0.6624,0.7131 L0.6624,0.7865 L0.7477,0.7865 L0.7477,0.7131 L0.6624,0.7131 Z M0.66,0.7089 L0.7501,0.7089 Q0.7526,0.7089,0.7526,0.711 L0.7526,0.7886 Q0.7526,0.7907,0.7501,0.7907 L0.66,0.7907 Q0.6576,0.7907,0.6576,0.7886 L0.6576,0.711 Q0.6576,0.7089,0.66,0.7089 Z M0.5407,0.2227 L0.5407,0.2836 L0.6113,0.2836 L0.6113,0.2227 L0.5407,0.2227 Z M0.5309,0.206 L0.621,0.206 Q0.623,0.206,0.6249,0.2068 T0.6281,0.2089 T0.6301,0.2116 T0.6308,0.2143 L0.6308,0.2919 Q0.6308,0.2957,0.6276,0.298 T0.621,0.3003 L0.5309,0.3003 Q0.5265,0.3003,0.5239,0.2976 T0.5212,0.2919 L0.5212,0.2143 Q0.5212,0.211,0.5244,0.2085 T0.5309,0.206 Z M0.5407,0.3184 L0.5407,0.3792 L0.6113,0.3792 L0.6113,0.3184 L0.5407,0.3184 Z M0.5309,0.3016 L0.621,0.3016 Q0.6254,0.3016,0.6281,0.3043 T0.6308,0.31 L0.6308,0.3876 Q0.6308,0.3914,0.6276,0.3937 T0.621,0.396 L0.5309,0.396 Q0.5265,0.396,0.5239,0.3932 T0.5212,0.3876 L0.5212,0.31 Q0.5212,0.3062,0.5244,0.3039 T0.5309,0.3016 Z M0.5309,0.4081 L0.621,0.4081 L0.621,0.4857 L0.5309,0.4857 L0.5309,0.4081 Z M0.5309,0.5059 L0.621,0.5059 L0.621,0.5835 L0.5309,0.5835 L0.5309,0.5059 Z M0.5407,0.6149 L0.5407,0.6758 L0.6113,0.6758 L0.6113,0.6149 L0.5407,0.6149 Z M0.5309,0.5982 L0.621,0.5982 Q0.6254,0.5982,0.6281,0.6009 T0.6308,0.6065 L0.6308,0.6841 Q0.6308,0.6879,0.6276,0.6902 T0.621,0.6925 L0.5309,0.6925 Q0.5265,0.6925,0.5239,0.6898 T0.5212,0.6841 L0.5212,0.6065 Q0.5212,0.6028,0.5244,0.6005 T0.5309,0.5982 Z M0.4062,0.1137 L0.4963,0.1137 L0.4963,0.1909 L0.4062,0.1909 L0.4062,0.1137 Z M0.4062,0.2143 L0.4963,0.2143 L0.4963,0.2919 L0.4062,0.2919 L0.4062,0.2143 Z M0.4184,0.4186 L0.4184,0.4753 L0.4842,0.4753 L0.4842,0.4186 L0.4184,0.4186 Z M0.4062,0.3977 L0.4963,0.3977 Q0.5017,0.3977,0.5051,0.401 T0.5085,0.4081 L0.5085,0.4857 Q0.5085,0.4904,0.5046,0.4933 T0.4963,0.4962 L0.4062,0.4962 Q0.4009,0.4962,0.3975,0.4929 T0.3941,0.4857 L0.3941,0.4081 Q0.3941,0.4035,0.398,0.4006 T0.4062,0.3977 Z M0.4062,0.5059 L0.4963,0.5059 L0.4963,0.5835 L0.4062,0.5835 L0.4062,0.5059 Z M0.4087,0.7131 L0.4087,0.7865 L0.4939,0.7865 L0.4939,0.7131 L0.4087,0.7131 Z M0.4062,0.7089 L0.4963,0.7089 Q0.4988,0.7089,0.4988,0.711 L0.4988,0.7886 Q0.4988,0.7907,0.4963,0.7907 L0.4062,0.7907 Q0.4038,0.7907,0.4038,0.7886 L0.4038,0.711 Q0.4038,0.7089,0.4062,0.7089 Z M0.2689,0.1137 L0.359,0.1137 L0.359,0.1909 L0.2689,0.1909 L0.2689,0.1137 Z M0.2689,0.2143 L0.359,0.2143 L0.359,0.2919 L0.2689,0.2919 L0.2689,0.2143 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.31 L0.359,0.31 L0.359,0.3876 L0.2689,0.3876 L0.2689,0.31 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.4081 L0.359,0.4081 L0.359,0.4857 L0.2689,0.4857 L0.2689,0.4081 Z M0.2689,0.5059 L0.359,0.5059 L0.359,0.5835 L0.2689,0.5835 L0.2689,0.5059 Z M0.2689,0.711 L0.359,0.711 L0.359,0.7886 L0.2689,0.7886 L0.2689,0.711 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.1374,0.1137 L0.2275,0.1137 L0.2275,0.1909 L0.1374,0.1909 L0.1374,0.1137 Z M0.1374,0.2143 L0.2275,0.2143 L0.2275,0.2919 L0.1374,0.2919 L0.1374,0.2143 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.31 L0.2275,0.31 L0.2275,0.3876 L0.1374,0.3876 L0.1374,0.31 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.4081 L0.2275,0.4081 L0.2275,0.4857 L0.1374,0.4857 L0.1374,0.4081 Z M0.1374,0.5059 L0.2275,0.5059 L0.2275,0.5835 L0.1374,0.5835 L0.1374,0.5059 Z M0.1374,0.6065 L0.2275,0.6065 L0.2275,0.6841 L0.1374,0.6841 L0.1374,0.6065 Z M0.1374,0.711 L0.2275,0.711 L0.2275,0.7886 L0.1374,0.7886 L0.1374,0.711 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0,0.1137 L0.0901,0.1137 L0.0901,0.1909 L0,0.1909 L0,0.1137 Z M0,0.2143 L0.0901,0.2143 L0.0901,0.2919 L0,0.2919 L0,0.2143 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.31 L0.0901,0.31 L0.0901,0.3876 L0,0.3876 L0,0.31 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.4081 L0.0901,0.4081 L0.0901,0.4857 L0,0.4857 L0,0.4081 Z M0,0.5059 L0.0901,0.5059 L0.0901,0.5835 L0,0.5835 L0,0.5059 Z M0,0.6065 L0.0901,0.6065 L0.0901,0.6841 L0,0.6841 L0,0.6065 Z M0,0.711 L0.0901,0.711 L0.0901,0.7886 L0,0.7886 L0,0.711 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z",type:0}},"":{type:5,data:{d:"M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M0.0901,0.1158 L0.0901,0.1888 L0.0049,0.1888 L0.0049,0.1158 L0.0901,0.1158 Z M0.0925,0.1116 L0.0024,0.1116 Q0,0.1116,0,0.1137 L0,0.1909 Q0,0.193,0.0024,0.193 L0.0925,0.193 Q0.095,0.193,0.095,0.1909 L0.095,0.1137 Q0.095,0.1116,0.0925,0.1116 Z M0.2148,0.6086 L0.2148,0.682 L0.1296,0.682 L0.1296,0.6086 L0.2148,0.6086 Z M0.2172,0.6044 L0.1271,0.6044 Q0.1247,0.6044,0.1247,0.6065 L0.1247,0.6841 Q0.1247,0.6862,0.1271,0.6862 L0.2172,0.6862 Q0.2197,0.6862,0.2197,0.6841 L0.2197,0.6065 Q0.2197,0.6044,0.2172,0.6044 Z M0.34,0.1137 L0.2499,0.1137 L0.2499,0.1909 L0.34,0.1909 L0.34,0.1137 Z M0.3376,0.4102 L0.3376,0.4836 L0.2523,0.4836 L0.2523,0.4102 L0.3376,0.4102 Z M0.34,0.406 L0.2499,0.406 Q0.2474,0.406,0.2474,0.4081 L0.2474,0.4857 Q0.2474,0.4878,0.2499,0.4878 L0.34,0.4878 Q0.3424,0.4878,0.3424,0.4857 L0.3424,0.4081 Q0.3424,0.406,0.34,0.406 Z M0.3376,0.7131 L0.3376,0.7865 L0.2523,0.7865 L0.2523,0.7131 L0.3376,0.7131 Z M0.34,0.7089 L0.2499,0.7089 Q0.2474,0.7089,0.2474,0.711 L0.2474,0.7886 Q0.2474,0.7907,0.2499,0.7907 L0.34,0.7907 Q0.3424,0.7907,0.3424,0.7886 L0.3424,0.711 Q0.3424,0.7089,0.34,0.7089 Z M0.4593,0.2227 L0.4593,0.2836 L0.3887,0.2836 L0.3887,0.2227 L0.4593,0.2227 Z M0.4691,0.206 L0.379,0.206 Q0.3746,0.206,0.3719,0.2087 T0.3692,0.2143 L0.3692,0.2919 Q0.3692,0.2957,0.3724,0.298 T0.379,0.3003 L0.4691,0.3003 Q0.4735,0.3003,0.4761,0.2976 T0.4788,0.2919 L0.4788,0.2143 Q0.4788,0.211,0.4756,0.2085 T0.4691,0.206 Z M0.4593,0.3184 L0.4593,0.3792 L0.3887,0.3792 L0.3887,0.3184 L0.4593,0.3184 Z M0.4691,0.3016 L0.379,0.3016 Q0.3746,0.3016,0.3719,0.3043 T0.3692,0.31 L0.3692,0.3876 Q0.3692,0.3914,0.3724,0.3937 T0.379,0.396 L0.4691,0.396 Q0.4735,0.396,0.4761,0.3932 T0.4788,0.3876 L0.4788,0.31 Q0.4788,0.3062,0.4756,0.3039 T0.4691,0.3016 Z M0.4691,0.4081 L0.379,0.4081 L0.379,0.4857 L0.4691,0.4857 L0.4691,0.4081 Z M0.4691,0.5059 L0.379,0.5059 L0.379,0.5835 L0.4691,0.5835 L0.4691,0.5059 Z M0.4593,0.6149 L0.4593,0.6758 L0.3887,0.6758 L0.3887,0.6149 L0.4593,0.6149 Z M0.4691,0.5982 L0.379,0.5982 Q0.3746,0.5982,0.3719,0.6009 T0.3692,0.6065 L0.3692,0.6841 Q0.3692,0.6879,0.3724,0.6902 T0.379,0.6925 L0.4691,0.6925 Q0.4735,0.6925,0.4761,0.6898 T0.4788,0.6841 L0.4788,0.6065 Q0.4788,0.6028,0.4756,0.6005 T0.4691,0.5982 Z M0.5938,0.1137 L0.5037,0.1137 L0.5037,0.1909 L0.5938,0.1909 L0.5938,0.1137 Z M0.5938,0.2143 L0.5037,0.2143 L0.5037,0.2919 L0.5938,0.2919 L0.5938,0.2143 Z M0.5816,0.4186 L0.5816,0.4753 L0.5158,0.4753 L0.5158,0.4186 L0.5816,0.4186 Z M0.5938,0.3977 L0.5037,0.3977 Q0.4983,0.3977,0.4949,0.401 T0.4915,0.4081 L0.4915,0.4857 Q0.4915,0.4904,0.4954,0.4933 T0.5037,0.4962 L0.5938,0.4962 Q0.5991,0.4962,0.6025,0.4929 T0.6059,0.4857 L0.6059,0.4081 Q0.6059,0.4035,0.602,0.4006 T0.5938,0.3977 Z M0.5938,0.5059 L0.5037,0.5059 L0.5037,0.5835 L0.5938,0.5835 L0.5938,0.5059 Z M0.5913,0.7131 L0.5913,0.7865 L0.5061,0.7865 L0.5061,0.7131 L0.5913,0.7131 Z M0.5938,0.7089 L0.5037,0.7089 Q0.5012,0.7089,0.5012,0.711 L0.5012,0.7886 Q0.5012,0.7907,0.5037,0.7907 L0.5938,0.7907 Q0.5962,0.7907,0.5962,0.7886 L0.5962,0.711 Q0.5962,0.7089,0.5938,0.7089 Z M0.7311,0.1137 L0.641,0.1137 L0.641,0.1909 L0.7311,0.1909 L0.7311,0.1137 Z M0.7311,0.2143 L0.641,0.2143 L0.641,0.2919 L0.7311,0.2919 L0.7311,0.2143 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.31 L0.641,0.31 L0.641,0.3876 L0.7311,0.3876 L0.7311,0.31 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.4081 L0.641,0.4081 L0.641,0.4857 L0.7311,0.4857 L0.7311,0.4081 Z M0.7311,0.5059 L0.641,0.5059 L0.641,0.5835 L0.7311,0.5835 L0.7311,0.5059 Z M0.7311,0.711 L0.641,0.711 L0.641,0.7886 L0.7311,0.7886 L0.7311,0.711 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.8626,0.1137 L0.7725,0.1137 L0.7725,0.1909 L0.8626,0.1909 L0.8626,0.1137 Z M0.8626,0.2143 L0.7725,0.2143 L0.7725,0.2919 L0.8626,0.2919 L0.8626,0.2143 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.31 L0.7725,0.31 L0.7725,0.3876 L0.8626,0.3876 L0.8626,0.31 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.4081 L0.7725,0.4081 L0.7725,0.4857 L0.8626,0.4857 L0.8626,0.4081 Z M0.8626,0.5059 L0.7725,0.5059 L0.7725,0.5835 L0.8626,0.5835 L0.8626,0.5059 Z M0.8626,0.6065 L0.7725,0.6065 L0.7725,0.6841 L0.8626,0.6841 L0.8626,0.6065 Z M0.8626,0.711 L0.7725,0.711 L0.7725,0.7886 L0.8626,0.7886 L0.8626,0.711 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M1,0.1137 L0.9099,0.1137 L0.9099,0.1909 L1,0.1909 L1,0.1137 Z M1,0.2143 L0.9099,0.2143 L0.9099,0.2919 L1,0.2919 L1,0.2143 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.31 L0.9099,0.31 L0.9099,0.3876 L1,0.3876 L1,0.31 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.4081 L0.9099,0.4081 L0.9099,0.4857 L1,0.4857 L1,0.4081 Z M1,0.5059 L0.9099,0.5059 L0.9099,0.5835 L1,0.5835 L1,0.5059 Z M1,0.6065 L0.9099,0.6065 L0.9099,0.6841 L1,0.6841 L1,0.6065 Z M1,0.711 L0.9099,0.711 L0.9099,0.7886 L1,0.7886 L1,0.711 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z",type:0}},"":{type:5,data:{d:"M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0.8574,0.3217 L0.8574,0.4098 L0.9691,0.4098 L0.9691,0.3217 L0.8574,0.3217 Z M0.8419,0.2978 L0.9846,0.2978 Q0.9892,0.2978,0.9928,0.2997 T0.9982,0.3043 T1,0.31 L1,0.4216 Q1,0.427,0.9951,0.4304 T0.9846,0.4337 L0.8419,0.4337 Q0.8352,0.4337,0.8308,0.4299 T0.8265,0.4216 L0.8265,0.31 Q0.8265,0.3062,0.829,0.3035 T0.835,0.2993 T0.8419,0.2978 Z M0.8574,0.888 L0.8574,0.9757 L0.9691,0.9757 L0.9691,0.888 L0.8574,0.888 Z M0.8419,0.8637 L0.9846,0.8637 Q0.9892,0.8637,0.9928,0.8658 T0.9982,0.8706 T1,0.8758 L1,0.9878 Q1,0.9929,0.9951,0.9964 T0.9846,1 L0.8419,1 Q0.8352,1,0.8308,0.996 T0.8265,0.9878 L0.8265,0.8758 Q0.8265,0.8708,0.8314,0.8672 T0.8419,0.8637 Z M0.6509,0.169 L0.6509,0.2706 L0.7806,0.2706 L0.7806,0.169 L0.6509,0.169 Z M0.6442,0.159 L0.7868,0.159 Q0.7899,0.159,0.7917,0.1604 T0.7935,0.164 L0.7935,0.2756 Q0.7935,0.2781,0.7915,0.2796 T0.7868,0.281 L0.6442,0.281 Q0.6416,0.281,0.6395,0.2794 T0.6375,0.2756 L0.6375,0.164 Q0.6375,0.1619,0.6398,0.1604 T0.6442,0.159 Z M0.6632,0.6044 L0.6632,0.6858 L0.7678,0.6858 L0.7678,0.6044 L0.6632,0.6044 Z M0.6442,0.5742 L0.7868,0.5742 Q0.7951,0.5742,0.8007,0.5791 T0.8064,0.5893 L0.8064,0.7013 Q0.8064,0.7076,0.8002,0.712 T0.7868,0.7164 L0.6442,0.7164 Q0.6359,0.7164,0.6305,0.7114 T0.6251,0.7013 L0.6251,0.5893 Q0.6251,0.5847,0.6282,0.5812 T0.6357,0.5759 T0.6442,0.5742 Z M0.4264,0.164 L0.5695,0.164 L0.5695,0.2756 L0.4264,0.2756 L0.4264,0.164 Z M0.4325,0.315 L0.4325,0.4165 L0.5628,0.4165 L0.5628,0.315 L0.4325,0.315 Z M0.4264,0.3049 L0.5695,0.3049 Q0.5721,0.3049,0.5739,0.3064 T0.5757,0.31 L0.5757,0.4216 Q0.5757,0.4237,0.5736,0.4251 T0.5695,0.4266 L0.4264,0.4266 Q0.4238,0.4266,0.422,0.4251 T0.4202,0.4216 L0.4202,0.31 Q0.4202,0.3087,0.4207,0.3077 T0.4222,0.306 T0.4243,0.3052 T0.4264,0.3049 Z M0.4264,0.4476 L0.5695,0.4476 L0.5695,0.5596 L0.4264,0.5596 L0.4264,0.4476 Z M0.4392,0.7408 L0.4392,0.8326 L0.5561,0.8326 L0.5561,0.7408 L0.4392,0.7408 Z M0.4264,0.7206 L0.5695,0.7206 Q0.5747,0.7206,0.5783,0.724 T0.5819,0.7307 L0.5819,0.8427 Q0.5819,0.8469,0.5778,0.8498 T0.5695,0.8528 L0.4264,0.8528 Q0.4207,0.8528,0.4171,0.8496 T0.4135,0.8427 L0.4135,0.7307 Q0.4135,0.7265,0.4176,0.7236 T0.4264,0.7206 Z M0.2178,0.164 L0.3605,0.164 L0.3605,0.2756 L0.2178,0.2756 L0.2178,0.164 Z M0.2178,0.31 L0.3605,0.31 L0.3605,0.4216 L0.2178,0.4216 L0.2178,0.31 Z M0.2178,0.5893 L0.3605,0.5893 L0.3605,0.7013 L0.2178,0.7013 L0.2178,0.5893 Z M0.2178,0.7307 L0.3605,0.7307 L0.3605,0.8427 L0.2178,0.8427 L0.2178,0.7307 Z M0.2178,0.8758 L0.3605,0.8758 L0.3605,0.9878 L0.2178,0.9878 L0.2178,0.8758 Z M0,0.164 L0.1432,0.164 L0.1432,0.2756 L0,0.2756 L0,0.164 Z M0,0.31 L0.1432,0.31 L0.1432,0.4216 L0,0.4216 L0,0.31 Z M0,0.4476 L0.1432,0.4476 L0.1432,0.5596 L0,0.5596 L0,0.4476 Z M0,0.5893 L0.1432,0.5893 L0.1432,0.7013 L0,0.7013 L0,0.5893 Z M0,0.7307 L0.1432,0.7307 L0.1432,0.8427 L0,0.8427 L0,0.7307 Z M0,0.8758 L0.1432,0.8758 L0.1432,0.9878 L0,0.9878 L0,0.8758 Z",type:0}},"":{type:5,data:{d:"M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M0.1432,0.3217 L0.1432,0.4098 L0.0309,0.4098 L0.0309,0.3217 L0.1432,0.3217 Z M0.1586,0.2978 L0.0154,0.2978 Q0.0088,0.2978,0.0044,0.3016 T0,0.31 L0,0.4216 Q0,0.427,0.0049,0.4304 T0.0154,0.4337 L0.1586,0.4337 Q0.1648,0.4337,0.1694,0.4299 T0.174,0.4216 L0.174,0.31 Q0.174,0.3062,0.1715,0.3035 T0.1653,0.2993 T0.1586,0.2978 Z M0.1432,0.888 L0.1432,0.9757 L0.0309,0.9757 L0.0309,0.888 L0.1432,0.888 Z M0.1586,0.8637 L0.0154,0.8637 Q0.0108,0.8637,0.0072,0.8658 T0.0018,0.8706 T0,0.8758 L0,0.9878 Q0,0.9929,0.0049,0.9964 T0.0154,1 L0.1586,1 Q0.1648,1,0.1694,0.996 T0.174,0.9878 L0.174,0.8758 Q0.174,0.8725,0.1715,0.8695 T0.1653,0.8651 T0.1586,0.8637 Z M0.3496,0.169 L0.3496,0.2706 L0.2194,0.2706 L0.2194,0.169 L0.3496,0.169 Z M0.3563,0.159 L0.2132,0.159 Q0.2106,0.159,0.2088,0.1604 T0.207,0.164 L0.207,0.2756 Q0.207,0.2781,0.2091,0.2796 T0.2132,0.281 L0.3563,0.281 Q0.3589,0.281,0.3607,0.2794 T0.3625,0.2756 L0.3625,0.164 Q0.3625,0.1619,0.3605,0.1604 T0.3563,0.159 Z M0.3368,0.6044 L0.3368,0.6858 L0.2327,0.6858 L0.2327,0.6044 L0.3368,0.6044 Z M0.3563,0.5742 L0.2132,0.5742 Q0.2049,0.5742,0.1993,0.5791 T0.1936,0.5893 L0.1936,0.7013 Q0.1936,0.7076,0.2001,0.712 T0.2132,0.7164 L0.3563,0.7164 Q0.3641,0.7164,0.3697,0.7114 T0.3754,0.7013 L0.3754,0.5893 Q0.3754,0.5847,0.3723,0.5812 T0.3648,0.5759 T0.3563,0.5742 Z M0.5736,0.164 L0.431,0.164 L0.431,0.2756 L0.5736,0.2756 L0.5736,0.164 Z M0.5675,0.315 L0.5675,0.4165 L0.4377,0.4165 L0.4377,0.315 L0.5675,0.315 Z M0.5736,0.3049 L0.431,0.3049 Q0.4284,0.3049,0.4264,0.3064 T0.4243,0.31 L0.4243,0.4216 Q0.4243,0.4237,0.4266,0.4251 T0.431,0.4266 L0.5736,0.4266 Q0.5767,0.4266,0.5785,0.4251 T0.5803,0.4216 L0.5803,0.31 Q0.5803,0.3087,0.5798,0.3077 T0.5783,0.306 T0.5762,0.3052 T0.5736,0.3049 Z M0.5736,0.4476 L0.431,0.4476 L0.431,0.5596 L0.5736,0.5596 L0.5736,0.4476 Z M0.5613,0.7408 L0.5613,0.8326 L0.4439,0.8326 L0.4439,0.7408 L0.5613,0.7408 Z M0.5736,0.7206 L0.431,0.7206 Q0.4253,0.7206,0.4217,0.724 T0.4181,0.7307 L0.4181,0.8427 Q0.4181,0.8469,0.4222,0.8498 T0.431,0.8528 L0.5736,0.8528 Q0.5778,0.8528,0.5808,0.8511 T0.5855,0.8471 T0.587,0.8427 L0.587,0.7307 Q0.587,0.7265,0.5826,0.7236 T0.5736,0.7206 Z M0.7827,0.164 L0.6395,0.164 L0.6395,0.2756 L0.7827,0.2756 L0.7827,0.164 Z M0.7827,0.31 L0.6395,0.31 L0.6395,0.4216 L0.7827,0.4216 L0.7827,0.31 Z M0.7827,0.5893 L0.6395,0.5893 L0.6395,0.7013 L0.7827,0.7013 L0.7827,0.5893 Z M0.7827,0.7307 L0.6395,0.7307 L0.6395,0.8427 L0.7827,0.8427 L0.7827,0.7307 Z M0.7827,0.8758 L0.6395,0.8758 L0.6395,0.9878 L0.7827,0.9878 L0.7827,0.8758 Z M1,0.164 L0.8574,0.164 L0.8574,0.2756 L1,0.2756 L1,0.164 Z M1,0.31 L0.8574,0.31 L0.8574,0.4216 L1,0.4216 L1,0.31 Z M1,0.4476 L0.8574,0.4476 L0.8574,0.5596 L1,0.5596 L1,0.4476 Z M1,0.5893 L0.8574,0.5893 L0.8574,0.7013 L1,0.7013 L1,0.5893 Z M1,0.7307 L0.8574,0.7307 L0.8574,0.8427 L1,0.8427 L1,0.7307 Z M1,0.8758 L0.8574,0.8758 L0.8574,0.9878 L1,0.9878 L1,0.8758 Z",type:0}},"":{type:5,data:{d:"M0.0008,0.9979 Q0.0008,1,0.0032,1 Q0.0482,1,0.0602,0.9975 Q0.0667,0.9963,0.0847,0.9917 T0.1084,0.9859 Q0.1124,0.9851,0.1221,0.9851 L0.1253,0.9851 L0.1285,0.9851 Q0.1518,0.9851,0.1655,0.9809 Q0.1695,0.9801,0.1731,0.9788 T0.1791,0.9766 T0.1839,0.9747 T0.1888,0.9732 L0.1936,0.972 T0.1988,0.9712 T0.2048,0.971 L0.2096,0.971 Q0.2201,0.9714,0.2233,0.9714 T0.2345,0.9693 Q0.2386,0.9685,0.2502,0.9674 T0.2715,0.966 L0.2811,0.9656 Q0.2916,0.9647,0.2916,0.9573 Q0.2916,0.954,0.2892,0.9515 T0.2819,0.9486 Q0.2755,0.9482,0.2683,0.9482 Q0.2643,0.9482,0.2582,0.9484 T0.2498,0.9486 Q0.2426,0.9486,0.2402,0.9473 Q0.2386,0.9469,0.2317,0.943 T0.2161,0.937 Q0.2104,0.9357,0.1992,0.933 T0.1831,0.9291 Q0.1807,0.9287,0.1783,0.9285 T0.1739,0.928 T0.1703,0.9276 T0.1675,0.9272 T0.1655,0.9266 T0.1639,0.9253 Q0.1598,0.9216,0.1462,0.9216 L0.143,0.9216 L0.1398,0.9216 L0.1365,0.9216 Q0.1197,0.9195,0.1197,0.9154 L0.1197,0.9154 Q0.1205,0.9121,0.1373,0.9088 T0.1703,0.9054 Q0.1791,0.9054,0.1863,0.904 T0.1984,0.9011 T0.2064,0.8992 Q0.2402,0.8967,0.2506,0.8934 Q0.2538,0.8926,0.2602,0.8899 T0.2707,0.8872 Q0.2715,0.8872,0.2731,0.8876 Q0.2795,0.8884,0.2884,0.8884 Q0.3068,0.8884,0.3092,0.8826 L0.3092,0.8797 Q0.3092,0.8772,0.3076,0.8747 T0.3044,0.8706 T0.3028,0.8681 Q0.3076,0.8656,0.3237,0.8656 Q0.3317,0.8656,0.3622,0.8623 Q0.3655,0.8623,0.3867,0.8617 T0.4217,0.8602 Q0.4241,0.8598,0.4289,0.8598 L0.4345,0.8598 L0.441,0.8598 Q0.4578,0.8598,0.4667,0.8586 Q0.4739,0.8573,0.4851,0.8567 T0.5004,0.8552 Q0.5012,0.8552,0.5108,0.855 T0.5269,0.853 T0.5333,0.8461 Q0.5333,0.8445,0.5325,0.8432 T0.5309,0.8409 T0.5289,0.8391 T0.5261,0.8378 L0.5229,0.837 T0.5185,0.8362 T0.5133,0.8355 T0.5076,0.8349 T0.502,0.8341 Q0.4932,0.8324,0.4859,0.8324 Q0.4827,0.8324,0.4787,0.8328 T0.4731,0.8333 Q0.4707,0.8333,0.4683,0.8324 Q0.4482,0.825,0.4394,0.825 Q0.4369,0.825,0.4345,0.8254 Q0.4225,0.827,0.4153,0.827 Q0.4088,0.827,0.4064,0.8258 Q0.3976,0.8204,0.3751,0.8204 Q0.3703,0.8204,0.3667,0.8214 T0.3622,0.8225 Q0.3598,0.8225,0.3558,0.82 Q0.351,0.8175,0.3402,0.8167 T0.3177,0.8156 T0.3028,0.8146 L0.2956,0.8121 T0.2871,0.8094 T0.2771,0.8073 T0.2635,0.8063 Q0.261,0.8063,0.2586,0.8067 Q0.2378,0.8071,0.2273,0.8071 Q0.2072,0.8071,0.2024,0.8051 Q0.1976,0.8034,0.1932,0.8026 T0.1867,0.8013 T0.1847,0.8001 L0.1847,0.7993 Q0.1855,0.7984,0.1855,0.7978 T0.1859,0.7966 T0.1867,0.7959 T0.188,0.7955 T0.1896,0.7951 T0.1916,0.7949 T0.1944,0.7945 T0.1984,0.7941 T0.2032,0.7939 Q0.212,0.7926,0.2325,0.7918 T0.2562,0.7905 Q0.2691,0.7893,0.2787,0.7847 Q0.2835,0.7827,0.2968,0.7791 T0.3149,0.7756 Q0.3189,0.7756,0.3305,0.7733 T0.3446,0.771 L0.3454,0.771 Q0.3462,0.771,0.3498,0.7721 T0.3574,0.774 T0.3655,0.7748 Q0.3703,0.7748,0.3743,0.7731 T0.3823,0.7708 T0.3916,0.77 T0.3992,0.7694 Q0.4008,0.7694,0.4076,0.7688 T0.4205,0.7675 L0.4305,0.7665 Q0.4345,0.7657,0.4402,0.7617 T0.4458,0.7545 Q0.4458,0.7503,0.4353,0.7487 Q0.4297,0.7478,0.4209,0.7462 T0.4044,0.7433 T0.3904,0.7416 L0.3847,0.7416 Q0.3807,0.7416,0.3747,0.7422 T0.3663,0.7428 T0.3606,0.7424 Q0.3582,0.742,0.3562,0.7418 T0.3522,0.7412 T0.3482,0.7406 T0.3446,0.7401 T0.341,0.7397 T0.3373,0.7393 T0.3341,0.7391 L0.3293,0.7391 Q0.3277,0.7395,0.3253,0.7395 Q0.3205,0.7395,0.3052,0.7387 T0.2835,0.7379 Q0.2755,0.7379,0.253,0.7325 Q0.2506,0.7316,0.2462,0.731 T0.2382,0.7296 T0.2305,0.7271 T0.2181,0.7234 T0.2048,0.7196 T0.2,0.7155 Q0.2,0.7142,0.2016,0.713 Q0.208,0.7059,0.2285,0.6978 T0.2618,0.6898 Q0.2739,0.6898,0.2831,0.6848 T0.2956,0.6794 Q0.3028,0.6786,0.3289,0.6765 T0.3566,0.674 Q0.3582,0.674,0.3855,0.6723 T0.4406,0.6688 T0.4755,0.6653 Q0.5004,0.6607,0.5124,0.6599 L0.5165,0.6599 Q0.5213,0.6599,0.5277,0.6605 T0.5373,0.6611 Q0.543,0.6611,0.5494,0.6599 Q0.592,0.6524,0.6,0.6524 Q0.6064,0.6524,0.61,0.6499 T0.6161,0.6474 Q0.6177,0.6474,0.6261,0.6495 T0.6418,0.6516 L0.6482,0.6516 Q0.653,0.6512,0.6651,0.6506 T0.6876,0.6493 T0.7084,0.6477 T0.7229,0.645 Q0.7269,0.6437,0.7333,0.6437 Q0.7373,0.6437,0.7458,0.6443 T0.7574,0.645 Q0.7614,0.645,0.7631,0.6445 T0.7655,0.6441 Q0.7671,0.6441,0.7723,0.6448 T0.7823,0.6454 Q0.788,0.6454,0.7952,0.6445 Q0.8233,0.6408,0.8723,0.6367 Q0.9012,0.6342,0.9092,0.6342 L0.9165,0.6342 L0.9205,0.6342 Q0.9277,0.6342,0.9382,0.6323 T0.9526,0.6304 Q0.9534,0.6304,0.9594,0.6307 T0.9695,0.6309 Q0.9976,0.6309,0.9992,0.6234 Q1,0.6201,1,0.618 Q1,0.6089,0.9775,0.608 Q0.9703,0.6076,0.9582,0.6076 Q0.9518,0.6076,0.9394,0.6078 T0.9213,0.608 Q0.9036,0.608,0.8972,0.6072 Q0.894,0.6068,0.8871,0.6058 T0.8751,0.6039 T0.8627,0.6024 T0.8506,0.6018 L0.8474,0.6018 Q0.841,0.6022,0.8281,0.6041 T0.8112,0.606 Q0.8096,0.606,0.808,0.6056 Q0.7783,0.6002,0.7647,0.6002 Q0.7598,0.6002,0.7454,0.6006 T0.7261,0.601 Q0.7221,0.601,0.7145,0.6022 T0.7036,0.6035 Q0.6996,0.6035,0.6964,0.6022 Q0.6723,0.5902,0.6442,0.5902 Q0.6426,0.5902,0.6386,0.5904 T0.6337,0.5906 Q0.6273,0.5906,0.6249,0.5894 L0.6177,0.5856 T0.6116,0.5838 T0.6016,0.5825 T0.5855,0.5823 Q0.5719,0.5823,0.5574,0.5798 T0.5373,0.5774 L0.5341,0.5774 Q0.5293,0.5778,0.5213,0.5786 T0.51,0.5794 Q0.5036,0.5794,0.4988,0.5769 Q0.4932,0.574,0.4771,0.574 Q0.4723,0.574,0.4631,0.5745 T0.4498,0.5749 Q0.4418,0.5749,0.4394,0.5736 Q0.4353,0.5724,0.4305,0.5715 T0.4225,0.5707 T0.4145,0.5705 T0.4056,0.5699 Q0.4008,0.5691,0.398,0.5689 T0.394,0.5689 T0.3908,0.5686 T0.3855,0.5674 Q0.3831,0.567,0.3811,0.5662 T0.3779,0.5645 T0.3743,0.563 T0.3695,0.5624 Q0.3655,0.5624,0.3594,0.5635 T0.3494,0.5645 T0.3406,0.5635 T0.3325,0.5624 Q0.3309,0.5624,0.3301,0.5628 L0.3141,0.5628 Q0.2635,0.5628,0.2506,0.5612 Q0.2474,0.5608,0.2434,0.5608 Q0.2402,0.5608,0.2349,0.561 T0.2273,0.5612 Q0.2209,0.5612,0.2177,0.5595 Q0.2145,0.557,0.2145,0.5558 Q0.2169,0.5537,0.2345,0.5521 Q0.2876,0.5475,0.3028,0.5425 Q0.3068,0.5413,0.3149,0.5396 T0.3309,0.5367 T0.3478,0.5338 T0.3606,0.5309 Q0.3631,0.5305,0.3755,0.5259 T0.3968,0.5214 Q0.3992,0.5214,0.4024,0.5218 T0.4096,0.5222 Q0.4161,0.5222,0.4213,0.5209 T0.4313,0.5185 T0.4402,0.5172 Q0.4418,0.5168,0.447,0.5168 L0.4558,0.5168 T0.4639,0.5162 T0.4707,0.5141 T0.4731,0.5102 Q0.4731,0.5089,0.4723,0.5081 Q0.4699,0.5019,0.4627,0.4994 T0.4369,0.4965 Q0.4273,0.4961,0.4193,0.4946 T0.4048,0.4915 T0.3952,0.4894 Q0.392,0.4886,0.388,0.4886 Q0.3847,0.4886,0.3775,0.4892 T0.3647,0.4898 Q0.3598,0.4898,0.355,0.4894 Q0.3165,0.4861,0.3141,0.4853 Q0.2779,0.4774,0.2715,0.4774 Q0.2699,0.4774,0.2683,0.4776 T0.2627,0.4778 Q0.2498,0.4778,0.2281,0.4762 Q0.2241,0.4749,0.2233,0.4737 Q0.2249,0.472,0.2321,0.4708 Q0.2402,0.4695,0.2554,0.4695 L0.2675,0.4695 L0.2795,0.4695 Q0.294,0.4695,0.2996,0.4679 Q0.3141,0.4629,0.3373,0.4616 Q0.3414,0.4612,0.3466,0.4606 T0.3582,0.4589 T0.3687,0.4562 T0.3727,0.4525 Q0.3727,0.4509,0.3703,0.4492 Q0.3639,0.4455,0.3474,0.4419 T0.3213,0.4384 L0.3157,0.4384 L0.31,0.4384 Q0.294,0.4384,0.2859,0.4363 Q0.2795,0.4347,0.2691,0.4347 L0.2618,0.4347 L0.2546,0.4347 Q0.2458,0.4347,0.2394,0.4338 Q0.2257,0.4318,0.2193,0.4303 T0.2092,0.4266 T0.2052,0.4224 T0.2024,0.4154 T0.196,0.4052 Q0.1912,0.3994,0.1867,0.3949 T0.1807,0.3884 T0.1791,0.3849 Q0.1791,0.3824,0.1839,0.3745 Q0.1871,0.3687,0.1944,0.3637 T0.2072,0.3561 T0.2221,0.3501 T0.2321,0.3463 Q0.2353,0.3455,0.241,0.3445 T0.2522,0.3428 T0.2639,0.3411 T0.2731,0.3384 T0.2956,0.3351 T0.3197,0.3326 Q0.3213,0.3322,0.3237,0.3322 T0.3325,0.3331 T0.3414,0.3339 Q0.3478,0.3339,0.3518,0.3314 Q0.3606,0.3264,0.3703,0.3264 Q0.3775,0.3264,0.3847,0.3293 Q0.3888,0.331,0.396,0.331 Q0.4024,0.331,0.4116,0.3295 T0.4265,0.3266 T0.4414,0.3227 T0.4514,0.3202 Q0.4578,0.3181,0.4839,0.3152 T0.5112,0.3123 T0.5177,0.3119 T0.5285,0.3111 T0.5398,0.3096 T0.549,0.3065 T0.5526,0.3015 Q0.5526,0.2999,0.5518,0.2982 Q0.547,0.2903,0.5386,0.2883 T0.5165,0.2862 Q0.5116,0.2862,0.5056,0.2866 T0.4972,0.287 Q0.4884,0.287,0.4787,0.2833 Q0.4594,0.2758,0.4265,0.2758 Q0.4169,0.2758,0.4129,0.2766 Q0.4112,0.2771,0.4104,0.2771 Q0.4088,0.2771,0.4056,0.2748 T0.3968,0.2721 Q0.3695,0.2696,0.359,0.2659 Q0.355,0.2646,0.351,0.2646 T0.3426,0.2661 T0.3365,0.2675 T0.3333,0.2659 Q0.3277,0.2605,0.3116,0.2553 T0.2859,0.2501 L0.2843,0.2501 L0.2819,0.2501 Q0.2779,0.2501,0.2723,0.2493 T0.2586,0.2472 T0.2474,0.2455 Q0.1799,0.236,0.1719,0.236 Q0.1663,0.236,0.1606,0.235 T0.1502,0.2316 T0.1454,0.2265 Q0.1454,0.2223,0.1558,0.2173 Q0.1679,0.2115,0.1859,0.2092 T0.2185,0.207 T0.2353,0.2057 Q0.2369,0.2049,0.2502,0.2041 T0.2799,0.2022 T0.302,0.2007 Q0.3084,0.1999,0.3245,0.1954 T0.347,0.1908 Q0.3502,0.1908,0.3534,0.1916 Q0.3663,0.197,0.388,0.197 Q0.404,0.197,0.4088,0.1929 Q0.4096,0.192,0.4108,0.192 T0.4177,0.1945 T0.4277,0.197 T0.4369,0.1949 Q0.4442,0.1908,0.4843,0.1875 Q0.4892,0.1871,0.4968,0.1839 T0.5084,0.1808 L0.5108,0.1808 Q0.5213,0.1825,0.5454,0.1825 Q0.5823,0.1825,0.5992,0.1779 Q0.6096,0.1746,0.6217,0.1746 Q0.6249,0.1746,0.6309,0.1748 T0.6394,0.175 Q0.6434,0.175,0.6466,0.1746 Q0.6474,0.1746,0.6594,0.1738 T0.6787,0.1713 T0.6892,0.1659 Q0.6924,0.1634,0.6924,0.1593 Q0.6924,0.1547,0.6888,0.151 T0.6795,0.1472 Q0.6779,0.1472,0.6763,0.1477 Q0.6699,0.1493,0.6667,0.1493 Q0.661,0.1493,0.6506,0.1456 Q0.6329,0.1394,0.6129,0.1394 Q0.6048,0.1394,0.5992,0.1377 T0.5888,0.136 T0.5803,0.1377 T0.5751,0.1394 Q0.5711,0.1394,0.5639,0.1369 Q0.5365,0.1273,0.5116,0.1273 Q0.4876,0.1273,0.4667,0.1253 Q0.4627,0.1248,0.4542,0.1211 T0.4337,0.1174 L0.4305,0.1174 Q0.4217,0.1178,0.4153,0.119 T0.408,0.1203 Q0.4056,0.1203,0.4,0.117 Q0.3976,0.1153,0.396,0.1136 T0.3932,0.1112 T0.39,0.1099 T0.3847,0.1095 Q0.3799,0.1095,0.3687,0.1103 Q0.355,0.1112,0.3434,0.1141 T0.3301,0.117 Q0.3261,0.117,0.3229,0.1145 Q0.3181,0.1116,0.3052,0.1087 T0.2787,0.1043 T0.2546,0.1029 Q0.2506,0.1029,0.2474,0.1033 Q0.2418,0.1037,0.2349,0.1054 T0.2249,0.107 Q0.2225,0.107,0.2193,0.1066 Q0.2024,0.1024,0.1863,0.1024 Q0.1823,0.1024,0.1562,0.0971 T0.1269,0.0917 T0.1161,0.0896 T0.106,0.0854 Q0.1076,0.0846,0.11,0.0842 Q0.1173,0.0821,0.1261,0.0821 Q0.1301,0.0821,0.1369,0.0825 T0.1462,0.083 Q0.1494,0.083,0.151,0.0825 T0.1831,0.0813 T0.2201,0.0784 T0.243,0.074 T0.2667,0.0718 Q0.2707,0.0718,0.2755,0.0724 T0.2843,0.073 T0.2936,0.0724 T0.3024,0.0705 T0.3072,0.068 T0.3092,0.0657 T0.3108,0.0647 Q0.3116,0.0643,0.3133,0.0643 L0.3157,0.0643 L0.3181,0.0643 Q0.3446,0.0643,0.3446,0.0556 T0.3205,0.0469 L0.3189,0.0469 Q0.3157,0.0469,0.3157,0.0465 Q0.3084,0.0427,0.2835,0.0386 Q0.2739,0.0369,0.2675,0.0342 T0.2538,0.0299 Q0.249,0.029,0.245,0.029 T0.2378,0.0303 T0.2321,0.0315 Q0.2305,0.0315,0.2273,0.0307 Q0.2201,0.0286,0.2004,0.0272 T0.1775,0.0245 Q0.1735,0.0228,0.1663,0.0226 T0.1522,0.0197 T0.1345,0.0145 T0.1124,0.0079 Q0.0996,0.0033,0.0671,0.0044 T0.0297,0.0041 Q0.0169,0,0.0024,0.0017 Q0,0.0021,0,0.0037 Z M0.0064,0.9954 L0.0056,0.0058 Q0.0177,0.005,0.0281,0.0083 Q0.0345,0.01,0.0675,0.0089 T0.1108,0.012 Q0.1221,0.0162,0.1329,0.0187 T0.1498,0.0236 T0.1606,0.0268 T0.1691,0.0274 T0.1759,0.0286 Q0.1807,0.0303,0.2,0.0315 T0.2257,0.0348 Q0.2305,0.0361,0.2337,0.0361 Q0.2361,0.0361,0.2398,0.0348 T0.2466,0.0336 Q0.249,0.0336,0.2522,0.034 Q0.2586,0.0353,0.2655,0.0382 T0.2827,0.0427 Q0.3068,0.0469,0.3124,0.0502 Q0.3157,0.0523,0.3237,0.0523 L0.3277,0.0523 L0.3309,0.0523 Q0.3398,0.0523,0.3398,0.0556 Q0.3398,0.0581,0.3341,0.0587 T0.3205,0.0593 T0.3092,0.0603 T0.3036,0.0643 T0.2932,0.068 Q0.2884,0.0684,0.2843,0.0684 Q0.2811,0.0684,0.2763,0.0678 T0.2667,0.0672 Q0.2586,0.0672,0.2422,0.0697 T0.2177,0.0747 Q0.2137,0.0759,0.1831,0.0767 T0.1494,0.0784 L0.1474,0.0784 T0.1398,0.078 T0.1285,0.0776 Q0.1173,0.0776,0.1084,0.08 Q0.1004,0.0817,0.1004,0.0846 Q0.1004,0.0867,0.104,0.0888 T0.1124,0.0923 T0.1213,0.0948 T0.1269,0.0958 T0.155,0.1014 T0.1863,0.107 Q0.2016,0.107,0.2185,0.1107 Q0.2217,0.1116,0.2257,0.1116 Q0.2289,0.1116,0.2365,0.1099 T0.2482,0.1074 L0.2538,0.1074 Q0.2683,0.1074,0.2912,0.1107 T0.3197,0.1182 Q0.3245,0.1215,0.3301,0.1215 Q0.3333,0.1215,0.3454,0.1184 T0.3687,0.1145 Q0.3735,0.1141,0.3779,0.1139 T0.3843,0.1134 T0.3871,0.1132 Q0.3896,0.1132,0.39,0.1136 T0.392,0.1161 T0.3968,0.1203 Q0.404,0.1248,0.408,0.1248 Q0.4096,0.1248,0.4165,0.1234 T0.4305,0.1215 L0.4337,0.1215 Q0.4442,0.1215,0.4518,0.1251 T0.4659,0.1294 Q0.4876,0.1319,0.5116,0.1319 T0.5622,0.141 Q0.5703,0.1439,0.5751,0.1439 Q0.5791,0.1439,0.5831,0.1423 T0.5888,0.1406 Q0.592,0.1406,0.5944,0.1412 T0.6012,0.1427 T0.6129,0.1435 Q0.6313,0.1435,0.649,0.1497 Q0.6602,0.1535,0.6667,0.1535 Q0.6715,0.1535,0.6779,0.1522 Q0.6787,0.1518,0.6795,0.1518 Q0.6827,0.1518,0.6847,0.1541 T0.6867,0.1593 Q0.6867,0.1618,0.6851,0.1634 Q0.6835,0.1655,0.6775,0.1667 T0.6598,0.169 T0.6458,0.1705 T0.6402,0.1709 Q0.6378,0.1709,0.6321,0.1705 T0.6225,0.1701 Q0.6096,0.1701,0.5968,0.1738 Q0.5823,0.1779,0.5446,0.1779 Q0.5205,0.1779,0.5116,0.1767 Q0.51,0.1763,0.5084,0.1763 Q0.5028,0.1763,0.4944,0.1796 T0.4835,0.1829 L0.4771,0.1833 T0.4659,0.1844 L0.4546,0.1858 T0.443,0.1881 T0.4337,0.1912 Q0.4321,0.1916,0.4305,0.1916 Q0.4273,0.1916,0.4209,0.1895 T0.412,0.1875 Q0.408,0.1875,0.4056,0.19 Q0.4024,0.1925,0.388,0.1925 Q0.3663,0.1925,0.3558,0.1879 Q0.3518,0.1862,0.3462,0.1862 Q0.3373,0.1862,0.3213,0.191 T0.3012,0.1962 Q0.2964,0.1966,0.2799,0.1976 T0.2494,0.1997 T0.2313,0.2024 L0.2313,0.2024 L0.2293,0.2024 L0.2261,0.2024 L0.2217,0.2024 Q0.204,0.2024,0.1851,0.2047 T0.1526,0.2136 Q0.1406,0.2198,0.1406,0.226 Q0.1406,0.2319,0.1518,0.2362 T0.1719,0.2406 Q0.1791,0.2406,0.2466,0.2497 Q0.2498,0.2501,0.2574,0.2516 T0.2711,0.2538 T0.2819,0.2547 L0.2851,0.2547 Q0.2851,0.2543,0.2859,0.2543 Q0.294,0.2543,0.3096,0.2592 T0.3285,0.2684 Q0.3317,0.2721,0.3373,0.2721 Q0.3406,0.2721,0.3462,0.2708 T0.3542,0.2696 Q0.3558,0.2696,0.3574,0.27 Q0.3679,0.2737,0.3968,0.2762 Q0.3984,0.2766,0.4004,0.2779 L0.4044,0.2804 T0.4096,0.2816 Q0.412,0.2816,0.4145,0.2808 Q0.4177,0.2804,0.4249,0.2804 Q0.4586,0.2804,0.4763,0.287 Q0.4867,0.2912,0.4972,0.2912 Q0.5004,0.2912,0.5064,0.2908 T0.5165,0.2903 Q0.5293,0.2903,0.5361,0.2922 T0.547,0.3003 L0.547,0.3011 Q0.547,0.3036,0.5414,0.3049 T0.5249,0.3067 T0.51,0.3082 Q0.5092,0.3082,0.4831,0.3111 T0.4498,0.3161 Q0.408,0.3264,0.3952,0.3264 Q0.3896,0.3264,0.3863,0.3252 Q0.3783,0.3223,0.3703,0.3223 Q0.359,0.3223,0.3494,0.3277 Q0.347,0.3293,0.343,0.3293 Q0.3414,0.3293,0.3353,0.3285 T0.3253,0.3277 T0.3181,0.3285 Q0.3149,0.3289,0.2952,0.3306 T0.2699,0.3347 Q0.2675,0.3364,0.2598,0.3372 T0.2434,0.3395 T0.2297,0.3426 L0.2205,0.3461 T0.2048,0.3523 T0.1908,0.3606 T0.1791,0.3725 Q0.1743,0.3803,0.1743,0.3845 Q0.1743,0.3874,0.1763,0.3901 T0.1827,0.3976 T0.1912,0.4073 T0.198,0.4189 T0.2032,0.4276 T0.2137,0.4326 T0.2386,0.438 Q0.2458,0.4392,0.2562,0.4392 L0.2639,0.4392 L0.2699,0.4392 Q0.2795,0.4392,0.2843,0.4405 Q0.2932,0.443,0.3092,0.443 L0.3157,0.443 L0.3213,0.443 Q0.3293,0.443,0.3458,0.4463 T0.3671,0.4525 Q0.3598,0.4558,0.3373,0.4571 Q0.3124,0.4587,0.298,0.4637 Q0.294,0.465,0.2811,0.465 L0.2703,0.465 L0.2586,0.465 Q0.241,0.465,0.2305,0.4666 Q0.2185,0.4687,0.2185,0.4728 Q0.2185,0.4745,0.2205,0.4764 T0.2241,0.4791 L0.2265,0.4803 L0.2273,0.4803 Q0.2506,0.4824,0.261,0.4824 Q0.2675,0.4824,0.2699,0.482 Q0.2699,0.4815,0.2707,0.4815 Q0.2771,0.4815,0.3124,0.4898 Q0.3173,0.4907,0.3229,0.4913 T0.3386,0.4925 T0.3542,0.4936 T0.3663,0.494 Q0.3711,0.494,0.3787,0.4936 T0.3888,0.4932 Q0.392,0.4932,0.3944,0.4936 T0.4032,0.4959 T0.4181,0.499 T0.4369,0.5006 Q0.449,0.501,0.455,0.5021 T0.4639,0.5048 T0.4675,0.5093 L0.4675,0.5097 Q0.4675,0.5106,0.4663,0.511 T0.4622,0.5116 L0.4566,0.512 T0.4486,0.5124 T0.4402,0.5127 Q0.4345,0.5131,0.4257,0.5153 T0.4096,0.5176 Q0.4064,0.5176,0.4024,0.5172 L0.3968,0.5172 Q0.3863,0.5172,0.3731,0.522 T0.359,0.5268 Q0.355,0.528,0.3317,0.5321 T0.3004,0.5388 Q0.2867,0.5433,0.2337,0.5479 Q0.2096,0.55,0.2096,0.5562 Q0.2096,0.5591,0.2145,0.5628 Q0.2193,0.5662,0.2289,0.5662 Q0.2313,0.5662,0.2373,0.5657 T0.2458,0.5653 L0.2498,0.5653 Q0.2635,0.5674,0.3124,0.5674 Q0.3261,0.5674,0.3301,0.567 L0.3317,0.567 Q0.3341,0.567,0.3394,0.568 T0.3486,0.5691 Q0.3542,0.5691,0.3606,0.5678 T0.3699,0.5666 T0.3759,0.5686 T0.3839,0.5718 T0.3908,0.573 T0.3964,0.5734 T0.4048,0.5742 T0.4165,0.5751 T0.4277,0.5757 T0.4369,0.5778 Q0.4426,0.5794,0.4538,0.5794 Q0.4586,0.5794,0.4679,0.5792 T0.4811,0.579 Q0.4924,0.579,0.4956,0.5807 Q0.502,0.584,0.5108,0.584 L0.5137,0.584 T0.5173,0.5838 L0.5205,0.5834 L0.5237,0.583 L0.5269,0.5825 T0.5305,0.5821 T0.5341,0.5819 L0.5365,0.5819 Q0.5414,0.5819,0.5562,0.5842 T0.5855,0.5865 Q0.5912,0.5865,0.5948,0.5867 T0.6012,0.5869 T0.6064,0.5873 T0.61,0.5877 T0.6133,0.5886 T0.6157,0.5896 L0.6185,0.591 T0.6217,0.5931 Q0.6265,0.5952,0.6369,0.5952 L0.6418,0.5952 L0.6466,0.5952 Q0.6723,0.5952,0.6932,0.606 Q0.698,0.608,0.7044,0.608 Q0.7084,0.608,0.7161,0.6068 T0.7261,0.6056 Q0.7309,0.6056,0.7454,0.6051 T0.7647,0.6047 Q0.7775,0.6047,0.8072,0.6101 Q0.8096,0.6105,0.812,0.6105 Q0.8177,0.6105,0.8297,0.6085 T0.8474,0.606 L0.8506,0.606 Q0.8562,0.606,0.8647,0.607 T0.8831,0.6095 T0.8964,0.6118 Q0.9036,0.6122,0.9221,0.6122 L0.9406,0.6122 L0.959,0.6122 L0.9767,0.6122 Q0.9952,0.613,0.9952,0.6172 Q0.9952,0.6176,0.9944,0.6221 Q0.9936,0.6259,0.9574,0.6259 L0.955,0.6259 L0.9526,0.6259 Q0.9478,0.6259,0.9373,0.628 T0.9205,0.63 L0.9173,0.63 Q0.9133,0.6296,0.9084,0.6296 Q0.9004,0.6296,0.8715,0.6321 Q0.8233,0.6367,0.7944,0.64 Q0.7888,0.6408,0.7839,0.6408 T0.7739,0.6402 T0.7671,0.6396 Q0.7639,0.6396,0.7622,0.64 Q0.7614,0.6404,0.759,0.6404 Q0.7574,0.6404,0.749,0.6398 T0.7357,0.6392 Q0.7261,0.6392,0.7213,0.6412 Q0.7173,0.6425,0.7032,0.6437 T0.6711,0.6458 T0.6474,0.647 Q0.645,0.6474,0.6418,0.6474 Q0.6353,0.6474,0.6277,0.6454 T0.6161,0.6433 Q0.6104,0.6433,0.6072,0.6456 T0.6,0.6479 Q0.5912,0.6479,0.5486,0.6557 Q0.5422,0.657,0.5373,0.657 Q0.5349,0.657,0.5289,0.6564 T0.5173,0.6557 L0.5124,0.6557 Q0.4996,0.6562,0.4739,0.6611 Q0.4675,0.6624,0.4398,0.6645 T0.3851,0.668 T0.3558,0.6698 Q0.355,0.6698,0.3285,0.6721 T0.2948,0.6752 Q0.2892,0.6761,0.2843,0.6786 T0.2747,0.6831 T0.2618,0.6852 Q0.253,0.6852,0.2394,0.6893 T0.2141,0.6993 T0.1968,0.7105 Q0.1944,0.713,0.1944,0.7155 Q0.1944,0.7196,0.2012,0.7229 T0.2177,0.7285 T0.2281,0.7308 Q0.2321,0.7329,0.2365,0.7339 T0.245,0.7356 T0.2514,0.7366 Q0.2522,0.737,0.2554,0.7379 T0.2614,0.7393 T0.2679,0.7406 T0.2755,0.7416 T0.2835,0.742 Q0.29,0.742,0.3048,0.7428 T0.3253,0.7437 L0.3301,0.7437 L0.3333,0.7437 Q0.3341,0.7437,0.3598,0.7466 Q0.3639,0.7474,0.3671,0.7474 T0.3759,0.7466 T0.3855,0.7457 Q0.388,0.7457,0.3904,0.7462 Q0.3984,0.7466,0.4137,0.7495 T0.4349,0.7532 T0.441,0.7557 Q0.441,0.7599,0.4289,0.7619 Q0.4257,0.7628,0.4197,0.7634 T0.4072,0.7644 T0.3984,0.7652 Q0.3968,0.7652,0.3912,0.7655 T0.3811,0.7665 T0.3719,0.7694 Q0.3695,0.7702,0.3655,0.7702 T0.3546,0.7686 T0.3462,0.7665 L0.3446,0.7665 Q0.3406,0.7665,0.3293,0.769 T0.3149,0.7715 Q0.3084,0.7715,0.2952,0.7748 T0.2763,0.781 Q0.2675,0.7847,0.2554,0.7864 Q0.253,0.7864,0.2325,0.7874 T0.2024,0.7893 Q0.2008,0.7893,0.1984,0.7897 T0.1948,0.7901 T0.1916,0.7903 T0.1888,0.7908 T0.1867,0.7914 T0.1847,0.7922 L0.1831,0.793 T0.1819,0.7943 L0.1811,0.7959 T0.1799,0.7976 Q0.1791,0.7993,0.1791,0.8001 Q0.1791,0.8034,0.1831,0.8051 T0.1932,0.8078 T0.2,0.8092 Q0.2072,0.8117,0.2257,0.8117 Q0.2337,0.8117,0.2586,0.8109 L0.2635,0.8109 Q0.2707,0.8109,0.2767,0.8117 T0.2859,0.8136 T0.2936,0.8163 T0.3012,0.8187 Q0.3068,0.82,0.3277,0.8206 T0.3526,0.8237 Q0.3582,0.8266,0.3622,0.8266 Q0.3647,0.8266,0.3687,0.8258 T0.3751,0.825 Q0.396,0.825,0.404,0.8291 Q0.408,0.8316,0.4161,0.8316 Q0.4217,0.8316,0.4353,0.8295 L0.4394,0.8295 Q0.4466,0.8295,0.4659,0.8366 Q0.4699,0.8378,0.4747,0.8378 Q0.4763,0.8378,0.4807,0.8374 T0.4884,0.837 Q0.494,0.837,0.5004,0.8382 Q0.5052,0.8391,0.5124,0.8399 Q0.5221,0.8411,0.5249,0.8422 T0.5277,0.8461 Q0.5277,0.8482,0.5233,0.849 T0.5112,0.8501 T0.4996,0.8511 Q0.4964,0.8519,0.4851,0.8523 T0.4659,0.8544 Q0.4578,0.8557,0.4402,0.8557 L0.4349,0.8557 L0.4297,0.8557 L0.4209,0.8557 Q0.408,0.8565,0.3867,0.8571 T0.3614,0.8582 Q0.3317,0.8611,0.3237,0.8611 L0.3225,0.8611 L0.3213,0.8611 Q0.2972,0.8611,0.2972,0.8681 Q0.2972,0.8714,0.3008,0.8747 T0.3044,0.8805 Q0.3044,0.881,0.3036,0.8814 Q0.3012,0.8839,0.2851,0.8839 Q0.2779,0.8839,0.2739,0.883 Q0.2723,0.8826,0.2699,0.8826 T0.2643,0.8835 T0.259,0.8853 T0.2542,0.8876 T0.249,0.8893 Q0.2386,0.8922,0.2056,0.8946 Q0.2016,0.8951,0.1916,0.898 T0.1703,0.9009 Q0.1518,0.9009,0.1337,0.9044 T0.1149,0.9146 L0.1149,0.9158 Q0.1149,0.9175,0.1157,0.9187 T0.1173,0.921 T0.1201,0.9226 T0.1233,0.9237 T0.1269,0.9245 L0.1305,0.9251 T0.1337,0.9255 L0.1357,0.9258 Q0.139,0.9262,0.1446,0.9262 T0.1542,0.9266 T0.1598,0.9282 Q0.1614,0.9303,0.1647,0.9314 T0.1739,0.9328 T0.1815,0.9336 Q0.1863,0.9345,0.1976,0.9372 T0.2145,0.9415 Q0.2225,0.9432,0.2285,0.9467 T0.2378,0.9515 Q0.2426,0.9531,0.2514,0.9531 Q0.2538,0.9531,0.2602,0.9529 T0.2707,0.9527 Q0.2763,0.9527,0.2815,0.9531 T0.2867,0.9569 T0.2811,0.9614 Q0.2434,0.9627,0.2329,0.9652 Q0.2249,0.9672,0.2241,0.9672 L0.2096,0.9668 L0.2056,0.9668 Q0.2,0.9668,0.196,0.9672 T0.1884,0.9687 T0.1815,0.9708 T0.1731,0.9737 T0.1639,0.9772 Q0.1518,0.9805,0.1285,0.9805 L0.1253,0.9805 Q0.1124,0.9805,0.1076,0.9818 Q0.1012,0.983,0.0831,0.9876 T0.0594,0.9934 Q0.049,0.9954,0.0064,0.9954 Z M0.0032,0.9979 L0.0024,0.0037 Q0.0161,0.0021,0.0289,0.0062 Q0.0337,0.0075,0.0671,0.0066 T0.1116,0.01 T0.1337,0.0166 T0.151,0.022 Q0.1582,0.0249,0.1659,0.0251 T0.1767,0.0265 Q0.1807,0.0278,0.2,0.0292 T0.2265,0.0328 Q0.2305,0.034,0.2329,0.034 T0.239,0.0326 T0.2458,0.0311 T0.253,0.0319 Q0.2578,0.0332,0.2614,0.0342 T0.2667,0.0363 T0.2723,0.0384 T0.2827,0.0406 Q0.3084,0.0448,0.3141,0.0485 Q0.3149,0.0494,0.3225,0.0494 T0.3361,0.0504 T0.3422,0.0554 T0.3357,0.0606 T0.3205,0.0618 T0.31,0.0626 Q0.3092,0.0626,0.3056,0.0659 T0.2932,0.0701 Q0.2884,0.0709,0.2843,0.0709 Q0.2811,0.0709,0.2759,0.0701 T0.2667,0.0693 Q0.2586,0.0693,0.2422,0.0718 T0.2193,0.0763 Q0.2137,0.0784,0.1831,0.079 T0.1502,0.0805 Q0.1494,0.0809,0.147,0.0809 Q0.1454,0.0809,0.1386,0.0803 T0.1277,0.0796 Q0.1173,0.0796,0.1092,0.0821 Q0.1036,0.0834,0.1036,0.0854 Q0.1036,0.0879,0.1129,0.0908 T0.1269,0.0937 Q0.1293,0.0937,0.1558,0.0991 T0.1863,0.1045 Q0.2016,0.1045,0.2193,0.1087 Q0.2225,0.1091,0.2249,0.1091 Q0.2289,0.1091,0.2357,0.1076 T0.2482,0.1054 Q0.2506,0.1049,0.2546,0.1049 Q0.2699,0.1049,0.2924,0.1085 T0.3213,0.1165 Q0.3253,0.119,0.3301,0.119 Q0.3325,0.119,0.3446,0.1161 T0.3687,0.1124 Q0.3831,0.1112,0.3863,0.1112 T0.3908,0.1118 T0.3936,0.1145 T0.3984,0.1186 Q0.4048,0.1228,0.408,0.1228 Q0.4096,0.1228,0.4161,0.1213 T0.4305,0.1195 L0.4337,0.1195 Q0.4426,0.1195,0.4474,0.1211 T0.4566,0.1246 T0.4667,0.1273 Q0.4876,0.1298,0.5116,0.1298 Q0.5365,0.1298,0.5631,0.1389 Q0.5703,0.1414,0.5751,0.1414 Q0.5783,0.1414,0.5819,0.1398 T0.5888,0.1381 Q0.5928,0.1381,0.5984,0.1398 T0.6129,0.1414 Q0.6321,0.1414,0.6498,0.1477 Q0.661,0.1514,0.6667,0.1514 Q0.6707,0.1514,0.6771,0.1501 Q0.6787,0.1497,0.6795,0.1497 Q0.6835,0.1497,0.6863,0.1526 T0.6892,0.1593 Q0.6892,0.1626,0.6876,0.1647 Q0.6851,0.1672,0.6799,0.1686 T0.6695,0.1705 T0.6566,0.1715 T0.6458,0.1725 Q0.6434,0.173,0.6402,0.173 Q0.6378,0.173,0.6317,0.1727 T0.6225,0.1725 Q0.6096,0.1725,0.5984,0.1759 Q0.5823,0.1804,0.5454,0.1804 Q0.5205,0.1804,0.5116,0.1788 L0.5084,0.1788 Q0.5036,0.1788,0.4956,0.1819 T0.4843,0.185 Q0.4434,0.1887,0.4353,0.1929 Q0.4321,0.1945,0.4289,0.1945 T0.4197,0.1922 T0.4112,0.19 T0.4072,0.1912 Q0.4032,0.1949,0.388,0.1949 Q0.3663,0.1949,0.3542,0.19 Q0.351,0.1883,0.3462,0.1883 Q0.3406,0.1883,0.3321,0.1906 T0.3153,0.1954 T0.302,0.1983 Q0.2972,0.1991,0.2859,0.1997 T0.2643,0.201 T0.245,0.2024 T0.2337,0.2041 Q0.2321,0.2045,0.2181,0.2045 T0.1851,0.207 T0.1542,0.2157 Q0.143,0.2211,0.143,0.226 Q0.143,0.2314,0.153,0.2348 T0.1719,0.2381 Q0.1791,0.2381,0.2474,0.2476 Q0.2506,0.248,0.2558,0.2489 T0.2651,0.2505 T0.2739,0.252 T0.2819,0.2526 Q0.2835,0.2526,0.2851,0.2522 L0.2859,0.2522 Q0.2948,0.2522,0.3104,0.2574 T0.3309,0.2671 Q0.3333,0.2696,0.3365,0.2696 Q0.339,0.2696,0.3442,0.2684 T0.3526,0.2671 T0.3582,0.2679 Q0.3687,0.2717,0.3968,0.2742 Q0.4,0.2746,0.4036,0.2771 T0.4096,0.2796 Q0.4112,0.2796,0.4137,0.2787 Q0.4169,0.2779,0.4257,0.2779 Q0.4594,0.2779,0.4779,0.2849 Q0.4876,0.2891,0.4972,0.2891 Q0.4996,0.2891,0.506,0.2887 T0.5165,0.2883 Q0.5253,0.2883,0.5305,0.2889 T0.541,0.292 T0.5494,0.299 L0.5494,0.3015 Q0.5494,0.3036,0.5466,0.3051 T0.5386,0.3073 T0.5285,0.3086 T0.5181,0.3094 T0.5108,0.3102 Q0.5068,0.3107,0.494,0.3121 L0.4683,0.315 T0.4506,0.3181 Q0.449,0.3181,0.4426,0.32 T0.4313,0.3229 T0.4197,0.3256 T0.4064,0.3281 T0.3952,0.3289 Q0.3888,0.3289,0.3855,0.3273 Q0.3783,0.3243,0.3703,0.3243 Q0.3598,0.3243,0.351,0.3297 Q0.3478,0.3314,0.3422,0.3314 Q0.3398,0.3314,0.3337,0.3306 T0.3245,0.3297 T0.3189,0.3306 Q0.3149,0.3314,0.2956,0.3328 T0.2715,0.3368 Q0.2691,0.338,0.2635,0.3391 T0.2522,0.3407 T0.2406,0.3424 T0.2313,0.3447 Q0.2305,0.3447,0.2213,0.348 T0.206,0.354 T0.1924,0.3621 T0.1815,0.3733 Q0.1767,0.3816,0.1767,0.3849 Q0.1767,0.387,0.1783,0.3893 T0.1847,0.3961 T0.1936,0.4063 T0.2004,0.4181 T0.2052,0.4264 T0.2145,0.4309 T0.2386,0.4359 Q0.2458,0.4372,0.2554,0.4372 Q0.2578,0.4372,0.2627,0.437 T0.2699,0.4367 Q0.2795,0.4367,0.2851,0.4384 Q0.294,0.4409,0.3092,0.4409 Q0.3116,0.4409,0.3157,0.4407 T0.3213,0.4405 Q0.3301,0.4405,0.3466,0.444 T0.3687,0.4509 Q0.3703,0.4517,0.3703,0.4525 Q0.3703,0.4575,0.3373,0.4596 Q0.3133,0.4608,0.2988,0.4658 Q0.294,0.4674,0.2803,0.4674 Q0.2763,0.4674,0.2687,0.4672 T0.257,0.467 Q0.2402,0.467,0.2313,0.4687 Q0.2209,0.4708,0.2209,0.4737 Q0.2209,0.4741,0.2213,0.4749 T0.2229,0.4764 L0.2249,0.4774 T0.2265,0.4778 L0.2273,0.4782 Q0.2498,0.4803,0.2618,0.4803 Q0.2667,0.4803,0.2691,0.4799 Q0.2699,0.4795,0.2715,0.4795 Q0.2779,0.4795,0.3133,0.4873 Q0.3181,0.4886,0.3233,0.4892 T0.3386,0.4905 T0.3542,0.4915 T0.3655,0.4919 Q0.3703,0.4919,0.3779,0.4915 T0.3888,0.4911 T0.3952,0.4915 Q0.3976,0.4919,0.4008,0.4927 L0.4072,0.4944 T0.4149,0.4961 T0.4249,0.4975 T0.4369,0.4985 Q0.449,0.499,0.4554,0.5 T0.4651,0.5031 T0.4699,0.5085 Q0.4707,0.5093,0.4707,0.5097 Q0.4707,0.5114,0.4687,0.5124 T0.4631,0.5139 T0.4562,0.5145 T0.4478,0.5147 L0.4402,0.5147 Q0.4353,0.5151,0.4265,0.5174 T0.4096,0.5197 L0.4024,0.5197 Q0.4,0.5193,0.3968,0.5193 Q0.3896,0.5193,0.3831,0.5209 T0.3703,0.5253 T0.3598,0.5288 Q0.3558,0.5301,0.3321,0.5342 T0.302,0.5409 Q0.2876,0.5454,0.2337,0.55 Q0.2112,0.5521,0.2112,0.5558 Q0.2112,0.5574,0.2161,0.5612 Q0.2201,0.5637,0.2281,0.5637 Q0.2305,0.5637,0.2361,0.5633 T0.2442,0.5628 Q0.2474,0.5628,0.2498,0.5633 Q0.2635,0.5653,0.3133,0.5653 Q0.3261,0.5653,0.3301,0.5649 L0.3325,0.5649 Q0.3349,0.5649,0.3402,0.5657 T0.3494,0.5666 Q0.3542,0.5666,0.3598,0.5657 Q0.3663,0.5645,0.3695,0.5645 Q0.3735,0.5645,0.3775,0.5666 T0.3847,0.5695 Q0.3888,0.5707,0.3912,0.5709 T0.3968,0.5711 T0.4048,0.572 Q0.4096,0.5724,0.4165,0.5726 T0.4281,0.5734 T0.4378,0.5757 Q0.4418,0.5774,0.4522,0.5774 Q0.4562,0.5774,0.4655,0.5769 T0.4795,0.5765 Q0.4932,0.5765,0.4972,0.579 Q0.5028,0.5819,0.51,0.5819 Q0.5141,0.5819,0.5221,0.5809 T0.5341,0.5798 L0.5373,0.5798 Q0.5422,0.5798,0.557,0.5821 T0.5855,0.5844 L0.5936,0.5844 L0.5992,0.5844 T0.604,0.5848 T0.6076,0.5852 T0.6108,0.5859 T0.6137,0.5865 T0.6161,0.5873 T0.6181,0.5881 T0.6209,0.5896 L0.6233,0.591 Q0.6265,0.5927,0.6353,0.5927 L0.6402,0.5927 L0.645,0.5927 Q0.6723,0.5927,0.6948,0.6039 Q0.6988,0.606,0.7036,0.606 Q0.7076,0.606,0.7153,0.6045 T0.7261,0.6031 Q0.7309,0.6031,0.7454,0.6027 T0.7647,0.6022 Q0.7783,0.6022,0.808,0.608 L0.812,0.608 Q0.8169,0.608,0.8293,0.6062 T0.8474,0.6039 L0.8506,0.6039 Q0.857,0.6039,0.8655,0.6049 T0.8835,0.6074 T0.8972,0.6093 Q0.9036,0.6101,0.9213,0.6101 L0.9398,0.6101 L0.959,0.6101 L0.9767,0.6101 Q0.9976,0.6109,0.9976,0.6176 Q0.9976,0.6188,0.9968,0.6226 Q0.9952,0.6284,0.9671,0.6284 L0.959,0.6284 L0.9526,0.6284 Q0.9486,0.6284,0.9382,0.6302 T0.9205,0.6321 L0.9173,0.6321 Q0.9133,0.6317,0.9092,0.6317 Q0.9012,0.6317,0.8715,0.6346 Q0.8233,0.6387,0.7944,0.6421 Q0.7888,0.6429,0.7831,0.6429 Q0.7783,0.6429,0.7731,0.6425 T0.7663,0.6421 L0.7622,0.6421 Q0.7614,0.6425,0.7586,0.6425 T0.7474,0.6421 T0.7349,0.6416 Q0.7261,0.6416,0.7221,0.6429 Q0.7173,0.645,0.7032,0.646 T0.6711,0.6479 T0.6482,0.6491 Q0.645,0.6495,0.6418,0.6495 Q0.6353,0.6495,0.6273,0.6474 T0.6161,0.6454 Q0.612,0.6454,0.6088,0.6477 T0.6,0.6499 Q0.5912,0.6499,0.5494,0.6578 Q0.5422,0.6591,0.5373,0.6591 Q0.5341,0.6591,0.5281,0.6584 T0.5173,0.6578 L0.5124,0.6578 Q0.5004,0.6582,0.4747,0.6632 Q0.4675,0.6649,0.4398,0.6667 T0.3851,0.6703 T0.3566,0.6719 Q0.3534,0.6723,0.3406,0.6734 T0.3141,0.6757 T0.2948,0.6773 Q0.2908,0.6781,0.2819,0.6829 T0.2618,0.6877 Q0.2482,0.6877,0.2273,0.6958 T0.1992,0.7117 Q0.1976,0.7138,0.1976,0.7155 Q0.1976,0.7188,0.2032,0.7213 T0.2181,0.7258 T0.2289,0.7292 Q0.2337,0.7308,0.2378,0.7316 L0.2458,0.7333 T0.2522,0.7345 Q0.2747,0.7399,0.2835,0.7399 Q0.29,0.7399,0.3048,0.7408 T0.3253,0.7416 Q0.3277,0.7416,0.3297,0.7414 T0.3341,0.7412 L0.3598,0.7445 Q0.3639,0.7449,0.3663,0.7449 Q0.3695,0.7449,0.3751,0.7443 T0.3855,0.7437 L0.3904,0.7437 Q0.3984,0.7441,0.4141,0.7472 T0.4353,0.7507 Q0.4434,0.752,0.4434,0.7553 Q0.4434,0.7578,0.439,0.7605 T0.4297,0.764 Q0.4257,0.7648,0.4201,0.7655 T0.4076,0.7665 T0.3984,0.7673 Q0.3968,0.7673,0.3912,0.7677 T0.3815,0.7688 T0.3735,0.771 T0.3655,0.7727 Q0.3606,0.7727,0.3534,0.7708 T0.3458,0.769 L0.3446,0.769 Q0.3414,0.769,0.3297,0.7713 T0.3149,0.7735 Q0.3092,0.7735,0.296,0.7771 T0.2771,0.7831 Q0.2683,0.7872,0.2554,0.7885 Q0.253,0.7889,0.2325,0.7897 T0.2032,0.7914 Q0.2008,0.7918,0.198,0.792 T0.194,0.7924 T0.1912,0.7928 T0.1888,0.793 T0.1867,0.7934 T0.1851,0.7943 T0.1843,0.7953 T0.1835,0.7968 T0.1823,0.7984 T0.1815,0.8001 Q0.1815,0.8022,0.1847,0.8032 T0.1932,0.8053 T0.2008,0.8071 Q0.2072,0.8092,0.2265,0.8092 Q0.2361,0.8092,0.2586,0.8088 L0.2635,0.8088 Q0.2731,0.8088,0.2795,0.8098 T0.2928,0.8134 T0.302,0.8167 Q0.306,0.8179,0.3277,0.8183 T0.3542,0.8221 Q0.359,0.8246,0.3622,0.8246 Q0.3639,0.8246,0.3675,0.8237 T0.3751,0.8229 Q0.3968,0.8229,0.4048,0.8275 Q0.4088,0.8291,0.4161,0.8291 Q0.4225,0.8291,0.4353,0.8275 Q0.4369,0.827,0.4394,0.827 Q0.4474,0.827,0.4675,0.8345 Q0.4707,0.8358,0.4739,0.8358 Q0.4755,0.8358,0.4799,0.8353 T0.4876,0.8349 Q0.494,0.8349,0.5012,0.8362 L0.5076,0.837 T0.5133,0.8376 T0.5181,0.8382 T0.5221,0.8391 L0.5253,0.8399 T0.5277,0.8409 L0.5293,0.8422 T0.5301,0.8438 L0.5301,0.8461 Q0.5301,0.8499,0.5249,0.8511 T0.5112,0.8526 T0.5004,0.8532 Q0.4964,0.854,0.4851,0.8546 T0.4667,0.8565 Q0.4578,0.8577,0.441,0.8577 L0.4345,0.8577 L0.4289,0.8577 L0.4209,0.8577 Q0.4153,0.8582,0.4088,0.8586 T0.3968,0.8592 T0.3855,0.8594 T0.3755,0.8596 T0.3675,0.86 T0.3622,0.8602 Q0.3317,0.8635,0.3237,0.8635 Q0.2996,0.8635,0.2996,0.8681 Q0.2996,0.8698,0.3032,0.8733 T0.3068,0.8797 L0.3068,0.8822 Q0.3052,0.8859,0.2859,0.8859 Q0.2787,0.8859,0.2739,0.8851 L0.2699,0.8851 Q0.2659,0.8851,0.259,0.888 T0.2498,0.8913 Q0.2394,0.8946,0.2056,0.8971 Q0.2032,0.8971,0.1928,0.9002 T0.1703,0.9034 Q0.1526,0.9034,0.1353,0.9067 T0.1173,0.915 L0.1173,0.9158 Q0.1173,0.9166,0.1177,0.9175 T0.1189,0.9191 T0.1205,0.9204 T0.1229,0.9212 T0.1257,0.922 T0.1285,0.9226 T0.1309,0.9231 T0.1337,0.9235 T0.1365,0.9237 L0.1446,0.9237 T0.1554,0.9243 T0.1614,0.9268 T0.1659,0.9293 T0.1743,0.9303 T0.1823,0.9316 Q0.1863,0.932,0.1912,0.9332 T0.2028,0.9361 T0.2153,0.939 Q0.2233,0.9411,0.2297,0.9448 T0.2386,0.9494 Q0.2426,0.9506,0.2506,0.9506 Q0.253,0.9506,0.2594,0.9504 T0.2699,0.9502 Q0.2763,0.9502,0.2819,0.9511 Q0.2851,0.9511,0.2871,0.9529 T0.2892,0.9573 Q0.2892,0.9627,0.2811,0.9635 Q0.2434,0.9652,0.2337,0.9672 Q0.2257,0.9693,0.2241,0.9693 Q0.2217,0.9693,0.2096,0.9689 L0.2056,0.9689 Q0.1976,0.9689,0.1924,0.9699 T0.1787,0.9741 L0.1647,0.9793 Q0.1518,0.983,0.1285,0.983 L0.1261,0.983 L0.1237,0.983 Q0.1124,0.983,0.1076,0.9838 Q0.102,0.9851,0.0839,0.9896 T0.0602,0.9954 T0.0406,0.9971 T0.0153,0.9979 L0.0032,0.9979 Z",type:0}},"":{type:5,data:{d:"M0.9992,0.998 Q0.9992,1,0.9968,1 Q0.9521,1,0.9392,0.998 Q0.9335,0.997,0.9152,0.9921 T0.8913,0.9862 Q0.8873,0.9852,0.8783,0.9852 L0.8747,0.9852 L0.871,0.9852 Q0.8483,0.9852,0.8345,0.9812 Q0.8289,0.9792,0.8228,0.9773 T0.8135,0.9743 T0.8054,0.9723 T0.7948,0.9713 L0.7908,0.9713 L0.777,0.9713 T0.7656,0.9693 Q0.7616,0.9683,0.7498,0.9674 T0.7283,0.9664 L0.7186,0.9654 Q0.708,0.9644,0.708,0.9575 Q0.708,0.9545,0.7109,0.952 T0.7178,0.9486 L0.7315,0.9486 L0.7417,0.9486 L0.7502,0.9486 Q0.7575,0.9486,0.7599,0.9476 Q0.7616,0.9466,0.7685,0.9426 T0.7843,0.9377 Q0.7899,0.9357,0.8009,0.9332 T0.8175,0.9298 Q0.82,0.9288,0.8228,0.9283 T0.8277,0.9278 T0.8313,0.9273 T0.8341,0.9263 T0.8362,0.9258 Q0.8402,0.9219,0.854,0.9219 L0.8569,0.9219 L0.8597,0.9219 L0.8637,0.9219 Q0.88,0.9199,0.88,0.9159 L0.88,0.9149 Q0.88,0.913,0.8719,0.911 T0.852,0.9075 T0.8297,0.906 Q0.8224,0.906,0.8167,0.905 T0.8074,0.9031 T0.8001,0.9006 T0.794,0.8991 Q0.7599,0.8971,0.7494,0.8942 Q0.7461,0.8932,0.7397,0.8902 T0.7299,0.8872 L0.7267,0.8872 Q0.721,0.8882,0.7121,0.8882 Q0.6926,0.8882,0.691,0.8833 L0.691,0.8803 Q0.691,0.8773,0.6922,0.8749 T0.6955,0.8704 L0.6975,0.8684 Q0.6926,0.8655,0.6764,0.8655 Q0.6683,0.8655,0.6375,0.8625 Q0.6358,0.8625,0.629,0.862 T0.6148,0.8615 T0.5973,0.861 T0.5791,0.8605 L0.5718,0.8605 L0.5661,0.8605 L0.5596,0.8605 Q0.5426,0.8605,0.5337,0.8586 Q0.5264,0.8576,0.515,0.8571 T0.4996,0.8556 Q0.498,0.8556,0.4947,0.8551 T0.4882,0.8546 T0.4809,0.8541 T0.474,0.8531 T0.4692,0.8506 T0.4672,0.8467 Q0.4672,0.8437,0.468,0.8422 T0.4704,0.8398 T0.4736,0.8383 T0.4781,0.8368 T0.4838,0.8358 T0.4911,0.8353 T0.4988,0.8338 Q0.5069,0.8328,0.5142,0.8328 Q0.5174,0.8328,0.5215,0.8333 T0.5264,0.8338 Q0.5296,0.8338,0.532,0.8328 Q0.5523,0.8249,0.5604,0.8249 L0.5653,0.8249 Q0.5775,0.8269,0.5848,0.8269 Q0.5912,0.8269,0.5937,0.8259 Q0.6026,0.821,0.6253,0.821 Q0.6294,0.821,0.6334,0.822 T0.6383,0.8229 Q0.6399,0.8229,0.644,0.82 Q0.6504,0.817,0.6723,0.816 T0.6975,0.814 Q0.6999,0.814,0.7048,0.8121 T0.7129,0.8091 T0.7226,0.8071 T0.7372,0.8061 L0.7421,0.8061 Q0.7624,0.8071,0.7721,0.8071 Q0.7924,0.8071,0.7981,0.8051 Q0.8021,0.8032,0.807,0.8027 T0.8135,0.8017 T0.8151,0.8002 L0.8151,0.7992 Q0.8143,0.7962,0.8127,0.7957 T0.8045,0.7943 Q0.7997,0.7943,0.7964,0.7933 Q0.7883,0.7933,0.7676,0.7923 T0.7437,0.7903 Q0.7307,0.7893,0.7218,0.7844 Q0.7194,0.7834,0.7141,0.7819 L0.7036,0.7789 T0.693,0.7765 T0.6853,0.7755 Q0.6805,0.7755,0.6691,0.773 T0.6553,0.7705 Q0.6545,0.7705,0.6545,0.7715 Q0.6537,0.7715,0.65,0.7725 T0.6423,0.774 T0.635,0.7745 Q0.6294,0.7745,0.6257,0.773 T0.618,0.771 T0.6083,0.77 T0.601,0.7695 Q0.5985,0.7695,0.5921,0.769 T0.5795,0.7676 T0.5702,0.7666 Q0.5653,0.7656,0.5596,0.7616 T0.5539,0.7547 Q0.5539,0.7498,0.5645,0.7488 Q0.5693,0.7478,0.5852,0.7448 T0.6099,0.7418 L0.6148,0.7418 Q0.6196,0.7418,0.6253,0.7423 T0.6338,0.7428 L0.6399,0.7428 Q0.6431,0.7418,0.6488,0.7409 T0.6586,0.7394 T0.6659,0.7389 L0.6707,0.7389 Q0.6723,0.7399,0.6748,0.7399 Q0.6796,0.7399,0.6946,0.7389 T0.7161,0.7379 Q0.7251,0.7379,0.7478,0.7319 Q0.7494,0.7319,0.7539,0.7315 T0.762,0.73 T0.7697,0.727 T0.7818,0.723 T0.7948,0.7196 T0.7997,0.7151 Q0.7997,0.7141,0.7989,0.7132 Q0.7924,0.7062,0.7717,0.6978 T0.738,0.6894 Q0.7267,0.6894,0.717,0.6845 T0.7048,0.6795 Q0.6975,0.6785,0.6711,0.6766 T0.6431,0.6746 Q0.6415,0.6736,0.6144,0.6721 T0.5596,0.6686 T0.5247,0.6657 Q0.4996,0.6607,0.4874,0.6597 L0.4834,0.6597 Q0.4785,0.6597,0.4724,0.6607 T0.4631,0.6617 Q0.4574,0.6617,0.4501,0.6597 Q0.4088,0.6518,0.4006,0.6518 Q0.3933,0.6518,0.3901,0.6499 T0.3844,0.6479 T0.3739,0.6499 T0.3585,0.6518 L0.352,0.6518 Q0.3471,0.6508,0.335,0.6503 T0.3122,0.6494 T0.2912,0.6479 T0.2766,0.6449 Q0.2733,0.6439,0.2668,0.6439 Q0.2628,0.6439,0.2543,0.6444 T0.2425,0.6449 T0.2368,0.6439 L0.2344,0.6439 Q0.2336,0.6439,0.2283,0.6444 T0.2182,0.6449 Q0.2117,0.6449,0.2052,0.6439 Q0.1768,0.6409,0.1281,0.637 Q0.0989,0.634,0.0916,0.634 L0.0835,0.634 L0.0795,0.634 Q0.0722,0.634,0.0616,0.632 T0.0479,0.6301 Q0.0462,0.6301,0.0406,0.6306 T0.0308,0.6311 Q0.0032,0.6311,0.0008,0.6231 Q0,0.6202,0,0.6182 Q0,0.6083,0.0227,0.6083 Q0.03,0.6073,0.0422,0.6073 Q0.0487,0.6073,0.0608,0.6078 T0.0787,0.6083 Q0.0973,0.6083,0.103,0.6073 Q0.1062,0.6063,0.1131,0.6053 T0.1253,0.6039 T0.1375,0.6024 T0.1492,0.6014 L0.1533,0.6014 Q0.1598,0.6024,0.1723,0.6044 T0.189,0.6063 Q0.1906,0.6063,0.1922,0.6053 Q0.2214,0.6004,0.236,0.6004 Q0.2409,0.6004,0.2551,0.6009 T0.2741,0.6014 Q0.2782,0.6014,0.2859,0.6024 T0.2968,0.6034 Q0.3009,0.6034,0.3041,0.6024 Q0.3277,0.5905,0.356,0.5905 L0.3613,0.5905 L0.3666,0.5905 Q0.3731,0.5905,0.3755,0.5895 Q0.382,0.5856,0.3844,0.5846 T0.3938,0.5831 T0.4144,0.5826 T0.4428,0.5801 T0.4631,0.5776 L0.4663,0.5776 Q0.4704,0.5776,0.4785,0.5786 T0.4899,0.5796 Q0.4964,0.5796,0.5012,0.5767 Q0.5069,0.5737,0.5223,0.5737 Q0.5272,0.5737,0.5369,0.5742 T0.5499,0.5747 Q0.558,0.5747,0.5612,0.5737 Q0.5661,0.5717,0.5714,0.5712 T0.5835,0.5702 T0.5945,0.5692 T0.6018,0.5687 L0.6062,0.5687 T0.6095,0.5682 T0.6148,0.5678 Q0.6172,0.5668,0.6196,0.5653 T0.6245,0.5633 T0.631,0.5628 T0.6407,0.5638 T0.6504,0.5648 T0.6594,0.5638 T0.6675,0.5628 L0.6707,0.5628 L0.6861,0.5628 Q0.7364,0.5628,0.7494,0.5608 L0.7567,0.5608 L0.7652,0.5608 L0.7729,0.5608 Q0.7794,0.5608,0.7818,0.5589 Q0.7851,0.5569,0.7859,0.5559 Q0.7835,0.5539,0.7656,0.5519 Q0.7121,0.547,0.6975,0.543 Q0.6934,0.541,0.6853,0.5396 L0.6691,0.5366 T0.6525,0.5336 T0.6391,0.5312 Q0.6367,0.5302,0.6245,0.5257 T0.6034,0.5213 L0.5977,0.5213 Q0.5945,0.5223,0.5904,0.5223 Q0.5839,0.5223,0.5787,0.5208 T0.5685,0.5183 T0.5596,0.5173 Q0.558,0.5173,0.5552,0.5168 T0.5495,0.5163 L0.5434,0.5163 T0.5373,0.5158 T0.532,0.5148 T0.5284,0.5129 T0.5272,0.5104 L0.5272,0.5074 Q0.5304,0.5015,0.5377,0.499 T0.5629,0.4965 Q0.5734,0.4955,0.5811,0.4946 T0.5953,0.4916 T0.605,0.4896 Q0.6083,0.4886,0.6123,0.4886 Q0.6148,0.4886,0.6225,0.4891 T0.635,0.4896 L0.6456,0.4896 Q0.6837,0.4857,0.6861,0.4857 Q0.7226,0.4768,0.7283,0.4768 Q0.7307,0.4768,0.732,0.4773 T0.7372,0.4777 Q0.7502,0.4777,0.7721,0.4758 Q0.7753,0.4748,0.777,0.4738 Q0.7745,0.4718,0.768,0.4708 Q0.7599,0.4688,0.7445,0.4688 Q0.7405,0.4688,0.7324,0.4693 T0.721,0.4698 Q0.7056,0.4698,0.6999,0.4679 Q0.6861,0.4629,0.6626,0.4619 Q0.6586,0.4609,0.6533,0.4604 T0.6419,0.459 T0.6314,0.456 T0.6269,0.452 Q0.6269,0.451,0.6302,0.4491 Q0.6358,0.4451,0.6525,0.4416 T0.6788,0.4382 L0.6845,0.4382 L0.6902,0.4382 Q0.7064,0.4382,0.7145,0.4362 Q0.7202,0.4342,0.7307,0.4342 L0.7356,0.4342 L0.7409,0.4342 L0.7453,0.4342 Q0.7543,0.4342,0.7607,0.4332 Q0.7778,0.4313,0.7847,0.4288 T0.7932,0.4248 T0.7972,0.4169 T0.8045,0.4045 L0.8094,0.3986 T0.8135,0.3942 L0.8167,0.3912 T0.8191,0.3887 T0.8204,0.3867 T0.8208,0.3848 Q0.8208,0.3818,0.8167,0.3739 Q0.8127,0.3689,0.8054,0.3635 T0.7924,0.3556 T0.7778,0.3497 T0.768,0.3462 Q0.764,0.3442,0.7478,0.3427 T0.7267,0.3383 Q0.7234,0.3363,0.7044,0.3348 T0.6805,0.3323 L0.6764,0.3323 T0.6679,0.3328 T0.6586,0.3333 Q0.6521,0.3333,0.648,0.3314 Q0.6391,0.3264,0.6294,0.3264 Q0.6229,0.3264,0.6156,0.3294 Q0.6115,0.3304,0.6042,0.3304 Q0.5977,0.3304,0.5888,0.3289 T0.5738,0.3264 T0.5584,0.3225 L0.5491,0.3195 Q0.5418,0.3185,0.5162,0.3155 T0.4895,0.3121 T0.4826,0.3116 T0.4716,0.3111 T0.4607,0.3096 T0.4513,0.3066 T0.4477,0.3017 Q0.4477,0.2997,0.4485,0.2977 Q0.4526,0.2898,0.4611,0.2878 T0.4842,0.2859 Q0.4882,0.2859,0.4943,0.2864 T0.5028,0.2868 Q0.5118,0.2868,0.5215,0.2829 Q0.5401,0.276,0.5734,0.276 Q0.5831,0.276,0.5872,0.277 L0.5904,0.277 T0.5949,0.2745 T0.6034,0.272 Q0.631,0.269,0.6407,0.2661 Q0.6448,0.2641,0.6488,0.2641 T0.6573,0.2656 T0.6634,0.2671 Q0.6659,0.2671,0.6675,0.2651 Q0.6723,0.2601,0.6886,0.2552 T0.7137,0.2502 L0.7153,0.2502 L0.7178,0.2502 Q0.7218,0.2502,0.7279,0.2493 T0.7417,0.2468 T0.7526,0.2453 Q0.8208,0.2354,0.8281,0.2354 Q0.8337,0.2354,0.8394,0.2344 T0.8496,0.2315 T0.854,0.2265 Q0.854,0.2216,0.8443,0.2176 Q0.8354,0.2127,0.8216,0.2102 T0.7972,0.2072 T0.777,0.2067 T0.7648,0.2057 Q0.7632,0.2047,0.7498,0.2038 T0.7202,0.2018 T0.6983,0.1998 Q0.6918,0.1998,0.676,0.1949 T0.6537,0.1899 Q0.6496,0.1899,0.6472,0.1919 Q0.6342,0.1968,0.6123,0.1968 Q0.5961,0.1968,0.5912,0.1929 Q0.5904,0.1919,0.5892,0.1919 T0.5823,0.1944 T0.5722,0.1968 T0.5637,0.1949 Q0.5556,0.1909,0.5158,0.1869 Q0.5109,0.1869,0.5032,0.1835 T0.4915,0.18 Q0.4907,0.18,0.4891,0.181 Q0.4793,0.182,0.455,0.182 Q0.4177,0.182,0.4015,0.1771 Q0.3901,0.1741,0.3779,0.1741 Q0.3747,0.1741,0.369,0.1746 T0.3609,0.1751 Q0.3569,0.1751,0.3536,0.1741 Q0.3512,0.1741,0.3459,0.1736 T0.3358,0.1726 T0.3256,0.1716 T0.3167,0.1696 T0.3106,0.1662 Q0.3082,0.1632,0.3082,0.1592 Q0.3082,0.1543,0.3114,0.1508 T0.3204,0.1474 L0.3236,0.1474 Q0.3301,0.1494,0.3333,0.1494 Q0.339,0.1494,0.3496,0.1454 Q0.3674,0.1385,0.3869,0.1385 Q0.395,0.1385,0.4011,0.137 T0.4116,0.1355 T0.4197,0.1375 T0.425,0.1395 Q0.429,0.1395,0.4355,0.1365 Q0.4631,0.1266,0.4882,0.1266 Q0.5126,0.1266,0.5337,0.1246 Q0.5369,0.1246,0.5458,0.1207 T0.5661,0.1167 L0.5693,0.1167 Q0.5791,0.1177,0.5852,0.1187 T0.5921,0.1197 Q0.5945,0.1197,0.6002,0.1167 Q0.6026,0.1147,0.605,0.1123 T0.6091,0.1093 T0.6156,0.1088 T0.6318,0.1098 Q0.6456,0.1108,0.6569,0.1137 T0.6707,0.1167 Q0.674,0.1167,0.6772,0.1147 Q0.6821,0.1108,0.6946,0.1083 T0.721,0.1044 T0.7453,0.1029 L0.7526,0.1029 Q0.7583,0.1039,0.7652,0.1053 T0.7753,0.1068 Q0.7778,0.1068,0.7802,0.1058 Q0.7981,0.1019,0.8143,0.1019 Q0.8175,0.1019,0.8439,0.0964 T0.8735,0.091 Q0.8759,0.091,0.8836,0.089 T0.8938,0.0851 Q0.8929,0.0841,0.8905,0.0841 Q0.8832,0.0821,0.8735,0.0821 Q0.8694,0.0821,0.8629,0.0826 T0.854,0.0831 Q0.8508,0.0831,0.8491,0.0821 Q0.8475,0.0821,0.8171,0.0811 T0.7802,0.0781 T0.7571,0.0737 T0.7332,0.0712 Q0.7299,0.0712,0.7247,0.0717 T0.7161,0.0722 L0.7064,0.0722 Q0.7032,0.0712,0.7003,0.0707 T0.6959,0.0692 T0.693,0.0678 T0.6914,0.0663 T0.6902,0.0648 T0.689,0.0643 L0.6869,0.0643 L0.6845,0.0643 L0.6821,0.0643 Q0.6553,0.0643,0.6553,0.0554 T0.6796,0.0465 L0.6813,0.0465 L0.6845,0.0465 Q0.6918,0.0425,0.717,0.0376 Q0.7226,0.0366,0.7267,0.0356 T0.7324,0.0336 T0.7376,0.0317 T0.747,0.0297 Q0.7518,0.0287,0.7551,0.0287 T0.762,0.0297 T0.768,0.0307 L0.7729,0.0307 Q0.7802,0.0277,0.7997,0.0267 T0.8224,0.0237 Q0.8273,0.0227,0.8341,0.0223 T0.8475,0.0193 T0.8654,0.0143 T0.8873,0.0079 Q0.9002,0.003,0.9331,0.004 T0.97,0.004 Q0.9838,0,0.9976,0.001 Q1,0.001,1,0.003 Z M0.9935,0.996 L0.9951,0.0049 Q0.9822,0.0049,0.9716,0.0079 Q0.9659,0.0099,0.9327,0.0089 T0.8897,0.0119 Q0.8775,0.0158,0.8666,0.0183 T0.85,0.0237 Q0.8418,0.0267,0.8341,0.0272 T0.8248,0.0277 Q0.82,0.0297,0.8001,0.0312 T0.7745,0.0346 Q0.7697,0.0356,0.7664,0.0356 Q0.764,0.0356,0.7603,0.0341 T0.7534,0.0326 Q0.751,0.0326,0.7478,0.0336 Q0.7429,0.0346,0.7397,0.0356 T0.7344,0.0376 T0.7283,0.0401 T0.7178,0.0425 Q0.6926,0.0465,0.6878,0.0495 Q0.6845,0.0514,0.6764,0.0514 L0.6723,0.0514 L0.6691,0.0514 Q0.6602,0.0514,0.6602,0.0554 Q0.6602,0.0574,0.6659,0.0579 T0.6796,0.0589 T0.691,0.0603 T0.6967,0.0643 T0.7072,0.0673 Q0.7121,0.0682,0.7153,0.0682 T0.7238,0.0678 T0.7332,0.0673 Q0.7413,0.0673,0.7579,0.0692 T0.7818,0.0742 Q0.7867,0.0752,0.8171,0.0762 T0.8508,0.0781 L0.852,0.0781 T0.8601,0.0776 T0.8719,0.0772 Q0.8832,0.0772,0.8921,0.0791 Q0.8994,0.0811,0.8994,0.0841 T0.8933,0.0895 T0.8812,0.094 T0.8735,0.0959 T0.8451,0.1014 T0.8143,0.1068 Q0.7989,0.1068,0.7818,0.1098 Q0.7778,0.1108,0.7745,0.1108 T0.768,0.1103 T0.7603,0.1088 T0.7518,0.1068 L0.7461,0.1068 Q0.7315,0.1068,0.7088,0.1103 T0.6805,0.1177 Q0.6756,0.1207,0.6699,0.1207 Q0.6667,0.1207,0.6545,0.1177 T0.631,0.1147 Q0.6269,0.1137,0.6225,0.1133 T0.616,0.1128 L0.6123,0.1128 T0.6103,0.1133 L0.6083,0.1157 T0.6034,0.1197 Q0.5961,0.1246,0.5921,0.1246 Q0.5904,0.1246,0.5835,0.1231 T0.5693,0.1217 L0.5661,0.1217 Q0.558,0.1217,0.5535,0.1231 T0.5446,0.1266 T0.5345,0.1296 Q0.5126,0.1316,0.4882,0.1316 T0.438,0.1405 Q0.4298,0.1434,0.425,0.1434 Q0.4209,0.1434,0.4173,0.1419 T0.4112,0.1405 T0.4027,0.1419 T0.3869,0.1434 Q0.3682,0.1434,0.3512,0.1494 Q0.3398,0.1533,0.3333,0.1533 Q0.3285,0.1533,0.3228,0.1513 L0.3212,0.1513 Q0.3179,0.1513,0.3155,0.1538 T0.3131,0.1592 Q0.3131,0.1612,0.3147,0.1632 Q0.3171,0.1652,0.3232,0.1667 T0.3406,0.1691 T0.3544,0.1701 L0.3601,0.1701 L0.3678,0.1701 L0.3771,0.1701 Q0.3909,0.1701,0.4031,0.1731 Q0.4177,0.178,0.4558,0.178 Q0.4793,0.178,0.4882,0.1761 L0.4915,0.1761 Q0.498,0.1761,0.5061,0.179 T0.5158,0.183 Q0.5166,0.183,0.5231,0.1835 T0.5341,0.1845 T0.545,0.1855 T0.5572,0.1874 T0.5661,0.1909 Q0.5677,0.1919,0.5702,0.1919 T0.5791,0.1894 T0.588,0.1869 Q0.5921,0.1869,0.5945,0.1899 Q0.5977,0.1919,0.6123,0.1919 Q0.6334,0.1919,0.6448,0.1879 Q0.6488,0.186,0.6537,0.186 Q0.6626,0.186,0.6784,0.1909 T0.6983,0.1958 Q0.704,0.1968,0.7206,0.1973 T0.7506,0.1993 T0.7689,0.2018 L0.7705,0.2018 L0.7741,0.2018 L0.7786,0.2018 Q0.8248,0.2018,0.8475,0.2136 Q0.8597,0.2196,0.8597,0.2255 T0.8483,0.2359 T0.8281,0.2404 Q0.8208,0.2404,0.7534,0.2493 Q0.7502,0.2502,0.7425,0.2512 T0.7287,0.2532 T0.7178,0.2542 L0.7153,0.2542 L0.7137,0.2542 Q0.7064,0.2542,0.6906,0.2591 T0.6715,0.2681 T0.6626,0.272 Q0.6594,0.272,0.6541,0.2705 T0.6464,0.269 T0.6431,0.27 Q0.6318,0.273,0.6034,0.276 Q0.6018,0.276,0.5998,0.2774 T0.5957,0.2799 T0.5904,0.2809 L0.5856,0.2809 Q0.5823,0.2799,0.575,0.2799 Q0.541,0.2799,0.5239,0.2868 Q0.5134,0.2908,0.5028,0.2908 Q0.4996,0.2908,0.4935,0.2903 T0.4842,0.2898 Q0.4704,0.2898,0.4635,0.2918 T0.4534,0.2997 L0.4534,0.3007 Q0.4534,0.3037,0.459,0.3046 T0.4753,0.3066 T0.4899,0.3076 Q0.4907,0.3076,0.5166,0.3106 T0.5507,0.3155 Q0.5921,0.3264,0.605,0.3264 Q0.6107,0.3264,0.6131,0.3254 Q0.6212,0.3225,0.6294,0.3225 Q0.6407,0.3225,0.6513,0.3274 Q0.6529,0.3294,0.6569,0.3294 Q0.6594,0.3294,0.665,0.3284 T0.6748,0.3274 T0.6821,0.3284 Q0.6861,0.3294,0.6967,0.3299 T0.7165,0.3314 T0.7299,0.3343 Q0.7324,0.3363,0.7486,0.3383 T0.7697,0.3422 Q0.7713,0.3432,0.7774,0.3452 T0.7887,0.3492 T0.8005,0.3546 T0.8127,0.3625 T0.8208,0.3719 Q0.8256,0.3798,0.8256,0.3848 Q0.8256,0.3877,0.8236,0.3902 T0.8171,0.3976 T0.809,0.4075 T0.8021,0.4189 T0.7968,0.4273 T0.7867,0.4322 T0.7616,0.4382 Q0.7543,0.4392,0.7437,0.4392 L0.7364,0.4392 L0.7299,0.4392 Q0.7202,0.4392,0.7161,0.4402 Q0.7072,0.4431,0.691,0.4431 L0.6845,0.4431 L0.6788,0.4431 Q0.6707,0.4431,0.6545,0.4461 T0.6334,0.452 Q0.6399,0.456,0.6626,0.457 Q0.6878,0.458,0.7024,0.4639 Q0.7064,0.4649,0.7186,0.4649 L0.7295,0.4649 L0.7413,0.4649 Q0.7591,0.4649,0.7697,0.4669 Q0.7818,0.4688,0.7818,0.4728 Q0.7818,0.4748,0.7798,0.4763 T0.7753,0.4787 L0.7737,0.4797 L0.7729,0.4797 Q0.7494,0.4827,0.7388,0.4827 Q0.7332,0.4827,0.7307,0.4817 L0.7291,0.4817 Q0.7226,0.4817,0.6878,0.4896 Q0.6829,0.4906,0.6772,0.4911 T0.6618,0.4921 T0.646,0.4931 T0.6342,0.4936 T0.6212,0.4931 T0.6115,0.4926 Q0.6083,0.4926,0.6058,0.4931 T0.5969,0.4955 T0.5819,0.499 T0.5629,0.5005 Q0.5572,0.5005,0.5527,0.501 T0.545,0.502 T0.5397,0.503 T0.5361,0.5045 T0.5337,0.5064 T0.5328,0.5094 L0.532,0.5094 Q0.532,0.5104,0.5337,0.5109 T0.5381,0.5114 T0.5438,0.5119 T0.5515,0.5124 L0.5604,0.5124 Q0.5661,0.5134,0.5746,0.5153 T0.5912,0.5173 L0.5977,0.5173 L0.6026,0.5173 Q0.6139,0.5173,0.6273,0.5218 T0.6407,0.5272 Q0.6448,0.5282,0.6683,0.5321 T0.6991,0.5381 Q0.7137,0.543,0.7664,0.548 Q0.7908,0.55,0.7908,0.5559 Q0.7908,0.5589,0.7859,0.5628 Q0.781,0.5658,0.7713,0.5658 Q0.7689,0.5658,0.7628,0.5653 T0.7543,0.5648 T0.7502,0.5658 Q0.7364,0.5678,0.6878,0.5678 Q0.674,0.5678,0.6699,0.5668 L0.6683,0.5668 Q0.6659,0.5668,0.6606,0.5678 T0.6513,0.5687 Q0.6464,0.5687,0.6391,0.5678 Q0.6334,0.5668,0.6302,0.5668 T0.6241,0.5687 T0.6164,0.5717 Q0.6123,0.5727,0.6099,0.5727 L0.6062,0.5727 T0.6022,0.5732 T0.5953,0.5737 Q0.5904,0.5747,0.5839,0.5747 T0.5726,0.5752 T0.5629,0.5776 T0.5458,0.5796 Q0.5418,0.5796,0.5324,0.5791 T0.5191,0.5786 Q0.5077,0.5786,0.5045,0.5806 Q0.498,0.5836,0.4899,0.5836 Q0.4858,0.5836,0.4777,0.5826 T0.4655,0.5816 L0.4631,0.5816 Q0.4582,0.5816,0.4436,0.5841 T0.4144,0.5865 L0.4051,0.5865 L0.3986,0.5865 T0.3933,0.587 T0.3897,0.5875 T0.3869,0.5885 T0.3844,0.5895 T0.3812,0.591 T0.3779,0.5925 Q0.3739,0.5955,0.3633,0.5955 L0.3585,0.5955 L0.3536,0.5955 Q0.3277,0.5955,0.3066,0.6053 Q0.3017,0.6083,0.296,0.6083 Q0.2912,0.6083,0.2839,0.6068 T0.2741,0.6053 Q0.2693,0.6053,0.2547,0.6048 T0.236,0.6044 Q0.2222,0.6044,0.193,0.6103 L0.1882,0.6103 Q0.1825,0.6103,0.1703,0.6083 T0.1525,0.6063 L0.15,0.6063 Q0.1436,0.6063,0.135,0.6073 T0.1168,0.6098 T0.1038,0.6113 Q0.0973,0.6123,0.0787,0.6123 L0.06,0.6123 L0.0414,0.6123 L0.0235,0.6123 Q0.0049,0.6133,0.0049,0.6172 L0.0057,0.6222 Q0.0073,0.6261,0.043,0.6261 L0.0454,0.6261 L0.0479,0.6261 Q0.0527,0.6261,0.0633,0.6281 T0.0803,0.6301 L0.0835,0.6301 L0.0916,0.6301 Q0.0998,0.6301,0.129,0.632 Q0.1768,0.636,0.206,0.64 Q0.2117,0.6409,0.2165,0.6409 Q0.2206,0.6409,0.2263,0.6405 T0.2336,0.64 L0.2384,0.64 L0.2409,0.64 T0.251,0.6395 T0.2644,0.639 Q0.2741,0.639,0.279,0.6409 Q0.283,0.6429,0.2972,0.6439 T0.3293,0.6459 T0.3528,0.6469 L0.3577,0.6469 Q0.3642,0.6469,0.3723,0.6449 T0.3844,0.6429 Q0.3901,0.6429,0.3933,0.6454 T0.4006,0.6479 Q0.4088,0.6479,0.4517,0.6558 Q0.4582,0.6568,0.4623,0.6568 Q0.4655,0.6568,0.4716,0.6563 T0.4826,0.6558 L0.4882,0.6558 Q0.5004,0.6558,0.5255,0.6607 Q0.5328,0.6627,0.5604,0.6647 T0.6152,0.6682 T0.644,0.6696 T0.6719,0.6721 T0.7056,0.6756 Q0.7113,0.6756,0.7198,0.6805 T0.738,0.6855 Q0.7453,0.6855,0.7551,0.6879 T0.7741,0.6939 T0.7912,0.7018 T0.8029,0.7102 Q0.8054,0.7132,0.8054,0.7151 Q0.8054,0.7191,0.8009,0.7216 T0.7908,0.7255 T0.779,0.7285 T0.7721,0.731 Q0.7672,0.7329,0.7632,0.7339 T0.7551,0.7354 T0.7486,0.7369 Q0.7478,0.7369,0.7445,0.7379 T0.7388,0.7394 T0.7324,0.7404 L0.7242,0.7413 T0.7161,0.7418 Q0.7105,0.7418,0.6955,0.7428 T0.6748,0.7438 L0.6699,0.7438 L0.6667,0.7438 Q0.6659,0.7438,0.6407,0.7468 Q0.6367,0.7478,0.6334,0.7478 T0.6245,0.7468 T0.6148,0.7458 L0.6099,0.7458 Q0.6018,0.7468,0.5864,0.7498 T0.5653,0.7532 T0.5596,0.7557 Q0.5596,0.7596,0.571,0.7616 Q0.5742,0.7626,0.5803,0.7631 T0.5929,0.7641 T0.6018,0.7656 L0.6087,0.7656 T0.6192,0.7666 T0.6277,0.7695 Q0.631,0.7705,0.6342,0.7705 Q0.6383,0.7705,0.6452,0.7685 T0.6537,0.7666 L0.6553,0.7666 Q0.6602,0.7666,0.6711,0.769 T0.6853,0.7715 Q0.691,0.7715,0.7048,0.775 T0.7242,0.7814 Q0.7324,0.7854,0.7445,0.7864 Q0.7478,0.7864,0.768,0.7873 T0.7972,0.7893 Q0.7989,0.7893,0.8017,0.7898 T0.8054,0.7903 L0.8082,0.7903 T0.811,0.7908 T0.8131,0.7913 T0.8151,0.7918 L0.8167,0.7928 T0.8179,0.7943 T0.8191,0.7957 T0.8204,0.7977 T0.8208,0.8002 Q0.8208,0.8032,0.8171,0.8051 T0.8074,0.8081 T0.7997,0.8091 Q0.7932,0.8121,0.7737,0.8121 Q0.7664,0.8121,0.7413,0.8111 L0.7364,0.8111 Q0.7275,0.8111,0.7214,0.8121 T0.7084,0.8155 T0.6991,0.819 Q0.6934,0.82,0.6723,0.8205 T0.6472,0.8239 Q0.6423,0.8269,0.6375,0.8269 Q0.6358,0.8269,0.6338,0.8264 T0.6294,0.8254 T0.6253,0.8249 Q0.6042,0.8249,0.5961,0.8289 Q0.5921,0.8318,0.5839,0.8318 Q0.5783,0.8318,0.5645,0.8299 L0.5604,0.8299 Q0.5531,0.8299,0.5337,0.8368 Q0.5296,0.8378,0.5255,0.8378 Q0.5239,0.8378,0.5195,0.8373 T0.5118,0.8368 Q0.5061,0.8368,0.4996,0.8388 Q0.4947,0.8388,0.4882,0.8398 Q0.4777,0.8417,0.4753,0.8427 T0.4728,0.8467 Q0.4728,0.8487,0.4769,0.8492 T0.4886,0.8501 T0.5004,0.8516 Q0.5036,0.8516,0.515,0.8521 T0.5345,0.8546 Q0.5426,0.8556,0.5596,0.8556 L0.5649,0.8556 L0.5702,0.8556 L0.5791,0.8556 Q0.5921,0.8566,0.6135,0.8571 T0.6383,0.8586 Q0.6683,0.8615,0.6764,0.8615 L0.6776,0.8615 L0.6788,0.8615 Q0.7032,0.8615,0.7032,0.8684 Q0.7032,0.8714,0.6995,0.8749 T0.6959,0.8803 L0.6959,0.8813 Q0.6991,0.8843,0.7153,0.8843 Q0.7218,0.8843,0.7259,0.8833 L0.7299,0.8833 Q0.7324,0.8833,0.7348,0.8838 T0.7393,0.8848 T0.7433,0.8863 L0.7474,0.8882 T0.751,0.8892 Q0.7616,0.8922,0.7948,0.8952 Q0.7981,0.8952,0.8082,0.8981 T0.8297,0.9011 T0.8528,0.9026 T0.8747,0.907 T0.8856,0.9149 L0.8856,0.9159 Q0.8856,0.9179,0.8848,0.9189 T0.8828,0.9209 T0.88,0.9228 T0.8767,0.9243 T0.8731,0.9248 T0.8698,0.9253 T0.8666,0.9258 L0.8646,0.9258 Q0.8621,0.9258,0.8577,0.9263 T0.85,0.9268 T0.8439,0.9273 T0.8402,0.9278 Q0.8386,0.9298,0.8358,0.9308 T0.8305,0.9322 T0.8244,0.9332 T0.8183,0.9337 Q0.8135,0.9347,0.8025,0.9372 T0.7859,0.9416 Q0.7778,0.9436,0.7717,0.9471 T0.7624,0.9515 Q0.7575,0.9535,0.7486,0.9535 Q0.7461,0.9535,0.7397,0.953 T0.7291,0.9525 Q0.7234,0.9525,0.7186,0.953 T0.7137,0.957 T0.7194,0.9614 Q0.7567,0.9634,0.7664,0.9654 Q0.7745,0.9674,0.7762,0.9674 L0.7908,0.9674 Q0.7924,0.9664,0.7948,0.9664 Q0.8029,0.9664,0.8082,0.9679 T0.8224,0.9723 T0.8362,0.9773 Q0.8483,0.9812,0.871,0.9812 L0.8751,0.9812 Q0.8873,0.9812,0.8929,0.9822 T0.9165,0.9876 T0.9408,0.9931 Q0.9513,0.996,0.9935,0.996 Z M0.9968,0.998 L0.9976,0.003 Q0.9838,0.002,0.9708,0.0059 Q0.9659,0.0069,0.9327,0.0059 T0.8881,0.0099 Q0.8767,0.0138,0.8658,0.0163 T0.8491,0.0218 Q0.8418,0.0247,0.8341,0.0247 T0.8232,0.0257 Q0.8191,0.0277,0.7997,0.0292 T0.7737,0.0326 Q0.7697,0.0336,0.7672,0.0336 T0.7612,0.0321 T0.7543,0.0307 T0.747,0.0317 Q0.7397,0.0326,0.7336,0.0356 T0.717,0.0406 Q0.6918,0.0445,0.6861,0.0475 Q0.6845,0.0485,0.6772,0.0485 T0.6638,0.05 T0.6577,0.0549 T0.6642,0.0598 T0.6796,0.0613 T0.6902,0.0623 Q0.691,0.0623,0.6946,0.0658 T0.7064,0.0702 L0.7161,0.0702 Q0.7194,0.0702,0.7242,0.0697 T0.7332,0.0692 Q0.7413,0.0692,0.7579,0.0717 T0.781,0.0762 Q0.7867,0.0781,0.8171,0.0786 T0.85,0.0801 L0.8532,0.0801 Q0.8548,0.0801,0.8613,0.0796 T0.8727,0.0791 Q0.8832,0.0791,0.8913,0.0811 Q0.897,0.0831,0.897,0.0851 Q0.897,0.088,0.8873,0.0905 T0.8735,0.093 Q0.871,0.093,0.8447,0.0984 T0.8143,0.1039 Q0.7981,0.1039,0.781,0.1078 Q0.7778,0.1088,0.7745,0.1088 T0.7644,0.1073 T0.7518,0.1048 L0.7453,0.1048 Q0.7299,0.1048,0.7076,0.1083 T0.6788,0.1157 Q0.6748,0.1187,0.6699,0.1187 Q0.6675,0.1187,0.6557,0.1157 T0.6318,0.1118 Q0.6164,0.1108,0.6135,0.1108 T0.6095,0.1113 T0.6067,0.1142 T0.6018,0.1187 Q0.5953,0.1227,0.5921,0.1227 Q0.5904,0.1227,0.5839,0.1212 T0.5693,0.1187 L0.5661,0.1187 Q0.558,0.1187,0.5527,0.1207 T0.5434,0.1246 T0.5337,0.1266 Q0.5126,0.1296,0.4882,0.1296 T0.4371,0.1385 Q0.4298,0.1414,0.425,0.1414 Q0.4225,0.1414,0.4189,0.1395 T0.4112,0.1375 Q0.4079,0.1375,0.4019,0.1395 T0.3869,0.1414 Q0.3682,0.1414,0.3504,0.1474 Q0.3398,0.1513,0.3333,0.1513 Q0.3293,0.1513,0.3228,0.1494 L0.3204,0.1494 Q0.3179,0.1494,0.3155,0.1508 T0.3118,0.1543 T0.3106,0.1592 T0.3127,0.1642 T0.32,0.1677 T0.3305,0.1701 T0.3435,0.1716 T0.3544,0.1721 Q0.3569,0.1731,0.3601,0.1731 Q0.3625,0.1731,0.3686,0.1726 T0.3779,0.1721 Q0.3901,0.1721,0.4023,0.1751 Q0.4177,0.18,0.455,0.18 Q0.4793,0.18,0.4882,0.178 L0.4915,0.178 Q0.4964,0.178,0.5045,0.1815 T0.5158,0.185 Q0.5564,0.1889,0.5645,0.1929 Q0.5677,0.1939,0.571,0.1939 Q0.575,0.1939,0.5807,0.1919 T0.5888,0.1899 T0.5929,0.1909 Q0.5969,0.1949,0.6123,0.1949 Q0.6334,0.1949,0.6456,0.1899 Q0.6488,0.1879,0.6537,0.1879 Q0.661,0.1879,0.6772,0.1929 T0.6983,0.1978 Q0.704,0.1988,0.7206,0.1998 T0.7502,0.2018 T0.7664,0.2038 Q0.7672,0.2038,0.7818,0.2043 T0.8151,0.2067 T0.8459,0.2156 Q0.8573,0.2206,0.8573,0.2255 Q0.8573,0.2295,0.8516,0.2324 T0.8394,0.2369 T0.8281,0.2384 Q0.8208,0.2384,0.7526,0.2473 Q0.7494,0.2483,0.7421,0.2493 T0.7287,0.2512 T0.7178,0.2522 L0.7153,0.2522 L0.7137,0.2522 Q0.7056,0.2522,0.6898,0.2572 T0.6691,0.2671 Q0.6667,0.269,0.6634,0.269 Q0.661,0.269,0.6557,0.2681 T0.6472,0.2671 Q0.6448,0.2671,0.6415,0.2681 Q0.631,0.271,0.6034,0.274 Q0.5994,0.274,0.5961,0.2765 T0.5904,0.2789 L0.5864,0.2789 Q0.5831,0.2779,0.5742,0.2779 Q0.541,0.2779,0.5223,0.2849 Q0.5126,0.2888,0.5028,0.2888 Q0.5004,0.2888,0.4943,0.2883 T0.4842,0.2878 Q0.4704,0.2878,0.4627,0.2898 T0.4509,0.2987 Q0.4501,0.2997,0.4501,0.3007 Q0.4501,0.3046,0.4574,0.3066 T0.4765,0.3091 T0.4899,0.3096 Q0.4931,0.3106,0.5061,0.3121 T0.5316,0.315 T0.5499,0.3175 Q0.5507,0.3175,0.5572,0.3195 T0.5685,0.3225 T0.5803,0.3254 T0.5933,0.3279 T0.605,0.3284 T0.6148,0.3274 Q0.6221,0.3244,0.6294,0.3244 Q0.6399,0.3244,0.6496,0.3294 Q0.6529,0.3314,0.6577,0.3314 Q0.6602,0.3314,0.6663,0.3304 T0.6756,0.3294 T0.6813,0.3304 Q0.6837,0.3304,0.6873,0.3309 L0.6946,0.3318 T0.7024,0.3323 T0.7105,0.3328 T0.7178,0.3338 T0.7238,0.3348 T0.7283,0.3363 Q0.7324,0.3383,0.7482,0.3403 T0.7689,0.3442 Q0.7697,0.3442,0.779,0.3477 T0.794,0.3536 T0.8074,0.3615 T0.8183,0.3729 Q0.8232,0.3808,0.8232,0.3848 Q0.8232,0.3867,0.8216,0.3892 T0.8151,0.3961 T0.8062,0.406 T0.7997,0.4179 T0.7952,0.4263 T0.7855,0.4308 T0.7616,0.4362 Q0.7543,0.4372,0.7445,0.4372 L0.7372,0.4372 L0.7307,0.4372 Q0.7202,0.4372,0.7153,0.4382 Q0.7064,0.4402,0.691,0.4402 L0.6845,0.4402 L0.6788,0.4402 Q0.6699,0.4402,0.6533,0.4436 T0.6318,0.451 Q0.6302,0.451,0.6302,0.452 Q0.6302,0.457,0.6626,0.459 Q0.6869,0.4609,0.7015,0.4659 Q0.7064,0.4669,0.7202,0.4669 L0.7311,0.4669 L0.7429,0.4669 Q0.7599,0.4669,0.7689,0.4688 Q0.7794,0.4708,0.7794,0.4738 L0.7786,0.4748 T0.777,0.4763 T0.7749,0.4773 L0.7737,0.4777 L0.7729,0.4777 Q0.7502,0.4797,0.738,0.4797 L0.7315,0.4797 L0.7291,0.4797 Q0.7226,0.4797,0.6869,0.4876 Q0.6821,0.4886,0.6768,0.4891 T0.6614,0.4901 T0.6456,0.4916 L0.6342,0.4916 Q0.6294,0.4916,0.6217,0.4911 T0.6115,0.4906 Q0.6083,0.4906,0.6054,0.4911 T0.5961,0.4936 T0.5815,0.4965 T0.5629,0.4985 Q0.5507,0.4985,0.5442,0.4995 T0.5345,0.5025 T0.5304,0.5084 L0.5296,0.5094 Q0.5296,0.5114,0.5316,0.5124 T0.5373,0.5138 T0.5442,0.5143 L0.5523,0.5143 L0.5604,0.5143 Q0.5637,0.5153,0.5677,0.5158 T0.5742,0.5173 T0.5811,0.5188 T0.5904,0.5193 L0.5977,0.5193 L0.6026,0.5193 Q0.6107,0.5193,0.6168,0.5208 T0.6294,0.5252 T0.6399,0.5292 Q0.6448,0.5302,0.6679,0.5341 T0.6983,0.541 Q0.7129,0.545,0.7664,0.55 Q0.7883,0.5519,0.7883,0.5559 Q0.7883,0.5579,0.7843,0.5608 T0.7721,0.5638 Q0.7697,0.5638,0.764,0.5633 T0.7559,0.5628 L0.7502,0.5628 Q0.7364,0.5648,0.6869,0.5648 L0.6699,0.5648 L0.6675,0.5648 Q0.665,0.5648,0.6602,0.5658 T0.6513,0.5668 Q0.6464,0.5668,0.6399,0.5658 Q0.6342,0.5648,0.6302,0.5648 T0.6225,0.5668 T0.6156,0.5697 Q0.6107,0.5707,0.6087,0.5707 T0.6034,0.5712 T0.5953,0.5717 Q0.5904,0.5727,0.5835,0.5727 T0.5718,0.5732 T0.562,0.5757 Q0.558,0.5767,0.5483,0.5767 L0.5349,0.5767 L0.5207,0.5767 Q0.5069,0.5767,0.5028,0.5786 Q0.4972,0.5816,0.4899,0.5816 Q0.4858,0.5816,0.4781,0.5806 T0.4663,0.5796 L0.4631,0.5796 Q0.4582,0.5796,0.4432,0.5821 T0.4144,0.5846 L0.4071,0.5846 L0.4011,0.5846 T0.3958,0.5851 T0.3921,0.5856 T0.3889,0.5861 T0.3865,0.5865 T0.384,0.5875 L0.382,0.5885 L0.3796,0.5895 L0.3771,0.5905 Q0.3731,0.5925,0.365,0.5925 L0.3601,0.5925 L0.3552,0.5925 Q0.3277,0.5925,0.3049,0.6044 Q0.3017,0.6053,0.296,0.6053 Q0.292,0.6053,0.2847,0.6044 T0.2741,0.6034 Q0.2693,0.6034,0.2547,0.6029 T0.236,0.6024 Q0.2222,0.6024,0.1922,0.6073 Q0.1906,0.6083,0.1882,0.6083 Q0.1833,0.6083,0.1711,0.6063 T0.1533,0.6044 Q0.1517,0.6034,0.1492,0.6034 Q0.1436,0.6034,0.135,0.6048 T0.1168,0.6078 T0.103,0.6093 Q0.0973,0.6103,0.0787,0.6103 L0.0604,0.6103 L0.0414,0.6103 L0.0235,0.6103 Q0.0024,0.6113,0.0024,0.6172 Q0.0024,0.6192,0.0032,0.6231 Q0.0049,0.6281,0.0333,0.6281 L0.0414,0.6281 L0.0479,0.6281 Q0.0519,0.6281,0.0624,0.6301 T0.0803,0.632 L0.0835,0.632 L0.0916,0.632 Q0.0989,0.632,0.1281,0.634 L0.206,0.6419 Q0.2117,0.6429,0.2174,0.6429 Q0.2214,0.6429,0.2271,0.6424 T0.2344,0.6419 L0.2376,0.6419 Q0.2393,0.6429,0.2417,0.6429 T0.2526,0.6419 T0.2652,0.6409 Q0.2741,0.6409,0.2782,0.6429 T0.2968,0.6459 T0.3293,0.6479 T0.352,0.6489 Q0.3552,0.6499,0.3585,0.6499 Q0.365,0.6499,0.3731,0.6474 T0.3844,0.6449 Q0.3885,0.6449,0.3917,0.6474 T0.4006,0.6499 Q0.4088,0.6499,0.4509,0.6578 Q0.4574,0.6588,0.4631,0.6588 Q0.4655,0.6588,0.4716,0.6583 T0.4834,0.6578 L0.4874,0.6578 Q0.5004,0.6588,0.5255,0.6637 Q0.532,0.6647,0.56,0.6667 T0.6148,0.6701 T0.644,0.6716 Q0.6464,0.6726,0.6594,0.6736 T0.6861,0.6756 T0.7048,0.6775 Q0.7097,0.6775,0.7186,0.6825 T0.738,0.6874 Q0.7518,0.6874,0.7729,0.6958 T0.8005,0.7122 Q0.8029,0.7141,0.8029,0.7151 Q0.8029,0.7191,0.7968,0.7216 T0.7818,0.726 T0.7705,0.729 L0.764,0.731 T0.7583,0.7324 T0.753,0.7334 T0.7486,0.7349 Q0.7251,0.7399,0.7161,0.7399 Q0.7097,0.7399,0.6951,0.7409 T0.6748,0.7418 L0.6703,0.7418 L0.6667,0.7418 Q0.6659,0.7418,0.6399,0.7448 L0.6334,0.7448 Q0.631,0.7448,0.6249,0.7443 T0.6148,0.7438 L0.6099,0.7438 Q0.601,0.7448,0.5856,0.7473 T0.5645,0.7507 Q0.5572,0.7517,0.5572,0.7547 T0.5616,0.7606 T0.5702,0.7646 Q0.5734,0.7646,0.5779,0.7651 T0.5864,0.7661 T0.5949,0.7671 T0.6018,0.7676 L0.6071,0.7676 T0.6135,0.7681 T0.62,0.769 T0.6269,0.771 T0.6342,0.7725 Q0.6391,0.7725,0.6464,0.7705 T0.6541,0.7685 L0.6553,0.7685 Q0.6586,0.7685,0.6699,0.771 T0.6853,0.7735 Q0.6902,0.7735,0.704,0.777 T0.7226,0.7834 Q0.7315,0.7873,0.7445,0.7883 Q0.747,0.7883,0.7676,0.7893 T0.7972,0.7913 Q0.7989,0.7913,0.8017,0.7918 T0.8058,0.7923 T0.809,0.7928 T0.8114,0.7933 T0.8131,0.7938 T0.8147,0.7943 T0.8159,0.7953 L0.8171,0.7967 T0.8175,0.7982 Q0.8183,0.7992,0.8183,0.8002 Q0.8183,0.8022,0.8155,0.8032 T0.807,0.8051 T0.7989,0.8071 Q0.7932,0.8091,0.7737,0.8091 L0.7413,0.8091 L0.7372,0.8091 Q0.7275,0.8091,0.721,0.8101 T0.7072,0.8136 T0.6983,0.817 Q0.6942,0.818,0.6825,0.818 T0.6602,0.819 T0.6456,0.822 Q0.6415,0.8249,0.6375,0.8249 Q0.6367,0.8249,0.6326,0.8239 T0.6253,0.8229 Q0.6034,0.8229,0.5953,0.8279 Q0.5912,0.8289,0.5848,0.8289 Q0.5775,0.8289,0.5645,0.8279 Q0.5629,0.8269,0.5604,0.8269 Q0.5523,0.8269,0.5328,0.8348 Q0.5296,0.8358,0.5264,0.8358 Q0.5247,0.8358,0.5203,0.8353 T0.5126,0.8348 Q0.5061,0.8348,0.4988,0.8358 Q0.4947,0.8368,0.4882,0.8378 Q0.4826,0.8388,0.4797,0.8388 T0.474,0.8398 T0.4704,0.8422 T0.4696,0.8462 T0.472,0.8501 T0.4781,0.8521 T0.4854,0.8526 L0.4935,0.8526 T0.4996,0.8536 Q0.5036,0.8536,0.515,0.8546 T0.5337,0.8566 Q0.5426,0.8576,0.5596,0.8576 L0.5657,0.8576 L0.571,0.8576 L0.5791,0.8576 Q0.5921,0.8586,0.6135,0.8591 T0.6383,0.8605 Q0.6683,0.8635,0.6764,0.8635 Q0.6999,0.8635,0.6999,0.8684 Q0.6999,0.8694,0.6967,0.8734 T0.6934,0.8803 L0.6934,0.8823 Q0.6951,0.8863,0.7137,0.8863 Q0.7218,0.8863,0.7267,0.8853 L0.7299,0.8853 Q0.734,0.8853,0.7409,0.8882 T0.7502,0.8912 Q0.7607,0.8942,0.794,0.8971 Q0.7972,0.8971,0.8078,0.9001 T0.8297,0.9031 Q0.8475,0.9031,0.8646,0.9065 T0.8824,0.9149 L0.8824,0.9159 Q0.8824,0.9169,0.882,0.9179 T0.8808,0.9194 L0.8792,0.9204 T0.8767,0.9214 T0.8743,0.9224 T0.8715,0.9228 L0.8686,0.9228 T0.8662,0.9233 T0.8637,0.9238 L0.8556,0.9238 T0.8447,0.9243 T0.8386,0.9268 Q0.837,0.9278,0.835,0.9288 T0.8305,0.9303 T0.8244,0.9308 T0.8175,0.9318 Q0.8127,0.9327,0.8017,0.9352 T0.7851,0.9397 Q0.777,0.9416,0.7705,0.9451 T0.7616,0.9496 Q0.7575,0.9505,0.7494,0.9505 L0.7405,0.9505 L0.7307,0.9505 Q0.7234,0.9505,0.7178,0.9515 Q0.7145,0.9515,0.7125,0.9535 T0.7105,0.9575 Q0.7105,0.9624,0.7194,0.9634 Q0.7567,0.9654,0.7664,0.9674 Q0.7745,0.9693,0.7762,0.9693 L0.7908,0.9693 L0.7948,0.9693 Q0.8005,0.9693,0.8058,0.9698 T0.8143,0.9718 T0.824,0.9753 T0.8354,0.9792 Q0.8483,0.9832,0.871,0.9832 L0.8739,0.9832 L0.8767,0.9832 Q0.8873,0.9832,0.8921,0.9842 Q0.8978,0.9852,0.9157,0.9896 T0.94,0.996 Q0.9424,0.996,0.9469,0.9965 T0.9566,0.997 T0.9676,0.9975 T0.9781,0.998 L0.9874,0.998 L0.9943,0.998 L0.9968,0.998 Z",type:0}},"":{type:5,data:{d:"M1,0.5071 L0.8623,0.7102 L0.5865,0.7102 L0.4489,0.5071 L0.5865,0.3045 L0.8623,0.3045 Z M0.4135,0.7974 L0.2758,1 L0,1 L0,0.5944 L0.2758,0.5944 Z M0.4135,0.2026 L0.2758,0.4056 L0,0.4056 L0,0 L0.2758,0 Z",type:0}},"":{type:5,data:{d:"M0.9726,0.5071 L0.8451,0.3184 L0.59,0.3184 L0.4624,0.5071 L0.59,0.6955 L0.8451,0.6955 Z M1,0.5071 L0.8588,0.716 L0.5768,0.716 L0.4355,0.5071 L0.5768,0.2982 L0.8588,0.2982 Z M0.401,0.7911 L0.2735,0.6028 L0.0236,0.6028 L0.0236,0.9799 L0.2735,0.9799 Z M0.4284,0.7911 L0.2872,1 L0,1 L0,0.5826 L0.2872,0.5826 Z M0.401,0.2089 L0.2735,0.0201 L0.0236,0.0201 L0.0236,0.3972 L0.2735,0.3972 Z M0.4284,0.2089 L0.2872,0.4174 L0,0.4174 L0,0 L0.2872,0 Z",type:0}},"":{type:5,data:{d:"M1,0.4996 Q1,0.5365,0.9924,0.568 T0.9718,0.6177 T0.9433,0.6363 L0.9425,0.6367 Q0.9355,0.6367,0.9285,0.6326 L0.9308,0.6326 Q0.9129,0.6195,0.9013,0.587 T0.8871,0.5164 T0.8943,0.4373 T0.9254,0.3687 L0.9254,0.3691 Q0.9339,0.3628,0.9425,0.3628 Q0.9584,0.3628,0.9716,0.3811 T0.9924,0.431 T1,0.4996 Z M0.9234,0.6321 L0.8776,0.7169 Q0.8791,0.732,0.8791,0.7441 Q0.8791,0.781,0.8716,0.8123 T0.8508,0.862 T0.8224,0.8809 L0.8216,0.8809 Q0.8154,0.8809,0.8092,0.8775 L0.8088,0.8775 Q0.7905,0.8633,0.7792,0.8297 T0.766,0.7571 T0.775,0.6768 T0.8088,0.6086 L0.7431,0.6065 Q0.719,0.6313,0.7072,0.6705 T0.6965,0.7487 T0.7097,0.823 T0.7423,0.8763 L0.7913,0.8775 L0.7314,0.9895 L0.4648,0.5038 L0.7299,0.0176 L0.7882,0.1229 L0.7404,0.1212 Q0.7244,0.138,0.7136,0.1617 T0.6982,0.2108 T0.6943,0.2632 T0.7003,0.3144 T0.7159,0.3586 T0.7396,0.3909 L0.8072,0.3926 Q0.7894,0.3796,0.7777,0.3479 T0.7635,0.2789 T0.7697,0.2011 T0.7987,0.1326 Q0.8092,0.1225,0.8204,0.1225 Q0.8321,0.1225,0.8426,0.1332 T0.8609,0.1623 T0.8731,0.2062 T0.8776,0.2592 Q0.8776,0.268,0.8768,0.2815 L0.9219,0.3628 L0.8644,0.3612 Q0.8403,0.3855,0.8284,0.4247 T0.8177,0.5029 T0.8309,0.5772 T0.8632,0.6305 Z M0.6759,0.6384 Q0.6576,0.625,0.6457,0.5914 T0.6319,0.5185 T0.6407,0.4375 T0.6751,0.3691 L0.609,0.367 Q0.5849,0.3918,0.5731,0.431 T0.5626,0.509 T0.5758,0.5833 T0.6082,0.6367 Z M0.6459,0.0025 L0.391,0.4551 L0.0035,0.4551 L0.246,0 Z M0.6553,1 L0.2421,1 L0,0.5449 L0.3875,0.5449 Z",type:0}},"":{type:5,data:{d:"M0.4996,0 Q0.5562,0,0.5961,0.0166 T0.6364,0.0566 L0.6368,0.0575 Q0.6368,0.0646,0.6324,0.0713 L0.6324,0.0692 Q0.6196,0.0868,0.5872,0.0986 T0.5166,0.1128 T0.4373,0.1057 T0.3689,0.0747 L0.3694,0.0747 Q0.3627,0.0663,0.3627,0.0575 Q0.3627,0.0336,0.4028,0.0168 T0.4996,0 Z M0.6324,0.0768 L0.717,0.1225 Q0.7321,0.1212,0.744,0.1212 Q0.8007,0.1212,0.8406,0.1378 T0.8809,0.1779 L0.8813,0.1783 Q0.8813,0.1846,0.8778,0.1909 Q0.8636,0.2093,0.8299,0.2208 T0.7573,0.2343 T0.6769,0.2253 T0.6089,0.1913 L0.6067,0.2567 Q0.6315,0.281,0.6707,0.2928 T0.7489,0.3035 T0.8231,0.2903 T0.8764,0.258 L0.8778,0.2085 L0.9898,0.2685 L0.504,0.5352 L0.0177,0.2701 L0.1227,0.2118 L0.1213,0.2596 Q0.1457,0.2836,0.1851,0.2955 T0.2635,0.3062 T0.3377,0.293 T0.3911,0.2605 L0.3928,0.193 Q0.38,0.2106,0.3483,0.2221 T0.2792,0.2364 T0.2013,0.2303 T0.1324,0.2013 Q0.1222,0.1909,0.1222,0.1795 Q0.1222,0.156,0.1623,0.1393 T0.2591,0.1225 Q0.2679,0.1225,0.2817,0.1233 L0.3627,0.078 L0.3609,0.1359 Q0.3857,0.1598,0.4249,0.1718 T0.5031,0.1825 T0.5773,0.1693 T0.6306,0.1367 Z M0.6386,0.3242 Q0.6253,0.3427,0.5917,0.3544 T0.5186,0.3683 T0.4376,0.3595 T0.3689,0.3251 L0.3671,0.3909 Q0.3915,0.4148,0.4309,0.4268 T0.5093,0.4375 T0.5835,0.4243 T0.6368,0.3918 Z M0.0027,0.354 L0.4553,0.6091 L0.4553,0.9962 L0,0.7542 Z M1,0.3448 L1,0.7576 L0.5447,1 L0.5447,0.6128 Z",type:0}},"":{type:5,data:{d:"M0,0.7699 Q0,0.7172,0.0277,0.6731 T0.103,0.6032 T0.2066,0.5774 Q0.2487,0.5774,0.2865,0.5922 T0.3526,0.6339 L0.3935,0.6715 Q0.4218,0.6984,0.438,0.7336 T0.4541,0.8075 Q0.4541,0.8602,0.4264,0.9046 T0.3511,0.9745 T0.2475,1 Q0.2054,1,0.1676,0.9852 T0.1016,0.9435 L0.0606,0.9059 Q0.0317,0.879,0.0159,0.8438 T0,0.7699 Z M0.5459,0.7699 Q0.5459,0.7172,0.5736,0.6731 T0.6489,0.6032 T0.7525,0.5774 Q0.7946,0.5774,0.8324,0.5922 T0.8984,0.6339 L0.9394,0.6715 Q0.9579,0.6892,0.9714,0.7105 T0.9925,0.7567 T1,0.8075 Q1,0.8602,0.9723,0.9046 T0.897,0.9745 T0.7934,1 Q0.7513,1,0.7135,0.9852 T0.6474,0.9435 L0.6065,0.9059 Q0.5776,0.879,0.5617,0.8438 T0.5459,0.7699 Z M0,0.1925 Q0,0.1398,0.0277,0.0957 T0.103,0.0258 T0.2066,0 Q0.2487,0,0.2865,0.0148 T0.3526,0.0565 L0.3935,0.0941 Q0.4218,0.121,0.438,0.1562 T0.4541,0.2301 Q0.4541,0.2828,0.4264,0.3269 T0.3511,0.3968 T0.2475,0.4226 Q0.2054,0.4226,0.1676,0.4078 T0.1016,0.3661 L0.0606,0.3285 Q0.0317,0.3016,0.0159,0.2664 T0,0.1925 Z M0.5459,0.1925 Q0.5459,0.1398,0.5736,0.0957 T0.6489,0.0258 T0.7525,0 Q0.7946,0,0.8324,0.0148 T0.8984,0.0565 L0.9394,0.0941 Q0.9677,0.121,0.9838,0.1562 T1,0.2301 Q1,0.2828,0.9723,0.3269 T0.897,0.3968 T0.7934,0.4226 Q0.7513,0.4226,0.7135,0.4078 T0.6474,0.3661 L0.6065,0.3285 Q0.5874,0.3108,0.5741,0.2895 T0.5534,0.2433 T0.5459,0.1925 Z M0.3301,0.6403 Q0.3306,0.6403,0.3312,0.6409 L0.3272,0.6371 L0.3272,0.6371 Z M0.8759,0.6403 Q0.8765,0.6403,0.8771,0.6409 Q0.8748,0.6387,0.8725,0.6371 L0.8731,0.6371 Z M0.3301,0.0629 Q0.3306,0.0629,0.3312,0.0634 L0.3272,0.0597 L0.3272,0.0602 Z M0.8759,0.0629 Q0.8765,0.0629,0.8771,0.0634 Q0.8748,0.0613,0.8725,0.0597 Q0.8731,0.0597,0.8731,0.0602 Z M0.779,0.4113 L0.7501,0.3849 Q0.7046,0.3844,0.6636,0.3661 Q0.7132,0.407,0.779,0.4113 Z M0.7957,0.4118 Q0.8477,0.4113,0.8918,0.3874 T0.9619,0.3223 T0.9885,0.2323 L0.9585,0.2048 Q0.9538,0.2769,0.8987,0.3282 T0.7657,0.3844 Z M0.9879,0.2167 Q0.9827,0.1554,0.9388,0.1097 Q0.9585,0.1478,0.959,0.1898 Z M0.2331,0.4113 L0.2043,0.3849 Q0.1587,0.3844,0.1177,0.3661 Q0.1673,0.407,0.2331,0.4113 Z M0.2499,0.4118 Q0.2885,0.4118,0.324,0.3973 T0.3852,0.3589 T0.4264,0.3019 T0.4426,0.2323 L0.4126,0.2048 Q0.408,0.2769,0.3529,0.3282 T0.2198,0.3844 Z M0.442,0.2167 Q0.4368,0.1554,0.393,0.1097 Q0.4126,0.1478,0.4132,0.1903 Z M0.779,0.9887 L0.7501,0.9624 Q0.7046,0.9618,0.6636,0.9435 Q0.7132,0.9844,0.779,0.9887 Z M0.7957,0.9892 Q0.8477,0.9887,0.8918,0.9648 T0.9619,0.8997 T0.9885,0.8097 L0.9585,0.7823 Q0.9538,0.8543,0.8987,0.9056 T0.7657,0.9618 Z M0.9879,0.7941 Q0.9827,0.7328,0.9388,0.6871 Q0.9585,0.7253,0.959,0.7672 Z M0.2331,0.9887 L0.2043,0.9624 Q0.1587,0.9618,0.1177,0.9435 Q0.1673,0.9844,0.2331,0.9887 Z M0.2499,0.9892 Q0.3018,0.9887,0.3459,0.9648 T0.416,0.8997 T0.4426,0.8102 L0.4126,0.7823 Q0.408,0.8543,0.3529,0.9056 T0.2198,0.9618 Z M0.442,0.7941 Q0.4368,0.7328,0.393,0.6871 Q0.4126,0.7253,0.4132,0.7672 Z M0.3191,0.6452 Q0.2943,0.622,0.2643,0.6091 T0.2066,0.5962 Q0.1795,0.5962,0.1497,0.6091 T0.0949,0.6441 T0.0537,0.6995 T0.0375,0.7699 Q0.0375,0.8419,0.0941,0.8941 Q0.1189,0.9172,0.1489,0.9304 T0.2066,0.9435 Q0.2337,0.9435,0.2634,0.9304 T0.3182,0.8952 T0.3595,0.8398 T0.3756,0.7699 Q0.3756,0.6978,0.3191,0.6452 Z M0.026,0.7731 L0.026,0.7699 Q0.026,0.6935,0.0854,0.6376 Q0.0658,0.6538,0.0514,0.6739 T0.0289,0.718 T0.0202,0.7677 Z M0.0271,0.7892 L0.0208,0.7833 Q0.0254,0.8419,0.0681,0.886 Q0.0664,0.8828,0.0646,0.879 Q0.0329,0.8382,0.0271,0.7892 Z M0.3866,0.7823 Q0.382,0.8511,0.3278,0.9016 Q0.3843,0.8565,0.3918,0.7871 Z M0.3872,0.7677 L0.393,0.7726 L0.393,0.7699 Q0.393,0.7349,0.3791,0.7038 Q0.3739,0.6973,0.3681,0.6914 Q0.3866,0.7274,0.3872,0.7677 Z M0.865,0.6452 Q0.8402,0.622,0.8102,0.6091 T0.7525,0.5962 Q0.7305,0.5962,0.7072,0.6043 T0.6619,0.628 T0.6223,0.6642 T0.5941,0.7124 T0.5834,0.7699 Q0.5834,0.8419,0.6399,0.8941 Q0.6561,0.9097,0.6757,0.9207 T0.7149,0.9376 T0.7525,0.9435 Q0.7796,0.9435,0.8093,0.9304 T0.8641,0.8952 T0.9054,0.8398 T0.9215,0.7699 Q0.9215,0.6978,0.865,0.6452 Z M0.5718,0.7731 L0.5718,0.7699 Q0.5718,0.6935,0.6313,0.6376 Q0.6013,0.6618,0.584,0.6954 T0.5661,0.7677 Z M0.573,0.7892 L0.5666,0.7833 Q0.5713,0.8419,0.614,0.886 Q0.6122,0.8828,0.6105,0.879 Q0.5788,0.8382,0.573,0.7892 Z M0.9325,0.7823 Q0.9279,0.8511,0.8736,0.9016 Q0.9308,0.8565,0.9377,0.7871 Z M0.9331,0.7672 L0.9388,0.7726 L0.9388,0.7699 Q0.9388,0.7349,0.925,0.7038 Q0.9198,0.6973,0.914,0.6914 Q0.9325,0.7274,0.9331,0.7672 Z M0.3191,0.0677 Q0.2943,0.0446,0.2643,0.0317 T0.2066,0.0188 Q0.1795,0.0188,0.1497,0.0317 T0.0949,0.0667 T0.0537,0.122 T0.0375,0.1925 Q0.0375,0.2645,0.0941,0.3167 Q0.1189,0.3398,0.1489,0.353 T0.2066,0.3661 Q0.2337,0.3661,0.2634,0.353 T0.3182,0.3177 T0.3595,0.2624 T0.3756,0.1925 Q0.3756,0.1204,0.3191,0.0677 Z M0.026,0.1957 L0.026,0.1925 Q0.026,0.1161,0.0854,0.0602 Q0.0554,0.0844,0.0381,0.118 T0.0202,0.1903 Z M0.0271,0.2118 L0.0208,0.2059 Q0.0254,0.2645,0.0681,0.3086 Q0.0664,0.3054,0.0646,0.3016 Q0.0329,0.2608,0.0271,0.2118 Z M0.3866,0.2048 Q0.382,0.2737,0.3278,0.3242 Q0.3849,0.279,0.3918,0.2097 Z M0.3872,0.1903 L0.393,0.1952 L0.393,0.1925 Q0.393,0.1581,0.3791,0.1263 Q0.3739,0.1199,0.3681,0.114 Q0.3866,0.15,0.3872,0.1903 Z M0.865,0.0677 Q0.8402,0.0446,0.8102,0.0317 T0.7525,0.0188 Q0.7253,0.0188,0.6956,0.0317 T0.6408,0.0667 T0.5995,0.122 T0.5834,0.1925 Q0.5834,0.2645,0.6399,0.3167 Q0.6647,0.3398,0.6947,0.353 T0.7525,0.3661 Q0.7796,0.3661,0.8093,0.353 T0.8641,0.3177 T0.9054,0.2624 T0.9215,0.1925 Q0.9215,0.1204,0.865,0.0677 Z M0.5718,0.1957 L0.5718,0.1925 Q0.5718,0.1161,0.6313,0.0602 Q0.6013,0.0844,0.584,0.118 T0.5661,0.1903 Z M0.573,0.2118 L0.5666,0.2059 Q0.5713,0.2645,0.614,0.3086 Q0.6122,0.3054,0.6105,0.3016 Q0.5788,0.2608,0.573,0.2118 Z M0.9325,0.2048 Q0.9279,0.2737,0.8736,0.3242 Q0.9308,0.279,0.9377,0.2097 Z M0.9331,0.1898 L0.9388,0.1952 L0.9388,0.1925 Q0.9388,0.1575,0.925,0.1263 Q0.9198,0.1199,0.914,0.114 Q0.9325,0.15,0.9331,0.1898 Z",type:0}},"":{type:5,data:{d:"M0.7639,0.1974 L0.9593,0.1974 L0.9593,0.1443 L0.7639,0.1443 L0.7639,0.1974 Z M0.7586,0.109 L0.9727,0.109 Q0.9839,0.109,0.992,0.1153 T1,0.1291 L1,0.382 Q1,0.3906,0.9912,0.3964 T0.9727,0.4021 L0.7586,0.4021 Q0.7468,0.4021,0.739,0.3956 T0.7313,0.382 L0.7313,0.1291 Q0.7313,0.1246,0.7339,0.1207 T0.7406,0.1143 T0.7495,0.1104 T0.7586,0.109 Z M0.7639,0.6575 L0.9593,0.6575 L0.9593,0.6044 L0.7639,0.6044 L0.7639,0.6575 Z M0.7313,0.8347 L0.7313,0.5843 Q0.7313,0.5757,0.7401,0.5699 T0.7586,0.5641 L0.9706,0.5641 Q0.9818,0.5641,0.9898,0.5705 T0.9979,0.5843 L0.9979,0.8347 Q0.9979,0.8433,0.989,0.8491 T0.9706,0.8549 L0.7586,0.8549 Q0.7468,0.8549,0.739,0.8483 T0.7313,0.8347 Z M0,1 L0,0 L0.7607,0 L0.7607,1 L0,1 Z",type:0}},"":{type:5,data:{d:"M0.9764,0.0029 L0.3179,0.4552 L0,0.4552 L0,0 Z M1,1 L0,1 L0,0.5448 L0.3091,0.5448 Z",type:0}},"":{type:5,data:{d:"M0.0236,0.0029 L0.6824,0.4552 L1,0.4552 L1,0 Z M0,1 L1,1 L1,0.5448 L0.6912,0.5448 Z",type:0}},"":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z"},"":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z"},"":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z"},"":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z M.25,.15 L1,.15 L1,.85 L.25,.85 Z"},"":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z M0,.15 L1,.15 L1,.85 L0,.85 Z"},"":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z M0,.15 L.75,.15 L.75,.85 L0,.85 Z"},"":{type:5,data:{d:"M0.6574,0.303 Q0.623,0.291,0.5852,0.285 T0.5082,0.279 T0.4311,0.285 T0.359,0.303 L0.3082,0.248 Q0.3525,0.232,0.4041,0.2235 T0.5082,0.215 T0.6123,0.2235 T0.7082,0.248 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.8557,0.582 L0.7656,0.551 Q0.7852,0.53,0.7951,0.507 T0.8049,0.46 Q0.8049,0.424,0.782,0.3905 T0.718,0.332 T0.6221,0.293 T0.5082,0.279 L0.5082,0.215 Q0.5607,0.215,0.6123,0.2235 T0.709,0.248 T0.7918,0.287 T0.8557,0.3375 T0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.582 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.5082,0.705 Q0.482,0.705,0.4557,0.703 T0.4049,0.697 L0.4311,0.635 Q0.4508,0.638,0.4697,0.6395 T0.5082,0.641 Q0.5672,0.641,0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 Q0.8049,0.436,0.7951,0.413 T0.7656,0.369 L0.8557,0.338 Q0.882,0.365,0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 L0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 T0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 L0.9098,0.46 Q0.9098,0.492,0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.338 L0.2508,0.369 Q0.2311,0.39,0.2213,0.413 T0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 Q0.5279,0.641,0.5467,0.6395 T0.5852,0.635 L0.6115,0.697 Q0.5869,0.701,0.5607,0.703 T0.5082,0.705 Z",type:0},scaleType:1},"":{type:5,data:{d:"M0.1607,0.582 Q0.1344,0.555,0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.3375 T0.2246,0.287 T0.3074,0.248 T0.4041,0.2235 T0.5082,0.215 L0.5082,0.279 Q0.4492,0.279,0.3943,0.293 T0.2984,0.332 T0.2344,0.3905 T0.2115,0.46 Q0.2115,0.484,0.2213,0.507 T0.2508,0.551 Z",type:0},scaleType:1},"":i.LINE_H,"":i.LINE_V,"":i.FADE_RIGHT,"":i.FADE_LEFT,"":i.FADE_DOWN,"":i.FADE_UP,"":i.CURVE_DOWN_RIGHT,"":i.CURVE_DOWN_LEFT,"":i.CURVE_UP_RIGHT,"":i.CURVE_UP_LEFT,"":[i.LINE_V,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_DOWN_RIGHT],"":[i.CURVE_DOWN_RIGHT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_UP_LEFT],"":[i.LINE_V,i.CURVE_DOWN_LEFT],"":[i.CURVE_DOWN_LEFT,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_DOWN_LEFT],"":[i.LINE_H,i.CURVE_DOWN_RIGHT],"":[i.CURVE_DOWN_LEFT,i.CURVE_DOWN_RIGHT],"":[i.LINE_H,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_UP_RIGHT],"":[i.CURVE_UP_LEFT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_UP_LEFT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_DOWN_LEFT,i.CURVE_DOWN_RIGHT],"":[i.LINE_H,i.CURVE_DOWN_LEFT,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_DOWN_RIGHT,i.CURVE_UP_RIGHT],"":[i.LINE_V,i.CURVE_DOWN_RIGHT,i.CURVE_UP_LEFT],"":[i.LINE_V,i.CURVE_DOWN_LEFT,i.CURVE_UP_RIGHT],"":[i.LINE_H,i.CURVE_DOWN_RIGHT,i.CURVE_UP_LEFT],"":[i.LINE_H,i.CURVE_DOWN_LEFT,i.CURVE_UP_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE],"":i.NODE_STROKE,"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN],"":[i.NODE_STROKE,i.NODE_LINE_DOWN],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP],"":[i.NODE_STROKE,i.NODE_LINE_UP],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_UP],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_UP],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_FILL,i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"":[i.NODE_STROKE,i.NODE_LINE_UP,i.NODE_LINE_DOWN,i.NODE_LINE_LEFT,i.NODE_LINE_RIGHT],"🬀":s(1),"🬁":s(2),"🬂":s(3),"🬃":s(4),"🬄":s(5),"🬅":s(6),"🬆":s(7),"🬇":s(8),"🬈":s(9),"🬉":s(10),"🬊":s(11),"🬋":s(12),"🬌":s(13),"🬍":s(14),"🬎":s(15),"🬏":s(16),"🬐":s(17),"🬑":s(18),"🬒":s(19),"🬓":s(20),"🬔":s(22),"🬕":s(23),"🬖":s(24),"🬗":s(25),"🬘":s(26),"🬙":s(27),"🬚":s(28),"🬛":s(29),"🬜":s(30),"🬝":s(31),"🬞":s(32),"🬟":s(33),"🬠":s(34),"🬡":s(35),"🬢":s(36),"🬣":s(37),"🬤":s(38),"🬥":s(39),"🬦":s(40),"🬧":s(41),"🬨":s(43),"🬩":s(44),"🬪":s(45),"🬫":s(46),"🬬":s(47),"🬭":s(48),"🬮":s(49),"🬯":s(50),"🬰":s(51),"🬱":s(52),"🬲":s(53),"🬳":s(54),"🬴":s(55),"🬵":s(56),"🬶":s(57),"🬷":s(58),"🬸":s(59),"🬹":s(60),"🬺":s(61),"🬻":s(62),"🬼":{type:3,data:"M0,0.6667 L0,1 L0.5,1 Z"},"🬽":{type:3,data:"M0,0.6667 L0,1 L1,1 Z"},"🬾":{type:3,data:"M0,0.3333 L0,1 L0.5,1 Z"},"🬿":{type:3,data:"M0,0.3333 L0,1 L1,1 Z"},"🭀":{type:3,data:"M0,0 L0,1 L0.5,1 Z"},"🭁":{type:3,data:"M0,0.3333 L0.5,0 L1,0 L1,1 L0,1 Z"},"🭂":{type:3,data:"M0,0.3333 L1,0 L1,1 L0,1 Z"},"🭃":{type:3,data:"M0,0.6667 L0.5,0 L1,0 L1,1 L0,1 Z"},"🭄":{type:3,data:"M0,0.6667 L1,0 L1,1 L0,1 Z"},"🭅":{type:3,data:"M0,1 L0.5,0 L1,0 L1,1 Z"},"🭆":{type:3,data:"M0,0.6667 L1,0.3333 L1,1 L0,1 Z"},"🭇":{type:3,data:"M0.5,1 L1,0.6667 L1,1 Z"},"🭈":{type:3,data:"M0,1 L1,0.6667 L1,1 Z"},"🭉":{type:3,data:"M0.5,1 L1,0.3333 L1,1 Z"},"🭊":{type:3,data:"M0,1 L1,0.3333 L1,1 Z"},"🭋":{type:3,data:"M0.5,1 L1,0 L1,1 Z"},"🭌":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.3333 Z"},"🭍":{type:3,data:"M0,0 L0,1 L1,1 L1,0.3333 Z"},"🭎":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.6667 Z"},"🭏":{type:3,data:"M0,0 L0,1 L1,1 L1,0.6667 Z"},"🭐":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 Z"},"🭑":{type:3,data:"M0,0.3333 L0,1 L1,1 L1,0.6667 Z"},"🭒":{type:3,data:"M0,0.6667 L0.5,1 L1,1 L1,0 L0,0 Z"},"🭓":{type:3,data:"M0,0.6667 L1,1 L1,0 L0,0 Z"},"🭔":{type:3,data:"M0,0.3333 L0.5,1 L1,1 L1,0 L0,0 Z"},"🭕":{type:3,data:"M0,0.3333 L1,1 L1,0 L0,0 Z"},"🭖":{type:3,data:"M0,0 L0.5,1 L1,1 L1,0 Z"},"🭗":{type:3,data:"M0,0.3333 L0,0 L0.5,0 Z"},"🭘":{type:3,data:"M0,0.3333 L0,0 L1,0 Z"},"🭙":{type:3,data:"M0,0.6667 L0,0 L0.5,0 Z"},"🭚":{type:3,data:"M0,0.6667 L0,0 L1,0 Z"},"🭛":{type:3,data:"M0,1 L0,0 L0.5,0 Z"},"🭜":{type:3,data:"M0,0.6667 L0,0 L1,0 L1,0.3333 Z"},"🭝":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.6667 Z"},"🭞":{type:3,data:"M0,1 L0,0 L1,0 L1,0.6667 Z"},"🭟":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.3333 Z"},"🭠":{type:3,data:"M0,1 L0,0 L1,0 L1,0.3333 Z"},"🭡":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 Z"},"🭢":{type:3,data:"M0.5,0 L1,0 L1,0.3333 Z"},"🭣":{type:3,data:"M0,0 L1,0 L1,0.3333 Z"},"🭤":{type:3,data:"M0.5,0 L1,0 L1,0.6667 Z"},"🭥":{type:3,data:"M0,0 L1,0 L1,0.6667 Z"},"🭦":{type:3,data:"M0.5,0 L1,0 L1,1 Z"},"🭧":{type:3,data:"M0,0.3333 L1,0.6667 L1,0 L0,0 Z"},"🭨":{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0.5,0.5 Z"},"🭩":{type:3,data:"M0,0 L0.5,0.5 L1,0 L1,1 L0,1 Z"},"🭪":{type:3,data:"M0,0 L1,0 L0.5,0.5 L1,1 L0,1 Z"},"🭫":{type:3,data:"M0,0 L1,0 L1,1 L0.5,0.5 L0,1 Z"},"🭬":{type:3,data:"M0,0 L0.5,0.5 L0,1 Z"},"🭭":{type:3,data:"M0,0 L1,0 L0.5,0.5 Z"},"🭮":{type:3,data:"M1,0 L1,1 L0.5,0.5 Z"},"🭯":{type:3,data:"M0,1 L1,1 L0.5,0.5 Z"},"🭰":{type:0,data:[{x:1,y:0,w:1,h:8}]},"🭱":{type:0,data:[{x:2,y:0,w:1,h:8}]},"🭲":{type:0,data:[{x:3,y:0,w:1,h:8}]},"🭳":{type:0,data:[{x:4,y:0,w:1,h:8}]},"🭴":{type:0,data:[{x:5,y:0,w:1,h:8}]},"🭵":{type:0,data:[{x:6,y:0,w:1,h:8}]},"🭶":{type:0,data:[{x:0,y:1,w:8,h:1}]},"🭷":{type:0,data:[{x:0,y:2,w:8,h:1}]},"🭸":{type:0,data:[{x:0,y:3,w:8,h:1}]},"🭹":{type:0,data:[{x:0,y:4,w:8,h:1}]},"🭺":{type:0,data:[{x:0,y:5,w:8,h:1}]},"🭻":{type:0,data:[{x:0,y:6,w:8,h:1}]},"🭼":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"🭽":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"🭾":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"🭿":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"🮀":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:7,w:8,h:1}]},"🮁":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:2,w:8,h:1},{x:0,y:4,w:8,h:1},{x:0,y:7,w:8,h:1}]},"🮂":{type:0,data:[{x:0,y:0,w:8,h:2}]},"🮃":{type:0,data:[{x:0,y:0,w:8,h:3}]},"🮄":{type:0,data:[{x:0,y:0,w:8,h:5}]},"🮅":{type:0,data:[{x:0,y:0,w:8,h:6}]},"🮆":{type:0,data:[{x:0,y:0,w:8,h:7}]},"🮇":{type:0,data:[{x:6,y:0,w:2,h:8}]},"🮈":{type:0,data:[{x:5,y:0,w:3,h:8}]},"🮉":{type:0,data:[{x:3,y:0,w:5,h:8}]},"🮊":{type:0,data:[{x:2,y:0,w:6,h:8}]},"🮋":{type:0,data:[{x:1,y:0,w:7,h:8}]},"🮌":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},"🮍":{type:1,data:[[1,0],[0,1]],clipPath:"M0.5,0 L1,0 L1,1 L0.5,1 Z"},"🮎":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},"🮏":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},"🮐":{type:1,data:[[0,1],[1,0]]},"🮑":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},{type:0,data:[{x:0,y:0,w:8,h:4}]}],"🮒":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},{type:0,data:[{x:0,y:4,w:8,h:4}]}],"🮔":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},{type:0,data:[{x:4,y:0,w:4,h:8}]}],"🮕":{type:0,data:[{x:0,y:0,w:2,h:2},{x:4,y:0,w:2,h:2},{x:2,y:2,w:2,h:2},{x:6,y:2,w:2,h:2},{x:0,y:4,w:2,h:2},{x:4,y:4,w:2,h:2},{x:2,y:6,w:2,h:2},{x:6,y:6,w:2,h:2}]},"🮖":{type:0,data:[{x:2,y:0,w:2,h:2},{x:6,y:0,w:2,h:2},{x:0,y:2,w:2,h:2},{x:4,y:2,w:2,h:2},{x:2,y:4,w:2,h:2},{x:6,y:4,w:2,h:2},{x:0,y:6,w:2,h:2},{x:4,y:6,w:2,h:2}]},"🮗":{type:0,data:[{x:0,y:2,w:8,h:2},{x:0,y:6,w:8,h:2}]},"🮘":{type:2,data:"M-0.25,-0.25 L1.25,1.25 M-0.25,0 L1,1.25 M-0.25,0.25 L0.75,1.25 M-0.25,0.5 L0.5,1.25 M0,-0.25 L1.25,1 M0.25,-0.25 L1.25,0.75 M0.5,-0.25 L1.25,0.5 M-0.25,0.75 L0.25,1.25 M0.75,-0.25 L1.25,0.25",strokeWidth:1},"🮙":{type:2,data:"M-0.25,0.5 L0.5,-0.25 M-0.25,0.75 L0.75,-0.25 M-0.25,1 L1,-0.25 M-0.25,1.25 L1.25,-0.25 M0,1.25 L1.25,0 M0.25,1.25 L1.25,0.25 M0.5,1.25 L1.25,0.5 M-0.25,0.25 L0.25,-0.25 M0.75,1.25 L1.25,0.75",strokeWidth:1},"🮚":{type:5,data:{d:"M0,0 L.5,.5 L0,1 L1,1 L.5,.5 L1,0",type:0}},"🮛":{type:5,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1",type:0}},"🮜":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L0,1 Z"},"🮝":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,1 Z"},"🮞":{type:1,data:[[1,0],[0,1]],clipPath:"M1,0 L1,1 L0,1 Z"},"🮟":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,1 L0,1 Z"},"🮠":{type:2,data:"M.5,0 L0,.5",strokeWidth:1},"🮡":{type:2,data:"M.5,0 L1,.5",strokeWidth:1},"🮢":{type:2,data:"M0,.5 L.5,1",strokeWidth:1},"🮣":{type:2,data:"M1,.5 L.5,1",strokeWidth:1},"🮤":{type:2,data:"M.5,0 L0,.5 L.5,1",strokeWidth:1},"🮥":{type:2,data:"M.5,0 L1,.5 L.5,1",strokeWidth:1},"🮦":{type:2,data:"M0,.5 L.5,1 L1,.5",strokeWidth:1},"🮧":{type:2,data:"M0,.5 L.5,0 L1,.5",strokeWidth:1},"🮨":{type:2,data:"M.5,0 L0,.5 M1,.5 L.5,1",strokeWidth:1},"🮩":{type:2,data:"M.5,0 L1,.5 M0,.5 L.5,1",strokeWidth:1},"🮪":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5",strokeWidth:1},"🮫":{type:2,data:"M.5,0 L0,.5 L.5,1 L1,.5",strokeWidth:1},"🮬":{type:2,data:"M0,.5 L.5,0 L1,.5 L.5,1",strokeWidth:1},"🮭":{type:2,data:"M1,.5 L.5,0 L0,.5 L.5,1",strokeWidth:1},"🮮":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5 Z",strokeWidth:1},"🮯":{type:2,data:"M0,.5 L1,.5 M.5,.35 L.5,.65",strokeWidth:1},"🮰":{type:3,data:"M0.1,0.2 L0.1,.8 L.4,.6 L.9,0.6 Z",scaleType:1},"🮱":{type:4,data:{d:"M.1,.525 L.35,.675 L.9,.35",type:1},scaleType:1},"🮲":{type:3,data:"M.29,.27 L0.13,.56 L.22,.59 L.35,0.35 L.67,.35 L.57,.57 L.71,.76 L.22,.76 L.42,1 L.53,.98 L.43,.86 L.9,.86 L.71,.6 L1,.6 L1,.52 L.83,.52 L.92,.36 L1,.36 L1,.27Z M.99,.13 A.12,.12,0,1,1,.75,.13 A.12,.12,0,1,1,.99,.13"},"🮳":{type:3,data:"M0,.27 L.3,.27 L.55,.12 L.63,.18 L.33,.36 L0,.36 M0,.52 L.33,.52 L.59,.89 L.73,.89 L.73,.98 L.53,.98 L.28,.6 L0,.6"},"🮴":{type:4,data:{d:"M.15,.55 L.5,.4 L.5,.45 L.65,.45 L.65,.35 L.85,.35 L.85,.625 L.5,.625 L.5,.7 Z",type:0},scaleType:1},"🮵":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.15,.5 L.5,.35 L.5,.425 L.85,.425 L.85,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"🮶":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.85,.5 L.5,.35 L.5,.425 L.15,.425 L.15,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"🮷":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.675 L.2,.5 L.35,.5 L.35,.325 L.65,.325 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"🮸":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.325 L.2,.5 L.35,.5 L.35,.675 L.65,.675 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"🮹":{type:5,data:{d:"M1,.89 L.11,.89 L.11,.37 L.36,.12 L.74,.12 L.96,.34 L1,.34 L1,.405 L.92,.405 L.69,.185 L.41,.185 L.21,.42 L.21,.825 L1,.825 Z",type:0}},"🮺":{type:5,data:{d:"M0,.89 L0,.825 L.78,.825 L.78,.53 L.7,.415 L0,.415 L0,.35 L.75,.35 L.88,.48 L.88,.89 Z",type:0}},"🮻":{type:5,data:{d:"M.31,.275 L.44,.275 L.44,.47 L.05,.47 L.05,.405 L.31,.405 Z M.56,.275 L.69,.275 L.69,.405 L.95,.405 L.95,.47 L.56,.47 Z M.05,.53 L.44,.53 L.44,.725 L.31,.725 L.31,.595 L.05,.595 Z M.56,.53 L.95,.53 L.95,.595 L.69,.595 L.69,.725 L.56,.725 Z",type:0},scaleType:1},"🮼":[{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0,.935 L.885,.935 L.885,.065 L0,.065 Z"},{type:3,data:"M.67,.5 A.17,.085,0,1,1,.33,.5 A.17,.085,0,1,1,.67,.5",scaleType:1}],"🮽":{type:4,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1 Z",type:1}},"🮾":{type:4,data:{d:"M1,.5 L.5,1",type:1}},"🮿":{type:4,data:{d:"M.5,0 L1,.5 L.5,1 L0,.5 Z",type:1}},"🯀":{type:3,data:"M.16,.445 A.02,.01,0,0,1,.39,.33 L.5,.375 L.61,.33 A.02,.01,0,0,1,.84,.445 L.75,.5 L.84,.555 A.02,.01,0,0,1,.61,.67 L.5,.625 L.39,.67 A.02,.01,0,0,1,.16,.555 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",scaleType:1},"🯁":{type:3,data:"M0.142308,0.924 Q0.130770,0.924,0.120193,0.922 T0.101924,0.916 T0.089424,0.9065 T0.084616,0.895 V0.025 Q0.084616,0.019,0.089424,0.0135 T0.101924,0.004 T0.120193,-0.002 T0.142308,-0.004 Q0.150000,-0.004,0.157693,-0.003 T0.173078,0.000 L0.430770,0.085 Q0.451924,0.059,0.494232,0.041 T0.587501,0.013 T0.692309,-0.0005 T0.800001,-0.004 H1 V0.055 H0.800001 Q0.771155,0.055,0.742309,0.056 T0.685578,0.060 T0.630770,0.0685 T0.580770,0.0825 T0.543270,0.1045 T0.528847,0.133 V0.647 H0.530770 Q0.596155,0.645,0.659616,0.638 T0.782693,0.6165 T0.893270,0.5805 T1,0.531 V0.623 Q0.934616,0.644,0.880770,0.6595 T0.769232,0.685 T0.650963,0.700 T0.528847,0.707 V0.787 Q0.528847,0.802,0.543270,0.8155 T0.580770,0.8375 T0.630770,0.8515 T0.685578,0.860 T0.742309,0.864 T0.800001,0.865 H1 V0.924 H0.800001 Q0.746155,0.924,0.692309,0.9205 T0.587501,0.907 T0.494232,0.879 T0.430770,0.835 L0.173078,0.920 Q0.165386,0.922,0.157693,0.923 T0.142308,0.924 Z M0.2,0.841 L0.415385,0.770 V0.150 L0.2,0.079 V0.841 Z M1,0.698 Q0.973077,0.694,0.969231,0.6885 T0.965385,0.677 Q0.965385,0.672,0.969231,0.6665 T1,0.657 V0.698 Z"},"🯂":{type:3,data:"M0,0.623 V0.531 Q0.044231,0.512,0.0625,0.4905 T0.092308,0.4465 T0.108654,0.4005 T0.113462,0.354 V0.351 Q0.113462,0.345,0.117308,0.3395 T0.129808,0.3305 T0.148846,0.3245 T0.171154,0.323 H0.501923 Q0.532692,0.323,0.563462,0.3185 T0.617308,0.303 T0.651923,0.2765 T0.663462,0.2435 V0.241 Q0.663462,0.219,0.657692,0.197 T0.639423,0.1545 T0.604808,0.115 T0.549615,0.082 T0.475577,0.0615 T0.392308,0.055 H0 V-0.004 H1 V0.055 H0.667308 Q0.694231,0.071,0.713462,0.09 T0.746154,0.129 T0.766346,0.1705 T0.775,0.213 H1 V0.316 Q0.971154,0.305,0.955769,0.2965 T0.920192,0.2825 T0.876923,0.2745 T0.830769,0.272 H0.773077 Q0.767308,0.297,0.743269,0.319 T0.680769,0.355 T0.595192,0.375 T0.501923,0.381 H0.227308 Q0.223462,0.415,0.211,0.4485 T0.172692,0.5135 T0.108269,0.573 T0,0.623 Z M0.611538,0.924 H0 V0.865 H0.611538 Q0.642308,0.865,0.673077,0.8605 T0.727885,0.845 T0.762308,0.8185 T0.773077,0.787 V0.785 Q0.773077,0.769,0.762308,0.7535 T0.727885,0.727 T0.673077,0.7115 T0.611538,0.707 H0.059615 Q0.048077,0.707,0.037115,0.7045 T0,0.694 V0.653 Q0.026923,0.648,0.037115,0.646 T0.059615,0.644 H0.722692 Q0.753462,0.644,0.784231,0.6395 T0.839038,0.624 T0.873846,0.5975 T0.884615,0.566 V0.564 Q0.884615,0.548,0.873846,0.532 T0.839038,0.5055 T0.784231,0.49 T0.722692,0.4855 H0.392308 Q0.380769,0.4855,0.370192,0.483 T0.351923,0.4765 T0.339423,0.467 T0.334615,0.4555 T0.339423,0.444 T0.351923,0.4345 T0.370192,0.428 T0.392308,0.4255 H0.832692 Q0.855769,0.4255,0.878846,0.4235 T0.922115,0.416 T0.957692,0.4015 T1,0.3815 V0.4685 Q0.975,0.4705,0.966346,0.4725 T0.95,0.4765 Q0.961538,0.4835,0.969231,0.4915 T1,0.5075 V0.6205 Q0.965385,0.6455,0.926923,0.665 T0.84,0.6935 Q0.866923,0.7115,0.877596,0.7345 T0.894231,0.7855 V0.787 Q0.894231,0.815,0.876923,0.8425 T0.820192,0.8895 T0.726923,0.916 T0.611538,0.924 Z"},"🯃":{type:3,data:"M0,0.473 V0.386 Q0.025490,0.378,0.028431,0.3695 T0.031373,0.352 V0.35 Q0.031373,0.342,0.028431,0.333 T0,0.316 V0.213 H0.652941 Q0.684314,0.213,0.715686,0.2085 T0.770588,0.193 T0.804902,0.1665 T0.815686,0.135 V0.133 Q0.815686,0.117,0.804902,0.101 T0.770588,0.0745 T0.715686,0.0595 T0.652941,0.055 H0 V-0.004 H0.652941 Q0.707843,-0.004,0.761765,0.004 T0.856863,0.031 T0.915686,0.0775 T0.933333,0.133 V0.135 Q0.933333,0.163,0.915686,0.1905 T0.856863,0.237 T0.761765,0.264 T0.652941,0.272 H0.109804 Q0.131373,0.29,0.140196,0.31 T0.149020,0.35 V0.352 Q0.149020,0.37,0.142157,0.388 T0.118627,0.4225 T0.076471,0.452 T0,0.473 Z M0,0.625 V0.513 Q0.029412,0.526,0.032353,0.54 T0.035294,0.568 V0.57 Q0.035294,0.584,0.032353,0.598 T0,0.625 Z"},"🯄":{type:3,data:"M0.019231,1.085 V-0.165 H0.980769 V1.085 H0.019231 Z M0.446154,0.527 H0.553846 Q0.553846,0.511,0.5625,0.495 T0.591346,0.466 T0.631731,0.4405 T0.666346,0.4135 T0.688462,0.3825 T0.696154,0.35 Q0.696154,0.33,0.682692,0.311 T0.641346,0.2785 T0.575,0.259 T0.498077,0.253 T0.421154,0.259 T0.356731,0.279 T0.315385,0.3125 T0.301923,0.352 V0.357 H0.409615 V0.354 Q0.409615,0.345,0.414423,0.335 T0.431731,0.318 T0.4625,0.3075 T0.498077,0.304 Q0.517308,0.304,0.534615,0.307 T0.564423,0.3165 T0.582692,0.332 T0.588462,0.35 Q0.588462,0.366,0.572115,0.3805 T0.535577,0.4075 T0.496154,0.4335 T0.465385,0.4625 T0.45,0.4945 T0.446154,0.527 Z M0.5,0.667 Q0.519231,0.667,0.5375,0.664 T0.569231,0.654 T0.588462,0.637 T0.594231,0.617 T0.588462,0.5975 T0.569231,0.581 T0.5375,0.571 T0.5,0.568 T0.4625,0.571 T0.430769,0.581 T0.411538,0.5975 T0.405769,0.617 T0.411538,0.637 T0.430769,0.654 T0.4625,0.664 T0.5,0.667 Z",scaleType:1},"🯅":{type:5,data:{d:"M.44,.425 L.44,.51 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.51 L.56,.425 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯆":{type:5,data:{d:"M.44,.425 L.44,.46 L.23,.385 L.19,.43 L.44,.51 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.61,.735 L.7,.71 L.56,.56 L.56,.51 L.81,.43 L.77,.385 L.56,.46 L.56,.425 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯇":{type:5,data:{d:"M.44,.425 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.425 Z M.18,.53 L.23,.575 L.81,.43 L.77,.385 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯈":{type:5,data:{d:"M.44,.425 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.62,.735 L.71,.71 L.56,.56 L.56,.425 Z M.23,.385 L.18,.43 L.77,.575 L.81,.53 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯉":{type:5,data:{d:"M.44,.425 L.45,.495 L.15,.645 L.34,.645 L.34,.7 L.44,.7 L.44,.645 L.56,.645 L.56,.7 L.66,.7 L.66,.645 L.84,.645 L.54,.495 L.56,.425 Z M.39,.6 L.5,.55 L.60,.6 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"🯊":{type:5,data:{d:"M.26,.375 L.5,.255 L.74,.375 L.74,.665 L.5,.55 L.26,.665 Z M.37,.395 L.37,.54 L.5,.475 L.63,.54 L.63,.395 L.5,.33 Z",type:0},scaleType:1},"🯋":{type:5,data:{d:"M.09,.41 L.32,.295 L.5,.375 L.68,.295 L.91,.41 L.75,.5 L.91,.59 L.68,.705 L.5,.625 L.32,.705 L.09,.59 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",type:0},scaleType:1},"🯌":{type:5,data:{d:"M.55,.305 L.88,.305 L.88,.355 L.65,.355 L.65,.47 L.88,.47 L.88,.52 L.55,.52 Z",type:0},scaleType:1},"🯍":{type:5,data:{d:"M.38,.39 L.5,.33 L.62,.39 L.62,.53 L.5,.47 L.38,.53 Z",type:0},scaleType:1},"🯎":{type:3,data:"M0,0 L0.6667,0 L0.6667,1 L0,1 Z"},"🯏":{type:3,data:"M0,0 L0.3333,0 L0.3333,1 L0,1 Z"},"🯐":{type:2,data:"M1,.5 L0,1",strokeWidth:1},"🯑":{type:2,data:"M1,0 L0,.5",strokeWidth:1},"🯒":{type:2,data:"M0,0 L1,.5",strokeWidth:1},"🯓":{type:2,data:"M0,.5 L1,1",strokeWidth:1},"🯔":{type:2,data:"M0,0 L.5,1",strokeWidth:1},"🯕":{type:2,data:"M.5,0 L1,1",strokeWidth:1},"🯖":{type:2,data:"M1,0 L.5,1",strokeWidth:1},"🯗":{type:2,data:"M.5,0 L0,1",strokeWidth:1},"🯘":{type:2,data:"M0,0 L.5,.5 L1,0",strokeWidth:1},"🯙":{type:2,data:"M1,0 L.5,.5 L1,1",strokeWidth:1},"🯚":{type:2,data:"M0,1 L.5,.5 L1,1",strokeWidth:1},"🯛":{type:2,data:"M0,0 L.5,.5 L0,1",strokeWidth:1},"🯜":{type:2,data:"M0,0 L.5,1 L1,0",strokeWidth:1},"🯝":{type:2,data:"M1,0 L0,.5 L1,1",strokeWidth:1},"🯞":{type:2,data:"M0,1 L.5,0 L1,1",strokeWidth:1},"🯟":{type:2,data:"M0,0 L1,.5 L0,1",strokeWidth:1},"🯠":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0",type:1}},"🯡":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1",type:1}},"🯢":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1",type:1}},"🯣":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1",type:1}},"🯤":{type:0,data:[{x:2,y:0,w:4,h:4}]},"🯥":{type:0,data:[{x:2,y:4,w:4,h:4}]},"🯦":{type:0,data:[{x:0,y:2,w:4,h:4}]},"🯧":{type:0,data:[{x:4,y:2,w:4,h:4}]},"🯨":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0 Z",type:0}},"🯩":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1 Z",type:0}},"🯪":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1 Z",type:0}},"🯫":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1 Z",type:0}},"🯬":{type:5,data:{d:"M1,0 L.5,0 C.5,.276,.724,.5,1,.5 Z",type:0}},"🯭":{type:5,data:{d:"M0,1 L.5,1 C.5,.724,.276,.5,0,.5 Z",type:0}},"🯮":{type:5,data:{d:"M1,1 L1,.5 C.724,.5,.5,.724,.5,1 Z",type:0}},"🯯":{type:5,data:{d:"M0,0 L0,.5 C.276,.5,.5,.276,.5,0 Z",type:0}},"🯰":{type:5,data:{d:r(126),type:0},scaleType:1},"🯱":{type:5,data:{d:r(48),type:0},scaleType:1},"🯲":{type:5,data:{d:r(109),type:0},scaleType:1},"🯳":{type:5,data:{d:r(121),type:0},scaleType:1},"🯴":{type:5,data:{d:r(51),type:0},scaleType:1},"🯵":{type:5,data:{d:r(91),type:0},scaleType:1},"🯶":{type:5,data:{d:r(95),type:0},scaleType:1},"🯷":{type:5,data:{d:r(114),type:0},scaleType:1},"🯸":{type:5,data:{d:r(127),type:0},scaleType:1},"🯹":{type:5,data:{d:r(123),type:0},scaleType:1},"🯺":{type:5,data:{d:"M.5,.175 C.2,.175,.15,.305,.15,.435 L.05,.63 L.35,.63 C.35,.682,.42,.76,.5,.76 C.58,.76,.65,.682,.65,.63 L.95,.63 L.85,.435 C.85,.305,.8,.175,.5,.175 Z",type:0},scaleType:1},...Object.fromEntries(Array.from({length:256},(t,e)=>[String.fromCodePoint(10240+e),{type:6,data:e}]))},e.blockPatternCodepoints=new Set([9617,9618,9619,129932,129933,129934,129935,129936,129937,129938,129940,129948,129949,129950,129951])},183(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.tryDrawCustomGlyph=function(t,e,i,s,o,n,L,h,T,l,d,c,_=0){const Q=r.customGlyphDefinitions[e];if(Q){const e=Array.isArray(Q)?Q:[Q];for(const r of e)a(t,r,i,s,o,n,L,h,T,l,d,c,_);return!0}return!1};const s=i(959),r=i(915);function a(t,e,i,r,a,h,d,c,_,Q,u,p,g=0){let M=a,y=h,v=i,f=r;switch(1===e.scaleType&&(M=d,y=c,v=i+(a-d)/2,f=r+(h-c)/2),e.clipPath&&(t.save(),function(t,e,i,s,r,a){t.beginPath();for(const o of e.split(" ")){const e=o[0];if("Z"===e){t.closePath();continue}const n=o.substring(1).split(",");if(!n[0]||!n[1])continue;const L=i+parseFloat(n[0])*r,h=s+parseFloat(n[1])*a;"M"===e?t.moveTo(L,h):"L"===e&&t.lineTo(L,h)}t.clip()}(t,e.clipPath,v,f,M,y)),e.type){case 0:!function(t,e,i,s,r,a){for(let o=0;o7&&parseInt(T.slice(7,9),16)||1;else{if(!T.startsWith("rgba"))throw new Error(`Unexpected fillStyle color format "${T}" when drawing pattern glyph`);[L,d,c,_]=T.substring(5,T.length-1).split(",").map(t=>parseFloat(t))}for(let t=0;t>1&1,c=1&n;0!==d||0!==c?l.setTransform((new DOMMatrix).translateSelf(-d,-c)):l.setTransform(new DOMMatrix),t.fillStyle=l,t.fillRect(i,r,a,o)}(t,e.data,v,f,M,y,g);break;case 2:!function(t,e,i,s,r,a,o,n,L){let h;t.save(),t.beginPath(),t.rect(i,s,r,a),t.clip(),t.beginPath(),h="function"==typeof e?e(.15,.15/a*r):e;const d={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(const e of h.split(" ")){const L=e[0];if("Z"===L){t.closePath(),d.lastCommand=L;continue}const h=T[L];if(!h){n.error(`Could not find drawing instructions for "${L}"`);continue}const c=e.substring(1).split(",");c[0]&&c[1]&&(h(t,l(c,r,a,i,s,!0,o,0,0,!1),d),d.lastCommand=L)}void 0!==L?(t.strokeStyle=t.fillStyle,t.lineWidth=o*L,t.stroke()):t.fill(),t.closePath(),t.restore()}(t,e.data,v,f,M,y,Q,u,e.strokeWidth);break;case 3:!function(t,e,i,s,r,a,o,L){const h="string"==typeof e?e:e(0,0);t.beginPath();let T=0,l=0,d=0,c=0,_="";for(const e of h.split(" ")){const o=e[0],L=e.substring(1).split(",");if("Z"===o){t.closePath(),_=o;continue}if("V"===o){const e=s+parseFloat(L[0])*a;t.lineTo(T,e),l=e,d=T,c=l,_=o;continue}if("H"===o){const e=i+parseFloat(L[0])*r;t.lineTo(e,l),T=e,d=T,c=l,_=o;continue}if(!L[0]||!L[1])continue;if("A"===o){const e=parseFloat(L[0])*r,o=parseFloat(L[1])*a,h=parseFloat(L[2])*Math.PI/180,d=parseInt(L[3],10),c=parseInt(L[4],10),_=i+parseFloat(L[5])*r,Q=s+parseFloat(L[6])*a;n(t,T,l,e,o,h,d,c,_,Q),T=_,l=Q;continue}const h=L.map((t,e)=>{const o=parseFloat(t);return e%2==0?i+o*r:s+o*a});if("M"===o)t.moveTo(h[0],h[1]),T=h[0],l=h[1],d=T,c=l;else if("L"===o)t.lineTo(h[0],h[1]),T=h[0],l=h[1],d=T,c=l;else if("Q"===o)t.quadraticCurveTo(h[0],h[1],h[2],h[3]),d=h[0],c=h[1],T=h[2],l=h[3];else if("T"===o){let e,i;"Q"===_||"T"===_?(e=2*T-d,i=2*l-c):(e=T,i=l),t.quadraticCurveTo(e,i,h[0],h[1]),d=e,c=i,T=h[0],l=h[1]}else"C"===o&&(t.bezierCurveTo(h[0],h[1],h[2],h[3],h[4],h[5]),d=h[2],c=h[3],T=h[4],l=h[5]);_=o}void 0!==L?(t.strokeStyle=t.fillStyle,t.lineWidth=o*L,t.stroke()):t.fill()}(t,e.data,v,f,M,y,Q,e.strokeWidth);break;case 4:!function(t,e,i,s,r,a,o,n){t.save(),t.fillRect(i,s,r,a),n&&(t.fillStyle=n,t.strokeStyle=n),t.lineWidth=o,t.lineCap="square",t.beginPath();for(const o of e.d.split(" ")){const e=o[0],n=o.substring(1).split(",");if(!n[0]||!n[1]){"Z"===e&&t.closePath();continue}const L=n.map((t,e)=>{const o=parseFloat(t);return e%2==0?i+o*r:s+o*a});"M"===e?t.moveTo(L[0],L[1]):"L"===e&&t.lineTo(L[0],L[1])}1===e.type?t.stroke():t.fill(),t.restore()}(t,e.data,v,f,M,y,Q,p);break;case 5:!function(t,e,i,s,r,a,o,n,L){const h=new Path2D;h.rect(i,s,r,a),t.clip(h),t.beginPath();const d=o/12;t.lineWidth=n*d;const c={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(const o of e.d.split(" ")){const h=o[0];if("Z"===h){t.closePath(),c.lastCommand=h;continue}const _=T[h];if(!_){L.error(`Could not find drawing instructions for "${h}"`);continue}const Q=o.substring(1).split(",");Q[0]&&Q[1]&&(_(t,l(Q,r,a,i,s,!1,n,(e.leftPadding??0)*(d/2),(e.rightPadding??0)*(d/2)),c),c.lastCommand=h)}1===e.type?(t.strokeStyle=t.fillStyle,t.stroke()):t.fill(),t.closePath()}(t,e.data,v,f,M,y,_,Q,u);break;case 6:!function(t,e,i,s,r,a){const n=r/8,L=.1*a,h=.8*a/8,T=Math.min(n,h);for(let r=0;r<8;r++)if(e&1<1){const t=Math.sqrt(y);u=(s*=t)*s,p=(r*=t)*r}let v=(u*p-u*M-p*g)/(u*M+p*g);v<0&&(v=0);const f=(o===n?-1:1)*Math.sqrt(v),C=f*(s*Q/r),m=f*(-r*_/s),w=T*C-l*m+(e+L)/2,x=l*C+T*m+(i+h)/2,b=(_-C)/s,E=(Q-m)/r,R=(-_-C)/s,k=(-Q-m)/r,A=Math.atan2(E,b);let Z=Math.atan2(k,R)-A;0===n&&Z>0?Z-=2*Math.PI:1===n&&Z<0&&(Z+=2*Math.PI);const D=A+Z;t.ellipse(w,x,s,r,a,A,D,0===n)}const L=new Map;function h(t,e,i=0){return Math.max(Math.min(t,e),i)}const T={C:(t,e,i)=>{t.bezierCurveTo(e[0],e[1],e[2],e[3],e[4],e[5]),i.lastControlX=e[2],i.lastControlY=e[3],i.currentX=e[4],i.currentY=e[5]},L:(t,e,i)=>{t.lineTo(e[0],e[1]),i.lastControlX=i.currentX=e[0],i.lastControlY=i.currentY=e[1]},M:(t,e,i)=>{t.moveTo(e[0],e[1]),i.lastControlX=i.currentX=e[0],i.lastControlY=i.currentY=e[1]},Q:(t,e,i)=>{t.quadraticCurveTo(e[0],e[1],e[2],e[3]),i.lastControlX=e[0],i.lastControlY=e[1],i.currentX=e[2],i.currentY=e[3]},T:(t,e,i)=>{let s,r;"Q"===i.lastCommand||"T"===i.lastCommand?(s=2*i.currentX-i.lastControlX,r=2*i.currentY-i.lastControlY):(s=i.currentX,r=i.currentY),t.quadraticCurveTo(s,r,e[0],e[1]),i.lastControlX=s,i.lastControlY=r,i.currentX=e[0],i.currentY=e[1]}};function l(t,e,i,s,r,a,o,n=0,L=0,T=!0){const l=t.map(t=>parseFloat(t)||parseInt(t));if(l.length<2)throw new Error("Too few arguments for instruction");for(let t=0;t{this._refreshCharAtlas(t,e),this.reset(t)})),this._register((0,r.toDisposable)(()=>{this._canvas.remove()}))}_initCanvas(){this._ctx=(0,a.throwIfFalsy)(this._canvas.getContext("2d",{alpha:this._alpha})),this._alpha||this._clearAll()}handleBlur(t){}handleFocus(t){}handleCursorMove(t){}handleGridChanged(t,e,i){}handleSelectionChanged(t,e,i,s=!1){}_setTransparency(t,e){if(e===this._alpha)return;const i=this._canvas;this._alpha=e,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,i),this._refreshCharAtlas(t,this._themeService.colors),this.handleGridChanged(t,0,t.rows-1)}_refreshCharAtlas(t,e){this._deviceCharWidth<=0&&this._deviceCharHeight<=0||(this._charAtlas=(0,s.acquireTextureAtlas)(t,this._optionsService.rawOptions,e,this._deviceCellWidth,this._deviceCellHeight,this._deviceCharWidth,this._deviceCharHeight,this._coreBrowserService.dpr,2048),this._charAtlas.warmUp())}resize(t,e){this._deviceCellWidth=e.device.cell.width,this._deviceCellHeight=e.device.cell.height,this._deviceCharWidth=e.device.char.width,this._deviceCharHeight=e.device.char.height,this._deviceCharLeft=e.device.char.left,this._deviceCharTop=e.device.char.top,this._canvas.width=e.device.canvas.width,this._canvas.height=e.device.canvas.height,this._canvas.style.width=`${e.css.canvas.width}px`,this._canvas.style.height=`${e.css.canvas.height}px`,this._alpha||this._clearAll(),this._refreshCharAtlas(t,this._themeService.colors)}_fillBottomLineAtCells(t,e,i=1){this._ctx.fillRect(t*this._deviceCellWidth,(e+1)*this._deviceCellHeight-this._coreBrowserService.dpr-1,i*this._deviceCellWidth,this._coreBrowserService.dpr)}_clearAll(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))}_clearCells(t,e,i,s){this._alpha?this._ctx.clearRect(t*this._deviceCellWidth,e*this._deviceCellHeight,i*this._deviceCellWidth,s*this._deviceCellHeight):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(t*this._deviceCellWidth,e*this._deviceCellHeight,i*this._deviceCellWidth,s*this._deviceCellHeight))}_fillCharTrueColor(t,e,i,s){this._ctx.font=this._getFont(t,!1,!1),this._ctx.textBaseline=o.TEXT_BASELINE,this._clipCell(i,s,e.getWidth()),this._ctx.fillText(e.getChars(),i*this._deviceCellWidth+this._deviceCharLeft,s*this._deviceCellHeight+this._deviceCharTop+this._deviceCharHeight)}_clipCell(t,e,i){this._ctx.beginPath(),this._ctx.rect(t*this._deviceCellWidth,e*this._deviceCellHeight,i*this._deviceCellWidth,this._deviceCellHeight),this._ctx.clip()}_getFont(t,e,i){return`${i?"italic":""} ${e?t.options.fontWeightBold:t.options.fontWeight} ${t.options.fontSize*this._coreBrowserService.dpr}px ${t.options.fontFamily}`}}e.BaseRenderLayer=n},306(t,e,i){Object.defineProperty(e,"__esModule",{value:!0}),e.LinkRenderLayer=void 0;const s=i(657),r=i(814),a=i(133);class o extends a.BaseRenderLayer{constructor(t,e,i,s,r,a,o){super(i,t,"link",e,!0,r,a,o),this._register(s.onShowLinkUnderline(t=>this._handleShowLinkUnderline(t))),this._register(s.onHideLinkUnderline(t=>this._handleHideLinkUnderline(t)))}resize(t,e){super.resize(t,e),this._state=void 0}reset(t){this._clearCurrentLink()}_clearCurrentLink(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);const t=this._state.y2-this._state.y1-1;t>0&&this._clearCells(0,this._state.y1+1,this._state.cols,t),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}}_handleShowLinkUnderline(t){if(t.fg===r.INVERTED_DEFAULT_COLOR?this._ctx.fillStyle=this._themeService.colors.background.css:void 0!==t.fg&&(0,s.is256Color)(t.fg)?this._ctx.fillStyle=this._themeService.colors.ansi[t.fg].css:this._ctx.fillStyle=this._themeService.colors.foreground.css,t.y1===t.y2)this._fillBottomLineAtCells(t.x1,t.y1,t.x2-t.x1);else{this._fillBottomLineAtCells(t.x1,t.y1,t.cols-t.x1);for(let e=t.y1+1;e{var t=s;Object.defineProperty(t,"__esModule",{value:!0}),t.WebglAddon=void 0;const e=i(426),r=i(95),a=i(399),o=i(414);class n extends e.Disposable{constructor(t){if(r.isSafari&&(0,r.getSafariVersion)()<16){const t={antialias:!1,depth:!1,preserveDrawingBuffer:!0};if(!document.createElement("canvas").getContext("webgl2",t))throw new Error("WebGL2 is only supported on Safari 16 and above")}super(),this._onChangeTextureAtlas=this._register(new o.Emitter),this.onChangeTextureAtlas=this._onChangeTextureAtlas.event,this._onAddTextureAtlasCanvas=this._register(new o.Emitter),this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=this._register(new o.Emitter),this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._onContextLoss=this._register(new o.Emitter),this.onContextLoss=this._onContextLoss.event,this._customGlyphs=t?.customGlyphs??!0,this._preserveDrawingBuffer=t?.preserveDrawingBuffer}activate(t){const i=t._core;if(!t.element)return void this._register(i.onWillOpen(()=>this.activate(t)));this._terminal=t;const s=i.coreService,r=i.optionsService,n=i,L=n._renderService,h=n._characterJoinerService,T=n._charSizeService,l=n._coreBrowserService,d=n._decorationService,c=n._logService,_=n._themeService;this._renderer=this._register(new a.WebglRenderer(t,h,T,l,s,d,c,r,_,this._customGlyphs,this._preserveDrawingBuffer)),this._register(o.EventUtils.forward(this._renderer.onContextLoss,this._onContextLoss)),this._register(o.EventUtils.forward(this._renderer.onChangeTextureAtlas,this._onChangeTextureAtlas)),this._register(o.EventUtils.forward(this._renderer.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas)),this._register(o.EventUtils.forward(this._renderer.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas)),L.setRenderer(this._renderer),this._register((0,e.toDisposable)(()=>{if(this._terminal._core._store._isDisposed)return;const e=this._terminal._core._renderService;e.setRenderer(this._terminal._core._createRenderer()),e.handleResize(t.cols,t.rows)}))}get textureAtlas(){return this._renderer?.textureAtlas}clearTextureAtlas(){this._renderer?.clearTextureAtlas()}}t.WebglAddon=n})(),s})()); //# sourceMappingURL=addon-webgl.js.map \ No newline at end of file diff --git a/lib/addon-webgl.mjs b/lib/addon-webgl.mjs -index 73e0de80affdf478c39b7ac1d8666e34bd3d6e31..dc563e7c5f0d5ce00729ceabece415b886a7a2ff 100644 +index 73e0de80affdf478c39b7ac1d8666e34bd3d6e31..e0f3c25039e12dc0c9094b2d19aa628849c354ca 100644 --- a/lib/addon-webgl.mjs +++ b/lib/addon-webgl.mjs @@ -14,7 +14,7 @@ @@ -16,7 +16,7 @@ index 73e0de80affdf478c39b7ac1d8666e34bd3d6e31..dc563e7c5f0d5ce00729ceabece415b8 * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -function M(i){return{dispose:i}}function Ft(i){if(!i)return i;if(Array.isArray(i)){for(let e of i)e.dispose();return[]}return i.dispose(),i}function De(...i){return M(()=>Ft(i))}var R0=class{constructor(){this._disposables=new Set;this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(e){return this._isDisposed?e.dispose():this._disposables.add(e),e}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.clear()}}clear(){for(let e of this._disposables)e.dispose();this._disposables.clear()}},W=class{constructor(){this._store=new R0}dispose(){this._store.dispose()}_register(e){return this._store.add(e)}};W.None=Object.freeze({dispose(){}});var m0=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}};var Pe=!!(typeof process<"u"&&"title"in process&&(typeof navigator>"u"||navigator.userAgent.startsWith("Node.js/"))),O0=Pe?"node":navigator.userAgent,ce=Pe?"node":navigator.platform,Be=O0.includes("Firefox"),n1=O0.includes("Chrome"),we=O0.includes("Edge"),ue=/^((?!chrome|android).)*safari/i.test(O0);function He(){if(!ue)return 0;let i=O0.match(/Version\/(\d+)/);return i===null||i.length<2?0:parseInt(i[1],10)}var a1=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(ce),o1=["Windows","Win16","Win32","WinCE"].includes(ce),T1=ce.indexOf("Linux")>=0,l1=/\bCrOS\b/.test(O0);var P=0,B=0,w=0,x=0,K={css:"#00000000",rgba:0},Z;(r=>{function i(s,a,o,n){return n!==void 0?`#${E0(s)}${E0(a)}${E0(o)}${E0(n)}`:`#${E0(s)}${E0(a)}${E0(o)}`}r.toCss=i;function e(s,a,o,n=255){return(s<<24|a<<16|o<<8|n)>>>0}r.toRgba=e;function t(s,a,o,n){return{css:r.toCss(s,a,o,n),rgba:r.toRgba(s,a,o,n)}}r.toColor=t})(Z||={});var I0;(n=>{function i(L,T){if(x=(T.rgba&255)/255,x===1)return{css:T.css,rgba:T.rgba};let h=T.rgba>>24&255,d=T.rgba>>16&255,_=T.rgba>>8&255,p=L.rgba>>24&255,c=L.rgba>>16&255,u=L.rgba>>8&255;P=p+Math.round((h-p)*x),B=c+Math.round((d-c)*x),w=u+Math.round((_-u)*x);let C=Z.toCss(P,B,w),Q=Z.toRgba(P,B,w);return{css:C,rgba:Q}}n.blend=i;function e(L){return(L.rgba&255)===255}n.isOpaque=e;function t(L,T,h){let d=d0.ensureContrastRatio(L.rgba,T.rgba,h);if(d)return Z.toColor(d>>24&255,d>>16&255,d>>8&255)}n.ensureContrastRatio=t;function r(L){let T=(L.rgba|255)>>>0;return[P,B,w]=d0.toChannels(T),{css:Z.toCss(P,B,w),rgba:T}}n.opaque=r;function s(L,T){return x=Math.round(T*255),[P,B,w]=d0.toChannels(L.rgba),{css:Z.toCss(P,B,w,x),rgba:Z.toRgba(P,B,w,x)}}n.opacity=s;function a(L,T){return x=L.rgba&255,s(L,x*T/255)}n.multiplyOpacity=a;function o(L){return[L.rgba>>24&255,L.rgba>>16&255,L.rgba>>8&255]}n.toColorRGB=o})(I0||={});var Mt;(r=>{let i,e;try{let s=document.createElement("canvas");s.width=1,s.height=1;let a=s.getContext("2d",{willReadFrequently:!0});a&&(i=a,i.globalCompositeOperation="copy",e=i.createLinearGradient(0,0,1,1))}catch{}function t(s){if(s.match(/#[\da-f]{3,8}/i))switch(s.length){case 4:return P=parseInt(s.slice(1,2).repeat(2),16),B=parseInt(s.slice(2,3).repeat(2),16),w=parseInt(s.slice(3,4).repeat(2),16),Z.toColor(P,B,w);case 5:return P=parseInt(s.slice(1,2).repeat(2),16),B=parseInt(s.slice(2,3).repeat(2),16),w=parseInt(s.slice(3,4).repeat(2),16),x=parseInt(s.slice(4,5).repeat(2),16),Z.toColor(P,B,w,x);case 7:return{css:s,rgba:(parseInt(s.slice(1),16)<<8|255)>>>0};case 9:return{css:s,rgba:parseInt(s.slice(1),16)>>>0}}let a=s.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(a)return P=parseInt(a[1],10),B=parseInt(a[2],10),w=parseInt(a[3],10),x=Math.round((a[5]===void 0?1:parseFloat(a[5]))*255),Z.toColor(P,B,w,x);if(s==="transparent")return{css:"transparent",rgba:0};if(!i||!e)throw new Error("css.toColor: Unsupported css format");if(i.fillStyle=e,i.fillStyle=s,typeof i.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(i.fillRect(0,0,1,1),[P,B,w,x]=i.getImageData(0,0,1,1).data,x!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Z.toRgba(P,B,w,x),css:s}}r.toColor=t})(Mt||={});var V;(t=>{function i(r){return e(r>>16&255,r>>8&255,r&255)}t.relativeLuminance=i;function e(r,s,a){let o=r/255,n=s/255,L=a/255,T=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),h=n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4),d=L<=.03928?L/12.92:Math.pow((L+.055)/1.055,2.4);return T*.2126+h*.7152+d*.0722}t.relativeLuminance2=e})(V||={});var d0;(a=>{function i(o,n){if(x=(n&255)/255,x===1)return n;let L=n>>24&255,T=n>>16&255,h=n>>8&255,d=o>>24&255,_=o>>16&255,p=o>>8&255;return P=d+Math.round((L-d)*x),B=_+Math.round((T-_)*x),w=p+Math.round((h-p)*x),Z.toRgba(P,B,w)}a.blend=i;function e(o,n,L){let T=V.relativeLuminance(o>>8),h=V.relativeLuminance(n>>8);if(h0(T,h)>8));if(u>8));return u>Q?c:C}return c}let _=r(o,n,L),p=h0(T,V.relativeLuminance(_>>8));if(p>8));return p>u?_:c}return _}}a.ensureContrastRatio=e;function t(o,n,L){let T=o>>24&255,h=o>>16&255,d=o>>8&255,_=n>>24&255,p=n>>16&255,c=n>>8&255,u=h0(V.relativeLuminance2(_,p,c),V.relativeLuminance2(T,h,d));for(;u0||p>0||c>0);)_-=Math.max(0,Math.ceil(_*.1)),p-=Math.max(0,Math.ceil(p*.1)),c-=Math.max(0,Math.ceil(c*.1)),u=h0(V.relativeLuminance2(_,p,c),V.relativeLuminance2(T,h,d));return(_<<24|p<<16|c<<8|255)>>>0}a.reduceLuminance=t;function r(o,n,L){let T=o>>24&255,h=o>>16&255,d=o>>8&255,_=n>>24&255,p=n>>16&255,c=n>>8&255,u=h0(V.relativeLuminance2(_,p,c),V.relativeLuminance2(T,h,d));for(;u>>0}a.increaseLuminance=r;function s(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}a.toChannels=s})(d0||={});function E0(i){let e=i.toString(16);return e.length<2?"0"+e:e}function h0(i,e){return i=128512&&i<=128591||i>=127744&&i<=128511||i>=128640&&i<=128767||i>=9728&&i<=9983||i>=9984&&i<=10175||i>=65024&&i<=65039||i>=129280&&i<=129535||i>=127462&&i<=127487}function Ze(i,e,t,r){return e===1&&t>Math.ceil(r*1.5)&&i!==void 0&&i>255&&!yt(i)&&!W0(i)&&!At(i)}function V0(i){return W0(i)||gt(i)}function Ue(){return{css:{canvas:U0(),cell:U0()},device:{canvas:U0(),cell:U0(),char:{width:0,height:0,left:0,top:0}}}}function U0(){return{width:0,height:0}}function We(i,e,t=0){return(i-(Math.round(e)*2-t))%(Math.round(e)*2)}var l;(C=>(C.LINE_H=Object.freeze({type:2,data:"M0,.5 L1,.5",strokeWidth:1}),C.LINE_V=Object.freeze({type:2,data:"M.5,0 L.5,1",strokeWidth:1}),C.FADE_RIGHT=Object.freeze({type:2,data:"M0,.5 L.28,.5 M.32,.5 L.52,.5 M.60,.5 L.72,.5 M.84,.5 L.90,.5",strokeWidth:1}),C.FADE_LEFT=Object.freeze({type:2,data:"M.10,.5 L.16,.5 M.28,.5 L.40,.5 M.48,.5 L.68,.5 M.72,.5 L1,.5",strokeWidth:1}),C.FADE_DOWN=Object.freeze({type:2,data:"M.5,0 L.5,.28 M.5,.32 L.5,.52 M.5,.60 L.5,.72 M.5,.84 L.5,.90",strokeWidth:1}),C.FADE_UP=Object.freeze({type:2,data:"M.5,.10 L.5,.16 M.5,.28 L.5,.40 M.5,.48 L.5,.68 M.5,.72 L.5,1",strokeWidth:1}),C.CURVE_DOWN_RIGHT=Object.freeze({type:2,data:(Q,m)=>`M.5,1 L.5,${.5+m/.15*.5} C.5,${.5+m/.15*.5},.5,.5,1,.5`,strokeWidth:1}),C.CURVE_DOWN_LEFT=Object.freeze({type:2,data:(Q,m)=>`M.5,1 L.5,${.5+m/.15*.5} C.5,${.5+m/.15*.5},.5,.5,0,.5`,strokeWidth:1}),C.CURVE_UP_RIGHT=Object.freeze({type:2,data:(Q,m)=>`M.5,0 L.5,${.5-m/.15*.5} C.5,${.5-m/.15*.5},.5,.5,1,.5`,strokeWidth:1}),C.CURVE_UP_LEFT=Object.freeze({type:2,data:(Q,m)=>`M.5,0 L.5,${.5-m/.15*.5} C.5,${.5-m/.15*.5},.5,.5,0,.5`,strokeWidth:1}),C.NODE_FILL=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5"}),C.NODE_STROKE=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5",strokeWidth:1}),C.NODE_LINE_RIGHT=Object.freeze({type:3,data:"M1,.5 L.85,.5",strokeWidth:1}),C.NODE_LINE_LEFT=Object.freeze({type:3,data:"M0,.5 L.15,.5",strokeWidth:1}),C.NODE_LINE_DOWN=Object.freeze({type:3,data:"M.5,1 L.5,.7",strokeWidth:1}),C.NODE_LINE_UP=Object.freeze({type:3,data:"M.5,0 L.5,.3",strokeWidth:1})))(l||={});var Ve={"\u2500":{type:2,data:"M0,.5 L1,.5",strokeWidth:1},"\u2501":{type:2,data:"M0,.5 L1,.5",strokeWidth:3},"\u2502":{type:2,data:"M.5,0 L.5,1",strokeWidth:1},"\u2503":{type:2,data:"M.5,0 L.5,1",strokeWidth:3},"\u2504":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:1},"\u2505":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:3},"\u2506":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:1},"\u2507":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:3},"\u2508":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:1},"\u2509":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:3},"\u250A":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:1},"\u250B":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:3},"\u250C":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},"\u250D":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u250E":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u250F":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3},"\u2510":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},"\u2511":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u2512":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2513":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3},"\u2514":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},"\u2515":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u2516":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2517":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3},"\u2518":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},"\u2519":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u251A":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u251B":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3},"\u251C":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},"\u251D":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u251E":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u251F":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2520":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"\u2521":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"\u2522":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"\u2523":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3},"\u2524":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},"\u2525":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u2526":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2527":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2528":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"\u2529":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"\u252A":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"\u252B":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3},"\u252C":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},"\u252D":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u252E":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u252F":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"\u2530":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2531":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"\u2532":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"\u2533":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3},"\u2534":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:1},"\u2535":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u2536":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u2537":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"\u2538":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2539":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"\u253A":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"\u253B":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:3},"\u253C":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:1},"\u253D":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u253E":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u253F":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"\u2540":[{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2541":[{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2542":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"\u2543":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"\u2544":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"\u2545":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"\u2546":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"\u2547":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:3}],"\u2548":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3}],"\u2549":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3}],"\u254A":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3}],"\u254B":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:3},"\u254C":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:1},"\u254D":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:3},"\u254E":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:1},"\u254F":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:3},"\u2550":{type:2,data:(i,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u2551":{type:2,data:(i,e)=>`M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1`,strokeWidth:1},"\u2552":{type:2,data:(i,e)=>`M.5,1 L.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u2553":{type:2,data:(i,e)=>`M${.5-i},1 L${.5-i},.5 L1,.5 M${.5+i},.5 L${.5+i},1`,strokeWidth:1},"\u2554":{type:2,data:(i,e)=>`M1,${.5-e} L${.5-i},${.5-e} L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1`,strokeWidth:1},"\u2555":{type:2,data:(i,e)=>`M0,${.5-e} L.5,${.5-e} L.5,1 M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"\u2556":{type:2,data:(i,e)=>`M${.5+i},1 L${.5+i},.5 L0,.5 M${.5-i},.5 L${.5-i},1`,strokeWidth:1},"\u2557":{type:2,data:(i,e)=>`M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M0,${.5-e} L${.5+i},${.5-e} L${.5+i},1`,strokeWidth:1},"\u2558":{type:2,data:(i,e)=>`M.5,0 L.5,${.5+e} L1,${.5+e} M.5,${.5-e} L1,${.5-e}`,strokeWidth:1},"\u2559":{type:2,data:(i,e)=>`M1,.5 L${.5-i},.5 L${.5-i},0 M${.5+i},.5 L${.5+i},0`,strokeWidth:1},"\u255A":{type:2,data:(i,e)=>`M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0 M1,${.5+e} L${.5-i},${.5+e} L${.5-i},0`,strokeWidth:1},"\u255B":{type:2,data:(i,e)=>`M0,${.5+e} L.5,${.5+e} L.5,0 M0,${.5-e} L.5,${.5-e}`,strokeWidth:1},"\u255C":{type:2,data:(i,e)=>`M0,.5 L${.5+i},.5 L${.5+i},0 M${.5-i},.5 L${.5-i},0`,strokeWidth:1},"\u255D":{type:2,data:(i,e)=>`M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0 M0,${.5+e} L${.5+i},${.5+e} L${.5+i},0`,strokeWidth:1},"\u255E":{type:2,data:(i,e)=>`M.5,0 L.5,1 M.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u255F":{type:2,data:(i,e)=>`M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1 M${.5+i},.5 L1,.5`,strokeWidth:1},"\u2560":{type:2,data:(i,e)=>`M${.5-i},0 L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1 M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0`,strokeWidth:1},"\u2561":{type:2,data:(i,e)=>`M.5,0 L.5,1 M0,${.5-e} L.5,${.5-e} M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"\u2562":{type:2,data:(i,e)=>`M0,.5 L${.5-i},.5 M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1`,strokeWidth:1},"\u2563":{type:2,data:(i,e)=>`M${.5+i},0 L${.5+i},1 M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0`,strokeWidth:1},"\u2564":{type:2,data:(i,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e} M.5,${.5+e} L.5,1`,strokeWidth:1},"\u2565":{type:2,data:(i,e)=>`M0,.5 L1,.5 M${.5-i},.5 L${.5-i},1 M${.5+i},.5 L${.5+i},1`,strokeWidth:1},"\u2566":{type:2,data:(i,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1`,strokeWidth:1},"\u2567":{type:2,data:(i,e)=>`M.5,0 L.5,${.5-e} M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u2568":{type:2,data:(i,e)=>`M0,.5 L1,.5 M${.5-i},.5 L${.5-i},0 M${.5+i},.5 L${.5+i},0`,strokeWidth:1},"\u2569":{type:2,data:(i,e)=>`M0,${.5+e} L1,${.5+e} M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0 M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0`,strokeWidth:1},"\u256A":{type:2,data:(i,e)=>`M.5,0 L.5,1 M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u256B":{type:2,data:(i,e)=>`M0,.5 L1,.5 M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1`,strokeWidth:1},"\u256C":{type:2,data:(i,e)=>`M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1 M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0 M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0`,strokeWidth:1},"\u256D":{type:2,data:(i,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"\u256E":{type:2,data:(i,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"\u256F":{type:2,data:(i,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"\u2570":{type:2,data:(i,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"\u2571":{type:2,data:"M1,0 L0,1",strokeWidth:1},"\u2572":{type:2,data:"M0,0 L1,1",strokeWidth:1},"\u2573":{type:2,data:"M1,0 L0,1 M0,0 L1,1",strokeWidth:1},"\u2574":{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},"\u2575":{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},"\u2576":{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},"\u2577":{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},"\u2578":{type:2,data:"M.5,.5 L0,.5",strokeWidth:3},"\u2579":{type:2,data:"M.5,.5 L.5,0",strokeWidth:3},"\u257A":{type:2,data:"M.5,.5 L1,.5",strokeWidth:3},"\u257B":{type:2,data:"M.5,.5 L.5,1",strokeWidth:3},"\u257C":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u257D":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u257E":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u257F":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2580":{type:0,data:[{x:0,y:0,w:8,h:4}]},"\u2581":{type:0,data:[{x:0,y:7,w:8,h:1}]},"\u2582":{type:0,data:[{x:0,y:6,w:8,h:2}]},"\u2583":{type:0,data:[{x:0,y:5,w:8,h:3}]},"\u2584":{type:0,data:[{x:0,y:4,w:8,h:4}]},"\u2585":{type:0,data:[{x:0,y:3,w:8,h:5}]},"\u2586":{type:0,data:[{x:0,y:2,w:8,h:6}]},"\u2587":{type:0,data:[{x:0,y:1,w:8,h:7}]},"\u2588":{type:0,data:[{x:0,y:0,w:8,h:8}]},"\u2589":{type:0,data:[{x:0,y:0,w:7,h:8}]},"\u258A":{type:0,data:[{x:0,y:0,w:6,h:8}]},"\u258B":{type:0,data:[{x:0,y:0,w:5,h:8}]},"\u258C":{type:0,data:[{x:0,y:0,w:4,h:8}]},"\u258D":{type:0,data:[{x:0,y:0,w:3,h:8}]},"\u258E":{type:0,data:[{x:0,y:0,w:2,h:8}]},"\u258F":{type:0,data:[{x:0,y:0,w:1,h:8}]},"\u2590":{type:0,data:[{x:4,y:0,w:4,h:8}]},"\u2591":{type:1,data:[[1,0],[0,0]]},"\u2592":{type:1,data:[[1,0],[0,1]]},"\u2593":{type:1,data:[[1,1],[1,0]]},"\u2594":{type:0,data:[{x:0,y:0,w:8,h:1}]},"\u2595":{type:0,data:[{x:7,y:0,w:1,h:8}]},"\u2596":{type:0,data:[{x:0,y:4,w:4,h:4}]},"\u2597":{type:0,data:[{x:4,y:4,w:4,h:4}]},"\u2598":{type:0,data:[{x:0,y:0,w:4,h:4}]},"\u2599":{type:0,data:[{x:0,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"\u259A":{type:0,data:[{x:0,y:0,w:4,h:4},{x:4,y:4,w:4,h:4}]},"\u259B":{type:0,data:[{x:0,y:0,w:4,h:8},{x:4,y:0,w:4,h:4}]},"\u259C":{type:0,data:[{x:0,y:0,w:8,h:4},{x:4,y:0,w:4,h:8}]},"\u259D":{type:0,data:[{x:4,y:0,w:4,h:4}]},"\u259E":{type:0,data:[{x:4,y:0,w:4,h:4},{x:0,y:4,w:4,h:4}]},"\u259F":{type:0,data:[{x:4,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"\uE0A0":{type:5,data:{d:"M.3,1 L.03,1 L.03,.88 C.03,.82,.06,.78,.11,.73 C.15,.7,.2,.68,.28,.65 L.43,.6 C.49,.58,.53,.56,.56,.53 C.59,.5,.6,.47,.6,.43 L.6,.27 L.4,.27 L.69,.1 L.98,.27 L.78,.27 L.78,.46 C.78,.52,.76,.56,.72,.61 C.68,.66,.63,.67,.56,.7 L.48,.72 C.42,.74,.38,.76,.35,.78 C.32,.8,.31,.84,.31,.88 L.31,1 M.3,.5 L.03,.59 L.03,.09 L.3,.09 L.3,.655",type:0}},"\uE0A1":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.355,.03 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"\uE0A2":{type:5,data:{d:"M.25,.94 C.16,.94,.11,.92,.11,.87 L.11,.53 C.11,.48,.15,.455,.23,.45 L.23,.3 C.23,.25,.26,.22,.31,.19 C.36,.16,.43,.15,.51,.15 C.59,.15,.66,.16,.71,.19 C.77,.22,.79,.26,.79,.3 L.79,.45 C.87,.45,.91,.48,.91,.53 L.91,.87 C.91,.92,.86,.94,.77,.94 L.24,.94 M.53,.2 C.49,.2,.45,.21,.42,.23 C.39,.25,.38,.27,.38,.3 L.38,.45 L.68,.45 L.68,.3 C.68,.27,.67,.25,.64,.23 C.61,.21,.58,.2,.53,.2 M.58,.82 L.58,.66 C.63,.65,.65,.63,.65,.6 C.65,.58,.64,.57,.61,.56 C.58,.55,.56,.54,.52,.54 C.48,.54,.46,.55,.43,.56 C.4,.57,.39,.59,.39,.6 C.39,.63,.41,.64,.46,.66 L.46,.82 L.57,.82",type:0}},"\uE0A3":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.7,.03 L.7,.1 L.355,.1 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"\uE0B0":{type:5,data:{d:"M0,0 L1,.5 L0,1",type:0,rightPadding:2}},"\uE0B1":{type:5,data:{d:"M-1,-.5 L1,.5 L-1,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0B2":{type:5,data:{d:"M1,0 L0,.5 L1,1",type:0,leftPadding:2}},"\uE0B3":{type:5,data:{d:"M2,-.5 L0,.5 L2,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0B4":{type:5,data:{d:"M0,0 L0,1 C0.552,1,1,0.776,1,.5 C1,0.224,0.552,0,0,0",type:0,rightPadding:1}},"\uE0B5":{type:5,data:{d:"M.2,1 C.422,1,.8,.826,.78,.5 C.8,.174,0.422,0,.2,0",type:1,rightPadding:1}},"\uE0B6":{type:5,data:{d:"M1,0 L1,1 C0.448,1,0,0.776,0,.5 C0,0.224,0.448,0,1,0",type:0,leftPadding:1}},"\uE0B7":{type:5,data:{d:"M.8,1 C0.578,1,0.2,.826,.22,.5 C0.2,0.174,0.578,0,0.8,0",type:1,leftPadding:1}},"\uE0B8":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L-.5,1.5",type:0}},"\uE0B9":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0BA":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L1.5,1.5",type:0}},"\uE0BB":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0BC":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L-.5,-.5",type:0}},"\uE0BD":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0BE":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L1.5,-.5",type:0}},"\uE0BF":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0C0":{type:5,data:{d:"M0.8069,0.6075 Q0.7991,0.612,0.7815,0.6218 T0.7542,0.6369 T0.7282,0.6508 T0.7016,0.6644 T0.6778,0.6758 T0.6551,0.6854 T0.637,0.6911 T0.622,0.6936 Q0.6186,0.6936,0.6128,0.6942 T0.6018,0.6952 T0.5894,0.6956 T0.5757,0.6952 T0.561,0.693 T0.5451,0.6879 Q0.5342,0.6834,0.5193,0.6756 T0.4925,0.6614 T0.4673,0.6485 T0.4436,0.6389 T0.4239,0.6363 T0.4089,0.6422 Q0.4045,0.6467,0.3958,0.6554 T0.3843,0.6669 T0.3748,0.6746 T0.3613,0.683 T0.3442,0.6903 L0.3499,0.6956 Q0.3584,0.7042,0.3679,0.7177 T0.3836,0.7403 T0.4019,0.7583 T0.4295,0.7703 Q0.4688,0.7785,0.5203,0.7605 Q0.4902,0.7817,0.449,0.7911 T0.3696,0.8001 Q0.3567,0.7997,0.341,0.7942 T0.3111,0.7813 T0.2805,0.766 T0.2493,0.753 T0.218,0.7472 T0.187,0.754 Q0.1762,0.7589,0.1653,0.7681 T0.1453,0.7895 T0.1308,0.818 T0.1264,0.8507 L0.1264,0.858 Q0.1453,0.8462,0.1607,0.8433 T0.1899,0.8452 T0.2226,0.8625 Q0.2344,0.8707,0.2485,0.8752 T0.2813,0.8831 T0.3089,0.889 Q0.2981,0.8915,0.2846,0.8956 T0.2603,0.9037 T0.2368,0.9115 T0.2129,0.9174 T0.1894,0.9194 T0.1653,0.9155 Q0.1504,0.9115,0.1328,0.9196 T0.0986,0.9421 T0.0655,0.9708 T0.0317,0.9943 T0,1 Q0.001,0.94,0.0017,0.6508 T0.0024,0.2322 Q0.002,0.2109,0.0007,0.1379 T0,0.0249 Q0.0058,0.0253,0.009,0.0257 T0.0156,0.0288 T0.0203,0.0333 T0.0264,0.0422 T0.0349,0.0539 Q0.044,0.0657,0.0542,0.072 T0.0752,0.0789 T0.096,0.0775 T0.1175,0.0694 T0.1379,0.0573 T0.1579,0.0432 Q0.2141,0,0.2673,0.0318 Q0.2588,0.0318,0.2517,0.033 T0.239,0.0361 T0.2276,0.0424 T0.218,0.0504 T0.2085,0.0612 T0.1997,0.0732 T0.1899,0.0875 T0.1795,0.1028 Q0.1748,0.1093,0.1507,0.1234 T0.1186,0.1448 Q0.0999,0.1612,0.1108,0.1783 Q0.1162,0.1877,0.1238,0.1928 T0.1404,0.1979 T0.158,0.1967 T0.1775,0.1895 T0.1963,0.1791 T0.2151,0.1663 T0.2314,0.1534 T0.2458,0.141 T0.2561,0.1322 Q0.2815,0.1106,0.3017,0.101 T0.344,0.0926 T0.3919,0.1077 Q0.4099,0.1175,0.4265,0.1206 T0.4588,0.1202 T0.488,0.1098 T0.5176,0.0914 Q0.5071,0.1032,0.4963,0.1122 T0.4722,0.1285 T0.4497,0.1401 T0.4223,0.1518 T0.3943,0.1636 Q0.374,0.1726,0.3623,0.1863 T0.3482,0.2162 Q0.3445,0.2403,0.3608,0.2605 T0.4072,0.2876 Q0.4194,0.2909,0.4326,0.2899 T0.457,0.2856 T0.4805,0.2764 T0.5032,0.264 T0.5256,0.2497 T0.5478,0.2352 T0.5698,0.2222 T0.5921,0.2118 Q0.6982,0.173,0.81,0.2436 Q0.833,0.2583,0.8496,0.2674 T0.887,0.2846 T0.925,0.294 T0.9617,0.2911 T1,0.2746 Q0.9817,0.2946,0.96,0.3056 T0.9175,0.3191 T0.8731,0.3209 T0.8277,0.3164 T0.7818,0.3109 T0.7359,0.3101 T0.6907,0.3197 T0.647,0.3448 Q0.6443,0.3472,0.6333,0.3562 T0.6194,0.3674 T0.6076,0.3766 T0.594,0.386 T0.5815,0.3931 T0.5661,0.4007 T0.5501,0.4064 L0.5556,0.4121 Q0.5627,0.4198,0.5722,0.4251 T0.5926,0.4337 T0.6131,0.439 T0.6343,0.4431 T0.6521,0.4468 Q0.6762,0.4529,0.7056,0.4463 Q0.6772,0.4623,0.6543,0.471 T0.604,0.4814 Q0.5962,0.4818,0.5815,0.4825 T0.5591,0.4835 T0.5393,0.4857 T0.519,0.4908 T0.5007,0.4996 T0.4812,0.5141 T0.4627,0.5353 L0.4549,0.5451 L0.4661,0.543 Q0.4759,0.541,0.4909,0.55 T0.5315,0.5796 T0.5684,0.6083 Q0.5799,0.6161,0.5915,0.6212 T0.6181,0.6308 L0.6331,0.6353 Q0.6514,0.6418,0.7004,0.633 T0.8069,0.6075 Z",type:0}},"\uE0C1":{type:5,data:{d:"M0.011,0.0469 Q0.0152,0.0412,0.02,0.0361 T0.0292,0.0281 T0.0365,0.0253 Q0.0426,0.0257,0.0461,0.0263 T0.0534,0.03 T0.0582,0.0345 T0.0645,0.0434 T0.0723,0.0546 Q0.0807,0.0653,0.0897,0.0712 T0.1081,0.0775 T0.1255,0.0765 T0.1438,0.0695 T0.1605,0.0593 T0.1772,0.0473 Q0.2388,0,0.2927,0.0326 L0.2614,0.0767 L0.2581,0.0767 Q0.2494,0.0767,0.2444,0.0773 T0.2359,0.0789 T0.2291,0.0842 T0.2233,0.0922 T0.2146,0.1054 T0.2026,0.1236 Q0.1943,0.1354,0.1843,0.1444 T0.1675,0.1574 T0.1526,0.1654 T0.1429,0.1701 Q0.1436,0.1717,0.1446,0.1733 Q0.1504,0.1823,0.1581,0.1866 T0.1733,0.1915 T0.1909,0.1884 T0.2085,0.1809 T0.2265,0.169 T0.2427,0.1564 T0.2575,0.1436 T0.2688,0.1338 Q0.2969,0.1101,0.3195,0.0995 T0.3643,0.0901 T0.4114,0.1048 Q0.4279,0.1138,0.4426,0.1168 T0.4705,0.117 T0.4945,0.1089 T0.5186,0.0942 L0.5211,0.0926 L0.5289,0.0922 Q0.5411,0.095,0.5189,0.1203 Q0.505,0.1358,0.4913,0.1474 T0.4634,0.167 T0.4389,0.1796 T0.4121,0.1909 T0.3866,0.2011 Q0.3782,0.2047,0.3727,0.2092 Q0.3717,0.2117,0.3714,0.2141 Q0.3695,0.2263,0.3751,0.2388 T0.394,0.2616 T0.4253,0.2761 Q0.4398,0.2785,0.4513,0.2779 T0.4756,0.2724 T0.4987,0.2616 T0.5216,0.2476 T0.5453,0.2321 T0.5703,0.217 T0.5976,0.2043 Q0.7015,0.166,0.8099,0.2345 Q0.8361,0.2512,0.8572,0.2616 T0.9006,0.2779 T0.9432,0.281 T0.9819,0.2663 L0.9887,0.2671 Q1,0.272,0.9768,0.2969 Q0.9558,0.3193,0.9319,0.333 T0.8858,0.3513 T0.8391,0.3569 T0.793,0.3546 T0.7485,0.3497 T0.7065,0.3473 T0.6681,0.3522 T0.6344,0.3699 Q0.5963,0.4005,0.5847,0.4082 Q0.595,0.4139,0.6079,0.4174 T0.6367,0.4237 T0.6586,0.4278 Q0.6793,0.4331,0.7044,0.4278 Q0.7057,0.4278,0.707,0.4274 Q0.7067,0.429,0.7062,0.4313 T0.7036,0.4398 T0.6993,0.4513 T0.6931,0.4619 T0.6851,0.4698 Q0.6573,0.4857,0.6336,0.4947 T0.5831,0.5053 Q0.577,0.5057,0.5615,0.5065 T0.5394,0.508 T0.5221,0.51 T0.5042,0.5139 T0.4905,0.5204 Q0.5008,0.5232,0.515,0.5328 T0.549,0.5585 T0.5799,0.5824 Q0.5905,0.5897,0.6013,0.5946 T0.6262,0.6036 T0.6409,0.6081 Q0.6567,0.6134,0.7035,0.605 T0.8028,0.5816 L0.7974,0.5922 T0.7867,0.6134 L0.7812,0.624 Q0.7799,0.6248,0.7786,0.6252 Q0.7709,0.6297,0.7573,0.6372 T0.7346,0.6499 T0.7123,0.6621 T0.6897,0.6741 T0.6686,0.6847 T0.648,0.6941 T0.6297,0.7013 T0.6129,0.7062 T0.5995,0.7076 Q0.5992,0.7076,0.5831,0.7092 T0.5529,0.7092 T0.525,0.7019 Q0.5105,0.6958,0.4824,0.6811 T0.4356,0.6586 T0.4079,0.6533 Q0.3872,0.6741,0.3827,0.6782 Q0.3872,0.6835,0.3934,0.6929 T0.4037,0.7078 T0.4142,0.7198 T0.4284,0.7304 T0.4466,0.7365 Q0.4824,0.7443,0.5292,0.728 L0.5292,0.7294 T0.529,0.7333 T0.5284,0.7392 T0.5266,0.7463 T0.5236,0.7539 T0.5186,0.7612 T0.5111,0.7679 Q0.5086,0.77,0.5056,0.7716 Q0.4466,0.8104,0.3591,0.8091 Q0.344,0.8091,0.3246,0.802 T0.2893,0.7863 T0.2543,0.77 T0.2206,0.76 T0.1894,0.7643 Q0.1804,0.7684,0.1733,0.7753 Q0.1591,0.7892,0.1601,0.8169 Q0.1784,0.8067,0.1938,0.8053 T0.2212,0.8087 T0.2507,0.825 Q0.2614,0.8324,0.2744,0.8365 T0.3053,0.844 T0.332,0.8499 L0.303,0.894 L0.2998,0.8948 Q0.2904,0.8968,0.278,0.9009 T0.2554,0.9086 T0.233,0.9158 T0.2099,0.9213 T0.1868,0.9229 T0.1633,0.9192 Q0.1517,0.916,0.1367,0.9241 T0.1065,0.9462 T0.0753,0.9737 T0.041,0.9955 T0.0061,1 Q0,0.9984,0.0068,0.9845 Q0.009,0.9804,0.0123,0.9755 Q0.0187,0.9666,0.0261,0.9606 T0.0374,0.9555 Q0.0481,0.958,0.0629,0.949 T0.0931,0.9262 T0.1247,0.8987 T0.1597,0.8777 T0.1949,0.8752 Q0.213,0.8805,0.2343,0.8772 Q0.2249,0.8736,0.2172,0.8683 Q0.1914,0.8511,0.1738,0.8497 T0.1349,0.8617 Q0.1304,0.865,0.1273,0.8646 T0.1242,0.8605 L0.1239,0.8536 Q0.1226,0.8295,0.1354,0.8016 T0.1723,0.7496 Q0.1914,0.7308,0.2104,0.7219 Q0.2259,0.7145,0.2425,0.7141 T0.273,0.7182 T0.3022,0.7296 T0.3301,0.7439 T0.3569,0.7571 T0.3821,0.7643 Q0.373,0.7561,0.3598,0.7367 T0.3382,0.7088 L0.3327,0.7035 Q0.3282,0.699,0.3353,0.6884 T0.3517,0.6692 L0.3611,0.6607 Q0.3711,0.657,0.3751,0.6554 T0.3837,0.6507 T0.3898,0.6458 T0.3979,0.637 T0.4111,0.6236 Q0.4172,0.6175,0.4234,0.6138 Q0.4327,0.6081,0.4439,0.6077 T0.4655,0.6105 T0.4884,0.6201 T0.5113,0.633 T0.5347,0.6468 T0.5573,0.6578 Q0.5705,0.6635,0.5833,0.665 T0.6112,0.665 T0.6286,0.6635 Q0.6421,0.6631,0.6718,0.6501 Q0.626,0.6578,0.6089,0.6517 Q0.6063,0.6509,0.6002,0.6491 T0.5884,0.6454 T0.5757,0.6409 T0.561,0.6344 T0.5466,0.6256 Q0.536,0.6183,0.5108,0.5989 T0.4722,0.5712 T0.4527,0.564 L0.4418,0.5661 Q0.4308,0.5681,0.4366,0.5563 Q0.4401,0.5485,0.4476,0.5392 L0.455,0.5298 Q0.4631,0.5188,0.4714,0.51 T0.4866,0.4947 T0.5021,0.4831 T0.516,0.4749 T0.53,0.4694 T0.5428,0.4657 T0.5558,0.4637 T0.5674,0.4629 T0.5795,0.4625 Q0.5489,0.4543,0.534,0.4384 L0.5286,0.4327 Q0.5244,0.4282,0.5318,0.4174 T0.5486,0.398 L0.5579,0.3899 Q0.567,0.387,0.5749,0.3834 T0.5878,0.3772 T0.6012,0.3687 T0.6126,0.3603 T0.6268,0.3487 T0.6421,0.3361 Q0.6567,0.3242,0.6712,0.3159 T0.7009,0.3034 T0.7277,0.2973 T0.7556,0.2961 T0.7809,0.2977 T0.8074,0.301 Q0.8096,0.3014,0.8109,0.3016 T0.8143,0.302 T0.818,0.3026 Q0.8012,0.2936,0.7767,0.2781 Q0.6718,0.2117,0.5744,0.2476 Q0.5637,0.2516,0.5492,0.2604 T0.5218,0.2779 T0.4923,0.2965 T0.461,0.3124 T0.4282,0.3216 T0.394,0.3206 Q0.3637,0.3136,0.3474,0.2936 T0.3353,0.2459 Q0.3385,0.2247,0.355,0.2023 Q0.3646,0.1892,0.3763,0.179 Q0.3898,0.1672,0.4063,0.1595 Q0.3927,0.1562,0.3785,0.1485 Q0.3604,0.1387,0.3453,0.1354 T0.3161,0.1354 T0.2899,0.1458 T0.2627,0.166 Q0.262,0.1664,0.254,0.1733 T0.2414,0.1841 T0.2267,0.196 T0.2094,0.2086 T0.1915,0.2196 T0.1725,0.2288 T0.1546,0.2337 T0.1373,0.2343 T0.1223,0.228 T0.1097,0.2145 Q0.0962,0.1929,0.1258,0.1582 Q0.131,0.1517,0.1371,0.1464 Q0.1462,0.1387,0.156,0.1321 T0.1752,0.1205 T0.1878,0.1134 Q0.1891,0.1117,0.1947,0.103 T0.2035,0.0899 T0.2125,0.0781 T0.2243,0.064 Q0.1949,0.0616,0.1672,0.0828 Q0.153,0.0934,0.1412,0.1009 T0.1146,0.1146 T0.0873,0.1213 T0.0616,0.116 T0.0374,0.0962 Q0.0339,0.0909,0.0295,0.0846 T0.024,0.0767 T0.0202,0.0728 T0.0148,0.0704 T0.0068,0.0697 Q0.0003,0.0693,0.0058,0.0567 Q0.0077,0.0522,0.011,0.0469 Z",type:0}},"\uE0C2":{type:5,data:{d:"M0.1934,0.6075 Q0.2012,0.612,0.2188,0.6218 T0.2459,0.6369 T0.2718,0.6508 T0.2983,0.6644 T0.322,0.6758 T0.3447,0.6854 T0.363,0.6911 T0.3783,0.6936 Q0.3796,0.6936,0.396,0.6952 T0.4265,0.6952 T0.4548,0.6879 Q0.4656,0.6834,0.4805,0.6756 T0.5073,0.6614 T0.5327,0.6485 T0.5564,0.6389 T0.5759,0.6363 T0.5909,0.6422 Q0.5953,0.6467,0.604,0.6554 T0.6155,0.6669 T0.6251,0.6746 T0.6387,0.683 T0.6556,0.6903 L0.6498,0.6956 Q0.6414,0.7042,0.6319,0.7177 T0.6162,0.7403 T0.5979,0.7583 T0.5703,0.7703 Q0.5313,0.7785,0.4799,0.7605 Q0.5097,0.7817,0.5508,0.7911 T0.6302,0.8001 Q0.6431,0.7997,0.659,0.7942 T0.6888,0.7813 T0.7194,0.766 T0.7506,0.753 T0.7819,0.7472 T0.8131,0.754 Q0.8239,0.7589,0.8346,0.7681 T0.8544,0.7895 T0.8689,0.818 T0.8737,0.8507 L0.8733,0.858 Q0.8591,0.849,0.8474,0.845 T0.8242,0.8421 T0.8021,0.8482 T0.7772,0.8625 Q0.7653,0.8707,0.7513,0.8752 T0.7184,0.8831 T0.6908,0.889 Q0.7017,0.8915,0.7152,0.8956 T0.7396,0.9037 T0.7633,0.9115 T0.7872,0.9174 T0.8107,0.9194 T0.8347,0.9155 Q0.8493,0.9115,0.8671,0.9196 T0.9015,0.9421 T0.9345,0.9708 T0.9682,0.9943 T0.9997,1 Q0.999,0.94,0.9983,0.6508 T0.9976,0.2322 Q0.9976,0.2109,0.9992,0.1379 T1,0.0249 Q0.9949,0.0249,0.9917,0.0257 T0.9863,0.0273 T0.9817,0.0308 T0.9776,0.0357 T0.9721,0.0437 T0.9651,0.0539 Q0.956,0.0657,0.9456,0.072 T0.9247,0.0789 T0.904,0.0775 T0.8823,0.0694 T0.862,0.0573 T0.8422,0.0432 Q0.7856,0,0.7328,0.0318 Q0.7392,0.0318,0.7452,0.0324 T0.756,0.0345 T0.7657,0.0386 T0.7741,0.0437 T0.7821,0.0506 T0.7894,0.0588 T0.7966,0.0683 T0.8039,0.0787 T0.8119,0.0904 T0.8202,0.1028 Q0.8249,0.1093,0.849,0.1234 T0.8811,0.1448 Q0.8998,0.1612,0.8893,0.1783 Q0.8835,0.1877,0.8759,0.1928 T0.8593,0.1979 T0.8417,0.1967 T0.8222,0.1895 T0.8034,0.1791 T0.7848,0.1663 T0.7687,0.1534 T0.7543,0.141 T0.744,0.1322 Q0.7186,0.1106,0.6984,0.101 T0.6559,0.0926 T0.6082,0.1077 Q0.5899,0.1175,0.5733,0.1206 T0.5411,0.1202 T0.5122,0.1098 T0.4822,0.0914 Q0.4927,0.1032,0.5036,0.1122 T0.5276,0.1285 T0.5503,0.1401 T0.5777,0.1518 T0.6055,0.1636 Q0.6258,0.1726,0.6375,0.1863 T0.6519,0.2162 Q0.6556,0.2403,0.6392,0.2605 T0.5926,0.2876 Q0.5804,0.2909,0.5672,0.2899 T0.5428,0.2856 T0.5193,0.2764 T0.4966,0.264 T0.4744,0.2497 T0.4523,0.2352 T0.4301,0.2222 T0.4077,0.2118 Q0.3021,0.173,0.1903,0.2436 Q0.1669,0.2583,0.1504,0.2674 T0.1129,0.2846 T0.075,0.294 T0.0384,0.2911 T0,0.2746 Q0.021,0.297,0.0459,0.3082 T0.0953,0.3207 T0.146,0.3193 T0.1988,0.3131 T0.2508,0.3095 T0.3029,0.3176 T0.3529,0.3448 Q0.3566,0.348,0.3652,0.355 T0.3771,0.3645 T0.3877,0.3731 T0.3993,0.3815 T0.4103,0.3884 T0.4226,0.3953 T0.4352,0.4009 T0.4497,0.4064 L0.4443,0.4121 Q0.4372,0.4198,0.4277,0.4251 T0.4072,0.4337 T0.3867,0.439 T0.3656,0.4431 T0.3481,0.4468 Q0.3241,0.4529,0.2943,0.4463 Q0.3227,0.4623,0.3458,0.471 T0.3959,0.4814 Q0.404,0.4818,0.4187,0.4825 T0.4409,0.4835 T0.4605,0.4857 T0.4809,0.4908 T0.4992,0.4996 T0.5186,0.5141 T0.5371,0.5353 L0.5449,0.5451 L0.5337,0.543 Q0.5242,0.541,0.5091,0.55 T0.4683,0.5796 T0.4314,0.6083 Q0.4203,0.6161,0.4086,0.6212 T0.382,0.6308 T0.3667,0.6353 Q0.3485,0.6418,0.2995,0.633 T0.1934,0.6075 Z",type:0}},"\uE0C3":{type:5,data:{d:"M0.989,0.0469 Q0.9829,0.0379,0.9753,0.0316 T0.9635,0.0253 Q0.9574,0.0257,0.9539,0.0263 T0.9466,0.03 T0.9418,0.0345 T0.9355,0.0434 T0.9277,0.0546 Q0.9193,0.0653,0.9103,0.0712 T0.8919,0.0775 T0.8745,0.0765 T0.8564,0.0695 T0.8396,0.0593 T0.8228,0.0473 Q0.7612,0,0.7073,0.0326 L0.7386,0.0767 L0.7419,0.0767 Q0.7506,0.0767,0.7556,0.0773 T0.7641,0.0789 T0.7709,0.0842 T0.7767,0.0922 T0.7854,0.1054 T0.7974,0.1236 Q0.8057,0.1354,0.8157,0.1444 T0.8325,0.1574 T0.8474,0.1654 T0.8571,0.1701 Q0.8564,0.1717,0.8554,0.1733 Q0.8503,0.1815,0.844,0.186 T0.8301,0.1909 T0.8153,0.1903 T0.7993,0.1845 T0.7836,0.1758 T0.768,0.1648 T0.754,0.1535 T0.741,0.1425 T0.7312,0.1338 Q0.7031,0.1101,0.6805,0.0995 T0.6357,0.0901 T0.5886,0.1048 Q0.5721,0.1138,0.5574,0.1168 T0.5295,0.117 T0.5055,0.1089 T0.4814,0.0942 L0.4789,0.0926 L0.4711,0.0922 Q0.4589,0.095,0.4811,0.1203 Q0.495,0.1358,0.5087,0.1474 T0.5366,0.167 T0.5611,0.1796 T0.5879,0.1909 T0.6134,0.2011 Q0.6218,0.2047,0.6273,0.2092 Q0.6283,0.2117,0.6286,0.2141 Q0.6305,0.2263,0.6249,0.2388 T0.606,0.2616 T0.5747,0.2761 Q0.5602,0.2785,0.5487,0.2779 T0.5245,0.2724 T0.5015,0.2616 T0.4784,0.2476 T0.4547,0.2321 T0.4297,0.217 T0.4024,0.2043 Q0.2985,0.166,0.1901,0.2345 Q0.1694,0.248,0.1523,0.2569 T0.1165,0.2726 T0.0818,0.2812 T0.0494,0.2796 T0.0181,0.2663 L0.0116,0.2671 Q0,0.272,0.0232,0.2969 Q0.0468,0.3222,0.0742,0.3365 T0.1278,0.3542 T0.1807,0.3564 T0.233,0.352 T0.2815,0.3473 T0.3269,0.3509 T0.3656,0.3699 Q0.4037,0.4005,0.4153,0.4082 Q0.405,0.4139,0.3921,0.4174 T0.3633,0.4237 T0.3414,0.4278 Q0.3207,0.4331,0.2956,0.4278 Q0.2943,0.4278,0.293,0.4274 Q0.2933,0.429,0.2938,0.4313 T0.2964,0.4398 T0.3007,0.4513 T0.3069,0.4619 T0.3149,0.4698 Q0.3427,0.4857,0.3664,0.4947 T0.4169,0.5053 Q0.423,0.5057,0.4385,0.5065 T0.4606,0.508 T0.4779,0.51 T0.4958,0.5139 T0.5095,0.5204 Q0.4992,0.5232,0.485,0.5328 T0.451,0.5585 T0.4201,0.5824 Q0.4095,0.5897,0.3987,0.5946 T0.3738,0.6036 T0.3591,0.6081 Q0.3433,0.6134,0.2965,0.605 T0.1972,0.5816 L0.2026,0.5922 T0.2133,0.6134 L0.2188,0.624 Q0.2201,0.6248,0.2214,0.6252 Q0.2291,0.6297,0.2486,0.6405 T0.2786,0.657 T0.3066,0.6721 T0.3353,0.6866 T0.3598,0.6972 T0.383,0.7051 T0.4005,0.7076 Q0.4008,0.7076,0.4169,0.7092 T0.4471,0.7092 T0.475,0.7019 Q0.4895,0.6958,0.5176,0.6811 T0.5644,0.6586 T0.5921,0.6533 Q0.6128,0.6741,0.6173,0.6782 Q0.6131,0.6835,0.6068,0.6929 T0.5963,0.7078 T0.5858,0.7198 T0.5716,0.7304 T0.5534,0.7365 Q0.5179,0.7443,0.4708,0.728 L0.4708,0.7294 T0.471,0.7333 T0.4716,0.7392 T0.4734,0.7463 T0.4764,0.7539 T0.4814,0.7612 T0.4889,0.7679 Q0.4914,0.77,0.4944,0.7716 Q0.5534,0.8104,0.6409,0.8091 Q0.6521,0.8091,0.6654,0.8053 T0.6907,0.7959 T0.7157,0.7838 T0.741,0.772 T0.7652,0.7631 T0.7888,0.7594 T0.8106,0.7643 Q0.8196,0.7684,0.8267,0.7753 Q0.8409,0.7892,0.8399,0.8169 Q0.8216,0.8067,0.8062,0.8053 T0.7788,0.8087 T0.7493,0.825 Q0.7386,0.8324,0.7256,0.8365 T0.6947,0.844 T0.668,0.8499 L0.697,0.894 L0.7002,0.8948 Q0.7099,0.8968,0.7222,0.9009 T0.7446,0.9086 T0.767,0.9158 T0.7901,0.9213 T0.8132,0.9229 T0.8367,0.9192 Q0.8483,0.916,0.8633,0.9241 T0.8937,0.9462 T0.9248,0.9737 T0.959,0.9955 T0.9939,1 Q1,0.9984,0.9932,0.9845 Q0.991,0.9804,0.9877,0.9755 Q0.9813,0.9666,0.9739,0.9606 T0.9626,0.9555 Q0.9519,0.958,0.9372,0.949 T0.9071,0.9262 T0.8753,0.8987 T0.8403,0.8777 T0.8051,0.8752 Q0.787,0.8805,0.7657,0.8772 Q0.7751,0.8736,0.7828,0.8683 Q0.8086,0.8511,0.8262,0.8497 T0.8651,0.8617 Q0.8696,0.865,0.8727,0.8646 T0.8758,0.8605 L0.8761,0.8536 Q0.8774,0.8295,0.8646,0.8016 T0.8277,0.7496 Q0.8086,0.7308,0.7896,0.7219 Q0.7741,0.7145,0.7575,0.7141 T0.727,0.7182 T0.6978,0.7296 T0.6699,0.7439 T0.6433,0.7571 T0.6179,0.7643 Q0.627,0.7561,0.6402,0.7367 T0.6618,0.7088 L0.6673,0.7035 Q0.6718,0.699,0.6647,0.6884 T0.6483,0.6692 L0.6389,0.6607 Q0.6289,0.657,0.6249,0.6554 T0.6163,0.6507 T0.6102,0.6458 T0.6021,0.637 T0.5889,0.6236 Q0.5828,0.6175,0.5766,0.6138 Q0.5673,0.6081,0.5561,0.6077 T0.5345,0.6105 T0.5116,0.6201 T0.4887,0.633 T0.4653,0.6468 T0.4427,0.6578 Q0.4295,0.6635,0.4167,0.665 T0.3888,0.665 T0.3714,0.6635 Q0.3579,0.6631,0.3282,0.6501 Q0.374,0.6578,0.3911,0.6517 Q0.3937,0.6509,0.4024,0.6482 T0.4179,0.6434 T0.4348,0.6364 T0.4534,0.6256 Q0.464,0.6183,0.4892,0.5989 T0.5278,0.5712 T0.5476,0.564 L0.5582,0.5661 Q0.5692,0.5681,0.5634,0.5563 Q0.5599,0.5485,0.5524,0.5392 L0.545,0.5298 Q0.5369,0.5188,0.5286,0.51 T0.5134,0.4947 T0.4979,0.4831 T0.484,0.4749 T0.47,0.4694 T0.4572,0.4657 T0.4442,0.4637 T0.4326,0.4629 T0.4205,0.4625 Q0.4511,0.4543,0.466,0.4384 L0.4714,0.4327 Q0.4795,0.4237,0.4469,0.394 L0.4421,0.3899 Q0.433,0.387,0.4251,0.3834 T0.4122,0.3772 T0.3988,0.3687 T0.3874,0.3603 T0.3732,0.3487 T0.3579,0.3361 Q0.3433,0.3242,0.3288,0.3159 T0.2993,0.3034 T0.2725,0.2973 T0.2446,0.2961 T0.2193,0.2977 T0.1926,0.301 Q0.1855,0.3022,0.182,0.3026 Q0.1991,0.2936,0.2233,0.2781 Q0.3282,0.2117,0.4256,0.2476 Q0.4363,0.2516,0.451,0.2604 T0.4784,0.2779 T0.5077,0.2965 T0.539,0.3124 T0.5718,0.3216 T0.606,0.3206 Q0.6363,0.3136,0.6526,0.2936 T0.6647,0.2459 Q0.6615,0.2247,0.645,0.2023 Q0.6354,0.1892,0.6237,0.179 Q0.6102,0.1672,0.5937,0.1595 Q0.6073,0.1562,0.6215,0.1485 Q0.6396,0.1387,0.6547,0.1354 T0.6839,0.1354 T0.7101,0.1458 T0.7373,0.166 Q0.738,0.1664,0.746,0.1733 T0.7586,0.1841 T0.7733,0.196 T0.7907,0.2086 T0.8086,0.2196 T0.8275,0.2288 T0.8454,0.2337 T0.8627,0.2343 T0.8777,0.228 T0.8903,0.2145 Q0.9038,0.1929,0.8742,0.1582 Q0.869,0.1517,0.8629,0.1464 Q0.8538,0.1387,0.844,0.1321 T0.8248,0.1205 T0.8122,0.1134 Q0.8109,0.1117,0.8053,0.103 T0.7965,0.0899 T0.7875,0.0781 T0.7757,0.064 Q0.8051,0.0616,0.8328,0.0828 Q0.847,0.0934,0.8588,0.1009 T0.8854,0.1146 T0.9127,0.1213 T0.9384,0.116 T0.9626,0.0962 Q0.9664,0.0909,0.9706,0.0846 T0.976,0.0767 T0.9798,0.0728 T0.9852,0.0704 T0.9932,0.0697 Q0.9997,0.0693,0.9942,0.0567 Q0.9923,0.0522,0.989,0.0469 Z",type:0}},"\uE0C4":{type:5,data:{d:"M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0.9099,0.1158 L0.9099,0.1888 L0.9951,0.1888 L0.9951,0.1158 L0.9099,0.1158 Z M0.9075,0.1116 L0.9976,0.1116 Q1,0.1116,1,0.1137 L1,0.1909 Q1,0.193,0.9976,0.193 L0.9075,0.193 Q0.905,0.193,0.905,0.1909 L0.905,0.1137 Q0.905,0.1116,0.9075,0.1116 Z M0.7852,0.6086 L0.7852,0.682 L0.8704,0.682 L0.8704,0.6086 L0.7852,0.6086 Z M0.7828,0.6044 L0.8729,0.6044 Q0.8753,0.6044,0.8753,0.6065 L0.8753,0.6841 Q0.8753,0.6862,0.8729,0.6862 L0.7828,0.6862 Q0.7803,0.6862,0.7803,0.6841 L0.7803,0.6065 Q0.7803,0.6044,0.7828,0.6044 Z M0.66,0.1137 L0.7501,0.1137 L0.7501,0.1909 L0.66,0.1909 L0.66,0.1137 Z M0.6624,0.4102 L0.6624,0.4836 L0.7477,0.4836 L0.7477,0.4102 L0.6624,0.4102 Z M0.66,0.406 L0.7501,0.406 Q0.7526,0.406,0.7526,0.4081 L0.7526,0.4857 Q0.7526,0.4878,0.7501,0.4878 L0.66,0.4878 Q0.6576,0.4878,0.6576,0.4857 L0.6576,0.4081 Q0.6576,0.406,0.66,0.406 Z M0.6624,0.7131 L0.6624,0.7865 L0.7477,0.7865 L0.7477,0.7131 L0.6624,0.7131 Z M0.66,0.7089 L0.7501,0.7089 Q0.7526,0.7089,0.7526,0.711 L0.7526,0.7886 Q0.7526,0.7907,0.7501,0.7907 L0.66,0.7907 Q0.6576,0.7907,0.6576,0.7886 L0.6576,0.711 Q0.6576,0.7089,0.66,0.7089 Z M0.5407,0.2227 L0.5407,0.2836 L0.6113,0.2836 L0.6113,0.2227 L0.5407,0.2227 Z M0.5309,0.206 L0.621,0.206 Q0.623,0.206,0.6249,0.2068 T0.6281,0.2089 T0.6301,0.2116 T0.6308,0.2143 L0.6308,0.2919 Q0.6308,0.2957,0.6276,0.298 T0.621,0.3003 L0.5309,0.3003 Q0.5265,0.3003,0.5239,0.2976 T0.5212,0.2919 L0.5212,0.2143 Q0.5212,0.211,0.5244,0.2085 T0.5309,0.206 Z M0.5407,0.3184 L0.5407,0.3792 L0.6113,0.3792 L0.6113,0.3184 L0.5407,0.3184 Z M0.5309,0.3016 L0.621,0.3016 Q0.6254,0.3016,0.6281,0.3043 T0.6308,0.31 L0.6308,0.3876 Q0.6308,0.3914,0.6276,0.3937 T0.621,0.396 L0.5309,0.396 Q0.5265,0.396,0.5239,0.3932 T0.5212,0.3876 L0.5212,0.31 Q0.5212,0.3062,0.5244,0.3039 T0.5309,0.3016 Z M0.5309,0.4081 L0.621,0.4081 L0.621,0.4857 L0.5309,0.4857 L0.5309,0.4081 Z M0.5309,0.5059 L0.621,0.5059 L0.621,0.5835 L0.5309,0.5835 L0.5309,0.5059 Z M0.5407,0.6149 L0.5407,0.6758 L0.6113,0.6758 L0.6113,0.6149 L0.5407,0.6149 Z M0.5309,0.5982 L0.621,0.5982 Q0.6254,0.5982,0.6281,0.6009 T0.6308,0.6065 L0.6308,0.6841 Q0.6308,0.6879,0.6276,0.6902 T0.621,0.6925 L0.5309,0.6925 Q0.5265,0.6925,0.5239,0.6898 T0.5212,0.6841 L0.5212,0.6065 Q0.5212,0.6028,0.5244,0.6005 T0.5309,0.5982 Z M0.4062,0.1137 L0.4963,0.1137 L0.4963,0.1909 L0.4062,0.1909 L0.4062,0.1137 Z M0.4062,0.2143 L0.4963,0.2143 L0.4963,0.2919 L0.4062,0.2919 L0.4062,0.2143 Z M0.4184,0.4186 L0.4184,0.4753 L0.4842,0.4753 L0.4842,0.4186 L0.4184,0.4186 Z M0.4062,0.3977 L0.4963,0.3977 Q0.5017,0.3977,0.5051,0.401 T0.5085,0.4081 L0.5085,0.4857 Q0.5085,0.4904,0.5046,0.4933 T0.4963,0.4962 L0.4062,0.4962 Q0.4009,0.4962,0.3975,0.4929 T0.3941,0.4857 L0.3941,0.4081 Q0.3941,0.4035,0.398,0.4006 T0.4062,0.3977 Z M0.4062,0.5059 L0.4963,0.5059 L0.4963,0.5835 L0.4062,0.5835 L0.4062,0.5059 Z M0.4087,0.7131 L0.4087,0.7865 L0.4939,0.7865 L0.4939,0.7131 L0.4087,0.7131 Z M0.4062,0.7089 L0.4963,0.7089 Q0.4988,0.7089,0.4988,0.711 L0.4988,0.7886 Q0.4988,0.7907,0.4963,0.7907 L0.4062,0.7907 Q0.4038,0.7907,0.4038,0.7886 L0.4038,0.711 Q0.4038,0.7089,0.4062,0.7089 Z M0.2689,0.1137 L0.359,0.1137 L0.359,0.1909 L0.2689,0.1909 L0.2689,0.1137 Z M0.2689,0.2143 L0.359,0.2143 L0.359,0.2919 L0.2689,0.2919 L0.2689,0.2143 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.31 L0.359,0.31 L0.359,0.3876 L0.2689,0.3876 L0.2689,0.31 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.4081 L0.359,0.4081 L0.359,0.4857 L0.2689,0.4857 L0.2689,0.4081 Z M0.2689,0.5059 L0.359,0.5059 L0.359,0.5835 L0.2689,0.5835 L0.2689,0.5059 Z M0.2689,0.711 L0.359,0.711 L0.359,0.7886 L0.2689,0.7886 L0.2689,0.711 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.1374,0.1137 L0.2275,0.1137 L0.2275,0.1909 L0.1374,0.1909 L0.1374,0.1137 Z M0.1374,0.2143 L0.2275,0.2143 L0.2275,0.2919 L0.1374,0.2919 L0.1374,0.2143 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.31 L0.2275,0.31 L0.2275,0.3876 L0.1374,0.3876 L0.1374,0.31 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.4081 L0.2275,0.4081 L0.2275,0.4857 L0.1374,0.4857 L0.1374,0.4081 Z M0.1374,0.5059 L0.2275,0.5059 L0.2275,0.5835 L0.1374,0.5835 L0.1374,0.5059 Z M0.1374,0.6065 L0.2275,0.6065 L0.2275,0.6841 L0.1374,0.6841 L0.1374,0.6065 Z M0.1374,0.711 L0.2275,0.711 L0.2275,0.7886 L0.1374,0.7886 L0.1374,0.711 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0,0.1137 L0.0901,0.1137 L0.0901,0.1909 L0,0.1909 L0,0.1137 Z M0,0.2143 L0.0901,0.2143 L0.0901,0.2919 L0,0.2919 L0,0.2143 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.31 L0.0901,0.31 L0.0901,0.3876 L0,0.3876 L0,0.31 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.4081 L0.0901,0.4081 L0.0901,0.4857 L0,0.4857 L0,0.4081 Z M0,0.5059 L0.0901,0.5059 L0.0901,0.5835 L0,0.5835 L0,0.5059 Z M0,0.6065 L0.0901,0.6065 L0.0901,0.6841 L0,0.6841 L0,0.6065 Z M0,0.711 L0.0901,0.711 L0.0901,0.7886 L0,0.7886 L0,0.711 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z",type:0}},"\uE0C5":{type:5,data:{d:"M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M0.0901,0.1158 L0.0901,0.1888 L0.0049,0.1888 L0.0049,0.1158 L0.0901,0.1158 Z M0.0925,0.1116 L0.0024,0.1116 Q0,0.1116,0,0.1137 L0,0.1909 Q0,0.193,0.0024,0.193 L0.0925,0.193 Q0.095,0.193,0.095,0.1909 L0.095,0.1137 Q0.095,0.1116,0.0925,0.1116 Z M0.2148,0.6086 L0.2148,0.682 L0.1296,0.682 L0.1296,0.6086 L0.2148,0.6086 Z M0.2172,0.6044 L0.1271,0.6044 Q0.1247,0.6044,0.1247,0.6065 L0.1247,0.6841 Q0.1247,0.6862,0.1271,0.6862 L0.2172,0.6862 Q0.2197,0.6862,0.2197,0.6841 L0.2197,0.6065 Q0.2197,0.6044,0.2172,0.6044 Z M0.34,0.1137 L0.2499,0.1137 L0.2499,0.1909 L0.34,0.1909 L0.34,0.1137 Z M0.3376,0.4102 L0.3376,0.4836 L0.2523,0.4836 L0.2523,0.4102 L0.3376,0.4102 Z M0.34,0.406 L0.2499,0.406 Q0.2474,0.406,0.2474,0.4081 L0.2474,0.4857 Q0.2474,0.4878,0.2499,0.4878 L0.34,0.4878 Q0.3424,0.4878,0.3424,0.4857 L0.3424,0.4081 Q0.3424,0.406,0.34,0.406 Z M0.3376,0.7131 L0.3376,0.7865 L0.2523,0.7865 L0.2523,0.7131 L0.3376,0.7131 Z M0.34,0.7089 L0.2499,0.7089 Q0.2474,0.7089,0.2474,0.711 L0.2474,0.7886 Q0.2474,0.7907,0.2499,0.7907 L0.34,0.7907 Q0.3424,0.7907,0.3424,0.7886 L0.3424,0.711 Q0.3424,0.7089,0.34,0.7089 Z M0.4593,0.2227 L0.4593,0.2836 L0.3887,0.2836 L0.3887,0.2227 L0.4593,0.2227 Z M0.4691,0.206 L0.379,0.206 Q0.3746,0.206,0.3719,0.2087 T0.3692,0.2143 L0.3692,0.2919 Q0.3692,0.2957,0.3724,0.298 T0.379,0.3003 L0.4691,0.3003 Q0.4735,0.3003,0.4761,0.2976 T0.4788,0.2919 L0.4788,0.2143 Q0.4788,0.211,0.4756,0.2085 T0.4691,0.206 Z M0.4593,0.3184 L0.4593,0.3792 L0.3887,0.3792 L0.3887,0.3184 L0.4593,0.3184 Z M0.4691,0.3016 L0.379,0.3016 Q0.3746,0.3016,0.3719,0.3043 T0.3692,0.31 L0.3692,0.3876 Q0.3692,0.3914,0.3724,0.3937 T0.379,0.396 L0.4691,0.396 Q0.4735,0.396,0.4761,0.3932 T0.4788,0.3876 L0.4788,0.31 Q0.4788,0.3062,0.4756,0.3039 T0.4691,0.3016 Z M0.4691,0.4081 L0.379,0.4081 L0.379,0.4857 L0.4691,0.4857 L0.4691,0.4081 Z M0.4691,0.5059 L0.379,0.5059 L0.379,0.5835 L0.4691,0.5835 L0.4691,0.5059 Z M0.4593,0.6149 L0.4593,0.6758 L0.3887,0.6758 L0.3887,0.6149 L0.4593,0.6149 Z M0.4691,0.5982 L0.379,0.5982 Q0.3746,0.5982,0.3719,0.6009 T0.3692,0.6065 L0.3692,0.6841 Q0.3692,0.6879,0.3724,0.6902 T0.379,0.6925 L0.4691,0.6925 Q0.4735,0.6925,0.4761,0.6898 T0.4788,0.6841 L0.4788,0.6065 Q0.4788,0.6028,0.4756,0.6005 T0.4691,0.5982 Z M0.5938,0.1137 L0.5037,0.1137 L0.5037,0.1909 L0.5938,0.1909 L0.5938,0.1137 Z M0.5938,0.2143 L0.5037,0.2143 L0.5037,0.2919 L0.5938,0.2919 L0.5938,0.2143 Z M0.5816,0.4186 L0.5816,0.4753 L0.5158,0.4753 L0.5158,0.4186 L0.5816,0.4186 Z M0.5938,0.3977 L0.5037,0.3977 Q0.4983,0.3977,0.4949,0.401 T0.4915,0.4081 L0.4915,0.4857 Q0.4915,0.4904,0.4954,0.4933 T0.5037,0.4962 L0.5938,0.4962 Q0.5991,0.4962,0.6025,0.4929 T0.6059,0.4857 L0.6059,0.4081 Q0.6059,0.4035,0.602,0.4006 T0.5938,0.3977 Z M0.5938,0.5059 L0.5037,0.5059 L0.5037,0.5835 L0.5938,0.5835 L0.5938,0.5059 Z M0.5913,0.7131 L0.5913,0.7865 L0.5061,0.7865 L0.5061,0.7131 L0.5913,0.7131 Z M0.5938,0.7089 L0.5037,0.7089 Q0.5012,0.7089,0.5012,0.711 L0.5012,0.7886 Q0.5012,0.7907,0.5037,0.7907 L0.5938,0.7907 Q0.5962,0.7907,0.5962,0.7886 L0.5962,0.711 Q0.5962,0.7089,0.5938,0.7089 Z M0.7311,0.1137 L0.641,0.1137 L0.641,0.1909 L0.7311,0.1909 L0.7311,0.1137 Z M0.7311,0.2143 L0.641,0.2143 L0.641,0.2919 L0.7311,0.2919 L0.7311,0.2143 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.31 L0.641,0.31 L0.641,0.3876 L0.7311,0.3876 L0.7311,0.31 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.4081 L0.641,0.4081 L0.641,0.4857 L0.7311,0.4857 L0.7311,0.4081 Z M0.7311,0.5059 L0.641,0.5059 L0.641,0.5835 L0.7311,0.5835 L0.7311,0.5059 Z M0.7311,0.711 L0.641,0.711 L0.641,0.7886 L0.7311,0.7886 L0.7311,0.711 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.8626,0.1137 L0.7725,0.1137 L0.7725,0.1909 L0.8626,0.1909 L0.8626,0.1137 Z M0.8626,0.2143 L0.7725,0.2143 L0.7725,0.2919 L0.8626,0.2919 L0.8626,0.2143 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.31 L0.7725,0.31 L0.7725,0.3876 L0.8626,0.3876 L0.8626,0.31 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.4081 L0.7725,0.4081 L0.7725,0.4857 L0.8626,0.4857 L0.8626,0.4081 Z M0.8626,0.5059 L0.7725,0.5059 L0.7725,0.5835 L0.8626,0.5835 L0.8626,0.5059 Z M0.8626,0.6065 L0.7725,0.6065 L0.7725,0.6841 L0.8626,0.6841 L0.8626,0.6065 Z M0.8626,0.711 L0.7725,0.711 L0.7725,0.7886 L0.8626,0.7886 L0.8626,0.711 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M1,0.1137 L0.9099,0.1137 L0.9099,0.1909 L1,0.1909 L1,0.1137 Z M1,0.2143 L0.9099,0.2143 L0.9099,0.2919 L1,0.2919 L1,0.2143 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.31 L0.9099,0.31 L0.9099,0.3876 L1,0.3876 L1,0.31 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.4081 L0.9099,0.4081 L0.9099,0.4857 L1,0.4857 L1,0.4081 Z M1,0.5059 L0.9099,0.5059 L0.9099,0.5835 L1,0.5835 L1,0.5059 Z M1,0.6065 L0.9099,0.6065 L0.9099,0.6841 L1,0.6841 L1,0.6065 Z M1,0.711 L0.9099,0.711 L0.9099,0.7886 L1,0.7886 L1,0.711 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z",type:0}},"\uE0C6":{type:5,data:{d:"M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0.8574,0.3217 L0.8574,0.4098 L0.9691,0.4098 L0.9691,0.3217 L0.8574,0.3217 Z M0.8419,0.2978 L0.9846,0.2978 Q0.9892,0.2978,0.9928,0.2997 T0.9982,0.3043 T1,0.31 L1,0.4216 Q1,0.427,0.9951,0.4304 T0.9846,0.4337 L0.8419,0.4337 Q0.8352,0.4337,0.8308,0.4299 T0.8265,0.4216 L0.8265,0.31 Q0.8265,0.3062,0.829,0.3035 T0.835,0.2993 T0.8419,0.2978 Z M0.8574,0.888 L0.8574,0.9757 L0.9691,0.9757 L0.9691,0.888 L0.8574,0.888 Z M0.8419,0.8637 L0.9846,0.8637 Q0.9892,0.8637,0.9928,0.8658 T0.9982,0.8706 T1,0.8758 L1,0.9878 Q1,0.9929,0.9951,0.9964 T0.9846,1 L0.8419,1 Q0.8352,1,0.8308,0.996 T0.8265,0.9878 L0.8265,0.8758 Q0.8265,0.8708,0.8314,0.8672 T0.8419,0.8637 Z M0.6509,0.169 L0.6509,0.2706 L0.7806,0.2706 L0.7806,0.169 L0.6509,0.169 Z M0.6442,0.159 L0.7868,0.159 Q0.7899,0.159,0.7917,0.1604 T0.7935,0.164 L0.7935,0.2756 Q0.7935,0.2781,0.7915,0.2796 T0.7868,0.281 L0.6442,0.281 Q0.6416,0.281,0.6395,0.2794 T0.6375,0.2756 L0.6375,0.164 Q0.6375,0.1619,0.6398,0.1604 T0.6442,0.159 Z M0.6632,0.6044 L0.6632,0.6858 L0.7678,0.6858 L0.7678,0.6044 L0.6632,0.6044 Z M0.6442,0.5742 L0.7868,0.5742 Q0.7951,0.5742,0.8007,0.5791 T0.8064,0.5893 L0.8064,0.7013 Q0.8064,0.7076,0.8002,0.712 T0.7868,0.7164 L0.6442,0.7164 Q0.6359,0.7164,0.6305,0.7114 T0.6251,0.7013 L0.6251,0.5893 Q0.6251,0.5847,0.6282,0.5812 T0.6357,0.5759 T0.6442,0.5742 Z M0.4264,0.164 L0.5695,0.164 L0.5695,0.2756 L0.4264,0.2756 L0.4264,0.164 Z M0.4325,0.315 L0.4325,0.4165 L0.5628,0.4165 L0.5628,0.315 L0.4325,0.315 Z M0.4264,0.3049 L0.5695,0.3049 Q0.5721,0.3049,0.5739,0.3064 T0.5757,0.31 L0.5757,0.4216 Q0.5757,0.4237,0.5736,0.4251 T0.5695,0.4266 L0.4264,0.4266 Q0.4238,0.4266,0.422,0.4251 T0.4202,0.4216 L0.4202,0.31 Q0.4202,0.3087,0.4207,0.3077 T0.4222,0.306 T0.4243,0.3052 T0.4264,0.3049 Z M0.4264,0.4476 L0.5695,0.4476 L0.5695,0.5596 L0.4264,0.5596 L0.4264,0.4476 Z M0.4392,0.7408 L0.4392,0.8326 L0.5561,0.8326 L0.5561,0.7408 L0.4392,0.7408 Z M0.4264,0.7206 L0.5695,0.7206 Q0.5747,0.7206,0.5783,0.724 T0.5819,0.7307 L0.5819,0.8427 Q0.5819,0.8469,0.5778,0.8498 T0.5695,0.8528 L0.4264,0.8528 Q0.4207,0.8528,0.4171,0.8496 T0.4135,0.8427 L0.4135,0.7307 Q0.4135,0.7265,0.4176,0.7236 T0.4264,0.7206 Z M0.2178,0.164 L0.3605,0.164 L0.3605,0.2756 L0.2178,0.2756 L0.2178,0.164 Z M0.2178,0.31 L0.3605,0.31 L0.3605,0.4216 L0.2178,0.4216 L0.2178,0.31 Z M0.2178,0.5893 L0.3605,0.5893 L0.3605,0.7013 L0.2178,0.7013 L0.2178,0.5893 Z M0.2178,0.7307 L0.3605,0.7307 L0.3605,0.8427 L0.2178,0.8427 L0.2178,0.7307 Z M0.2178,0.8758 L0.3605,0.8758 L0.3605,0.9878 L0.2178,0.9878 L0.2178,0.8758 Z M0,0.164 L0.1432,0.164 L0.1432,0.2756 L0,0.2756 L0,0.164 Z M0,0.31 L0.1432,0.31 L0.1432,0.4216 L0,0.4216 L0,0.31 Z M0,0.4476 L0.1432,0.4476 L0.1432,0.5596 L0,0.5596 L0,0.4476 Z M0,0.5893 L0.1432,0.5893 L0.1432,0.7013 L0,0.7013 L0,0.5893 Z M0,0.7307 L0.1432,0.7307 L0.1432,0.8427 L0,0.8427 L0,0.7307 Z M0,0.8758 L0.1432,0.8758 L0.1432,0.9878 L0,0.9878 L0,0.8758 Z",type:0}},"\uE0C7":{type:5,data:{d:"M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M0.1432,0.3217 L0.1432,0.4098 L0.0309,0.4098 L0.0309,0.3217 L0.1432,0.3217 Z M0.1586,0.2978 L0.0154,0.2978 Q0.0088,0.2978,0.0044,0.3016 T0,0.31 L0,0.4216 Q0,0.427,0.0049,0.4304 T0.0154,0.4337 L0.1586,0.4337 Q0.1648,0.4337,0.1694,0.4299 T0.174,0.4216 L0.174,0.31 Q0.174,0.3062,0.1715,0.3035 T0.1653,0.2993 T0.1586,0.2978 Z M0.1432,0.888 L0.1432,0.9757 L0.0309,0.9757 L0.0309,0.888 L0.1432,0.888 Z M0.1586,0.8637 L0.0154,0.8637 Q0.0108,0.8637,0.0072,0.8658 T0.0018,0.8706 T0,0.8758 L0,0.9878 Q0,0.9929,0.0049,0.9964 T0.0154,1 L0.1586,1 Q0.1648,1,0.1694,0.996 T0.174,0.9878 L0.174,0.8758 Q0.174,0.8725,0.1715,0.8695 T0.1653,0.8651 T0.1586,0.8637 Z M0.3496,0.169 L0.3496,0.2706 L0.2194,0.2706 L0.2194,0.169 L0.3496,0.169 Z M0.3563,0.159 L0.2132,0.159 Q0.2106,0.159,0.2088,0.1604 T0.207,0.164 L0.207,0.2756 Q0.207,0.2781,0.2091,0.2796 T0.2132,0.281 L0.3563,0.281 Q0.3589,0.281,0.3607,0.2794 T0.3625,0.2756 L0.3625,0.164 Q0.3625,0.1619,0.3605,0.1604 T0.3563,0.159 Z M0.3368,0.6044 L0.3368,0.6858 L0.2327,0.6858 L0.2327,0.6044 L0.3368,0.6044 Z M0.3563,0.5742 L0.2132,0.5742 Q0.2049,0.5742,0.1993,0.5791 T0.1936,0.5893 L0.1936,0.7013 Q0.1936,0.7076,0.2001,0.712 T0.2132,0.7164 L0.3563,0.7164 Q0.3641,0.7164,0.3697,0.7114 T0.3754,0.7013 L0.3754,0.5893 Q0.3754,0.5847,0.3723,0.5812 T0.3648,0.5759 T0.3563,0.5742 Z M0.5736,0.164 L0.431,0.164 L0.431,0.2756 L0.5736,0.2756 L0.5736,0.164 Z M0.5675,0.315 L0.5675,0.4165 L0.4377,0.4165 L0.4377,0.315 L0.5675,0.315 Z M0.5736,0.3049 L0.431,0.3049 Q0.4284,0.3049,0.4264,0.3064 T0.4243,0.31 L0.4243,0.4216 Q0.4243,0.4237,0.4266,0.4251 T0.431,0.4266 L0.5736,0.4266 Q0.5767,0.4266,0.5785,0.4251 T0.5803,0.4216 L0.5803,0.31 Q0.5803,0.3087,0.5798,0.3077 T0.5783,0.306 T0.5762,0.3052 T0.5736,0.3049 Z M0.5736,0.4476 L0.431,0.4476 L0.431,0.5596 L0.5736,0.5596 L0.5736,0.4476 Z M0.5613,0.7408 L0.5613,0.8326 L0.4439,0.8326 L0.4439,0.7408 L0.5613,0.7408 Z M0.5736,0.7206 L0.431,0.7206 Q0.4253,0.7206,0.4217,0.724 T0.4181,0.7307 L0.4181,0.8427 Q0.4181,0.8469,0.4222,0.8498 T0.431,0.8528 L0.5736,0.8528 Q0.5778,0.8528,0.5808,0.8511 T0.5855,0.8471 T0.587,0.8427 L0.587,0.7307 Q0.587,0.7265,0.5826,0.7236 T0.5736,0.7206 Z M0.7827,0.164 L0.6395,0.164 L0.6395,0.2756 L0.7827,0.2756 L0.7827,0.164 Z M0.7827,0.31 L0.6395,0.31 L0.6395,0.4216 L0.7827,0.4216 L0.7827,0.31 Z M0.7827,0.5893 L0.6395,0.5893 L0.6395,0.7013 L0.7827,0.7013 L0.7827,0.5893 Z M0.7827,0.7307 L0.6395,0.7307 L0.6395,0.8427 L0.7827,0.8427 L0.7827,0.7307 Z M0.7827,0.8758 L0.6395,0.8758 L0.6395,0.9878 L0.7827,0.9878 L0.7827,0.8758 Z M1,0.164 L0.8574,0.164 L0.8574,0.2756 L1,0.2756 L1,0.164 Z M1,0.31 L0.8574,0.31 L0.8574,0.4216 L1,0.4216 L1,0.31 Z M1,0.4476 L0.8574,0.4476 L0.8574,0.5596 L1,0.5596 L1,0.4476 Z M1,0.5893 L0.8574,0.5893 L0.8574,0.7013 L1,0.7013 L1,0.5893 Z M1,0.7307 L0.8574,0.7307 L0.8574,0.8427 L1,0.8427 L1,0.7307 Z M1,0.8758 L0.8574,0.8758 L0.8574,0.9878 L1,0.9878 L1,0.8758 Z",type:0}},"\uE0C8":{type:5,data:{d:"M0.0008,0.9979 Q0.0008,1,0.0032,1 Q0.0482,1,0.0602,0.9975 Q0.0667,0.9963,0.0847,0.9917 T0.1084,0.9859 Q0.1124,0.9851,0.1221,0.9851 L0.1253,0.9851 L0.1285,0.9851 Q0.1518,0.9851,0.1655,0.9809 Q0.1695,0.9801,0.1731,0.9788 T0.1791,0.9766 T0.1839,0.9747 T0.1888,0.9732 L0.1936,0.972 T0.1988,0.9712 T0.2048,0.971 L0.2096,0.971 Q0.2201,0.9714,0.2233,0.9714 T0.2345,0.9693 Q0.2386,0.9685,0.2502,0.9674 T0.2715,0.966 L0.2811,0.9656 Q0.2916,0.9647,0.2916,0.9573 Q0.2916,0.954,0.2892,0.9515 T0.2819,0.9486 Q0.2755,0.9482,0.2683,0.9482 Q0.2643,0.9482,0.2582,0.9484 T0.2498,0.9486 Q0.2426,0.9486,0.2402,0.9473 Q0.2386,0.9469,0.2317,0.943 T0.2161,0.937 Q0.2104,0.9357,0.1992,0.933 T0.1831,0.9291 Q0.1807,0.9287,0.1783,0.9285 T0.1739,0.928 T0.1703,0.9276 T0.1675,0.9272 T0.1655,0.9266 T0.1639,0.9253 Q0.1598,0.9216,0.1462,0.9216 L0.143,0.9216 L0.1398,0.9216 L0.1365,0.9216 Q0.1197,0.9195,0.1197,0.9154 L0.1197,0.9154 Q0.1205,0.9121,0.1373,0.9088 T0.1703,0.9054 Q0.1791,0.9054,0.1863,0.904 T0.1984,0.9011 T0.2064,0.8992 Q0.2402,0.8967,0.2506,0.8934 Q0.2538,0.8926,0.2602,0.8899 T0.2707,0.8872 Q0.2715,0.8872,0.2731,0.8876 Q0.2795,0.8884,0.2884,0.8884 Q0.3068,0.8884,0.3092,0.8826 L0.3092,0.8797 Q0.3092,0.8772,0.3076,0.8747 T0.3044,0.8706 T0.3028,0.8681 Q0.3076,0.8656,0.3237,0.8656 Q0.3317,0.8656,0.3622,0.8623 Q0.3655,0.8623,0.3867,0.8617 T0.4217,0.8602 Q0.4241,0.8598,0.4289,0.8598 L0.4345,0.8598 L0.441,0.8598 Q0.4578,0.8598,0.4667,0.8586 Q0.4739,0.8573,0.4851,0.8567 T0.5004,0.8552 Q0.5012,0.8552,0.5108,0.855 T0.5269,0.853 T0.5333,0.8461 Q0.5333,0.8445,0.5325,0.8432 T0.5309,0.8409 T0.5289,0.8391 T0.5261,0.8378 L0.5229,0.837 T0.5185,0.8362 T0.5133,0.8355 T0.5076,0.8349 T0.502,0.8341 Q0.4932,0.8324,0.4859,0.8324 Q0.4827,0.8324,0.4787,0.8328 T0.4731,0.8333 Q0.4707,0.8333,0.4683,0.8324 Q0.4482,0.825,0.4394,0.825 Q0.4369,0.825,0.4345,0.8254 Q0.4225,0.827,0.4153,0.827 Q0.4088,0.827,0.4064,0.8258 Q0.3976,0.8204,0.3751,0.8204 Q0.3703,0.8204,0.3667,0.8214 T0.3622,0.8225 Q0.3598,0.8225,0.3558,0.82 Q0.351,0.8175,0.3402,0.8167 T0.3177,0.8156 T0.3028,0.8146 L0.2956,0.8121 T0.2871,0.8094 T0.2771,0.8073 T0.2635,0.8063 Q0.261,0.8063,0.2586,0.8067 Q0.2378,0.8071,0.2273,0.8071 Q0.2072,0.8071,0.2024,0.8051 Q0.1976,0.8034,0.1932,0.8026 T0.1867,0.8013 T0.1847,0.8001 L0.1847,0.7993 Q0.1855,0.7984,0.1855,0.7978 T0.1859,0.7966 T0.1867,0.7959 T0.188,0.7955 T0.1896,0.7951 T0.1916,0.7949 T0.1944,0.7945 T0.1984,0.7941 T0.2032,0.7939 Q0.212,0.7926,0.2325,0.7918 T0.2562,0.7905 Q0.2691,0.7893,0.2787,0.7847 Q0.2835,0.7827,0.2968,0.7791 T0.3149,0.7756 Q0.3189,0.7756,0.3305,0.7733 T0.3446,0.771 L0.3454,0.771 Q0.3462,0.771,0.3498,0.7721 T0.3574,0.774 T0.3655,0.7748 Q0.3703,0.7748,0.3743,0.7731 T0.3823,0.7708 T0.3916,0.77 T0.3992,0.7694 Q0.4008,0.7694,0.4076,0.7688 T0.4205,0.7675 L0.4305,0.7665 Q0.4345,0.7657,0.4402,0.7617 T0.4458,0.7545 Q0.4458,0.7503,0.4353,0.7487 Q0.4297,0.7478,0.4209,0.7462 T0.4044,0.7433 T0.3904,0.7416 L0.3847,0.7416 Q0.3807,0.7416,0.3747,0.7422 T0.3663,0.7428 T0.3606,0.7424 Q0.3582,0.742,0.3562,0.7418 T0.3522,0.7412 T0.3482,0.7406 T0.3446,0.7401 T0.341,0.7397 T0.3373,0.7393 T0.3341,0.7391 L0.3293,0.7391 Q0.3277,0.7395,0.3253,0.7395 Q0.3205,0.7395,0.3052,0.7387 T0.2835,0.7379 Q0.2755,0.7379,0.253,0.7325 Q0.2506,0.7316,0.2462,0.731 T0.2382,0.7296 T0.2305,0.7271 T0.2181,0.7234 T0.2048,0.7196 T0.2,0.7155 Q0.2,0.7142,0.2016,0.713 Q0.208,0.7059,0.2285,0.6978 T0.2618,0.6898 Q0.2739,0.6898,0.2831,0.6848 T0.2956,0.6794 Q0.3028,0.6786,0.3289,0.6765 T0.3566,0.674 Q0.3582,0.674,0.3855,0.6723 T0.4406,0.6688 T0.4755,0.6653 Q0.5004,0.6607,0.5124,0.6599 L0.5165,0.6599 Q0.5213,0.6599,0.5277,0.6605 T0.5373,0.6611 Q0.543,0.6611,0.5494,0.6599 Q0.592,0.6524,0.6,0.6524 Q0.6064,0.6524,0.61,0.6499 T0.6161,0.6474 Q0.6177,0.6474,0.6261,0.6495 T0.6418,0.6516 L0.6482,0.6516 Q0.653,0.6512,0.6651,0.6506 T0.6876,0.6493 T0.7084,0.6477 T0.7229,0.645 Q0.7269,0.6437,0.7333,0.6437 Q0.7373,0.6437,0.7458,0.6443 T0.7574,0.645 Q0.7614,0.645,0.7631,0.6445 T0.7655,0.6441 Q0.7671,0.6441,0.7723,0.6448 T0.7823,0.6454 Q0.788,0.6454,0.7952,0.6445 Q0.8233,0.6408,0.8723,0.6367 Q0.9012,0.6342,0.9092,0.6342 L0.9165,0.6342 L0.9205,0.6342 Q0.9277,0.6342,0.9382,0.6323 T0.9526,0.6304 Q0.9534,0.6304,0.9594,0.6307 T0.9695,0.6309 Q0.9976,0.6309,0.9992,0.6234 Q1,0.6201,1,0.618 Q1,0.6089,0.9775,0.608 Q0.9703,0.6076,0.9582,0.6076 Q0.9518,0.6076,0.9394,0.6078 T0.9213,0.608 Q0.9036,0.608,0.8972,0.6072 Q0.894,0.6068,0.8871,0.6058 T0.8751,0.6039 T0.8627,0.6024 T0.8506,0.6018 L0.8474,0.6018 Q0.841,0.6022,0.8281,0.6041 T0.8112,0.606 Q0.8096,0.606,0.808,0.6056 Q0.7783,0.6002,0.7647,0.6002 Q0.7598,0.6002,0.7454,0.6006 T0.7261,0.601 Q0.7221,0.601,0.7145,0.6022 T0.7036,0.6035 Q0.6996,0.6035,0.6964,0.6022 Q0.6723,0.5902,0.6442,0.5902 Q0.6426,0.5902,0.6386,0.5904 T0.6337,0.5906 Q0.6273,0.5906,0.6249,0.5894 L0.6177,0.5856 T0.6116,0.5838 T0.6016,0.5825 T0.5855,0.5823 Q0.5719,0.5823,0.5574,0.5798 T0.5373,0.5774 L0.5341,0.5774 Q0.5293,0.5778,0.5213,0.5786 T0.51,0.5794 Q0.5036,0.5794,0.4988,0.5769 Q0.4932,0.574,0.4771,0.574 Q0.4723,0.574,0.4631,0.5745 T0.4498,0.5749 Q0.4418,0.5749,0.4394,0.5736 Q0.4353,0.5724,0.4305,0.5715 T0.4225,0.5707 T0.4145,0.5705 T0.4056,0.5699 Q0.4008,0.5691,0.398,0.5689 T0.394,0.5689 T0.3908,0.5686 T0.3855,0.5674 Q0.3831,0.567,0.3811,0.5662 T0.3779,0.5645 T0.3743,0.563 T0.3695,0.5624 Q0.3655,0.5624,0.3594,0.5635 T0.3494,0.5645 T0.3406,0.5635 T0.3325,0.5624 Q0.3309,0.5624,0.3301,0.5628 L0.3141,0.5628 Q0.2635,0.5628,0.2506,0.5612 Q0.2474,0.5608,0.2434,0.5608 Q0.2402,0.5608,0.2349,0.561 T0.2273,0.5612 Q0.2209,0.5612,0.2177,0.5595 Q0.2145,0.557,0.2145,0.5558 Q0.2169,0.5537,0.2345,0.5521 Q0.2876,0.5475,0.3028,0.5425 Q0.3068,0.5413,0.3149,0.5396 T0.3309,0.5367 T0.3478,0.5338 T0.3606,0.5309 Q0.3631,0.5305,0.3755,0.5259 T0.3968,0.5214 Q0.3992,0.5214,0.4024,0.5218 T0.4096,0.5222 Q0.4161,0.5222,0.4213,0.5209 T0.4313,0.5185 T0.4402,0.5172 Q0.4418,0.5168,0.447,0.5168 L0.4558,0.5168 T0.4639,0.5162 T0.4707,0.5141 T0.4731,0.5102 Q0.4731,0.5089,0.4723,0.5081 Q0.4699,0.5019,0.4627,0.4994 T0.4369,0.4965 Q0.4273,0.4961,0.4193,0.4946 T0.4048,0.4915 T0.3952,0.4894 Q0.392,0.4886,0.388,0.4886 Q0.3847,0.4886,0.3775,0.4892 T0.3647,0.4898 Q0.3598,0.4898,0.355,0.4894 Q0.3165,0.4861,0.3141,0.4853 Q0.2779,0.4774,0.2715,0.4774 Q0.2699,0.4774,0.2683,0.4776 T0.2627,0.4778 Q0.2498,0.4778,0.2281,0.4762 Q0.2241,0.4749,0.2233,0.4737 Q0.2249,0.472,0.2321,0.4708 Q0.2402,0.4695,0.2554,0.4695 L0.2675,0.4695 L0.2795,0.4695 Q0.294,0.4695,0.2996,0.4679 Q0.3141,0.4629,0.3373,0.4616 Q0.3414,0.4612,0.3466,0.4606 T0.3582,0.4589 T0.3687,0.4562 T0.3727,0.4525 Q0.3727,0.4509,0.3703,0.4492 Q0.3639,0.4455,0.3474,0.4419 T0.3213,0.4384 L0.3157,0.4384 L0.31,0.4384 Q0.294,0.4384,0.2859,0.4363 Q0.2795,0.4347,0.2691,0.4347 L0.2618,0.4347 L0.2546,0.4347 Q0.2458,0.4347,0.2394,0.4338 Q0.2257,0.4318,0.2193,0.4303 T0.2092,0.4266 T0.2052,0.4224 T0.2024,0.4154 T0.196,0.4052 Q0.1912,0.3994,0.1867,0.3949 T0.1807,0.3884 T0.1791,0.3849 Q0.1791,0.3824,0.1839,0.3745 Q0.1871,0.3687,0.1944,0.3637 T0.2072,0.3561 T0.2221,0.3501 T0.2321,0.3463 Q0.2353,0.3455,0.241,0.3445 T0.2522,0.3428 T0.2639,0.3411 T0.2731,0.3384 T0.2956,0.3351 T0.3197,0.3326 Q0.3213,0.3322,0.3237,0.3322 T0.3325,0.3331 T0.3414,0.3339 Q0.3478,0.3339,0.3518,0.3314 Q0.3606,0.3264,0.3703,0.3264 Q0.3775,0.3264,0.3847,0.3293 Q0.3888,0.331,0.396,0.331 Q0.4024,0.331,0.4116,0.3295 T0.4265,0.3266 T0.4414,0.3227 T0.4514,0.3202 Q0.4578,0.3181,0.4839,0.3152 T0.5112,0.3123 T0.5177,0.3119 T0.5285,0.3111 T0.5398,0.3096 T0.549,0.3065 T0.5526,0.3015 Q0.5526,0.2999,0.5518,0.2982 Q0.547,0.2903,0.5386,0.2883 T0.5165,0.2862 Q0.5116,0.2862,0.5056,0.2866 T0.4972,0.287 Q0.4884,0.287,0.4787,0.2833 Q0.4594,0.2758,0.4265,0.2758 Q0.4169,0.2758,0.4129,0.2766 Q0.4112,0.2771,0.4104,0.2771 Q0.4088,0.2771,0.4056,0.2748 T0.3968,0.2721 Q0.3695,0.2696,0.359,0.2659 Q0.355,0.2646,0.351,0.2646 T0.3426,0.2661 T0.3365,0.2675 T0.3333,0.2659 Q0.3277,0.2605,0.3116,0.2553 T0.2859,0.2501 L0.2843,0.2501 L0.2819,0.2501 Q0.2779,0.2501,0.2723,0.2493 T0.2586,0.2472 T0.2474,0.2455 Q0.1799,0.236,0.1719,0.236 Q0.1663,0.236,0.1606,0.235 T0.1502,0.2316 T0.1454,0.2265 Q0.1454,0.2223,0.1558,0.2173 Q0.1679,0.2115,0.1859,0.2092 T0.2185,0.207 T0.2353,0.2057 Q0.2369,0.2049,0.2502,0.2041 T0.2799,0.2022 T0.302,0.2007 Q0.3084,0.1999,0.3245,0.1954 T0.347,0.1908 Q0.3502,0.1908,0.3534,0.1916 Q0.3663,0.197,0.388,0.197 Q0.404,0.197,0.4088,0.1929 Q0.4096,0.192,0.4108,0.192 T0.4177,0.1945 T0.4277,0.197 T0.4369,0.1949 Q0.4442,0.1908,0.4843,0.1875 Q0.4892,0.1871,0.4968,0.1839 T0.5084,0.1808 L0.5108,0.1808 Q0.5213,0.1825,0.5454,0.1825 Q0.5823,0.1825,0.5992,0.1779 Q0.6096,0.1746,0.6217,0.1746 Q0.6249,0.1746,0.6309,0.1748 T0.6394,0.175 Q0.6434,0.175,0.6466,0.1746 Q0.6474,0.1746,0.6594,0.1738 T0.6787,0.1713 T0.6892,0.1659 Q0.6924,0.1634,0.6924,0.1593 Q0.6924,0.1547,0.6888,0.151 T0.6795,0.1472 Q0.6779,0.1472,0.6763,0.1477 Q0.6699,0.1493,0.6667,0.1493 Q0.661,0.1493,0.6506,0.1456 Q0.6329,0.1394,0.6129,0.1394 Q0.6048,0.1394,0.5992,0.1377 T0.5888,0.136 T0.5803,0.1377 T0.5751,0.1394 Q0.5711,0.1394,0.5639,0.1369 Q0.5365,0.1273,0.5116,0.1273 Q0.4876,0.1273,0.4667,0.1253 Q0.4627,0.1248,0.4542,0.1211 T0.4337,0.1174 L0.4305,0.1174 Q0.4217,0.1178,0.4153,0.119 T0.408,0.1203 Q0.4056,0.1203,0.4,0.117 Q0.3976,0.1153,0.396,0.1136 T0.3932,0.1112 T0.39,0.1099 T0.3847,0.1095 Q0.3799,0.1095,0.3687,0.1103 Q0.355,0.1112,0.3434,0.1141 T0.3301,0.117 Q0.3261,0.117,0.3229,0.1145 Q0.3181,0.1116,0.3052,0.1087 T0.2787,0.1043 T0.2546,0.1029 Q0.2506,0.1029,0.2474,0.1033 Q0.2418,0.1037,0.2349,0.1054 T0.2249,0.107 Q0.2225,0.107,0.2193,0.1066 Q0.2024,0.1024,0.1863,0.1024 Q0.1823,0.1024,0.1562,0.0971 T0.1269,0.0917 T0.1161,0.0896 T0.106,0.0854 Q0.1076,0.0846,0.11,0.0842 Q0.1173,0.0821,0.1261,0.0821 Q0.1301,0.0821,0.1369,0.0825 T0.1462,0.083 Q0.1494,0.083,0.151,0.0825 T0.1831,0.0813 T0.2201,0.0784 T0.243,0.074 T0.2667,0.0718 Q0.2707,0.0718,0.2755,0.0724 T0.2843,0.073 T0.2936,0.0724 T0.3024,0.0705 T0.3072,0.068 T0.3092,0.0657 T0.3108,0.0647 Q0.3116,0.0643,0.3133,0.0643 L0.3157,0.0643 L0.3181,0.0643 Q0.3446,0.0643,0.3446,0.0556 T0.3205,0.0469 L0.3189,0.0469 Q0.3157,0.0469,0.3157,0.0465 Q0.3084,0.0427,0.2835,0.0386 Q0.2739,0.0369,0.2675,0.0342 T0.2538,0.0299 Q0.249,0.029,0.245,0.029 T0.2378,0.0303 T0.2321,0.0315 Q0.2305,0.0315,0.2273,0.0307 Q0.2201,0.0286,0.2004,0.0272 T0.1775,0.0245 Q0.1735,0.0228,0.1663,0.0226 T0.1522,0.0197 T0.1345,0.0145 T0.1124,0.0079 Q0.0996,0.0033,0.0671,0.0044 T0.0297,0.0041 Q0.0169,0,0.0024,0.0017 Q0,0.0021,0,0.0037 Z M0.0064,0.9954 L0.0056,0.0058 Q0.0177,0.005,0.0281,0.0083 Q0.0345,0.01,0.0675,0.0089 T0.1108,0.012 Q0.1221,0.0162,0.1329,0.0187 T0.1498,0.0236 T0.1606,0.0268 T0.1691,0.0274 T0.1759,0.0286 Q0.1807,0.0303,0.2,0.0315 T0.2257,0.0348 Q0.2305,0.0361,0.2337,0.0361 Q0.2361,0.0361,0.2398,0.0348 T0.2466,0.0336 Q0.249,0.0336,0.2522,0.034 Q0.2586,0.0353,0.2655,0.0382 T0.2827,0.0427 Q0.3068,0.0469,0.3124,0.0502 Q0.3157,0.0523,0.3237,0.0523 L0.3277,0.0523 L0.3309,0.0523 Q0.3398,0.0523,0.3398,0.0556 Q0.3398,0.0581,0.3341,0.0587 T0.3205,0.0593 T0.3092,0.0603 T0.3036,0.0643 T0.2932,0.068 Q0.2884,0.0684,0.2843,0.0684 Q0.2811,0.0684,0.2763,0.0678 T0.2667,0.0672 Q0.2586,0.0672,0.2422,0.0697 T0.2177,0.0747 Q0.2137,0.0759,0.1831,0.0767 T0.1494,0.0784 L0.1474,0.0784 T0.1398,0.078 T0.1285,0.0776 Q0.1173,0.0776,0.1084,0.08 Q0.1004,0.0817,0.1004,0.0846 Q0.1004,0.0867,0.104,0.0888 T0.1124,0.0923 T0.1213,0.0948 T0.1269,0.0958 T0.155,0.1014 T0.1863,0.107 Q0.2016,0.107,0.2185,0.1107 Q0.2217,0.1116,0.2257,0.1116 Q0.2289,0.1116,0.2365,0.1099 T0.2482,0.1074 L0.2538,0.1074 Q0.2683,0.1074,0.2912,0.1107 T0.3197,0.1182 Q0.3245,0.1215,0.3301,0.1215 Q0.3333,0.1215,0.3454,0.1184 T0.3687,0.1145 Q0.3735,0.1141,0.3779,0.1139 T0.3843,0.1134 T0.3871,0.1132 Q0.3896,0.1132,0.39,0.1136 T0.392,0.1161 T0.3968,0.1203 Q0.404,0.1248,0.408,0.1248 Q0.4096,0.1248,0.4165,0.1234 T0.4305,0.1215 L0.4337,0.1215 Q0.4442,0.1215,0.4518,0.1251 T0.4659,0.1294 Q0.4876,0.1319,0.5116,0.1319 T0.5622,0.141 Q0.5703,0.1439,0.5751,0.1439 Q0.5791,0.1439,0.5831,0.1423 T0.5888,0.1406 Q0.592,0.1406,0.5944,0.1412 T0.6012,0.1427 T0.6129,0.1435 Q0.6313,0.1435,0.649,0.1497 Q0.6602,0.1535,0.6667,0.1535 Q0.6715,0.1535,0.6779,0.1522 Q0.6787,0.1518,0.6795,0.1518 Q0.6827,0.1518,0.6847,0.1541 T0.6867,0.1593 Q0.6867,0.1618,0.6851,0.1634 Q0.6835,0.1655,0.6775,0.1667 T0.6598,0.169 T0.6458,0.1705 T0.6402,0.1709 Q0.6378,0.1709,0.6321,0.1705 T0.6225,0.1701 Q0.6096,0.1701,0.5968,0.1738 Q0.5823,0.1779,0.5446,0.1779 Q0.5205,0.1779,0.5116,0.1767 Q0.51,0.1763,0.5084,0.1763 Q0.5028,0.1763,0.4944,0.1796 T0.4835,0.1829 L0.4771,0.1833 T0.4659,0.1844 L0.4546,0.1858 T0.443,0.1881 T0.4337,0.1912 Q0.4321,0.1916,0.4305,0.1916 Q0.4273,0.1916,0.4209,0.1895 T0.412,0.1875 Q0.408,0.1875,0.4056,0.19 Q0.4024,0.1925,0.388,0.1925 Q0.3663,0.1925,0.3558,0.1879 Q0.3518,0.1862,0.3462,0.1862 Q0.3373,0.1862,0.3213,0.191 T0.3012,0.1962 Q0.2964,0.1966,0.2799,0.1976 T0.2494,0.1997 T0.2313,0.2024 L0.2313,0.2024 L0.2293,0.2024 L0.2261,0.2024 L0.2217,0.2024 Q0.204,0.2024,0.1851,0.2047 T0.1526,0.2136 Q0.1406,0.2198,0.1406,0.226 Q0.1406,0.2319,0.1518,0.2362 T0.1719,0.2406 Q0.1791,0.2406,0.2466,0.2497 Q0.2498,0.2501,0.2574,0.2516 T0.2711,0.2538 T0.2819,0.2547 L0.2851,0.2547 Q0.2851,0.2543,0.2859,0.2543 Q0.294,0.2543,0.3096,0.2592 T0.3285,0.2684 Q0.3317,0.2721,0.3373,0.2721 Q0.3406,0.2721,0.3462,0.2708 T0.3542,0.2696 Q0.3558,0.2696,0.3574,0.27 Q0.3679,0.2737,0.3968,0.2762 Q0.3984,0.2766,0.4004,0.2779 L0.4044,0.2804 T0.4096,0.2816 Q0.412,0.2816,0.4145,0.2808 Q0.4177,0.2804,0.4249,0.2804 Q0.4586,0.2804,0.4763,0.287 Q0.4867,0.2912,0.4972,0.2912 Q0.5004,0.2912,0.5064,0.2908 T0.5165,0.2903 Q0.5293,0.2903,0.5361,0.2922 T0.547,0.3003 L0.547,0.3011 Q0.547,0.3036,0.5414,0.3049 T0.5249,0.3067 T0.51,0.3082 Q0.5092,0.3082,0.4831,0.3111 T0.4498,0.3161 Q0.408,0.3264,0.3952,0.3264 Q0.3896,0.3264,0.3863,0.3252 Q0.3783,0.3223,0.3703,0.3223 Q0.359,0.3223,0.3494,0.3277 Q0.347,0.3293,0.343,0.3293 Q0.3414,0.3293,0.3353,0.3285 T0.3253,0.3277 T0.3181,0.3285 Q0.3149,0.3289,0.2952,0.3306 T0.2699,0.3347 Q0.2675,0.3364,0.2598,0.3372 T0.2434,0.3395 T0.2297,0.3426 L0.2205,0.3461 T0.2048,0.3523 T0.1908,0.3606 T0.1791,0.3725 Q0.1743,0.3803,0.1743,0.3845 Q0.1743,0.3874,0.1763,0.3901 T0.1827,0.3976 T0.1912,0.4073 T0.198,0.4189 T0.2032,0.4276 T0.2137,0.4326 T0.2386,0.438 Q0.2458,0.4392,0.2562,0.4392 L0.2639,0.4392 L0.2699,0.4392 Q0.2795,0.4392,0.2843,0.4405 Q0.2932,0.443,0.3092,0.443 L0.3157,0.443 L0.3213,0.443 Q0.3293,0.443,0.3458,0.4463 T0.3671,0.4525 Q0.3598,0.4558,0.3373,0.4571 Q0.3124,0.4587,0.298,0.4637 Q0.294,0.465,0.2811,0.465 L0.2703,0.465 L0.2586,0.465 Q0.241,0.465,0.2305,0.4666 Q0.2185,0.4687,0.2185,0.4728 Q0.2185,0.4745,0.2205,0.4764 T0.2241,0.4791 L0.2265,0.4803 L0.2273,0.4803 Q0.2506,0.4824,0.261,0.4824 Q0.2675,0.4824,0.2699,0.482 Q0.2699,0.4815,0.2707,0.4815 Q0.2771,0.4815,0.3124,0.4898 Q0.3173,0.4907,0.3229,0.4913 T0.3386,0.4925 T0.3542,0.4936 T0.3663,0.494 Q0.3711,0.494,0.3787,0.4936 T0.3888,0.4932 Q0.392,0.4932,0.3944,0.4936 T0.4032,0.4959 T0.4181,0.499 T0.4369,0.5006 Q0.449,0.501,0.455,0.5021 T0.4639,0.5048 T0.4675,0.5093 L0.4675,0.5097 Q0.4675,0.5106,0.4663,0.511 T0.4622,0.5116 L0.4566,0.512 T0.4486,0.5124 T0.4402,0.5127 Q0.4345,0.5131,0.4257,0.5153 T0.4096,0.5176 Q0.4064,0.5176,0.4024,0.5172 L0.3968,0.5172 Q0.3863,0.5172,0.3731,0.522 T0.359,0.5268 Q0.355,0.528,0.3317,0.5321 T0.3004,0.5388 Q0.2867,0.5433,0.2337,0.5479 Q0.2096,0.55,0.2096,0.5562 Q0.2096,0.5591,0.2145,0.5628 Q0.2193,0.5662,0.2289,0.5662 Q0.2313,0.5662,0.2373,0.5657 T0.2458,0.5653 L0.2498,0.5653 Q0.2635,0.5674,0.3124,0.5674 Q0.3261,0.5674,0.3301,0.567 L0.3317,0.567 Q0.3341,0.567,0.3394,0.568 T0.3486,0.5691 Q0.3542,0.5691,0.3606,0.5678 T0.3699,0.5666 T0.3759,0.5686 T0.3839,0.5718 T0.3908,0.573 T0.3964,0.5734 T0.4048,0.5742 T0.4165,0.5751 T0.4277,0.5757 T0.4369,0.5778 Q0.4426,0.5794,0.4538,0.5794 Q0.4586,0.5794,0.4679,0.5792 T0.4811,0.579 Q0.4924,0.579,0.4956,0.5807 Q0.502,0.584,0.5108,0.584 L0.5137,0.584 T0.5173,0.5838 L0.5205,0.5834 L0.5237,0.583 L0.5269,0.5825 T0.5305,0.5821 T0.5341,0.5819 L0.5365,0.5819 Q0.5414,0.5819,0.5562,0.5842 T0.5855,0.5865 Q0.5912,0.5865,0.5948,0.5867 T0.6012,0.5869 T0.6064,0.5873 T0.61,0.5877 T0.6133,0.5886 T0.6157,0.5896 L0.6185,0.591 T0.6217,0.5931 Q0.6265,0.5952,0.6369,0.5952 L0.6418,0.5952 L0.6466,0.5952 Q0.6723,0.5952,0.6932,0.606 Q0.698,0.608,0.7044,0.608 Q0.7084,0.608,0.7161,0.6068 T0.7261,0.6056 Q0.7309,0.6056,0.7454,0.6051 T0.7647,0.6047 Q0.7775,0.6047,0.8072,0.6101 Q0.8096,0.6105,0.812,0.6105 Q0.8177,0.6105,0.8297,0.6085 T0.8474,0.606 L0.8506,0.606 Q0.8562,0.606,0.8647,0.607 T0.8831,0.6095 T0.8964,0.6118 Q0.9036,0.6122,0.9221,0.6122 L0.9406,0.6122 L0.959,0.6122 L0.9767,0.6122 Q0.9952,0.613,0.9952,0.6172 Q0.9952,0.6176,0.9944,0.6221 Q0.9936,0.6259,0.9574,0.6259 L0.955,0.6259 L0.9526,0.6259 Q0.9478,0.6259,0.9373,0.628 T0.9205,0.63 L0.9173,0.63 Q0.9133,0.6296,0.9084,0.6296 Q0.9004,0.6296,0.8715,0.6321 Q0.8233,0.6367,0.7944,0.64 Q0.7888,0.6408,0.7839,0.6408 T0.7739,0.6402 T0.7671,0.6396 Q0.7639,0.6396,0.7622,0.64 Q0.7614,0.6404,0.759,0.6404 Q0.7574,0.6404,0.749,0.6398 T0.7357,0.6392 Q0.7261,0.6392,0.7213,0.6412 Q0.7173,0.6425,0.7032,0.6437 T0.6711,0.6458 T0.6474,0.647 Q0.645,0.6474,0.6418,0.6474 Q0.6353,0.6474,0.6277,0.6454 T0.6161,0.6433 Q0.6104,0.6433,0.6072,0.6456 T0.6,0.6479 Q0.5912,0.6479,0.5486,0.6557 Q0.5422,0.657,0.5373,0.657 Q0.5349,0.657,0.5289,0.6564 T0.5173,0.6557 L0.5124,0.6557 Q0.4996,0.6562,0.4739,0.6611 Q0.4675,0.6624,0.4398,0.6645 T0.3851,0.668 T0.3558,0.6698 Q0.355,0.6698,0.3285,0.6721 T0.2948,0.6752 Q0.2892,0.6761,0.2843,0.6786 T0.2747,0.6831 T0.2618,0.6852 Q0.253,0.6852,0.2394,0.6893 T0.2141,0.6993 T0.1968,0.7105 Q0.1944,0.713,0.1944,0.7155 Q0.1944,0.7196,0.2012,0.7229 T0.2177,0.7285 T0.2281,0.7308 Q0.2321,0.7329,0.2365,0.7339 T0.245,0.7356 T0.2514,0.7366 Q0.2522,0.737,0.2554,0.7379 T0.2614,0.7393 T0.2679,0.7406 T0.2755,0.7416 T0.2835,0.742 Q0.29,0.742,0.3048,0.7428 T0.3253,0.7437 L0.3301,0.7437 L0.3333,0.7437 Q0.3341,0.7437,0.3598,0.7466 Q0.3639,0.7474,0.3671,0.7474 T0.3759,0.7466 T0.3855,0.7457 Q0.388,0.7457,0.3904,0.7462 Q0.3984,0.7466,0.4137,0.7495 T0.4349,0.7532 T0.441,0.7557 Q0.441,0.7599,0.4289,0.7619 Q0.4257,0.7628,0.4197,0.7634 T0.4072,0.7644 T0.3984,0.7652 Q0.3968,0.7652,0.3912,0.7655 T0.3811,0.7665 T0.3719,0.7694 Q0.3695,0.7702,0.3655,0.7702 T0.3546,0.7686 T0.3462,0.7665 L0.3446,0.7665 Q0.3406,0.7665,0.3293,0.769 T0.3149,0.7715 Q0.3084,0.7715,0.2952,0.7748 T0.2763,0.781 Q0.2675,0.7847,0.2554,0.7864 Q0.253,0.7864,0.2325,0.7874 T0.2024,0.7893 Q0.2008,0.7893,0.1984,0.7897 T0.1948,0.7901 T0.1916,0.7903 T0.1888,0.7908 T0.1867,0.7914 T0.1847,0.7922 L0.1831,0.793 T0.1819,0.7943 L0.1811,0.7959 T0.1799,0.7976 Q0.1791,0.7993,0.1791,0.8001 Q0.1791,0.8034,0.1831,0.8051 T0.1932,0.8078 T0.2,0.8092 Q0.2072,0.8117,0.2257,0.8117 Q0.2337,0.8117,0.2586,0.8109 L0.2635,0.8109 Q0.2707,0.8109,0.2767,0.8117 T0.2859,0.8136 T0.2936,0.8163 T0.3012,0.8187 Q0.3068,0.82,0.3277,0.8206 T0.3526,0.8237 Q0.3582,0.8266,0.3622,0.8266 Q0.3647,0.8266,0.3687,0.8258 T0.3751,0.825 Q0.396,0.825,0.404,0.8291 Q0.408,0.8316,0.4161,0.8316 Q0.4217,0.8316,0.4353,0.8295 L0.4394,0.8295 Q0.4466,0.8295,0.4659,0.8366 Q0.4699,0.8378,0.4747,0.8378 Q0.4763,0.8378,0.4807,0.8374 T0.4884,0.837 Q0.494,0.837,0.5004,0.8382 Q0.5052,0.8391,0.5124,0.8399 Q0.5221,0.8411,0.5249,0.8422 T0.5277,0.8461 Q0.5277,0.8482,0.5233,0.849 T0.5112,0.8501 T0.4996,0.8511 Q0.4964,0.8519,0.4851,0.8523 T0.4659,0.8544 Q0.4578,0.8557,0.4402,0.8557 L0.4349,0.8557 L0.4297,0.8557 L0.4209,0.8557 Q0.408,0.8565,0.3867,0.8571 T0.3614,0.8582 Q0.3317,0.8611,0.3237,0.8611 L0.3225,0.8611 L0.3213,0.8611 Q0.2972,0.8611,0.2972,0.8681 Q0.2972,0.8714,0.3008,0.8747 T0.3044,0.8805 Q0.3044,0.881,0.3036,0.8814 Q0.3012,0.8839,0.2851,0.8839 Q0.2779,0.8839,0.2739,0.883 Q0.2723,0.8826,0.2699,0.8826 T0.2643,0.8835 T0.259,0.8853 T0.2542,0.8876 T0.249,0.8893 Q0.2386,0.8922,0.2056,0.8946 Q0.2016,0.8951,0.1916,0.898 T0.1703,0.9009 Q0.1518,0.9009,0.1337,0.9044 T0.1149,0.9146 L0.1149,0.9158 Q0.1149,0.9175,0.1157,0.9187 T0.1173,0.921 T0.1201,0.9226 T0.1233,0.9237 T0.1269,0.9245 L0.1305,0.9251 T0.1337,0.9255 L0.1357,0.9258 Q0.139,0.9262,0.1446,0.9262 T0.1542,0.9266 T0.1598,0.9282 Q0.1614,0.9303,0.1647,0.9314 T0.1739,0.9328 T0.1815,0.9336 Q0.1863,0.9345,0.1976,0.9372 T0.2145,0.9415 Q0.2225,0.9432,0.2285,0.9467 T0.2378,0.9515 Q0.2426,0.9531,0.2514,0.9531 Q0.2538,0.9531,0.2602,0.9529 T0.2707,0.9527 Q0.2763,0.9527,0.2815,0.9531 T0.2867,0.9569 T0.2811,0.9614 Q0.2434,0.9627,0.2329,0.9652 Q0.2249,0.9672,0.2241,0.9672 L0.2096,0.9668 L0.2056,0.9668 Q0.2,0.9668,0.196,0.9672 T0.1884,0.9687 T0.1815,0.9708 T0.1731,0.9737 T0.1639,0.9772 Q0.1518,0.9805,0.1285,0.9805 L0.1253,0.9805 Q0.1124,0.9805,0.1076,0.9818 Q0.1012,0.983,0.0831,0.9876 T0.0594,0.9934 Q0.049,0.9954,0.0064,0.9954 Z M0.0032,0.9979 L0.0024,0.0037 Q0.0161,0.0021,0.0289,0.0062 Q0.0337,0.0075,0.0671,0.0066 T0.1116,0.01 T0.1337,0.0166 T0.151,0.022 Q0.1582,0.0249,0.1659,0.0251 T0.1767,0.0265 Q0.1807,0.0278,0.2,0.0292 T0.2265,0.0328 Q0.2305,0.034,0.2329,0.034 T0.239,0.0326 T0.2458,0.0311 T0.253,0.0319 Q0.2578,0.0332,0.2614,0.0342 T0.2667,0.0363 T0.2723,0.0384 T0.2827,0.0406 Q0.3084,0.0448,0.3141,0.0485 Q0.3149,0.0494,0.3225,0.0494 T0.3361,0.0504 T0.3422,0.0554 T0.3357,0.0606 T0.3205,0.0618 T0.31,0.0626 Q0.3092,0.0626,0.3056,0.0659 T0.2932,0.0701 Q0.2884,0.0709,0.2843,0.0709 Q0.2811,0.0709,0.2759,0.0701 T0.2667,0.0693 Q0.2586,0.0693,0.2422,0.0718 T0.2193,0.0763 Q0.2137,0.0784,0.1831,0.079 T0.1502,0.0805 Q0.1494,0.0809,0.147,0.0809 Q0.1454,0.0809,0.1386,0.0803 T0.1277,0.0796 Q0.1173,0.0796,0.1092,0.0821 Q0.1036,0.0834,0.1036,0.0854 Q0.1036,0.0879,0.1129,0.0908 T0.1269,0.0937 Q0.1293,0.0937,0.1558,0.0991 T0.1863,0.1045 Q0.2016,0.1045,0.2193,0.1087 Q0.2225,0.1091,0.2249,0.1091 Q0.2289,0.1091,0.2357,0.1076 T0.2482,0.1054 Q0.2506,0.1049,0.2546,0.1049 Q0.2699,0.1049,0.2924,0.1085 T0.3213,0.1165 Q0.3253,0.119,0.3301,0.119 Q0.3325,0.119,0.3446,0.1161 T0.3687,0.1124 Q0.3831,0.1112,0.3863,0.1112 T0.3908,0.1118 T0.3936,0.1145 T0.3984,0.1186 Q0.4048,0.1228,0.408,0.1228 Q0.4096,0.1228,0.4161,0.1213 T0.4305,0.1195 L0.4337,0.1195 Q0.4426,0.1195,0.4474,0.1211 T0.4566,0.1246 T0.4667,0.1273 Q0.4876,0.1298,0.5116,0.1298 Q0.5365,0.1298,0.5631,0.1389 Q0.5703,0.1414,0.5751,0.1414 Q0.5783,0.1414,0.5819,0.1398 T0.5888,0.1381 Q0.5928,0.1381,0.5984,0.1398 T0.6129,0.1414 Q0.6321,0.1414,0.6498,0.1477 Q0.661,0.1514,0.6667,0.1514 Q0.6707,0.1514,0.6771,0.1501 Q0.6787,0.1497,0.6795,0.1497 Q0.6835,0.1497,0.6863,0.1526 T0.6892,0.1593 Q0.6892,0.1626,0.6876,0.1647 Q0.6851,0.1672,0.6799,0.1686 T0.6695,0.1705 T0.6566,0.1715 T0.6458,0.1725 Q0.6434,0.173,0.6402,0.173 Q0.6378,0.173,0.6317,0.1727 T0.6225,0.1725 Q0.6096,0.1725,0.5984,0.1759 Q0.5823,0.1804,0.5454,0.1804 Q0.5205,0.1804,0.5116,0.1788 L0.5084,0.1788 Q0.5036,0.1788,0.4956,0.1819 T0.4843,0.185 Q0.4434,0.1887,0.4353,0.1929 Q0.4321,0.1945,0.4289,0.1945 T0.4197,0.1922 T0.4112,0.19 T0.4072,0.1912 Q0.4032,0.1949,0.388,0.1949 Q0.3663,0.1949,0.3542,0.19 Q0.351,0.1883,0.3462,0.1883 Q0.3406,0.1883,0.3321,0.1906 T0.3153,0.1954 T0.302,0.1983 Q0.2972,0.1991,0.2859,0.1997 T0.2643,0.201 T0.245,0.2024 T0.2337,0.2041 Q0.2321,0.2045,0.2181,0.2045 T0.1851,0.207 T0.1542,0.2157 Q0.143,0.2211,0.143,0.226 Q0.143,0.2314,0.153,0.2348 T0.1719,0.2381 Q0.1791,0.2381,0.2474,0.2476 Q0.2506,0.248,0.2558,0.2489 T0.2651,0.2505 T0.2739,0.252 T0.2819,0.2526 Q0.2835,0.2526,0.2851,0.2522 L0.2859,0.2522 Q0.2948,0.2522,0.3104,0.2574 T0.3309,0.2671 Q0.3333,0.2696,0.3365,0.2696 Q0.339,0.2696,0.3442,0.2684 T0.3526,0.2671 T0.3582,0.2679 Q0.3687,0.2717,0.3968,0.2742 Q0.4,0.2746,0.4036,0.2771 T0.4096,0.2796 Q0.4112,0.2796,0.4137,0.2787 Q0.4169,0.2779,0.4257,0.2779 Q0.4594,0.2779,0.4779,0.2849 Q0.4876,0.2891,0.4972,0.2891 Q0.4996,0.2891,0.506,0.2887 T0.5165,0.2883 Q0.5253,0.2883,0.5305,0.2889 T0.541,0.292 T0.5494,0.299 L0.5494,0.3015 Q0.5494,0.3036,0.5466,0.3051 T0.5386,0.3073 T0.5285,0.3086 T0.5181,0.3094 T0.5108,0.3102 Q0.5068,0.3107,0.494,0.3121 L0.4683,0.315 T0.4506,0.3181 Q0.449,0.3181,0.4426,0.32 T0.4313,0.3229 T0.4197,0.3256 T0.4064,0.3281 T0.3952,0.3289 Q0.3888,0.3289,0.3855,0.3273 Q0.3783,0.3243,0.3703,0.3243 Q0.3598,0.3243,0.351,0.3297 Q0.3478,0.3314,0.3422,0.3314 Q0.3398,0.3314,0.3337,0.3306 T0.3245,0.3297 T0.3189,0.3306 Q0.3149,0.3314,0.2956,0.3328 T0.2715,0.3368 Q0.2691,0.338,0.2635,0.3391 T0.2522,0.3407 T0.2406,0.3424 T0.2313,0.3447 Q0.2305,0.3447,0.2213,0.348 T0.206,0.354 T0.1924,0.3621 T0.1815,0.3733 Q0.1767,0.3816,0.1767,0.3849 Q0.1767,0.387,0.1783,0.3893 T0.1847,0.3961 T0.1936,0.4063 T0.2004,0.4181 T0.2052,0.4264 T0.2145,0.4309 T0.2386,0.4359 Q0.2458,0.4372,0.2554,0.4372 Q0.2578,0.4372,0.2627,0.437 T0.2699,0.4367 Q0.2795,0.4367,0.2851,0.4384 Q0.294,0.4409,0.3092,0.4409 Q0.3116,0.4409,0.3157,0.4407 T0.3213,0.4405 Q0.3301,0.4405,0.3466,0.444 T0.3687,0.4509 Q0.3703,0.4517,0.3703,0.4525 Q0.3703,0.4575,0.3373,0.4596 Q0.3133,0.4608,0.2988,0.4658 Q0.294,0.4674,0.2803,0.4674 Q0.2763,0.4674,0.2687,0.4672 T0.257,0.467 Q0.2402,0.467,0.2313,0.4687 Q0.2209,0.4708,0.2209,0.4737 Q0.2209,0.4741,0.2213,0.4749 T0.2229,0.4764 L0.2249,0.4774 T0.2265,0.4778 L0.2273,0.4782 Q0.2498,0.4803,0.2618,0.4803 Q0.2667,0.4803,0.2691,0.4799 Q0.2699,0.4795,0.2715,0.4795 Q0.2779,0.4795,0.3133,0.4873 Q0.3181,0.4886,0.3233,0.4892 T0.3386,0.4905 T0.3542,0.4915 T0.3655,0.4919 Q0.3703,0.4919,0.3779,0.4915 T0.3888,0.4911 T0.3952,0.4915 Q0.3976,0.4919,0.4008,0.4927 L0.4072,0.4944 T0.4149,0.4961 T0.4249,0.4975 T0.4369,0.4985 Q0.449,0.499,0.4554,0.5 T0.4651,0.5031 T0.4699,0.5085 Q0.4707,0.5093,0.4707,0.5097 Q0.4707,0.5114,0.4687,0.5124 T0.4631,0.5139 T0.4562,0.5145 T0.4478,0.5147 L0.4402,0.5147 Q0.4353,0.5151,0.4265,0.5174 T0.4096,0.5197 L0.4024,0.5197 Q0.4,0.5193,0.3968,0.5193 Q0.3896,0.5193,0.3831,0.5209 T0.3703,0.5253 T0.3598,0.5288 Q0.3558,0.5301,0.3321,0.5342 T0.302,0.5409 Q0.2876,0.5454,0.2337,0.55 Q0.2112,0.5521,0.2112,0.5558 Q0.2112,0.5574,0.2161,0.5612 Q0.2201,0.5637,0.2281,0.5637 Q0.2305,0.5637,0.2361,0.5633 T0.2442,0.5628 Q0.2474,0.5628,0.2498,0.5633 Q0.2635,0.5653,0.3133,0.5653 Q0.3261,0.5653,0.3301,0.5649 L0.3325,0.5649 Q0.3349,0.5649,0.3402,0.5657 T0.3494,0.5666 Q0.3542,0.5666,0.3598,0.5657 Q0.3663,0.5645,0.3695,0.5645 Q0.3735,0.5645,0.3775,0.5666 T0.3847,0.5695 Q0.3888,0.5707,0.3912,0.5709 T0.3968,0.5711 T0.4048,0.572 Q0.4096,0.5724,0.4165,0.5726 T0.4281,0.5734 T0.4378,0.5757 Q0.4418,0.5774,0.4522,0.5774 Q0.4562,0.5774,0.4655,0.5769 T0.4795,0.5765 Q0.4932,0.5765,0.4972,0.579 Q0.5028,0.5819,0.51,0.5819 Q0.5141,0.5819,0.5221,0.5809 T0.5341,0.5798 L0.5373,0.5798 Q0.5422,0.5798,0.557,0.5821 T0.5855,0.5844 L0.5936,0.5844 L0.5992,0.5844 T0.604,0.5848 T0.6076,0.5852 T0.6108,0.5859 T0.6137,0.5865 T0.6161,0.5873 T0.6181,0.5881 T0.6209,0.5896 L0.6233,0.591 Q0.6265,0.5927,0.6353,0.5927 L0.6402,0.5927 L0.645,0.5927 Q0.6723,0.5927,0.6948,0.6039 Q0.6988,0.606,0.7036,0.606 Q0.7076,0.606,0.7153,0.6045 T0.7261,0.6031 Q0.7309,0.6031,0.7454,0.6027 T0.7647,0.6022 Q0.7783,0.6022,0.808,0.608 L0.812,0.608 Q0.8169,0.608,0.8293,0.6062 T0.8474,0.6039 L0.8506,0.6039 Q0.857,0.6039,0.8655,0.6049 T0.8835,0.6074 T0.8972,0.6093 Q0.9036,0.6101,0.9213,0.6101 L0.9398,0.6101 L0.959,0.6101 L0.9767,0.6101 Q0.9976,0.6109,0.9976,0.6176 Q0.9976,0.6188,0.9968,0.6226 Q0.9952,0.6284,0.9671,0.6284 L0.959,0.6284 L0.9526,0.6284 Q0.9486,0.6284,0.9382,0.6302 T0.9205,0.6321 L0.9173,0.6321 Q0.9133,0.6317,0.9092,0.6317 Q0.9012,0.6317,0.8715,0.6346 Q0.8233,0.6387,0.7944,0.6421 Q0.7888,0.6429,0.7831,0.6429 Q0.7783,0.6429,0.7731,0.6425 T0.7663,0.6421 L0.7622,0.6421 Q0.7614,0.6425,0.7586,0.6425 T0.7474,0.6421 T0.7349,0.6416 Q0.7261,0.6416,0.7221,0.6429 Q0.7173,0.645,0.7032,0.646 T0.6711,0.6479 T0.6482,0.6491 Q0.645,0.6495,0.6418,0.6495 Q0.6353,0.6495,0.6273,0.6474 T0.6161,0.6454 Q0.612,0.6454,0.6088,0.6477 T0.6,0.6499 Q0.5912,0.6499,0.5494,0.6578 Q0.5422,0.6591,0.5373,0.6591 Q0.5341,0.6591,0.5281,0.6584 T0.5173,0.6578 L0.5124,0.6578 Q0.5004,0.6582,0.4747,0.6632 Q0.4675,0.6649,0.4398,0.6667 T0.3851,0.6703 T0.3566,0.6719 Q0.3534,0.6723,0.3406,0.6734 T0.3141,0.6757 T0.2948,0.6773 Q0.2908,0.6781,0.2819,0.6829 T0.2618,0.6877 Q0.2482,0.6877,0.2273,0.6958 T0.1992,0.7117 Q0.1976,0.7138,0.1976,0.7155 Q0.1976,0.7188,0.2032,0.7213 T0.2181,0.7258 T0.2289,0.7292 Q0.2337,0.7308,0.2378,0.7316 L0.2458,0.7333 T0.2522,0.7345 Q0.2747,0.7399,0.2835,0.7399 Q0.29,0.7399,0.3048,0.7408 T0.3253,0.7416 Q0.3277,0.7416,0.3297,0.7414 T0.3341,0.7412 L0.3598,0.7445 Q0.3639,0.7449,0.3663,0.7449 Q0.3695,0.7449,0.3751,0.7443 T0.3855,0.7437 L0.3904,0.7437 Q0.3984,0.7441,0.4141,0.7472 T0.4353,0.7507 Q0.4434,0.752,0.4434,0.7553 Q0.4434,0.7578,0.439,0.7605 T0.4297,0.764 Q0.4257,0.7648,0.4201,0.7655 T0.4076,0.7665 T0.3984,0.7673 Q0.3968,0.7673,0.3912,0.7677 T0.3815,0.7688 T0.3735,0.771 T0.3655,0.7727 Q0.3606,0.7727,0.3534,0.7708 T0.3458,0.769 L0.3446,0.769 Q0.3414,0.769,0.3297,0.7713 T0.3149,0.7735 Q0.3092,0.7735,0.296,0.7771 T0.2771,0.7831 Q0.2683,0.7872,0.2554,0.7885 Q0.253,0.7889,0.2325,0.7897 T0.2032,0.7914 Q0.2008,0.7918,0.198,0.792 T0.194,0.7924 T0.1912,0.7928 T0.1888,0.793 T0.1867,0.7934 T0.1851,0.7943 T0.1843,0.7953 T0.1835,0.7968 T0.1823,0.7984 T0.1815,0.8001 Q0.1815,0.8022,0.1847,0.8032 T0.1932,0.8053 T0.2008,0.8071 Q0.2072,0.8092,0.2265,0.8092 Q0.2361,0.8092,0.2586,0.8088 L0.2635,0.8088 Q0.2731,0.8088,0.2795,0.8098 T0.2928,0.8134 T0.302,0.8167 Q0.306,0.8179,0.3277,0.8183 T0.3542,0.8221 Q0.359,0.8246,0.3622,0.8246 Q0.3639,0.8246,0.3675,0.8237 T0.3751,0.8229 Q0.3968,0.8229,0.4048,0.8275 Q0.4088,0.8291,0.4161,0.8291 Q0.4225,0.8291,0.4353,0.8275 Q0.4369,0.827,0.4394,0.827 Q0.4474,0.827,0.4675,0.8345 Q0.4707,0.8358,0.4739,0.8358 Q0.4755,0.8358,0.4799,0.8353 T0.4876,0.8349 Q0.494,0.8349,0.5012,0.8362 L0.5076,0.837 T0.5133,0.8376 T0.5181,0.8382 T0.5221,0.8391 L0.5253,0.8399 T0.5277,0.8409 L0.5293,0.8422 T0.5301,0.8438 L0.5301,0.8461 Q0.5301,0.8499,0.5249,0.8511 T0.5112,0.8526 T0.5004,0.8532 Q0.4964,0.854,0.4851,0.8546 T0.4667,0.8565 Q0.4578,0.8577,0.441,0.8577 L0.4345,0.8577 L0.4289,0.8577 L0.4209,0.8577 Q0.4153,0.8582,0.4088,0.8586 T0.3968,0.8592 T0.3855,0.8594 T0.3755,0.8596 T0.3675,0.86 T0.3622,0.8602 Q0.3317,0.8635,0.3237,0.8635 Q0.2996,0.8635,0.2996,0.8681 Q0.2996,0.8698,0.3032,0.8733 T0.3068,0.8797 L0.3068,0.8822 Q0.3052,0.8859,0.2859,0.8859 Q0.2787,0.8859,0.2739,0.8851 L0.2699,0.8851 Q0.2659,0.8851,0.259,0.888 T0.2498,0.8913 Q0.2394,0.8946,0.2056,0.8971 Q0.2032,0.8971,0.1928,0.9002 T0.1703,0.9034 Q0.1526,0.9034,0.1353,0.9067 T0.1173,0.915 L0.1173,0.9158 Q0.1173,0.9166,0.1177,0.9175 T0.1189,0.9191 T0.1205,0.9204 T0.1229,0.9212 T0.1257,0.922 T0.1285,0.9226 T0.1309,0.9231 T0.1337,0.9235 T0.1365,0.9237 L0.1446,0.9237 T0.1554,0.9243 T0.1614,0.9268 T0.1659,0.9293 T0.1743,0.9303 T0.1823,0.9316 Q0.1863,0.932,0.1912,0.9332 T0.2028,0.9361 T0.2153,0.939 Q0.2233,0.9411,0.2297,0.9448 T0.2386,0.9494 Q0.2426,0.9506,0.2506,0.9506 Q0.253,0.9506,0.2594,0.9504 T0.2699,0.9502 Q0.2763,0.9502,0.2819,0.9511 Q0.2851,0.9511,0.2871,0.9529 T0.2892,0.9573 Q0.2892,0.9627,0.2811,0.9635 Q0.2434,0.9652,0.2337,0.9672 Q0.2257,0.9693,0.2241,0.9693 Q0.2217,0.9693,0.2096,0.9689 L0.2056,0.9689 Q0.1976,0.9689,0.1924,0.9699 T0.1787,0.9741 L0.1647,0.9793 Q0.1518,0.983,0.1285,0.983 L0.1261,0.983 L0.1237,0.983 Q0.1124,0.983,0.1076,0.9838 Q0.102,0.9851,0.0839,0.9896 T0.0602,0.9954 T0.0406,0.9971 T0.0153,0.9979 L0.0032,0.9979 Z",type:0}},"\uE0CA":{type:5,data:{d:"M0.9992,0.998 Q0.9992,1,0.9968,1 Q0.9521,1,0.9392,0.998 Q0.9335,0.997,0.9152,0.9921 T0.8913,0.9862 Q0.8873,0.9852,0.8783,0.9852 L0.8747,0.9852 L0.871,0.9852 Q0.8483,0.9852,0.8345,0.9812 Q0.8289,0.9792,0.8228,0.9773 T0.8135,0.9743 T0.8054,0.9723 T0.7948,0.9713 L0.7908,0.9713 L0.777,0.9713 T0.7656,0.9693 Q0.7616,0.9683,0.7498,0.9674 T0.7283,0.9664 L0.7186,0.9654 Q0.708,0.9644,0.708,0.9575 Q0.708,0.9545,0.7109,0.952 T0.7178,0.9486 L0.7315,0.9486 L0.7417,0.9486 L0.7502,0.9486 Q0.7575,0.9486,0.7599,0.9476 Q0.7616,0.9466,0.7685,0.9426 T0.7843,0.9377 Q0.7899,0.9357,0.8009,0.9332 T0.8175,0.9298 Q0.82,0.9288,0.8228,0.9283 T0.8277,0.9278 T0.8313,0.9273 T0.8341,0.9263 T0.8362,0.9258 Q0.8402,0.9219,0.854,0.9219 L0.8569,0.9219 L0.8597,0.9219 L0.8637,0.9219 Q0.88,0.9199,0.88,0.9159 L0.88,0.9149 Q0.88,0.913,0.8719,0.911 T0.852,0.9075 T0.8297,0.906 Q0.8224,0.906,0.8167,0.905 T0.8074,0.9031 T0.8001,0.9006 T0.794,0.8991 Q0.7599,0.8971,0.7494,0.8942 Q0.7461,0.8932,0.7397,0.8902 T0.7299,0.8872 L0.7267,0.8872 Q0.721,0.8882,0.7121,0.8882 Q0.6926,0.8882,0.691,0.8833 L0.691,0.8803 Q0.691,0.8773,0.6922,0.8749 T0.6955,0.8704 L0.6975,0.8684 Q0.6926,0.8655,0.6764,0.8655 Q0.6683,0.8655,0.6375,0.8625 Q0.6358,0.8625,0.629,0.862 T0.6148,0.8615 T0.5973,0.861 T0.5791,0.8605 L0.5718,0.8605 L0.5661,0.8605 L0.5596,0.8605 Q0.5426,0.8605,0.5337,0.8586 Q0.5264,0.8576,0.515,0.8571 T0.4996,0.8556 Q0.498,0.8556,0.4947,0.8551 T0.4882,0.8546 T0.4809,0.8541 T0.474,0.8531 T0.4692,0.8506 T0.4672,0.8467 Q0.4672,0.8437,0.468,0.8422 T0.4704,0.8398 T0.4736,0.8383 T0.4781,0.8368 T0.4838,0.8358 T0.4911,0.8353 T0.4988,0.8338 Q0.5069,0.8328,0.5142,0.8328 Q0.5174,0.8328,0.5215,0.8333 T0.5264,0.8338 Q0.5296,0.8338,0.532,0.8328 Q0.5523,0.8249,0.5604,0.8249 L0.5653,0.8249 Q0.5775,0.8269,0.5848,0.8269 Q0.5912,0.8269,0.5937,0.8259 Q0.6026,0.821,0.6253,0.821 Q0.6294,0.821,0.6334,0.822 T0.6383,0.8229 Q0.6399,0.8229,0.644,0.82 Q0.6504,0.817,0.6723,0.816 T0.6975,0.814 Q0.6999,0.814,0.7048,0.8121 T0.7129,0.8091 T0.7226,0.8071 T0.7372,0.8061 L0.7421,0.8061 Q0.7624,0.8071,0.7721,0.8071 Q0.7924,0.8071,0.7981,0.8051 Q0.8021,0.8032,0.807,0.8027 T0.8135,0.8017 T0.8151,0.8002 L0.8151,0.7992 Q0.8143,0.7962,0.8127,0.7957 T0.8045,0.7943 Q0.7997,0.7943,0.7964,0.7933 Q0.7883,0.7933,0.7676,0.7923 T0.7437,0.7903 Q0.7307,0.7893,0.7218,0.7844 Q0.7194,0.7834,0.7141,0.7819 L0.7036,0.7789 T0.693,0.7765 T0.6853,0.7755 Q0.6805,0.7755,0.6691,0.773 T0.6553,0.7705 Q0.6545,0.7705,0.6545,0.7715 Q0.6537,0.7715,0.65,0.7725 T0.6423,0.774 T0.635,0.7745 Q0.6294,0.7745,0.6257,0.773 T0.618,0.771 T0.6083,0.77 T0.601,0.7695 Q0.5985,0.7695,0.5921,0.769 T0.5795,0.7676 T0.5702,0.7666 Q0.5653,0.7656,0.5596,0.7616 T0.5539,0.7547 Q0.5539,0.7498,0.5645,0.7488 Q0.5693,0.7478,0.5852,0.7448 T0.6099,0.7418 L0.6148,0.7418 Q0.6196,0.7418,0.6253,0.7423 T0.6338,0.7428 L0.6399,0.7428 Q0.6431,0.7418,0.6488,0.7409 T0.6586,0.7394 T0.6659,0.7389 L0.6707,0.7389 Q0.6723,0.7399,0.6748,0.7399 Q0.6796,0.7399,0.6946,0.7389 T0.7161,0.7379 Q0.7251,0.7379,0.7478,0.7319 Q0.7494,0.7319,0.7539,0.7315 T0.762,0.73 T0.7697,0.727 T0.7818,0.723 T0.7948,0.7196 T0.7997,0.7151 Q0.7997,0.7141,0.7989,0.7132 Q0.7924,0.7062,0.7717,0.6978 T0.738,0.6894 Q0.7267,0.6894,0.717,0.6845 T0.7048,0.6795 Q0.6975,0.6785,0.6711,0.6766 T0.6431,0.6746 Q0.6415,0.6736,0.6144,0.6721 T0.5596,0.6686 T0.5247,0.6657 Q0.4996,0.6607,0.4874,0.6597 L0.4834,0.6597 Q0.4785,0.6597,0.4724,0.6607 T0.4631,0.6617 Q0.4574,0.6617,0.4501,0.6597 Q0.4088,0.6518,0.4006,0.6518 Q0.3933,0.6518,0.3901,0.6499 T0.3844,0.6479 T0.3739,0.6499 T0.3585,0.6518 L0.352,0.6518 Q0.3471,0.6508,0.335,0.6503 T0.3122,0.6494 T0.2912,0.6479 T0.2766,0.6449 Q0.2733,0.6439,0.2668,0.6439 Q0.2628,0.6439,0.2543,0.6444 T0.2425,0.6449 T0.2368,0.6439 L0.2344,0.6439 Q0.2336,0.6439,0.2283,0.6444 T0.2182,0.6449 Q0.2117,0.6449,0.2052,0.6439 Q0.1768,0.6409,0.1281,0.637 Q0.0989,0.634,0.0916,0.634 L0.0835,0.634 L0.0795,0.634 Q0.0722,0.634,0.0616,0.632 T0.0479,0.6301 Q0.0462,0.6301,0.0406,0.6306 T0.0308,0.6311 Q0.0032,0.6311,0.0008,0.6231 Q0,0.6202,0,0.6182 Q0,0.6083,0.0227,0.6083 Q0.03,0.6073,0.0422,0.6073 Q0.0487,0.6073,0.0608,0.6078 T0.0787,0.6083 Q0.0973,0.6083,0.103,0.6073 Q0.1062,0.6063,0.1131,0.6053 T0.1253,0.6039 T0.1375,0.6024 T0.1492,0.6014 L0.1533,0.6014 Q0.1598,0.6024,0.1723,0.6044 T0.189,0.6063 Q0.1906,0.6063,0.1922,0.6053 Q0.2214,0.6004,0.236,0.6004 Q0.2409,0.6004,0.2551,0.6009 T0.2741,0.6014 Q0.2782,0.6014,0.2859,0.6024 T0.2968,0.6034 Q0.3009,0.6034,0.3041,0.6024 Q0.3277,0.5905,0.356,0.5905 L0.3613,0.5905 L0.3666,0.5905 Q0.3731,0.5905,0.3755,0.5895 Q0.382,0.5856,0.3844,0.5846 T0.3938,0.5831 T0.4144,0.5826 T0.4428,0.5801 T0.4631,0.5776 L0.4663,0.5776 Q0.4704,0.5776,0.4785,0.5786 T0.4899,0.5796 Q0.4964,0.5796,0.5012,0.5767 Q0.5069,0.5737,0.5223,0.5737 Q0.5272,0.5737,0.5369,0.5742 T0.5499,0.5747 Q0.558,0.5747,0.5612,0.5737 Q0.5661,0.5717,0.5714,0.5712 T0.5835,0.5702 T0.5945,0.5692 T0.6018,0.5687 L0.6062,0.5687 T0.6095,0.5682 T0.6148,0.5678 Q0.6172,0.5668,0.6196,0.5653 T0.6245,0.5633 T0.631,0.5628 T0.6407,0.5638 T0.6504,0.5648 T0.6594,0.5638 T0.6675,0.5628 L0.6707,0.5628 L0.6861,0.5628 Q0.7364,0.5628,0.7494,0.5608 L0.7567,0.5608 L0.7652,0.5608 L0.7729,0.5608 Q0.7794,0.5608,0.7818,0.5589 Q0.7851,0.5569,0.7859,0.5559 Q0.7835,0.5539,0.7656,0.5519 Q0.7121,0.547,0.6975,0.543 Q0.6934,0.541,0.6853,0.5396 L0.6691,0.5366 T0.6525,0.5336 T0.6391,0.5312 Q0.6367,0.5302,0.6245,0.5257 T0.6034,0.5213 L0.5977,0.5213 Q0.5945,0.5223,0.5904,0.5223 Q0.5839,0.5223,0.5787,0.5208 T0.5685,0.5183 T0.5596,0.5173 Q0.558,0.5173,0.5552,0.5168 T0.5495,0.5163 L0.5434,0.5163 T0.5373,0.5158 T0.532,0.5148 T0.5284,0.5129 T0.5272,0.5104 L0.5272,0.5074 Q0.5304,0.5015,0.5377,0.499 T0.5629,0.4965 Q0.5734,0.4955,0.5811,0.4946 T0.5953,0.4916 T0.605,0.4896 Q0.6083,0.4886,0.6123,0.4886 Q0.6148,0.4886,0.6225,0.4891 T0.635,0.4896 L0.6456,0.4896 Q0.6837,0.4857,0.6861,0.4857 Q0.7226,0.4768,0.7283,0.4768 Q0.7307,0.4768,0.732,0.4773 T0.7372,0.4777 Q0.7502,0.4777,0.7721,0.4758 Q0.7753,0.4748,0.777,0.4738 Q0.7745,0.4718,0.768,0.4708 Q0.7599,0.4688,0.7445,0.4688 Q0.7405,0.4688,0.7324,0.4693 T0.721,0.4698 Q0.7056,0.4698,0.6999,0.4679 Q0.6861,0.4629,0.6626,0.4619 Q0.6586,0.4609,0.6533,0.4604 T0.6419,0.459 T0.6314,0.456 T0.6269,0.452 Q0.6269,0.451,0.6302,0.4491 Q0.6358,0.4451,0.6525,0.4416 T0.6788,0.4382 L0.6845,0.4382 L0.6902,0.4382 Q0.7064,0.4382,0.7145,0.4362 Q0.7202,0.4342,0.7307,0.4342 L0.7356,0.4342 L0.7409,0.4342 L0.7453,0.4342 Q0.7543,0.4342,0.7607,0.4332 Q0.7778,0.4313,0.7847,0.4288 T0.7932,0.4248 T0.7972,0.4169 T0.8045,0.4045 L0.8094,0.3986 T0.8135,0.3942 L0.8167,0.3912 T0.8191,0.3887 T0.8204,0.3867 T0.8208,0.3848 Q0.8208,0.3818,0.8167,0.3739 Q0.8127,0.3689,0.8054,0.3635 T0.7924,0.3556 T0.7778,0.3497 T0.768,0.3462 Q0.764,0.3442,0.7478,0.3427 T0.7267,0.3383 Q0.7234,0.3363,0.7044,0.3348 T0.6805,0.3323 L0.6764,0.3323 T0.6679,0.3328 T0.6586,0.3333 Q0.6521,0.3333,0.648,0.3314 Q0.6391,0.3264,0.6294,0.3264 Q0.6229,0.3264,0.6156,0.3294 Q0.6115,0.3304,0.6042,0.3304 Q0.5977,0.3304,0.5888,0.3289 T0.5738,0.3264 T0.5584,0.3225 L0.5491,0.3195 Q0.5418,0.3185,0.5162,0.3155 T0.4895,0.3121 T0.4826,0.3116 T0.4716,0.3111 T0.4607,0.3096 T0.4513,0.3066 T0.4477,0.3017 Q0.4477,0.2997,0.4485,0.2977 Q0.4526,0.2898,0.4611,0.2878 T0.4842,0.2859 Q0.4882,0.2859,0.4943,0.2864 T0.5028,0.2868 Q0.5118,0.2868,0.5215,0.2829 Q0.5401,0.276,0.5734,0.276 Q0.5831,0.276,0.5872,0.277 L0.5904,0.277 T0.5949,0.2745 T0.6034,0.272 Q0.631,0.269,0.6407,0.2661 Q0.6448,0.2641,0.6488,0.2641 T0.6573,0.2656 T0.6634,0.2671 Q0.6659,0.2671,0.6675,0.2651 Q0.6723,0.2601,0.6886,0.2552 T0.7137,0.2502 L0.7153,0.2502 L0.7178,0.2502 Q0.7218,0.2502,0.7279,0.2493 T0.7417,0.2468 T0.7526,0.2453 Q0.8208,0.2354,0.8281,0.2354 Q0.8337,0.2354,0.8394,0.2344 T0.8496,0.2315 T0.854,0.2265 Q0.854,0.2216,0.8443,0.2176 Q0.8354,0.2127,0.8216,0.2102 T0.7972,0.2072 T0.777,0.2067 T0.7648,0.2057 Q0.7632,0.2047,0.7498,0.2038 T0.7202,0.2018 T0.6983,0.1998 Q0.6918,0.1998,0.676,0.1949 T0.6537,0.1899 Q0.6496,0.1899,0.6472,0.1919 Q0.6342,0.1968,0.6123,0.1968 Q0.5961,0.1968,0.5912,0.1929 Q0.5904,0.1919,0.5892,0.1919 T0.5823,0.1944 T0.5722,0.1968 T0.5637,0.1949 Q0.5556,0.1909,0.5158,0.1869 Q0.5109,0.1869,0.5032,0.1835 T0.4915,0.18 Q0.4907,0.18,0.4891,0.181 Q0.4793,0.182,0.455,0.182 Q0.4177,0.182,0.4015,0.1771 Q0.3901,0.1741,0.3779,0.1741 Q0.3747,0.1741,0.369,0.1746 T0.3609,0.1751 Q0.3569,0.1751,0.3536,0.1741 Q0.3512,0.1741,0.3459,0.1736 T0.3358,0.1726 T0.3256,0.1716 T0.3167,0.1696 T0.3106,0.1662 Q0.3082,0.1632,0.3082,0.1592 Q0.3082,0.1543,0.3114,0.1508 T0.3204,0.1474 L0.3236,0.1474 Q0.3301,0.1494,0.3333,0.1494 Q0.339,0.1494,0.3496,0.1454 Q0.3674,0.1385,0.3869,0.1385 Q0.395,0.1385,0.4011,0.137 T0.4116,0.1355 T0.4197,0.1375 T0.425,0.1395 Q0.429,0.1395,0.4355,0.1365 Q0.4631,0.1266,0.4882,0.1266 Q0.5126,0.1266,0.5337,0.1246 Q0.5369,0.1246,0.5458,0.1207 T0.5661,0.1167 L0.5693,0.1167 Q0.5791,0.1177,0.5852,0.1187 T0.5921,0.1197 Q0.5945,0.1197,0.6002,0.1167 Q0.6026,0.1147,0.605,0.1123 T0.6091,0.1093 T0.6156,0.1088 T0.6318,0.1098 Q0.6456,0.1108,0.6569,0.1137 T0.6707,0.1167 Q0.674,0.1167,0.6772,0.1147 Q0.6821,0.1108,0.6946,0.1083 T0.721,0.1044 T0.7453,0.1029 L0.7526,0.1029 Q0.7583,0.1039,0.7652,0.1053 T0.7753,0.1068 Q0.7778,0.1068,0.7802,0.1058 Q0.7981,0.1019,0.8143,0.1019 Q0.8175,0.1019,0.8439,0.0964 T0.8735,0.091 Q0.8759,0.091,0.8836,0.089 T0.8938,0.0851 Q0.8929,0.0841,0.8905,0.0841 Q0.8832,0.0821,0.8735,0.0821 Q0.8694,0.0821,0.8629,0.0826 T0.854,0.0831 Q0.8508,0.0831,0.8491,0.0821 Q0.8475,0.0821,0.8171,0.0811 T0.7802,0.0781 T0.7571,0.0737 T0.7332,0.0712 Q0.7299,0.0712,0.7247,0.0717 T0.7161,0.0722 L0.7064,0.0722 Q0.7032,0.0712,0.7003,0.0707 T0.6959,0.0692 T0.693,0.0678 T0.6914,0.0663 T0.6902,0.0648 T0.689,0.0643 L0.6869,0.0643 L0.6845,0.0643 L0.6821,0.0643 Q0.6553,0.0643,0.6553,0.0554 T0.6796,0.0465 L0.6813,0.0465 L0.6845,0.0465 Q0.6918,0.0425,0.717,0.0376 Q0.7226,0.0366,0.7267,0.0356 T0.7324,0.0336 T0.7376,0.0317 T0.747,0.0297 Q0.7518,0.0287,0.7551,0.0287 T0.762,0.0297 T0.768,0.0307 L0.7729,0.0307 Q0.7802,0.0277,0.7997,0.0267 T0.8224,0.0237 Q0.8273,0.0227,0.8341,0.0223 T0.8475,0.0193 T0.8654,0.0143 T0.8873,0.0079 Q0.9002,0.003,0.9331,0.004 T0.97,0.004 Q0.9838,0,0.9976,0.001 Q1,0.001,1,0.003 Z M0.9935,0.996 L0.9951,0.0049 Q0.9822,0.0049,0.9716,0.0079 Q0.9659,0.0099,0.9327,0.0089 T0.8897,0.0119 Q0.8775,0.0158,0.8666,0.0183 T0.85,0.0237 Q0.8418,0.0267,0.8341,0.0272 T0.8248,0.0277 Q0.82,0.0297,0.8001,0.0312 T0.7745,0.0346 Q0.7697,0.0356,0.7664,0.0356 Q0.764,0.0356,0.7603,0.0341 T0.7534,0.0326 Q0.751,0.0326,0.7478,0.0336 Q0.7429,0.0346,0.7397,0.0356 T0.7344,0.0376 T0.7283,0.0401 T0.7178,0.0425 Q0.6926,0.0465,0.6878,0.0495 Q0.6845,0.0514,0.6764,0.0514 L0.6723,0.0514 L0.6691,0.0514 Q0.6602,0.0514,0.6602,0.0554 Q0.6602,0.0574,0.6659,0.0579 T0.6796,0.0589 T0.691,0.0603 T0.6967,0.0643 T0.7072,0.0673 Q0.7121,0.0682,0.7153,0.0682 T0.7238,0.0678 T0.7332,0.0673 Q0.7413,0.0673,0.7579,0.0692 T0.7818,0.0742 Q0.7867,0.0752,0.8171,0.0762 T0.8508,0.0781 L0.852,0.0781 T0.8601,0.0776 T0.8719,0.0772 Q0.8832,0.0772,0.8921,0.0791 Q0.8994,0.0811,0.8994,0.0841 T0.8933,0.0895 T0.8812,0.094 T0.8735,0.0959 T0.8451,0.1014 T0.8143,0.1068 Q0.7989,0.1068,0.7818,0.1098 Q0.7778,0.1108,0.7745,0.1108 T0.768,0.1103 T0.7603,0.1088 T0.7518,0.1068 L0.7461,0.1068 Q0.7315,0.1068,0.7088,0.1103 T0.6805,0.1177 Q0.6756,0.1207,0.6699,0.1207 Q0.6667,0.1207,0.6545,0.1177 T0.631,0.1147 Q0.6269,0.1137,0.6225,0.1133 T0.616,0.1128 L0.6123,0.1128 T0.6103,0.1133 L0.6083,0.1157 T0.6034,0.1197 Q0.5961,0.1246,0.5921,0.1246 Q0.5904,0.1246,0.5835,0.1231 T0.5693,0.1217 L0.5661,0.1217 Q0.558,0.1217,0.5535,0.1231 T0.5446,0.1266 T0.5345,0.1296 Q0.5126,0.1316,0.4882,0.1316 T0.438,0.1405 Q0.4298,0.1434,0.425,0.1434 Q0.4209,0.1434,0.4173,0.1419 T0.4112,0.1405 T0.4027,0.1419 T0.3869,0.1434 Q0.3682,0.1434,0.3512,0.1494 Q0.3398,0.1533,0.3333,0.1533 Q0.3285,0.1533,0.3228,0.1513 L0.3212,0.1513 Q0.3179,0.1513,0.3155,0.1538 T0.3131,0.1592 Q0.3131,0.1612,0.3147,0.1632 Q0.3171,0.1652,0.3232,0.1667 T0.3406,0.1691 T0.3544,0.1701 L0.3601,0.1701 L0.3678,0.1701 L0.3771,0.1701 Q0.3909,0.1701,0.4031,0.1731 Q0.4177,0.178,0.4558,0.178 Q0.4793,0.178,0.4882,0.1761 L0.4915,0.1761 Q0.498,0.1761,0.5061,0.179 T0.5158,0.183 Q0.5166,0.183,0.5231,0.1835 T0.5341,0.1845 T0.545,0.1855 T0.5572,0.1874 T0.5661,0.1909 Q0.5677,0.1919,0.5702,0.1919 T0.5791,0.1894 T0.588,0.1869 Q0.5921,0.1869,0.5945,0.1899 Q0.5977,0.1919,0.6123,0.1919 Q0.6334,0.1919,0.6448,0.1879 Q0.6488,0.186,0.6537,0.186 Q0.6626,0.186,0.6784,0.1909 T0.6983,0.1958 Q0.704,0.1968,0.7206,0.1973 T0.7506,0.1993 T0.7689,0.2018 L0.7705,0.2018 L0.7741,0.2018 L0.7786,0.2018 Q0.8248,0.2018,0.8475,0.2136 Q0.8597,0.2196,0.8597,0.2255 T0.8483,0.2359 T0.8281,0.2404 Q0.8208,0.2404,0.7534,0.2493 Q0.7502,0.2502,0.7425,0.2512 T0.7287,0.2532 T0.7178,0.2542 L0.7153,0.2542 L0.7137,0.2542 Q0.7064,0.2542,0.6906,0.2591 T0.6715,0.2681 T0.6626,0.272 Q0.6594,0.272,0.6541,0.2705 T0.6464,0.269 T0.6431,0.27 Q0.6318,0.273,0.6034,0.276 Q0.6018,0.276,0.5998,0.2774 T0.5957,0.2799 T0.5904,0.2809 L0.5856,0.2809 Q0.5823,0.2799,0.575,0.2799 Q0.541,0.2799,0.5239,0.2868 Q0.5134,0.2908,0.5028,0.2908 Q0.4996,0.2908,0.4935,0.2903 T0.4842,0.2898 Q0.4704,0.2898,0.4635,0.2918 T0.4534,0.2997 L0.4534,0.3007 Q0.4534,0.3037,0.459,0.3046 T0.4753,0.3066 T0.4899,0.3076 Q0.4907,0.3076,0.5166,0.3106 T0.5507,0.3155 Q0.5921,0.3264,0.605,0.3264 Q0.6107,0.3264,0.6131,0.3254 Q0.6212,0.3225,0.6294,0.3225 Q0.6407,0.3225,0.6513,0.3274 Q0.6529,0.3294,0.6569,0.3294 Q0.6594,0.3294,0.665,0.3284 T0.6748,0.3274 T0.6821,0.3284 Q0.6861,0.3294,0.6967,0.3299 T0.7165,0.3314 T0.7299,0.3343 Q0.7324,0.3363,0.7486,0.3383 T0.7697,0.3422 Q0.7713,0.3432,0.7774,0.3452 T0.7887,0.3492 T0.8005,0.3546 T0.8127,0.3625 T0.8208,0.3719 Q0.8256,0.3798,0.8256,0.3848 Q0.8256,0.3877,0.8236,0.3902 T0.8171,0.3976 T0.809,0.4075 T0.8021,0.4189 T0.7968,0.4273 T0.7867,0.4322 T0.7616,0.4382 Q0.7543,0.4392,0.7437,0.4392 L0.7364,0.4392 L0.7299,0.4392 Q0.7202,0.4392,0.7161,0.4402 Q0.7072,0.4431,0.691,0.4431 L0.6845,0.4431 L0.6788,0.4431 Q0.6707,0.4431,0.6545,0.4461 T0.6334,0.452 Q0.6399,0.456,0.6626,0.457 Q0.6878,0.458,0.7024,0.4639 Q0.7064,0.4649,0.7186,0.4649 L0.7295,0.4649 L0.7413,0.4649 Q0.7591,0.4649,0.7697,0.4669 Q0.7818,0.4688,0.7818,0.4728 Q0.7818,0.4748,0.7798,0.4763 T0.7753,0.4787 L0.7737,0.4797 L0.7729,0.4797 Q0.7494,0.4827,0.7388,0.4827 Q0.7332,0.4827,0.7307,0.4817 L0.7291,0.4817 Q0.7226,0.4817,0.6878,0.4896 Q0.6829,0.4906,0.6772,0.4911 T0.6618,0.4921 T0.646,0.4931 T0.6342,0.4936 T0.6212,0.4931 T0.6115,0.4926 Q0.6083,0.4926,0.6058,0.4931 T0.5969,0.4955 T0.5819,0.499 T0.5629,0.5005 Q0.5572,0.5005,0.5527,0.501 T0.545,0.502 T0.5397,0.503 T0.5361,0.5045 T0.5337,0.5064 T0.5328,0.5094 L0.532,0.5094 Q0.532,0.5104,0.5337,0.5109 T0.5381,0.5114 T0.5438,0.5119 T0.5515,0.5124 L0.5604,0.5124 Q0.5661,0.5134,0.5746,0.5153 T0.5912,0.5173 L0.5977,0.5173 L0.6026,0.5173 Q0.6139,0.5173,0.6273,0.5218 T0.6407,0.5272 Q0.6448,0.5282,0.6683,0.5321 T0.6991,0.5381 Q0.7137,0.543,0.7664,0.548 Q0.7908,0.55,0.7908,0.5559 Q0.7908,0.5589,0.7859,0.5628 Q0.781,0.5658,0.7713,0.5658 Q0.7689,0.5658,0.7628,0.5653 T0.7543,0.5648 T0.7502,0.5658 Q0.7364,0.5678,0.6878,0.5678 Q0.674,0.5678,0.6699,0.5668 L0.6683,0.5668 Q0.6659,0.5668,0.6606,0.5678 T0.6513,0.5687 Q0.6464,0.5687,0.6391,0.5678 Q0.6334,0.5668,0.6302,0.5668 T0.6241,0.5687 T0.6164,0.5717 Q0.6123,0.5727,0.6099,0.5727 L0.6062,0.5727 T0.6022,0.5732 T0.5953,0.5737 Q0.5904,0.5747,0.5839,0.5747 T0.5726,0.5752 T0.5629,0.5776 T0.5458,0.5796 Q0.5418,0.5796,0.5324,0.5791 T0.5191,0.5786 Q0.5077,0.5786,0.5045,0.5806 Q0.498,0.5836,0.4899,0.5836 Q0.4858,0.5836,0.4777,0.5826 T0.4655,0.5816 L0.4631,0.5816 Q0.4582,0.5816,0.4436,0.5841 T0.4144,0.5865 L0.4051,0.5865 L0.3986,0.5865 T0.3933,0.587 T0.3897,0.5875 T0.3869,0.5885 T0.3844,0.5895 T0.3812,0.591 T0.3779,0.5925 Q0.3739,0.5955,0.3633,0.5955 L0.3585,0.5955 L0.3536,0.5955 Q0.3277,0.5955,0.3066,0.6053 Q0.3017,0.6083,0.296,0.6083 Q0.2912,0.6083,0.2839,0.6068 T0.2741,0.6053 Q0.2693,0.6053,0.2547,0.6048 T0.236,0.6044 Q0.2222,0.6044,0.193,0.6103 L0.1882,0.6103 Q0.1825,0.6103,0.1703,0.6083 T0.1525,0.6063 L0.15,0.6063 Q0.1436,0.6063,0.135,0.6073 T0.1168,0.6098 T0.1038,0.6113 Q0.0973,0.6123,0.0787,0.6123 L0.06,0.6123 L0.0414,0.6123 L0.0235,0.6123 Q0.0049,0.6133,0.0049,0.6172 L0.0057,0.6222 Q0.0073,0.6261,0.043,0.6261 L0.0454,0.6261 L0.0479,0.6261 Q0.0527,0.6261,0.0633,0.6281 T0.0803,0.6301 L0.0835,0.6301 L0.0916,0.6301 Q0.0998,0.6301,0.129,0.632 Q0.1768,0.636,0.206,0.64 Q0.2117,0.6409,0.2165,0.6409 Q0.2206,0.6409,0.2263,0.6405 T0.2336,0.64 L0.2384,0.64 L0.2409,0.64 T0.251,0.6395 T0.2644,0.639 Q0.2741,0.639,0.279,0.6409 Q0.283,0.6429,0.2972,0.6439 T0.3293,0.6459 T0.3528,0.6469 L0.3577,0.6469 Q0.3642,0.6469,0.3723,0.6449 T0.3844,0.6429 Q0.3901,0.6429,0.3933,0.6454 T0.4006,0.6479 Q0.4088,0.6479,0.4517,0.6558 Q0.4582,0.6568,0.4623,0.6568 Q0.4655,0.6568,0.4716,0.6563 T0.4826,0.6558 L0.4882,0.6558 Q0.5004,0.6558,0.5255,0.6607 Q0.5328,0.6627,0.5604,0.6647 T0.6152,0.6682 T0.644,0.6696 T0.6719,0.6721 T0.7056,0.6756 Q0.7113,0.6756,0.7198,0.6805 T0.738,0.6855 Q0.7453,0.6855,0.7551,0.6879 T0.7741,0.6939 T0.7912,0.7018 T0.8029,0.7102 Q0.8054,0.7132,0.8054,0.7151 Q0.8054,0.7191,0.8009,0.7216 T0.7908,0.7255 T0.779,0.7285 T0.7721,0.731 Q0.7672,0.7329,0.7632,0.7339 T0.7551,0.7354 T0.7486,0.7369 Q0.7478,0.7369,0.7445,0.7379 T0.7388,0.7394 T0.7324,0.7404 L0.7242,0.7413 T0.7161,0.7418 Q0.7105,0.7418,0.6955,0.7428 T0.6748,0.7438 L0.6699,0.7438 L0.6667,0.7438 Q0.6659,0.7438,0.6407,0.7468 Q0.6367,0.7478,0.6334,0.7478 T0.6245,0.7468 T0.6148,0.7458 L0.6099,0.7458 Q0.6018,0.7468,0.5864,0.7498 T0.5653,0.7532 T0.5596,0.7557 Q0.5596,0.7596,0.571,0.7616 Q0.5742,0.7626,0.5803,0.7631 T0.5929,0.7641 T0.6018,0.7656 L0.6087,0.7656 T0.6192,0.7666 T0.6277,0.7695 Q0.631,0.7705,0.6342,0.7705 Q0.6383,0.7705,0.6452,0.7685 T0.6537,0.7666 L0.6553,0.7666 Q0.6602,0.7666,0.6711,0.769 T0.6853,0.7715 Q0.691,0.7715,0.7048,0.775 T0.7242,0.7814 Q0.7324,0.7854,0.7445,0.7864 Q0.7478,0.7864,0.768,0.7873 T0.7972,0.7893 Q0.7989,0.7893,0.8017,0.7898 T0.8054,0.7903 L0.8082,0.7903 T0.811,0.7908 T0.8131,0.7913 T0.8151,0.7918 L0.8167,0.7928 T0.8179,0.7943 T0.8191,0.7957 T0.8204,0.7977 T0.8208,0.8002 Q0.8208,0.8032,0.8171,0.8051 T0.8074,0.8081 T0.7997,0.8091 Q0.7932,0.8121,0.7737,0.8121 Q0.7664,0.8121,0.7413,0.8111 L0.7364,0.8111 Q0.7275,0.8111,0.7214,0.8121 T0.7084,0.8155 T0.6991,0.819 Q0.6934,0.82,0.6723,0.8205 T0.6472,0.8239 Q0.6423,0.8269,0.6375,0.8269 Q0.6358,0.8269,0.6338,0.8264 T0.6294,0.8254 T0.6253,0.8249 Q0.6042,0.8249,0.5961,0.8289 Q0.5921,0.8318,0.5839,0.8318 Q0.5783,0.8318,0.5645,0.8299 L0.5604,0.8299 Q0.5531,0.8299,0.5337,0.8368 Q0.5296,0.8378,0.5255,0.8378 Q0.5239,0.8378,0.5195,0.8373 T0.5118,0.8368 Q0.5061,0.8368,0.4996,0.8388 Q0.4947,0.8388,0.4882,0.8398 Q0.4777,0.8417,0.4753,0.8427 T0.4728,0.8467 Q0.4728,0.8487,0.4769,0.8492 T0.4886,0.8501 T0.5004,0.8516 Q0.5036,0.8516,0.515,0.8521 T0.5345,0.8546 Q0.5426,0.8556,0.5596,0.8556 L0.5649,0.8556 L0.5702,0.8556 L0.5791,0.8556 Q0.5921,0.8566,0.6135,0.8571 T0.6383,0.8586 Q0.6683,0.8615,0.6764,0.8615 L0.6776,0.8615 L0.6788,0.8615 Q0.7032,0.8615,0.7032,0.8684 Q0.7032,0.8714,0.6995,0.8749 T0.6959,0.8803 L0.6959,0.8813 Q0.6991,0.8843,0.7153,0.8843 Q0.7218,0.8843,0.7259,0.8833 L0.7299,0.8833 Q0.7324,0.8833,0.7348,0.8838 T0.7393,0.8848 T0.7433,0.8863 L0.7474,0.8882 T0.751,0.8892 Q0.7616,0.8922,0.7948,0.8952 Q0.7981,0.8952,0.8082,0.8981 T0.8297,0.9011 T0.8528,0.9026 T0.8747,0.907 T0.8856,0.9149 L0.8856,0.9159 Q0.8856,0.9179,0.8848,0.9189 T0.8828,0.9209 T0.88,0.9228 T0.8767,0.9243 T0.8731,0.9248 T0.8698,0.9253 T0.8666,0.9258 L0.8646,0.9258 Q0.8621,0.9258,0.8577,0.9263 T0.85,0.9268 T0.8439,0.9273 T0.8402,0.9278 Q0.8386,0.9298,0.8358,0.9308 T0.8305,0.9322 T0.8244,0.9332 T0.8183,0.9337 Q0.8135,0.9347,0.8025,0.9372 T0.7859,0.9416 Q0.7778,0.9436,0.7717,0.9471 T0.7624,0.9515 Q0.7575,0.9535,0.7486,0.9535 Q0.7461,0.9535,0.7397,0.953 T0.7291,0.9525 Q0.7234,0.9525,0.7186,0.953 T0.7137,0.957 T0.7194,0.9614 Q0.7567,0.9634,0.7664,0.9654 Q0.7745,0.9674,0.7762,0.9674 L0.7908,0.9674 Q0.7924,0.9664,0.7948,0.9664 Q0.8029,0.9664,0.8082,0.9679 T0.8224,0.9723 T0.8362,0.9773 Q0.8483,0.9812,0.871,0.9812 L0.8751,0.9812 Q0.8873,0.9812,0.8929,0.9822 T0.9165,0.9876 T0.9408,0.9931 Q0.9513,0.996,0.9935,0.996 Z M0.9968,0.998 L0.9976,0.003 Q0.9838,0.002,0.9708,0.0059 Q0.9659,0.0069,0.9327,0.0059 T0.8881,0.0099 Q0.8767,0.0138,0.8658,0.0163 T0.8491,0.0218 Q0.8418,0.0247,0.8341,0.0247 T0.8232,0.0257 Q0.8191,0.0277,0.7997,0.0292 T0.7737,0.0326 Q0.7697,0.0336,0.7672,0.0336 T0.7612,0.0321 T0.7543,0.0307 T0.747,0.0317 Q0.7397,0.0326,0.7336,0.0356 T0.717,0.0406 Q0.6918,0.0445,0.6861,0.0475 Q0.6845,0.0485,0.6772,0.0485 T0.6638,0.05 T0.6577,0.0549 T0.6642,0.0598 T0.6796,0.0613 T0.6902,0.0623 Q0.691,0.0623,0.6946,0.0658 T0.7064,0.0702 L0.7161,0.0702 Q0.7194,0.0702,0.7242,0.0697 T0.7332,0.0692 Q0.7413,0.0692,0.7579,0.0717 T0.781,0.0762 Q0.7867,0.0781,0.8171,0.0786 T0.85,0.0801 L0.8532,0.0801 Q0.8548,0.0801,0.8613,0.0796 T0.8727,0.0791 Q0.8832,0.0791,0.8913,0.0811 Q0.897,0.0831,0.897,0.0851 Q0.897,0.088,0.8873,0.0905 T0.8735,0.093 Q0.871,0.093,0.8447,0.0984 T0.8143,0.1039 Q0.7981,0.1039,0.781,0.1078 Q0.7778,0.1088,0.7745,0.1088 T0.7644,0.1073 T0.7518,0.1048 L0.7453,0.1048 Q0.7299,0.1048,0.7076,0.1083 T0.6788,0.1157 Q0.6748,0.1187,0.6699,0.1187 Q0.6675,0.1187,0.6557,0.1157 T0.6318,0.1118 Q0.6164,0.1108,0.6135,0.1108 T0.6095,0.1113 T0.6067,0.1142 T0.6018,0.1187 Q0.5953,0.1227,0.5921,0.1227 Q0.5904,0.1227,0.5839,0.1212 T0.5693,0.1187 L0.5661,0.1187 Q0.558,0.1187,0.5527,0.1207 T0.5434,0.1246 T0.5337,0.1266 Q0.5126,0.1296,0.4882,0.1296 T0.4371,0.1385 Q0.4298,0.1414,0.425,0.1414 Q0.4225,0.1414,0.4189,0.1395 T0.4112,0.1375 Q0.4079,0.1375,0.4019,0.1395 T0.3869,0.1414 Q0.3682,0.1414,0.3504,0.1474 Q0.3398,0.1513,0.3333,0.1513 Q0.3293,0.1513,0.3228,0.1494 L0.3204,0.1494 Q0.3179,0.1494,0.3155,0.1508 T0.3118,0.1543 T0.3106,0.1592 T0.3127,0.1642 T0.32,0.1677 T0.3305,0.1701 T0.3435,0.1716 T0.3544,0.1721 Q0.3569,0.1731,0.3601,0.1731 Q0.3625,0.1731,0.3686,0.1726 T0.3779,0.1721 Q0.3901,0.1721,0.4023,0.1751 Q0.4177,0.18,0.455,0.18 Q0.4793,0.18,0.4882,0.178 L0.4915,0.178 Q0.4964,0.178,0.5045,0.1815 T0.5158,0.185 Q0.5564,0.1889,0.5645,0.1929 Q0.5677,0.1939,0.571,0.1939 Q0.575,0.1939,0.5807,0.1919 T0.5888,0.1899 T0.5929,0.1909 Q0.5969,0.1949,0.6123,0.1949 Q0.6334,0.1949,0.6456,0.1899 Q0.6488,0.1879,0.6537,0.1879 Q0.661,0.1879,0.6772,0.1929 T0.6983,0.1978 Q0.704,0.1988,0.7206,0.1998 T0.7502,0.2018 T0.7664,0.2038 Q0.7672,0.2038,0.7818,0.2043 T0.8151,0.2067 T0.8459,0.2156 Q0.8573,0.2206,0.8573,0.2255 Q0.8573,0.2295,0.8516,0.2324 T0.8394,0.2369 T0.8281,0.2384 Q0.8208,0.2384,0.7526,0.2473 Q0.7494,0.2483,0.7421,0.2493 T0.7287,0.2512 T0.7178,0.2522 L0.7153,0.2522 L0.7137,0.2522 Q0.7056,0.2522,0.6898,0.2572 T0.6691,0.2671 Q0.6667,0.269,0.6634,0.269 Q0.661,0.269,0.6557,0.2681 T0.6472,0.2671 Q0.6448,0.2671,0.6415,0.2681 Q0.631,0.271,0.6034,0.274 Q0.5994,0.274,0.5961,0.2765 T0.5904,0.2789 L0.5864,0.2789 Q0.5831,0.2779,0.5742,0.2779 Q0.541,0.2779,0.5223,0.2849 Q0.5126,0.2888,0.5028,0.2888 Q0.5004,0.2888,0.4943,0.2883 T0.4842,0.2878 Q0.4704,0.2878,0.4627,0.2898 T0.4509,0.2987 Q0.4501,0.2997,0.4501,0.3007 Q0.4501,0.3046,0.4574,0.3066 T0.4765,0.3091 T0.4899,0.3096 Q0.4931,0.3106,0.5061,0.3121 T0.5316,0.315 T0.5499,0.3175 Q0.5507,0.3175,0.5572,0.3195 T0.5685,0.3225 T0.5803,0.3254 T0.5933,0.3279 T0.605,0.3284 T0.6148,0.3274 Q0.6221,0.3244,0.6294,0.3244 Q0.6399,0.3244,0.6496,0.3294 Q0.6529,0.3314,0.6577,0.3314 Q0.6602,0.3314,0.6663,0.3304 T0.6756,0.3294 T0.6813,0.3304 Q0.6837,0.3304,0.6873,0.3309 L0.6946,0.3318 T0.7024,0.3323 T0.7105,0.3328 T0.7178,0.3338 T0.7238,0.3348 T0.7283,0.3363 Q0.7324,0.3383,0.7482,0.3403 T0.7689,0.3442 Q0.7697,0.3442,0.779,0.3477 T0.794,0.3536 T0.8074,0.3615 T0.8183,0.3729 Q0.8232,0.3808,0.8232,0.3848 Q0.8232,0.3867,0.8216,0.3892 T0.8151,0.3961 T0.8062,0.406 T0.7997,0.4179 T0.7952,0.4263 T0.7855,0.4308 T0.7616,0.4362 Q0.7543,0.4372,0.7445,0.4372 L0.7372,0.4372 L0.7307,0.4372 Q0.7202,0.4372,0.7153,0.4382 Q0.7064,0.4402,0.691,0.4402 L0.6845,0.4402 L0.6788,0.4402 Q0.6699,0.4402,0.6533,0.4436 T0.6318,0.451 Q0.6302,0.451,0.6302,0.452 Q0.6302,0.457,0.6626,0.459 Q0.6869,0.4609,0.7015,0.4659 Q0.7064,0.4669,0.7202,0.4669 L0.7311,0.4669 L0.7429,0.4669 Q0.7599,0.4669,0.7689,0.4688 Q0.7794,0.4708,0.7794,0.4738 L0.7786,0.4748 T0.777,0.4763 T0.7749,0.4773 L0.7737,0.4777 L0.7729,0.4777 Q0.7502,0.4797,0.738,0.4797 L0.7315,0.4797 L0.7291,0.4797 Q0.7226,0.4797,0.6869,0.4876 Q0.6821,0.4886,0.6768,0.4891 T0.6614,0.4901 T0.6456,0.4916 L0.6342,0.4916 Q0.6294,0.4916,0.6217,0.4911 T0.6115,0.4906 Q0.6083,0.4906,0.6054,0.4911 T0.5961,0.4936 T0.5815,0.4965 T0.5629,0.4985 Q0.5507,0.4985,0.5442,0.4995 T0.5345,0.5025 T0.5304,0.5084 L0.5296,0.5094 Q0.5296,0.5114,0.5316,0.5124 T0.5373,0.5138 T0.5442,0.5143 L0.5523,0.5143 L0.5604,0.5143 Q0.5637,0.5153,0.5677,0.5158 T0.5742,0.5173 T0.5811,0.5188 T0.5904,0.5193 L0.5977,0.5193 L0.6026,0.5193 Q0.6107,0.5193,0.6168,0.5208 T0.6294,0.5252 T0.6399,0.5292 Q0.6448,0.5302,0.6679,0.5341 T0.6983,0.541 Q0.7129,0.545,0.7664,0.55 Q0.7883,0.5519,0.7883,0.5559 Q0.7883,0.5579,0.7843,0.5608 T0.7721,0.5638 Q0.7697,0.5638,0.764,0.5633 T0.7559,0.5628 L0.7502,0.5628 Q0.7364,0.5648,0.6869,0.5648 L0.6699,0.5648 L0.6675,0.5648 Q0.665,0.5648,0.6602,0.5658 T0.6513,0.5668 Q0.6464,0.5668,0.6399,0.5658 Q0.6342,0.5648,0.6302,0.5648 T0.6225,0.5668 T0.6156,0.5697 Q0.6107,0.5707,0.6087,0.5707 T0.6034,0.5712 T0.5953,0.5717 Q0.5904,0.5727,0.5835,0.5727 T0.5718,0.5732 T0.562,0.5757 Q0.558,0.5767,0.5483,0.5767 L0.5349,0.5767 L0.5207,0.5767 Q0.5069,0.5767,0.5028,0.5786 Q0.4972,0.5816,0.4899,0.5816 Q0.4858,0.5816,0.4781,0.5806 T0.4663,0.5796 L0.4631,0.5796 Q0.4582,0.5796,0.4432,0.5821 T0.4144,0.5846 L0.4071,0.5846 L0.4011,0.5846 T0.3958,0.5851 T0.3921,0.5856 T0.3889,0.5861 T0.3865,0.5865 T0.384,0.5875 L0.382,0.5885 L0.3796,0.5895 L0.3771,0.5905 Q0.3731,0.5925,0.365,0.5925 L0.3601,0.5925 L0.3552,0.5925 Q0.3277,0.5925,0.3049,0.6044 Q0.3017,0.6053,0.296,0.6053 Q0.292,0.6053,0.2847,0.6044 T0.2741,0.6034 Q0.2693,0.6034,0.2547,0.6029 T0.236,0.6024 Q0.2222,0.6024,0.1922,0.6073 Q0.1906,0.6083,0.1882,0.6083 Q0.1833,0.6083,0.1711,0.6063 T0.1533,0.6044 Q0.1517,0.6034,0.1492,0.6034 Q0.1436,0.6034,0.135,0.6048 T0.1168,0.6078 T0.103,0.6093 Q0.0973,0.6103,0.0787,0.6103 L0.0604,0.6103 L0.0414,0.6103 L0.0235,0.6103 Q0.0024,0.6113,0.0024,0.6172 Q0.0024,0.6192,0.0032,0.6231 Q0.0049,0.6281,0.0333,0.6281 L0.0414,0.6281 L0.0479,0.6281 Q0.0519,0.6281,0.0624,0.6301 T0.0803,0.632 L0.0835,0.632 L0.0916,0.632 Q0.0989,0.632,0.1281,0.634 L0.206,0.6419 Q0.2117,0.6429,0.2174,0.6429 Q0.2214,0.6429,0.2271,0.6424 T0.2344,0.6419 L0.2376,0.6419 Q0.2393,0.6429,0.2417,0.6429 T0.2526,0.6419 T0.2652,0.6409 Q0.2741,0.6409,0.2782,0.6429 T0.2968,0.6459 T0.3293,0.6479 T0.352,0.6489 Q0.3552,0.6499,0.3585,0.6499 Q0.365,0.6499,0.3731,0.6474 T0.3844,0.6449 Q0.3885,0.6449,0.3917,0.6474 T0.4006,0.6499 Q0.4088,0.6499,0.4509,0.6578 Q0.4574,0.6588,0.4631,0.6588 Q0.4655,0.6588,0.4716,0.6583 T0.4834,0.6578 L0.4874,0.6578 Q0.5004,0.6588,0.5255,0.6637 Q0.532,0.6647,0.56,0.6667 T0.6148,0.6701 T0.644,0.6716 Q0.6464,0.6726,0.6594,0.6736 T0.6861,0.6756 T0.7048,0.6775 Q0.7097,0.6775,0.7186,0.6825 T0.738,0.6874 Q0.7518,0.6874,0.7729,0.6958 T0.8005,0.7122 Q0.8029,0.7141,0.8029,0.7151 Q0.8029,0.7191,0.7968,0.7216 T0.7818,0.726 T0.7705,0.729 L0.764,0.731 T0.7583,0.7324 T0.753,0.7334 T0.7486,0.7349 Q0.7251,0.7399,0.7161,0.7399 Q0.7097,0.7399,0.6951,0.7409 T0.6748,0.7418 L0.6703,0.7418 L0.6667,0.7418 Q0.6659,0.7418,0.6399,0.7448 L0.6334,0.7448 Q0.631,0.7448,0.6249,0.7443 T0.6148,0.7438 L0.6099,0.7438 Q0.601,0.7448,0.5856,0.7473 T0.5645,0.7507 Q0.5572,0.7517,0.5572,0.7547 T0.5616,0.7606 T0.5702,0.7646 Q0.5734,0.7646,0.5779,0.7651 T0.5864,0.7661 T0.5949,0.7671 T0.6018,0.7676 L0.6071,0.7676 T0.6135,0.7681 T0.62,0.769 T0.6269,0.771 T0.6342,0.7725 Q0.6391,0.7725,0.6464,0.7705 T0.6541,0.7685 L0.6553,0.7685 Q0.6586,0.7685,0.6699,0.771 T0.6853,0.7735 Q0.6902,0.7735,0.704,0.777 T0.7226,0.7834 Q0.7315,0.7873,0.7445,0.7883 Q0.747,0.7883,0.7676,0.7893 T0.7972,0.7913 Q0.7989,0.7913,0.8017,0.7918 T0.8058,0.7923 T0.809,0.7928 T0.8114,0.7933 T0.8131,0.7938 T0.8147,0.7943 T0.8159,0.7953 L0.8171,0.7967 T0.8175,0.7982 Q0.8183,0.7992,0.8183,0.8002 Q0.8183,0.8022,0.8155,0.8032 T0.807,0.8051 T0.7989,0.8071 Q0.7932,0.8091,0.7737,0.8091 L0.7413,0.8091 L0.7372,0.8091 Q0.7275,0.8091,0.721,0.8101 T0.7072,0.8136 T0.6983,0.817 Q0.6942,0.818,0.6825,0.818 T0.6602,0.819 T0.6456,0.822 Q0.6415,0.8249,0.6375,0.8249 Q0.6367,0.8249,0.6326,0.8239 T0.6253,0.8229 Q0.6034,0.8229,0.5953,0.8279 Q0.5912,0.8289,0.5848,0.8289 Q0.5775,0.8289,0.5645,0.8279 Q0.5629,0.8269,0.5604,0.8269 Q0.5523,0.8269,0.5328,0.8348 Q0.5296,0.8358,0.5264,0.8358 Q0.5247,0.8358,0.5203,0.8353 T0.5126,0.8348 Q0.5061,0.8348,0.4988,0.8358 Q0.4947,0.8368,0.4882,0.8378 Q0.4826,0.8388,0.4797,0.8388 T0.474,0.8398 T0.4704,0.8422 T0.4696,0.8462 T0.472,0.8501 T0.4781,0.8521 T0.4854,0.8526 L0.4935,0.8526 T0.4996,0.8536 Q0.5036,0.8536,0.515,0.8546 T0.5337,0.8566 Q0.5426,0.8576,0.5596,0.8576 L0.5657,0.8576 L0.571,0.8576 L0.5791,0.8576 Q0.5921,0.8586,0.6135,0.8591 T0.6383,0.8605 Q0.6683,0.8635,0.6764,0.8635 Q0.6999,0.8635,0.6999,0.8684 Q0.6999,0.8694,0.6967,0.8734 T0.6934,0.8803 L0.6934,0.8823 Q0.6951,0.8863,0.7137,0.8863 Q0.7218,0.8863,0.7267,0.8853 L0.7299,0.8853 Q0.734,0.8853,0.7409,0.8882 T0.7502,0.8912 Q0.7607,0.8942,0.794,0.8971 Q0.7972,0.8971,0.8078,0.9001 T0.8297,0.9031 Q0.8475,0.9031,0.8646,0.9065 T0.8824,0.9149 L0.8824,0.9159 Q0.8824,0.9169,0.882,0.9179 T0.8808,0.9194 L0.8792,0.9204 T0.8767,0.9214 T0.8743,0.9224 T0.8715,0.9228 L0.8686,0.9228 T0.8662,0.9233 T0.8637,0.9238 L0.8556,0.9238 T0.8447,0.9243 T0.8386,0.9268 Q0.837,0.9278,0.835,0.9288 T0.8305,0.9303 T0.8244,0.9308 T0.8175,0.9318 Q0.8127,0.9327,0.8017,0.9352 T0.7851,0.9397 Q0.777,0.9416,0.7705,0.9451 T0.7616,0.9496 Q0.7575,0.9505,0.7494,0.9505 L0.7405,0.9505 L0.7307,0.9505 Q0.7234,0.9505,0.7178,0.9515 Q0.7145,0.9515,0.7125,0.9535 T0.7105,0.9575 Q0.7105,0.9624,0.7194,0.9634 Q0.7567,0.9654,0.7664,0.9674 Q0.7745,0.9693,0.7762,0.9693 L0.7908,0.9693 L0.7948,0.9693 Q0.8005,0.9693,0.8058,0.9698 T0.8143,0.9718 T0.824,0.9753 T0.8354,0.9792 Q0.8483,0.9832,0.871,0.9832 L0.8739,0.9832 L0.8767,0.9832 Q0.8873,0.9832,0.8921,0.9842 Q0.8978,0.9852,0.9157,0.9896 T0.94,0.996 Q0.9424,0.996,0.9469,0.9965 T0.9566,0.997 T0.9676,0.9975 T0.9781,0.998 L0.9874,0.998 L0.9943,0.998 L0.9968,0.998 Z",type:0}},"\uE0CC":{type:5,data:{d:"M1,0.5071 L0.8623,0.7102 L0.5865,0.7102 L0.4489,0.5071 L0.5865,0.3045 L0.8623,0.3045 Z M0.4135,0.7974 L0.2758,1 L0,1 L0,0.5944 L0.2758,0.5944 Z M0.4135,0.2026 L0.2758,0.4056 L0,0.4056 L0,0 L0.2758,0 Z",type:0}},"\uE0CD":{type:5,data:{d:"M0.9726,0.5071 L0.8451,0.3184 L0.59,0.3184 L0.4624,0.5071 L0.59,0.6955 L0.8451,0.6955 Z M1,0.5071 L0.8588,0.716 L0.5768,0.716 L0.4355,0.5071 L0.5768,0.2982 L0.8588,0.2982 Z M0.401,0.7911 L0.2735,0.6028 L0.0236,0.6028 L0.0236,0.9799 L0.2735,0.9799 Z M0.4284,0.7911 L0.2872,1 L0,1 L0,0.5826 L0.2872,0.5826 Z M0.401,0.2089 L0.2735,0.0201 L0.0236,0.0201 L0.0236,0.3972 L0.2735,0.3972 Z M0.4284,0.2089 L0.2872,0.4174 L0,0.4174 L0,0 L0.2872,0 Z",type:0}},"\uE0CE":{type:5,data:{d:"M1,0.4996 Q1,0.5365,0.9924,0.568 T0.9718,0.6177 T0.9433,0.6363 L0.9425,0.6367 Q0.9355,0.6367,0.9285,0.6326 L0.9308,0.6326 Q0.9129,0.6195,0.9013,0.587 T0.8871,0.5164 T0.8943,0.4373 T0.9254,0.3687 L0.9254,0.3691 Q0.9339,0.3628,0.9425,0.3628 Q0.9584,0.3628,0.9716,0.3811 T0.9924,0.431 T1,0.4996 Z M0.9234,0.6321 L0.8776,0.7169 Q0.8791,0.732,0.8791,0.7441 Q0.8791,0.781,0.8716,0.8123 T0.8508,0.862 T0.8224,0.8809 L0.8216,0.8809 Q0.8154,0.8809,0.8092,0.8775 L0.8088,0.8775 Q0.7905,0.8633,0.7792,0.8297 T0.766,0.7571 T0.775,0.6768 T0.8088,0.6086 L0.7431,0.6065 Q0.719,0.6313,0.7072,0.6705 T0.6965,0.7487 T0.7097,0.823 T0.7423,0.8763 L0.7913,0.8775 L0.7314,0.9895 L0.4648,0.5038 L0.7299,0.0176 L0.7882,0.1229 L0.7404,0.1212 Q0.7244,0.138,0.7136,0.1617 T0.6982,0.2108 T0.6943,0.2632 T0.7003,0.3144 T0.7159,0.3586 T0.7396,0.3909 L0.8072,0.3926 Q0.7894,0.3796,0.7777,0.3479 T0.7635,0.2789 T0.7697,0.2011 T0.7987,0.1326 Q0.8092,0.1225,0.8204,0.1225 Q0.8321,0.1225,0.8426,0.1332 T0.8609,0.1623 T0.8731,0.2062 T0.8776,0.2592 Q0.8776,0.268,0.8768,0.2815 L0.9219,0.3628 L0.8644,0.3612 Q0.8403,0.3855,0.8284,0.4247 T0.8177,0.5029 T0.8309,0.5772 T0.8632,0.6305 Z M0.6759,0.6384 Q0.6576,0.625,0.6457,0.5914 T0.6319,0.5185 T0.6407,0.4375 T0.6751,0.3691 L0.609,0.367 Q0.5849,0.3918,0.5731,0.431 T0.5626,0.509 T0.5758,0.5833 T0.6082,0.6367 Z M0.6459,0.0025 L0.391,0.4551 L0.0035,0.4551 L0.246,0 Z M0.6553,1 L0.2421,1 L0,0.5449 L0.3875,0.5449 Z",type:0}},"\uE0CF":{type:5,data:{d:"M0.4996,0 Q0.5562,0,0.5961,0.0166 T0.6364,0.0566 L0.6368,0.0575 Q0.6368,0.0646,0.6324,0.0713 L0.6324,0.0692 Q0.6196,0.0868,0.5872,0.0986 T0.5166,0.1128 T0.4373,0.1057 T0.3689,0.0747 L0.3694,0.0747 Q0.3627,0.0663,0.3627,0.0575 Q0.3627,0.0336,0.4028,0.0168 T0.4996,0 Z M0.6324,0.0768 L0.717,0.1225 Q0.7321,0.1212,0.744,0.1212 Q0.8007,0.1212,0.8406,0.1378 T0.8809,0.1779 L0.8813,0.1783 Q0.8813,0.1846,0.8778,0.1909 Q0.8636,0.2093,0.8299,0.2208 T0.7573,0.2343 T0.6769,0.2253 T0.6089,0.1913 L0.6067,0.2567 Q0.6315,0.281,0.6707,0.2928 T0.7489,0.3035 T0.8231,0.2903 T0.8764,0.258 L0.8778,0.2085 L0.9898,0.2685 L0.504,0.5352 L0.0177,0.2701 L0.1227,0.2118 L0.1213,0.2596 Q0.1457,0.2836,0.1851,0.2955 T0.2635,0.3062 T0.3377,0.293 T0.3911,0.2605 L0.3928,0.193 Q0.38,0.2106,0.3483,0.2221 T0.2792,0.2364 T0.2013,0.2303 T0.1324,0.2013 Q0.1222,0.1909,0.1222,0.1795 Q0.1222,0.156,0.1623,0.1393 T0.2591,0.1225 Q0.2679,0.1225,0.2817,0.1233 L0.3627,0.078 L0.3609,0.1359 Q0.3857,0.1598,0.4249,0.1718 T0.5031,0.1825 T0.5773,0.1693 T0.6306,0.1367 Z M0.6386,0.3242 Q0.6253,0.3427,0.5917,0.3544 T0.5186,0.3683 T0.4376,0.3595 T0.3689,0.3251 L0.3671,0.3909 Q0.3915,0.4148,0.4309,0.4268 T0.5093,0.4375 T0.5835,0.4243 T0.6368,0.3918 Z M0.0027,0.354 L0.4553,0.6091 L0.4553,0.9962 L0,0.7542 Z M1,0.3448 L1,0.7576 L0.5447,1 L0.5447,0.6128 Z",type:0}},"\uE0D0":{type:5,data:{d:"M0,0.7699 Q0,0.7172,0.0277,0.6731 T0.103,0.6032 T0.2066,0.5774 Q0.2487,0.5774,0.2865,0.5922 T0.3526,0.6339 L0.3935,0.6715 Q0.4218,0.6984,0.438,0.7336 T0.4541,0.8075 Q0.4541,0.8602,0.4264,0.9046 T0.3511,0.9745 T0.2475,1 Q0.2054,1,0.1676,0.9852 T0.1016,0.9435 L0.0606,0.9059 Q0.0317,0.879,0.0159,0.8438 T0,0.7699 Z M0.5459,0.7699 Q0.5459,0.7172,0.5736,0.6731 T0.6489,0.6032 T0.7525,0.5774 Q0.7946,0.5774,0.8324,0.5922 T0.8984,0.6339 L0.9394,0.6715 Q0.9579,0.6892,0.9714,0.7105 T0.9925,0.7567 T1,0.8075 Q1,0.8602,0.9723,0.9046 T0.897,0.9745 T0.7934,1 Q0.7513,1,0.7135,0.9852 T0.6474,0.9435 L0.6065,0.9059 Q0.5776,0.879,0.5617,0.8438 T0.5459,0.7699 Z M0,0.1925 Q0,0.1398,0.0277,0.0957 T0.103,0.0258 T0.2066,0 Q0.2487,0,0.2865,0.0148 T0.3526,0.0565 L0.3935,0.0941 Q0.4218,0.121,0.438,0.1562 T0.4541,0.2301 Q0.4541,0.2828,0.4264,0.3269 T0.3511,0.3968 T0.2475,0.4226 Q0.2054,0.4226,0.1676,0.4078 T0.1016,0.3661 L0.0606,0.3285 Q0.0317,0.3016,0.0159,0.2664 T0,0.1925 Z M0.5459,0.1925 Q0.5459,0.1398,0.5736,0.0957 T0.6489,0.0258 T0.7525,0 Q0.7946,0,0.8324,0.0148 T0.8984,0.0565 L0.9394,0.0941 Q0.9677,0.121,0.9838,0.1562 T1,0.2301 Q1,0.2828,0.9723,0.3269 T0.897,0.3968 T0.7934,0.4226 Q0.7513,0.4226,0.7135,0.4078 T0.6474,0.3661 L0.6065,0.3285 Q0.5874,0.3108,0.5741,0.2895 T0.5534,0.2433 T0.5459,0.1925 Z M0.3301,0.6403 Q0.3306,0.6403,0.3312,0.6409 L0.3272,0.6371 L0.3272,0.6371 Z M0.8759,0.6403 Q0.8765,0.6403,0.8771,0.6409 Q0.8748,0.6387,0.8725,0.6371 L0.8731,0.6371 Z M0.3301,0.0629 Q0.3306,0.0629,0.3312,0.0634 L0.3272,0.0597 L0.3272,0.0602 Z M0.8759,0.0629 Q0.8765,0.0629,0.8771,0.0634 Q0.8748,0.0613,0.8725,0.0597 Q0.8731,0.0597,0.8731,0.0602 Z M0.779,0.4113 L0.7501,0.3849 Q0.7046,0.3844,0.6636,0.3661 Q0.7132,0.407,0.779,0.4113 Z M0.7957,0.4118 Q0.8477,0.4113,0.8918,0.3874 T0.9619,0.3223 T0.9885,0.2323 L0.9585,0.2048 Q0.9538,0.2769,0.8987,0.3282 T0.7657,0.3844 Z M0.9879,0.2167 Q0.9827,0.1554,0.9388,0.1097 Q0.9585,0.1478,0.959,0.1898 Z M0.2331,0.4113 L0.2043,0.3849 Q0.1587,0.3844,0.1177,0.3661 Q0.1673,0.407,0.2331,0.4113 Z M0.2499,0.4118 Q0.2885,0.4118,0.324,0.3973 T0.3852,0.3589 T0.4264,0.3019 T0.4426,0.2323 L0.4126,0.2048 Q0.408,0.2769,0.3529,0.3282 T0.2198,0.3844 Z M0.442,0.2167 Q0.4368,0.1554,0.393,0.1097 Q0.4126,0.1478,0.4132,0.1903 Z M0.779,0.9887 L0.7501,0.9624 Q0.7046,0.9618,0.6636,0.9435 Q0.7132,0.9844,0.779,0.9887 Z M0.7957,0.9892 Q0.8477,0.9887,0.8918,0.9648 T0.9619,0.8997 T0.9885,0.8097 L0.9585,0.7823 Q0.9538,0.8543,0.8987,0.9056 T0.7657,0.9618 Z M0.9879,0.7941 Q0.9827,0.7328,0.9388,0.6871 Q0.9585,0.7253,0.959,0.7672 Z M0.2331,0.9887 L0.2043,0.9624 Q0.1587,0.9618,0.1177,0.9435 Q0.1673,0.9844,0.2331,0.9887 Z M0.2499,0.9892 Q0.3018,0.9887,0.3459,0.9648 T0.416,0.8997 T0.4426,0.8102 L0.4126,0.7823 Q0.408,0.8543,0.3529,0.9056 T0.2198,0.9618 Z M0.442,0.7941 Q0.4368,0.7328,0.393,0.6871 Q0.4126,0.7253,0.4132,0.7672 Z M0.3191,0.6452 Q0.2943,0.622,0.2643,0.6091 T0.2066,0.5962 Q0.1795,0.5962,0.1497,0.6091 T0.0949,0.6441 T0.0537,0.6995 T0.0375,0.7699 Q0.0375,0.8419,0.0941,0.8941 Q0.1189,0.9172,0.1489,0.9304 T0.2066,0.9435 Q0.2337,0.9435,0.2634,0.9304 T0.3182,0.8952 T0.3595,0.8398 T0.3756,0.7699 Q0.3756,0.6978,0.3191,0.6452 Z M0.026,0.7731 L0.026,0.7699 Q0.026,0.6935,0.0854,0.6376 Q0.0658,0.6538,0.0514,0.6739 T0.0289,0.718 T0.0202,0.7677 Z M0.0271,0.7892 L0.0208,0.7833 Q0.0254,0.8419,0.0681,0.886 Q0.0664,0.8828,0.0646,0.879 Q0.0329,0.8382,0.0271,0.7892 Z M0.3866,0.7823 Q0.382,0.8511,0.3278,0.9016 Q0.3843,0.8565,0.3918,0.7871 Z M0.3872,0.7677 L0.393,0.7726 L0.393,0.7699 Q0.393,0.7349,0.3791,0.7038 Q0.3739,0.6973,0.3681,0.6914 Q0.3866,0.7274,0.3872,0.7677 Z M0.865,0.6452 Q0.8402,0.622,0.8102,0.6091 T0.7525,0.5962 Q0.7305,0.5962,0.7072,0.6043 T0.6619,0.628 T0.6223,0.6642 T0.5941,0.7124 T0.5834,0.7699 Q0.5834,0.8419,0.6399,0.8941 Q0.6561,0.9097,0.6757,0.9207 T0.7149,0.9376 T0.7525,0.9435 Q0.7796,0.9435,0.8093,0.9304 T0.8641,0.8952 T0.9054,0.8398 T0.9215,0.7699 Q0.9215,0.6978,0.865,0.6452 Z M0.5718,0.7731 L0.5718,0.7699 Q0.5718,0.6935,0.6313,0.6376 Q0.6013,0.6618,0.584,0.6954 T0.5661,0.7677 Z M0.573,0.7892 L0.5666,0.7833 Q0.5713,0.8419,0.614,0.886 Q0.6122,0.8828,0.6105,0.879 Q0.5788,0.8382,0.573,0.7892 Z M0.9325,0.7823 Q0.9279,0.8511,0.8736,0.9016 Q0.9308,0.8565,0.9377,0.7871 Z M0.9331,0.7672 L0.9388,0.7726 L0.9388,0.7699 Q0.9388,0.7349,0.925,0.7038 Q0.9198,0.6973,0.914,0.6914 Q0.9325,0.7274,0.9331,0.7672 Z M0.3191,0.0677 Q0.2943,0.0446,0.2643,0.0317 T0.2066,0.0188 Q0.1795,0.0188,0.1497,0.0317 T0.0949,0.0667 T0.0537,0.122 T0.0375,0.1925 Q0.0375,0.2645,0.0941,0.3167 Q0.1189,0.3398,0.1489,0.353 T0.2066,0.3661 Q0.2337,0.3661,0.2634,0.353 T0.3182,0.3177 T0.3595,0.2624 T0.3756,0.1925 Q0.3756,0.1204,0.3191,0.0677 Z M0.026,0.1957 L0.026,0.1925 Q0.026,0.1161,0.0854,0.0602 Q0.0554,0.0844,0.0381,0.118 T0.0202,0.1903 Z M0.0271,0.2118 L0.0208,0.2059 Q0.0254,0.2645,0.0681,0.3086 Q0.0664,0.3054,0.0646,0.3016 Q0.0329,0.2608,0.0271,0.2118 Z M0.3866,0.2048 Q0.382,0.2737,0.3278,0.3242 Q0.3849,0.279,0.3918,0.2097 Z M0.3872,0.1903 L0.393,0.1952 L0.393,0.1925 Q0.393,0.1581,0.3791,0.1263 Q0.3739,0.1199,0.3681,0.114 Q0.3866,0.15,0.3872,0.1903 Z M0.865,0.0677 Q0.8402,0.0446,0.8102,0.0317 T0.7525,0.0188 Q0.7253,0.0188,0.6956,0.0317 T0.6408,0.0667 T0.5995,0.122 T0.5834,0.1925 Q0.5834,0.2645,0.6399,0.3167 Q0.6647,0.3398,0.6947,0.353 T0.7525,0.3661 Q0.7796,0.3661,0.8093,0.353 T0.8641,0.3177 T0.9054,0.2624 T0.9215,0.1925 Q0.9215,0.1204,0.865,0.0677 Z M0.5718,0.1957 L0.5718,0.1925 Q0.5718,0.1161,0.6313,0.0602 Q0.6013,0.0844,0.584,0.118 T0.5661,0.1903 Z M0.573,0.2118 L0.5666,0.2059 Q0.5713,0.2645,0.614,0.3086 Q0.6122,0.3054,0.6105,0.3016 Q0.5788,0.2608,0.573,0.2118 Z M0.9325,0.2048 Q0.9279,0.2737,0.8736,0.3242 Q0.9308,0.279,0.9377,0.2097 Z M0.9331,0.1898 L0.9388,0.1952 L0.9388,0.1925 Q0.9388,0.1575,0.925,0.1263 Q0.9198,0.1199,0.914,0.114 Q0.9325,0.15,0.9331,0.1898 Z",type:0}},"\uE0D1":{type:5,data:{d:"M0.7639,0.1974 L0.9593,0.1974 L0.9593,0.1443 L0.7639,0.1443 L0.7639,0.1974 Z M0.7586,0.109 L0.9727,0.109 Q0.9839,0.109,0.992,0.1153 T1,0.1291 L1,0.382 Q1,0.3906,0.9912,0.3964 T0.9727,0.4021 L0.7586,0.4021 Q0.7468,0.4021,0.739,0.3956 T0.7313,0.382 L0.7313,0.1291 Q0.7313,0.1246,0.7339,0.1207 T0.7406,0.1143 T0.7495,0.1104 T0.7586,0.109 Z M0.7639,0.6575 L0.9593,0.6575 L0.9593,0.6044 L0.7639,0.6044 L0.7639,0.6575 Z M0.7313,0.8347 L0.7313,0.5843 Q0.7313,0.5757,0.7401,0.5699 T0.7586,0.5641 L0.9706,0.5641 Q0.9818,0.5641,0.9898,0.5705 T0.9979,0.5843 L0.9979,0.8347 Q0.9979,0.8433,0.989,0.8491 T0.9706,0.8549 L0.7586,0.8549 Q0.7468,0.8549,0.739,0.8483 T0.7313,0.8347 Z M0,1 L0,0 L0.7607,0 L0.7607,1 L0,1 Z",type:0}},"\uE0D2":{type:5,data:{d:"M0.9764,0.0029 L0.3179,0.4552 L0,0.4552 L0,0 Z M1,1 L0,1 L0,0.5448 L0.3091,0.5448 Z",type:0}},"\uE0D4":{type:5,data:{d:"M0.0236,0.0029 L0.6824,0.4552 L1,0.4552 L1,0 Z M0,1 L1,1 L1,0.5448 L0.6912,0.5448 Z",type:0}},"\uEE00":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z"},"\uEE01":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z"},"\uEE02":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z"},"\uEE03":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z M.25,.15 L1,.15 L1,.85 L.25,.85 Z"},"\uEE04":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z M0,.15 L1,.15 L1,.85 L0,.85 Z"},"\uEE05":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z M0,.15 L.75,.15 L.75,.85 L0,.85 Z"},"\uEE06":{type:5,data:{d:"M0.6574,0.303 Q0.623,0.291,0.5852,0.285 T0.5082,0.279 T0.4311,0.285 T0.359,0.303 L0.3082,0.248 Q0.3525,0.232,0.4041,0.2235 T0.5082,0.215 T0.6123,0.2235 T0.7082,0.248 Z",type:0},scaleType:1},"\uEE07":{type:5,data:{d:"M0.8557,0.582 L0.7656,0.551 Q0.7852,0.53,0.7951,0.507 T0.8049,0.46 Q0.8049,0.424,0.782,0.3905 T0.718,0.332 T0.6221,0.293 T0.5082,0.279 L0.5082,0.215 Q0.5607,0.215,0.6123,0.2235 T0.709,0.248 T0.7918,0.287 T0.8557,0.3375 T0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.582 Z",type:0},scaleType:1},"\uEE08":{type:5,data:{d:"M0.5082,0.705 Q0.482,0.705,0.4557,0.703 T0.4049,0.697 L0.4311,0.635 Q0.4508,0.638,0.4697,0.6395 T0.5082,0.641 Q0.5672,0.641,0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 Q0.8049,0.436,0.7951,0.413 T0.7656,0.369 L0.8557,0.338 Q0.882,0.365,0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"\uEE09":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 L0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 T0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 L0.9098,0.46 Q0.9098,0.492,0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"\uEE0A":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.338 L0.2508,0.369 Q0.2311,0.39,0.2213,0.413 T0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 Q0.5279,0.641,0.5467,0.6395 T0.5852,0.635 L0.6115,0.697 Q0.5869,0.701,0.5607,0.703 T0.5082,0.705 Z",type:0},scaleType:1},"\uEE0B":{type:5,data:{d:"M0.1607,0.582 Q0.1344,0.555,0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.3375 T0.2246,0.287 T0.3074,0.248 T0.4041,0.2235 T0.5082,0.215 L0.5082,0.279 Q0.4492,0.279,0.3943,0.293 T0.2984,0.332 T0.2344,0.3905 T0.2115,0.46 Q0.2115,0.484,0.2213,0.507 T0.2508,0.551 Z",type:0},scaleType:1},"\uF5D0":l.LINE_H,"\uF5D1":l.LINE_V,"\uF5D2":l.FADE_RIGHT,"\uF5D3":l.FADE_LEFT,"\uF5D4":l.FADE_DOWN,"\uF5D5":l.FADE_UP,"\uF5D6":l.CURVE_DOWN_RIGHT,"\uF5D7":l.CURVE_DOWN_LEFT,"\uF5D8":l.CURVE_UP_RIGHT,"\uF5D9":l.CURVE_UP_LEFT,"\uF5DA":[l.LINE_V,l.CURVE_UP_RIGHT],"\uF5DB":[l.LINE_V,l.CURVE_DOWN_RIGHT],"\uF5DC":[l.CURVE_DOWN_RIGHT,l.CURVE_UP_RIGHT],"\uF5DD":[l.LINE_V,l.CURVE_UP_LEFT],"\uF5DE":[l.LINE_V,l.CURVE_DOWN_LEFT],"\uF5DF":[l.CURVE_DOWN_LEFT,l.CURVE_UP_LEFT],"\uF5E0":[l.LINE_H,l.CURVE_DOWN_LEFT],"\uF5E1":[l.LINE_H,l.CURVE_DOWN_RIGHT],"\uF5E2":[l.CURVE_DOWN_LEFT,l.CURVE_DOWN_RIGHT],"\uF5E3":[l.LINE_H,l.CURVE_UP_LEFT],"\uF5E4":[l.LINE_H,l.CURVE_UP_RIGHT],"\uF5E5":[l.CURVE_UP_LEFT,l.CURVE_UP_RIGHT],"\uF5E6":[l.LINE_V,l.CURVE_UP_LEFT,l.CURVE_UP_RIGHT],"\uF5E7":[l.LINE_V,l.CURVE_DOWN_LEFT,l.CURVE_DOWN_RIGHT],"\uF5E8":[l.LINE_H,l.CURVE_DOWN_LEFT,l.CURVE_UP_LEFT],"\uF5E9":[l.LINE_H,l.CURVE_DOWN_RIGHT,l.CURVE_UP_RIGHT],"\uF5EA":[l.LINE_V,l.CURVE_DOWN_RIGHT,l.CURVE_UP_LEFT],"\uF5EB":[l.LINE_V,l.CURVE_DOWN_LEFT,l.CURVE_UP_RIGHT],"\uF5EC":[l.LINE_H,l.CURVE_DOWN_RIGHT,l.CURVE_UP_LEFT],"\uF5ED":[l.LINE_H,l.CURVE_DOWN_LEFT,l.CURVE_UP_RIGHT],"\uF5EE":[l.NODE_FILL,l.NODE_STROKE],"\uF5EF":l.NODE_STROKE,"\uF5F0":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_RIGHT],"\uF5F1":[l.NODE_STROKE,l.NODE_LINE_RIGHT],"\uF5F2":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_LEFT],"\uF5F3":[l.NODE_STROKE,l.NODE_LINE_LEFT],"\uF5F4":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF5F5":[l.NODE_STROKE,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF5F6":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN],"\uF5F7":[l.NODE_STROKE,l.NODE_LINE_DOWN],"\uF5F8":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP],"\uF5F9":[l.NODE_STROKE,l.NODE_LINE_UP],"\uF5FA":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_UP],"\uF5FB":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_UP],"\uF5FC":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF5FD":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF5FE":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF5FF":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF600":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_RIGHT],"\uF601":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_RIGHT],"\uF602":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT],"\uF603":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT],"\uF604":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF605":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF606":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF607":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF608":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF609":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60A":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60B":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60C":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60D":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\u{1FB00}":f(1),"\u{1FB01}":f(2),"\u{1FB02}":f(3),"\u{1FB03}":f(4),"\u{1FB04}":f(5),"\u{1FB05}":f(6),"\u{1FB06}":f(7),"\u{1FB07}":f(8),"\u{1FB08}":f(9),"\u{1FB09}":f(10),"\u{1FB0A}":f(11),"\u{1FB0B}":f(12),"\u{1FB0C}":f(13),"\u{1FB0D}":f(14),"\u{1FB0E}":f(15),"\u{1FB0F}":f(16),"\u{1FB10}":f(17),"\u{1FB11}":f(18),"\u{1FB12}":f(19),"\u{1FB13}":f(20),"\u{1FB14}":f(22),"\u{1FB15}":f(23),"\u{1FB16}":f(24),"\u{1FB17}":f(25),"\u{1FB18}":f(26),"\u{1FB19}":f(27),"\u{1FB1A}":f(28),"\u{1FB1B}":f(29),"\u{1FB1C}":f(30),"\u{1FB1D}":f(31),"\u{1FB1E}":f(32),"\u{1FB1F}":f(33),"\u{1FB20}":f(34),"\u{1FB21}":f(35),"\u{1FB22}":f(36),"\u{1FB23}":f(37),"\u{1FB24}":f(38),"\u{1FB25}":f(39),"\u{1FB26}":f(40),"\u{1FB27}":f(41),"\u{1FB28}":f(43),"\u{1FB29}":f(44),"\u{1FB2A}":f(45),"\u{1FB2B}":f(46),"\u{1FB2C}":f(47),"\u{1FB2D}":f(48),"\u{1FB2E}":f(49),"\u{1FB2F}":f(50),"\u{1FB30}":f(51),"\u{1FB31}":f(52),"\u{1FB32}":f(53),"\u{1FB33}":f(54),"\u{1FB34}":f(55),"\u{1FB35}":f(56),"\u{1FB36}":f(57),"\u{1FB37}":f(58),"\u{1FB38}":f(59),"\u{1FB39}":f(60),"\u{1FB3A}":f(61),"\u{1FB3B}":f(62),"\u{1FB3C}":{type:3,data:"M0,0.6667 L0,1 L0.5,1 Z"},"\u{1FB3D}":{type:3,data:"M0,0.6667 L0,1 L1,1 Z"},"\u{1FB3E}":{type:3,data:"M0,0.3333 L0,1 L0.5,1 Z"},"\u{1FB3F}":{type:3,data:"M0,0.3333 L0,1 L1,1 Z"},"\u{1FB40}":{type:3,data:"M0,0 L0,1 L0.5,1 Z"},"\u{1FB41}":{type:3,data:"M0,0.3333 L0.5,0 L1,0 L1,1 L0,1 Z"},"\u{1FB42}":{type:3,data:"M0,0.3333 L1,0 L1,1 L0,1 Z"},"\u{1FB43}":{type:3,data:"M0,0.6667 L0.5,0 L1,0 L1,1 L0,1 Z"},"\u{1FB44}":{type:3,data:"M0,0.6667 L1,0 L1,1 L0,1 Z"},"\u{1FB45}":{type:3,data:"M0,1 L0.5,0 L1,0 L1,1 Z"},"\u{1FB46}":{type:3,data:"M0,0.6667 L1,0.3333 L1,1 L0,1 Z"},"\u{1FB47}":{type:3,data:"M0.5,1 L1,0.6667 L1,1 Z"},"\u{1FB48}":{type:3,data:"M0,1 L1,0.6667 L1,1 Z"},"\u{1FB49}":{type:3,data:"M0.5,1 L1,0.3333 L1,1 Z"},"\u{1FB4A}":{type:3,data:"M0,1 L1,0.3333 L1,1 Z"},"\u{1FB4B}":{type:3,data:"M0.5,1 L1,0 L1,1 Z"},"\u{1FB4C}":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.3333 Z"},"\u{1FB4D}":{type:3,data:"M0,0 L0,1 L1,1 L1,0.3333 Z"},"\u{1FB4E}":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.6667 Z"},"\u{1FB4F}":{type:3,data:"M0,0 L0,1 L1,1 L1,0.6667 Z"},"\u{1FB50}":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 Z"},"\u{1FB51}":{type:3,data:"M0,0.3333 L0,1 L1,1 L1,0.6667 Z"},"\u{1FB52}":{type:3,data:"M0,0.6667 L0.5,1 L1,1 L1,0 L0,0 Z"},"\u{1FB53}":{type:3,data:"M0,0.6667 L1,1 L1,0 L0,0 Z"},"\u{1FB54}":{type:3,data:"M0,0.3333 L0.5,1 L1,1 L1,0 L0,0 Z"},"\u{1FB55}":{type:3,data:"M0,0.3333 L1,1 L1,0 L0,0 Z"},"\u{1FB56}":{type:3,data:"M0,0 L0.5,1 L1,1 L1,0 Z"},"\u{1FB57}":{type:3,data:"M0,0.3333 L0,0 L0.5,0 Z"},"\u{1FB58}":{type:3,data:"M0,0.3333 L0,0 L1,0 Z"},"\u{1FB59}":{type:3,data:"M0,0.6667 L0,0 L0.5,0 Z"},"\u{1FB5A}":{type:3,data:"M0,0.6667 L0,0 L1,0 Z"},"\u{1FB5B}":{type:3,data:"M0,1 L0,0 L0.5,0 Z"},"\u{1FB5C}":{type:3,data:"M0,0.6667 L0,0 L1,0 L1,0.3333 Z"},"\u{1FB5D}":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.6667 Z"},"\u{1FB5E}":{type:3,data:"M0,1 L0,0 L1,0 L1,0.6667 Z"},"\u{1FB5F}":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.3333 Z"},"\u{1FB60}":{type:3,data:"M0,1 L0,0 L1,0 L1,0.3333 Z"},"\u{1FB61}":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 Z"},"\u{1FB62}":{type:3,data:"M0.5,0 L1,0 L1,0.3333 Z"},"\u{1FB63}":{type:3,data:"M0,0 L1,0 L1,0.3333 Z"},"\u{1FB64}":{type:3,data:"M0.5,0 L1,0 L1,0.6667 Z"},"\u{1FB65}":{type:3,data:"M0,0 L1,0 L1,0.6667 Z"},"\u{1FB66}":{type:3,data:"M0.5,0 L1,0 L1,1 Z"},"\u{1FB67}":{type:3,data:"M0,0.3333 L1,0.6667 L1,0 L0,0 Z"},"\u{1FB68}":{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0.5,0.5 Z"},"\u{1FB69}":{type:3,data:"M0,0 L0.5,0.5 L1,0 L1,1 L0,1 Z"},"\u{1FB6A}":{type:3,data:"M0,0 L1,0 L0.5,0.5 L1,1 L0,1 Z"},"\u{1FB6B}":{type:3,data:"M0,0 L1,0 L1,1 L0.5,0.5 L0,1 Z"},"\u{1FB6C}":{type:3,data:"M0,0 L0.5,0.5 L0,1 Z"},"\u{1FB6D}":{type:3,data:"M0,0 L1,0 L0.5,0.5 Z"},"\u{1FB6E}":{type:3,data:"M1,0 L1,1 L0.5,0.5 Z"},"\u{1FB6F}":{type:3,data:"M0,1 L1,1 L0.5,0.5 Z"},"\u{1FB70}":{type:0,data:[{x:1,y:0,w:1,h:8}]},"\u{1FB71}":{type:0,data:[{x:2,y:0,w:1,h:8}]},"\u{1FB72}":{type:0,data:[{x:3,y:0,w:1,h:8}]},"\u{1FB73}":{type:0,data:[{x:4,y:0,w:1,h:8}]},"\u{1FB74}":{type:0,data:[{x:5,y:0,w:1,h:8}]},"\u{1FB75}":{type:0,data:[{x:6,y:0,w:1,h:8}]},"\u{1FB76}":{type:0,data:[{x:0,y:1,w:8,h:1}]},"\u{1FB77}":{type:0,data:[{x:0,y:2,w:8,h:1}]},"\u{1FB78}":{type:0,data:[{x:0,y:3,w:8,h:1}]},"\u{1FB79}":{type:0,data:[{x:0,y:4,w:8,h:1}]},"\u{1FB7A}":{type:0,data:[{x:0,y:5,w:8,h:1}]},"\u{1FB7B}":{type:0,data:[{x:0,y:6,w:8,h:1}]},"\u{1FB7C}":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"\u{1FB7D}":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"\u{1FB7E}":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"\u{1FB7F}":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"\u{1FB80}":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:7,w:8,h:1}]},"\u{1FB81}":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:2,w:8,h:1},{x:0,y:4,w:8,h:1},{x:0,y:7,w:8,h:1}]},"\u{1FB82}":{type:0,data:[{x:0,y:0,w:8,h:2}]},"\u{1FB83}":{type:0,data:[{x:0,y:0,w:8,h:3}]},"\u{1FB84}":{type:0,data:[{x:0,y:0,w:8,h:5}]},"\u{1FB85}":{type:0,data:[{x:0,y:0,w:8,h:6}]},"\u{1FB86}":{type:0,data:[{x:0,y:0,w:8,h:7}]},"\u{1FB87}":{type:0,data:[{x:6,y:0,w:2,h:8}]},"\u{1FB88}":{type:0,data:[{x:5,y:0,w:3,h:8}]},"\u{1FB89}":{type:0,data:[{x:3,y:0,w:5,h:8}]},"\u{1FB8A}":{type:0,data:[{x:2,y:0,w:6,h:8}]},"\u{1FB8B}":{type:0,data:[{x:1,y:0,w:7,h:8}]},"\u{1FB8C}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},"\u{1FB8D}":{type:1,data:[[1,0],[0,1]],clipPath:"M0.5,0 L1,0 L1,1 L0.5,1 Z"},"\u{1FB8E}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},"\u{1FB8F}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},"\u{1FB90}":{type:1,data:[[0,1],[1,0]]},"\u{1FB91}":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},{type:0,data:[{x:0,y:0,w:8,h:4}]}],"\u{1FB92}":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},{type:0,data:[{x:0,y:4,w:8,h:4}]}],"\u{1FB94}":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},{type:0,data:[{x:4,y:0,w:4,h:8}]}],"\u{1FB95}":{type:0,data:[{x:0,y:0,w:2,h:2},{x:4,y:0,w:2,h:2},{x:2,y:2,w:2,h:2},{x:6,y:2,w:2,h:2},{x:0,y:4,w:2,h:2},{x:4,y:4,w:2,h:2},{x:2,y:6,w:2,h:2},{x:6,y:6,w:2,h:2}]},"\u{1FB96}":{type:0,data:[{x:2,y:0,w:2,h:2},{x:6,y:0,w:2,h:2},{x:0,y:2,w:2,h:2},{x:4,y:2,w:2,h:2},{x:2,y:4,w:2,h:2},{x:6,y:4,w:2,h:2},{x:0,y:6,w:2,h:2},{x:4,y:6,w:2,h:2}]},"\u{1FB97}":{type:0,data:[{x:0,y:2,w:8,h:2},{x:0,y:6,w:8,h:2}]},"\u{1FB98}":{type:2,data:"M-0.25,-0.25 L1.25,1.25 M-0.25,0 L1,1.25 M-0.25,0.25 L0.75,1.25 M-0.25,0.5 L0.5,1.25 M0,-0.25 L1.25,1 M0.25,-0.25 L1.25,0.75 M0.5,-0.25 L1.25,0.5 M-0.25,0.75 L0.25,1.25 M0.75,-0.25 L1.25,0.25",strokeWidth:1},"\u{1FB99}":{type:2,data:"M-0.25,0.5 L0.5,-0.25 M-0.25,0.75 L0.75,-0.25 M-0.25,1 L1,-0.25 M-0.25,1.25 L1.25,-0.25 M0,1.25 L1.25,0 M0.25,1.25 L1.25,0.25 M0.5,1.25 L1.25,0.5 M-0.25,0.25 L0.25,-0.25 M0.75,1.25 L1.25,0.75",strokeWidth:1},"\u{1FB9A}":{type:5,data:{d:"M0,0 L.5,.5 L0,1 L1,1 L.5,.5 L1,0",type:0}},"\u{1FB9B}":{type:5,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1",type:0}},"\u{1FB9C}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L0,1 Z"},"\u{1FB9D}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,1 Z"},"\u{1FB9E}":{type:1,data:[[1,0],[0,1]],clipPath:"M1,0 L1,1 L0,1 Z"},"\u{1FB9F}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,1 L0,1 Z"},"\u{1FBA0}":{type:2,data:"M.5,0 L0,.5",strokeWidth:1},"\u{1FBA1}":{type:2,data:"M.5,0 L1,.5",strokeWidth:1},"\u{1FBA2}":{type:2,data:"M0,.5 L.5,1",strokeWidth:1},"\u{1FBA3}":{type:2,data:"M1,.5 L.5,1",strokeWidth:1},"\u{1FBA4}":{type:2,data:"M.5,0 L0,.5 L.5,1",strokeWidth:1},"\u{1FBA5}":{type:2,data:"M.5,0 L1,.5 L.5,1",strokeWidth:1},"\u{1FBA6}":{type:2,data:"M0,.5 L.5,1 L1,.5",strokeWidth:1},"\u{1FBA7}":{type:2,data:"M0,.5 L.5,0 L1,.5",strokeWidth:1},"\u{1FBA8}":{type:2,data:"M.5,0 L0,.5 M1,.5 L.5,1",strokeWidth:1},"\u{1FBA9}":{type:2,data:"M.5,0 L1,.5 M0,.5 L.5,1",strokeWidth:1},"\u{1FBAA}":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5",strokeWidth:1},"\u{1FBAB}":{type:2,data:"M.5,0 L0,.5 L.5,1 L1,.5",strokeWidth:1},"\u{1FBAC}":{type:2,data:"M0,.5 L.5,0 L1,.5 L.5,1",strokeWidth:1},"\u{1FBAD}":{type:2,data:"M1,.5 L.5,0 L0,.5 L.5,1",strokeWidth:1},"\u{1FBAE}":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5 Z",strokeWidth:1},"\u{1FBAF}":{type:2,data:"M0,.5 L1,.5 M.5,.35 L.5,.65",strokeWidth:1},"\u{1FBB0}":{type:3,data:"M0.1,0.2 L0.1,.8 L.4,.6 L.9,0.6 Z",scaleType:1},"\u{1FBB1}":{type:4,data:{d:"M.1,.525 L.35,.675 L.9,.35",type:1},scaleType:1},"\u{1FBB2}":{type:3,data:"M.29,.27 L0.13,.56 L.22,.59 L.35,0.35 L.67,.35 L.57,.57 L.71,.76 L.22,.76 L.42,1 L.53,.98 L.43,.86 L.9,.86 L.71,.6 L1,.6 L1,.52 L.83,.52 L.92,.36 L1,.36 L1,.27Z M.99,.13 A.12,.12,0,1,1,.75,.13 A.12,.12,0,1,1,.99,.13"},"\u{1FBB3}":{type:3,data:"M0,.27 L.3,.27 L.55,.12 L.63,.18 L.33,.36 L0,.36 M0,.52 L.33,.52 L.59,.89 L.73,.89 L.73,.98 L.53,.98 L.28,.6 L0,.6"},"\u{1FBB4}":{type:4,data:{d:"M.15,.55 L.5,.4 L.5,.45 L.65,.45 L.65,.35 L.85,.35 L.85,.625 L.5,.625 L.5,.7 Z",type:0},scaleType:1},"\u{1FBB5}":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.15,.5 L.5,.35 L.5,.425 L.85,.425 L.85,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"\u{1FBB6}":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.85,.5 L.5,.35 L.5,.425 L.15,.425 L.15,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"\u{1FBB7}":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.675 L.2,.5 L.35,.5 L.35,.325 L.65,.325 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"\u{1FBB8}":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.325 L.2,.5 L.35,.5 L.35,.675 L.65,.675 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"\u{1FBB9}":{type:5,data:{d:"M1,.89 L.11,.89 L.11,.37 L.36,.12 L.74,.12 L.96,.34 L1,.34 L1,.405 L.92,.405 L.69,.185 L.41,.185 L.21,.42 L.21,.825 L1,.825 Z",type:0}},"\u{1FBBA}":{type:5,data:{d:"M0,.89 L0,.825 L.78,.825 L.78,.53 L.7,.415 L0,.415 L0,.35 L.75,.35 L.88,.48 L.88,.89 Z",type:0}},"\u{1FBBB}":{type:5,data:{d:"M.31,.275 L.44,.275 L.44,.47 L.05,.47 L.05,.405 L.31,.405 Z M.56,.275 L.69,.275 L.69,.405 L.95,.405 L.95,.47 L.56,.47 Z M.05,.53 L.44,.53 L.44,.725 L.31,.725 L.31,.595 L.05,.595 Z M.56,.53 L.95,.53 L.95,.595 L.69,.595 L.69,.725 L.56,.725 Z",type:0},scaleType:1},"\u{1FBBC}":[{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0,.935 L.885,.935 L.885,.065 L0,.065 Z"},{type:3,data:"M.67,.5 A.17,.085,0,1,1,.33,.5 A.17,.085,0,1,1,.67,.5",scaleType:1}],"\u{1FBBD}":{type:4,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1 Z",type:1}},"\u{1FBBE}":{type:4,data:{d:"M1,.5 L.5,1",type:1}},"\u{1FBBF}":{type:4,data:{d:"M.5,0 L1,.5 L.5,1 L0,.5 Z",type:1}},"\u{1FBC0}":{type:3,data:"M.16,.445 A.02,.01,0,0,1,.39,.33 L.5,.375 L.61,.33 A.02,.01,0,0,1,.84,.445 L.75,.5 L.84,.555 A.02,.01,0,0,1,.61,.67 L.5,.625 L.39,.67 A.02,.01,0,0,1,.16,.555 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",scaleType:1},"\u{1FBC1}":{type:3,data:"M0.142308,0.924 Q0.130770,0.924,0.120193,0.922 T0.101924,0.916 T0.089424,0.9065 T0.084616,0.895 V0.025 Q0.084616,0.019,0.089424,0.0135 T0.101924,0.004 T0.120193,-0.002 T0.142308,-0.004 Q0.150000,-0.004,0.157693,-0.003 T0.173078,0.000 L0.430770,0.085 Q0.451924,0.059,0.494232,0.041 T0.587501,0.013 T0.692309,-0.0005 T0.800001,-0.004 H1 V0.055 H0.800001 Q0.771155,0.055,0.742309,0.056 T0.685578,0.060 T0.630770,0.0685 T0.580770,0.0825 T0.543270,0.1045 T0.528847,0.133 V0.647 H0.530770 Q0.596155,0.645,0.659616,0.638 T0.782693,0.6165 T0.893270,0.5805 T1,0.531 V0.623 Q0.934616,0.644,0.880770,0.6595 T0.769232,0.685 T0.650963,0.700 T0.528847,0.707 V0.787 Q0.528847,0.802,0.543270,0.8155 T0.580770,0.8375 T0.630770,0.8515 T0.685578,0.860 T0.742309,0.864 T0.800001,0.865 H1 V0.924 H0.800001 Q0.746155,0.924,0.692309,0.9205 T0.587501,0.907 T0.494232,0.879 T0.430770,0.835 L0.173078,0.920 Q0.165386,0.922,0.157693,0.923 T0.142308,0.924 Z M0.2,0.841 L0.415385,0.770 V0.150 L0.2,0.079 V0.841 Z M1,0.698 Q0.973077,0.694,0.969231,0.6885 T0.965385,0.677 Q0.965385,0.672,0.969231,0.6665 T1,0.657 V0.698 Z"},"\u{1FBC2}":{type:3,data:"M0,0.623 V0.531 Q0.044231,0.512,0.0625,0.4905 T0.092308,0.4465 T0.108654,0.4005 T0.113462,0.354 V0.351 Q0.113462,0.345,0.117308,0.3395 T0.129808,0.3305 T0.148846,0.3245 T0.171154,0.323 H0.501923 Q0.532692,0.323,0.563462,0.3185 T0.617308,0.303 T0.651923,0.2765 T0.663462,0.2435 V0.241 Q0.663462,0.219,0.657692,0.197 T0.639423,0.1545 T0.604808,0.115 T0.549615,0.082 T0.475577,0.0615 T0.392308,0.055 H0 V-0.004 H1 V0.055 H0.667308 Q0.694231,0.071,0.713462,0.09 T0.746154,0.129 T0.766346,0.1705 T0.775,0.213 H1 V0.316 Q0.971154,0.305,0.955769,0.2965 T0.920192,0.2825 T0.876923,0.2745 T0.830769,0.272 H0.773077 Q0.767308,0.297,0.743269,0.319 T0.680769,0.355 T0.595192,0.375 T0.501923,0.381 H0.227308 Q0.223462,0.415,0.211,0.4485 T0.172692,0.5135 T0.108269,0.573 T0,0.623 Z M0.611538,0.924 H0 V0.865 H0.611538 Q0.642308,0.865,0.673077,0.8605 T0.727885,0.845 T0.762308,0.8185 T0.773077,0.787 V0.785 Q0.773077,0.769,0.762308,0.7535 T0.727885,0.727 T0.673077,0.7115 T0.611538,0.707 H0.059615 Q0.048077,0.707,0.037115,0.7045 T0,0.694 V0.653 Q0.026923,0.648,0.037115,0.646 T0.059615,0.644 H0.722692 Q0.753462,0.644,0.784231,0.6395 T0.839038,0.624 T0.873846,0.5975 T0.884615,0.566 V0.564 Q0.884615,0.548,0.873846,0.532 T0.839038,0.5055 T0.784231,0.49 T0.722692,0.4855 H0.392308 Q0.380769,0.4855,0.370192,0.483 T0.351923,0.4765 T0.339423,0.467 T0.334615,0.4555 T0.339423,0.444 T0.351923,0.4345 T0.370192,0.428 T0.392308,0.4255 H0.832692 Q0.855769,0.4255,0.878846,0.4235 T0.922115,0.416 T0.957692,0.4015 T1,0.3815 V0.4685 Q0.975,0.4705,0.966346,0.4725 T0.95,0.4765 Q0.961538,0.4835,0.969231,0.4915 T1,0.5075 V0.6205 Q0.965385,0.6455,0.926923,0.665 T0.84,0.6935 Q0.866923,0.7115,0.877596,0.7345 T0.894231,0.7855 V0.787 Q0.894231,0.815,0.876923,0.8425 T0.820192,0.8895 T0.726923,0.916 T0.611538,0.924 Z"},"\u{1FBC3}":{type:3,data:"M0,0.473 V0.386 Q0.025490,0.378,0.028431,0.3695 T0.031373,0.352 V0.35 Q0.031373,0.342,0.028431,0.333 T0,0.316 V0.213 H0.652941 Q0.684314,0.213,0.715686,0.2085 T0.770588,0.193 T0.804902,0.1665 T0.815686,0.135 V0.133 Q0.815686,0.117,0.804902,0.101 T0.770588,0.0745 T0.715686,0.0595 T0.652941,0.055 H0 V-0.004 H0.652941 Q0.707843,-0.004,0.761765,0.004 T0.856863,0.031 T0.915686,0.0775 T0.933333,0.133 V0.135 Q0.933333,0.163,0.915686,0.1905 T0.856863,0.237 T0.761765,0.264 T0.652941,0.272 H0.109804 Q0.131373,0.29,0.140196,0.31 T0.149020,0.35 V0.352 Q0.149020,0.37,0.142157,0.388 T0.118627,0.4225 T0.076471,0.452 T0,0.473 Z M0,0.625 V0.513 Q0.029412,0.526,0.032353,0.54 T0.035294,0.568 V0.57 Q0.035294,0.584,0.032353,0.598 T0,0.625 Z"},"\u{1FBC4}":{type:3,data:"M0.019231,1.085 V-0.165 H0.980769 V1.085 H0.019231 Z M0.446154,0.527 H0.553846 Q0.553846,0.511,0.5625,0.495 T0.591346,0.466 T0.631731,0.4405 T0.666346,0.4135 T0.688462,0.3825 T0.696154,0.35 Q0.696154,0.33,0.682692,0.311 T0.641346,0.2785 T0.575,0.259 T0.498077,0.253 T0.421154,0.259 T0.356731,0.279 T0.315385,0.3125 T0.301923,0.352 V0.357 H0.409615 V0.354 Q0.409615,0.345,0.414423,0.335 T0.431731,0.318 T0.4625,0.3075 T0.498077,0.304 Q0.517308,0.304,0.534615,0.307 T0.564423,0.3165 T0.582692,0.332 T0.588462,0.35 Q0.588462,0.366,0.572115,0.3805 T0.535577,0.4075 T0.496154,0.4335 T0.465385,0.4625 T0.45,0.4945 T0.446154,0.527 Z M0.5,0.667 Q0.519231,0.667,0.5375,0.664 T0.569231,0.654 T0.588462,0.637 T0.594231,0.617 T0.588462,0.5975 T0.569231,0.581 T0.5375,0.571 T0.5,0.568 T0.4625,0.571 T0.430769,0.581 T0.411538,0.5975 T0.405769,0.617 T0.411538,0.637 T0.430769,0.654 T0.4625,0.664 T0.5,0.667 Z",scaleType:1},"\u{1FBC5}":{type:5,data:{d:"M.44,.425 L.44,.51 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.51 L.56,.425 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC6}":{type:5,data:{d:"M.44,.425 L.44,.46 L.23,.385 L.19,.43 L.44,.51 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.61,.735 L.7,.71 L.56,.56 L.56,.51 L.81,.43 L.77,.385 L.56,.46 L.56,.425 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC7}":{type:5,data:{d:"M.44,.425 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.425 Z M.18,.53 L.23,.575 L.81,.43 L.77,.385 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC8}":{type:5,data:{d:"M.44,.425 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.62,.735 L.71,.71 L.56,.56 L.56,.425 Z M.23,.385 L.18,.43 L.77,.575 L.81,.53 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC9}":{type:5,data:{d:"M.44,.425 L.45,.495 L.15,.645 L.34,.645 L.34,.7 L.44,.7 L.44,.645 L.56,.645 L.56,.7 L.66,.7 L.66,.645 L.84,.645 L.54,.495 L.56,.425 Z M.39,.6 L.5,.55 L.60,.6 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBCA}":{type:5,data:{d:"M.26,.375 L.5,.255 L.74,.375 L.74,.665 L.5,.55 L.26,.665 Z M.37,.395 L.37,.54 L.5,.475 L.63,.54 L.63,.395 L.5,.33 Z",type:0},scaleType:1},"\u{1FBCB}":{type:5,data:{d:"M.09,.41 L.32,.295 L.5,.375 L.68,.295 L.91,.41 L.75,.5 L.91,.59 L.68,.705 L.5,.625 L.32,.705 L.09,.59 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",type:0},scaleType:1},"\u{1FBCC}":{type:5,data:{d:"M.55,.305 L.88,.305 L.88,.355 L.65,.355 L.65,.47 L.88,.47 L.88,.52 L.55,.52 Z",type:0},scaleType:1},"\u{1FBCD}":{type:5,data:{d:"M.38,.39 L.5,.33 L.62,.39 L.62,.53 L.5,.47 L.38,.53 Z",type:0},scaleType:1},"\u{1FBCE}":{type:3,data:"M0,0 L0.6667,0 L0.6667,1 L0,1 Z"},"\u{1FBCF}":{type:3,data:"M0,0 L0.3333,0 L0.3333,1 L0,1 Z"},"\u{1FBD0}":{type:2,data:"M1,.5 L0,1",strokeWidth:1},"\u{1FBD1}":{type:2,data:"M1,0 L0,.5",strokeWidth:1},"\u{1FBD2}":{type:2,data:"M0,0 L1,.5",strokeWidth:1},"\u{1FBD3}":{type:2,data:"M0,.5 L1,1",strokeWidth:1},"\u{1FBD4}":{type:2,data:"M0,0 L.5,1",strokeWidth:1},"\u{1FBD5}":{type:2,data:"M.5,0 L1,1",strokeWidth:1},"\u{1FBD6}":{type:2,data:"M1,0 L.5,1",strokeWidth:1},"\u{1FBD7}":{type:2,data:"M.5,0 L0,1",strokeWidth:1},"\u{1FBD8}":{type:2,data:"M0,0 L.5,.5 L1,0",strokeWidth:1},"\u{1FBD9}":{type:2,data:"M1,0 L.5,.5 L1,1",strokeWidth:1},"\u{1FBDA}":{type:2,data:"M0,1 L.5,.5 L1,1",strokeWidth:1},"\u{1FBDB}":{type:2,data:"M0,0 L.5,.5 L0,1",strokeWidth:1},"\u{1FBDC}":{type:2,data:"M0,0 L.5,1 L1,0",strokeWidth:1},"\u{1FBDD}":{type:2,data:"M1,0 L0,.5 L1,1",strokeWidth:1},"\u{1FBDE}":{type:2,data:"M0,1 L.5,0 L1,1",strokeWidth:1},"\u{1FBDF}":{type:2,data:"M0,0 L1,.5 L0,1",strokeWidth:1},"\u{1FBE0}":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0",type:1}},"\u{1FBE1}":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1",type:1}},"\u{1FBE2}":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1",type:1}},"\u{1FBE3}":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1",type:1}},"\u{1FBE4}":{type:0,data:[{x:2,y:0,w:4,h:4}]},"\u{1FBE5}":{type:0,data:[{x:2,y:4,w:4,h:4}]},"\u{1FBE6}":{type:0,data:[{x:0,y:2,w:4,h:4}]},"\u{1FBE7}":{type:0,data:[{x:4,y:2,w:4,h:4}]},"\u{1FBE8}":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0 Z",type:0}},"\u{1FBE9}":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1 Z",type:0}},"\u{1FBEA}":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1 Z",type:0}},"\u{1FBEB}":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1 Z",type:0}},"\u{1FBEC}":{type:5,data:{d:"M1,0 L.5,0 C.5,.276,.724,.5,1,.5 Z",type:0}},"\u{1FBED}":{type:5,data:{d:"M0,1 L.5,1 C.5,.724,.276,.5,0,.5 Z",type:0}},"\u{1FBEE}":{type:5,data:{d:"M1,1 L1,.5 C.724,.5,.5,.724,.5,1 Z",type:0}},"\u{1FBEF}":{type:5,data:{d:"M0,0 L0,.5 C.276,.5,.5,.276,.5,0 Z",type:0}},"\u{1FBF0}":{type:5,data:{d:o0(126),type:0},scaleType:1},"\u{1FBF1}":{type:5,data:{d:o0(48),type:0},scaleType:1},"\u{1FBF2}":{type:5,data:{d:o0(109),type:0},scaleType:1},"\u{1FBF3}":{type:5,data:{d:o0(121),type:0},scaleType:1},"\u{1FBF4}":{type:5,data:{d:o0(51),type:0},scaleType:1},"\u{1FBF5}":{type:5,data:{d:o0(91),type:0},scaleType:1},"\u{1FBF6}":{type:5,data:{d:o0(95),type:0},scaleType:1},"\u{1FBF7}":{type:5,data:{d:o0(114),type:0},scaleType:1},"\u{1FBF8}":{type:5,data:{d:o0(127),type:0},scaleType:1},"\u{1FBF9}":{type:5,data:{d:o0(123),type:0},scaleType:1},"\u{1FBFA}":{type:5,data:{d:"M.5,.175 C.2,.175,.15,.305,.15,.435 L.05,.63 L.35,.63 C.35,.682,.42,.76,.5,.76 C.58,.76,.65,.682,.65,.63 L.95,.63 L.85,.435 C.85,.305,.8,.175,.5,.175 Z",type:0},scaleType:1},...Object.fromEntries(Array.from({length:256},(i,e)=>[String.fromCodePoint(10240+e),{type:6,data:e}]))},$e=new Set([9617,9618,9619,129932,129933,129934,129935,129936,129937,129938,129940,129948,129949,129950,129951]);function f(i){return{type:2,data:()=>{let e=[],r=[.375,.25,.375],s=[0,3/8,5/8];for(let a=0;a<3;a++){let o=i>>a*2&1,n=i>>a*2+1&1;o&&n?e.push(`M0,${s[a]} L1,${s[a]} L1,${s[a]+r[a]} L0,${s[a]+r[a]} Z`):o?e.push(`M0,${s[a]} L${.5},${s[a]} L${.5},${s[a]+r[a]} L0,${s[a]+r[a]} Z`):n&&e.push(`M${.5},${s[a]} L1,${s[a]} L1,${s[a]+r[a]} L${.5},${s[a]+r[a]} Z`)}return e.join(" ")}}}function o0(i){let e=[];if(i&64){let Q=.21500000000000002,m=.95-.15-.015;e.push(`M${Q},${.2125} L${Q+.075},${.175} L${m-.075},${.175} L${m},${.2125} L${m-.075},${.25} L${Q+.075},${.25} Z`)}if(i&32){let c=.7999999999999999,u=.95-.15/2,C=.95,Q=.175+.075+.015,m=.5-.015;e.push(`M${u},${Q} L${C},${Q+.0375} L${C},${m-.0375} L${u},${m} L${c},${m-.0375} L${c},${Q+.0375} Z`)}if(i&16){let c=.7999999999999999,u=.95-.15/2,C=.95,Q=.5+.015,m=.825-.075-.015;e.push(`M${u},${Q} L${C},${Q+.0375} L${C},${m-.0375} L${u},${m} L${c},${m-.0375} L${c},${Q+.0375} Z`)}if(i&8){let Q=.21500000000000002,m=.95-.15-.015;e.push(`M${Q},${.7875} L${Q+.075},${.75} L${m-.075},${.75} L${m},${.7875} L${m-.075},${.825} L${Q+.075},${.825} Z`)}if(i&4&&e.push(`M${.125},${.515} L${.2},${.515+.0375} L${.2},${.735-.0375} L${.125},${.735} L${.05},${.735-.0375} L${.05},${.515+.0375} Z`),i&2&&e.push(`M${.125},${.265} L${.2},${.265+.0375} L${.2},${.485-.0375} L${.125},${.485} L${.05},${.485-.0375} L${.05},${.265+.0375} Z`),i&1){let Q=.21500000000000002,m=.95-.15-.015;e.push(`M${Q},${.5} L${Q+.075},${.4625} L${m-.075},${.4625} L${m},${.5} L${m-.075},${.5375} L${Q+.075},${.5375} Z`)}return e.join(" ")}var k=0,H=0,T0=!1,_0=!1,$0=!1,z,x0=0,G0=class{constructor(e,t,r,s,a,o){this._terminal=e;this._optionService=t;this._selectionRenderModel=r;this._decorationService=s;this._coreBrowserService=a;this._themeService=o;this.result={fg:0,bg:0,ext:0}}resolve(e,t,r,s,a){this.result.bg=e.bg,this.result.fg=e.fg,this.result.ext=e.bg&268435456?e.extended.ext:0,H=0,k=0,_0=!1,T0=!1,$0=!1,z=this._themeService.colors,x0=0;let o=e.getCode();if(o!==0&&e.extended.underlineStyle===4){let n=Math.max(1,Math.floor(this._optionService.rawOptions.fontSize*this._coreBrowserService.dpr/15));x0=t*s%(Math.round(n)*2)}if(x0===0&&$e.has(o)&&(x0=t*s%2*2+r*a%2),this._decorationService.forEachDecorationAtCell(t,r,"bottom",n=>{n.backgroundColorRGB&&(H=n.backgroundColorRGB.rgba>>8&16777215,_0=!0),n.foregroundColorRGB&&(k=n.foregroundColorRGB.rgba>>8&16777215,T0=!0)}),$0=this._selectionRenderModel.isCellSelected(this._terminal,t,r),$0){if(this.result.fg&67108864||(this.result.bg&50331648)!==0){if(this.result.fg&67108864)switch(this.result.fg&50331648){case 16777216:case 33554432:H=this._themeService.colors.ansi[this.result.fg&255].rgba;break;case 50331648:H=(this.result.fg&16777215)<<8|255;break;case 0:default:H=this._themeService.colors.foreground.rgba}else switch(this.result.bg&50331648){case 16777216:case 33554432:H=this._themeService.colors.ansi[this.result.bg&255].rgba;break;case 50331648:H=(this.result.bg&16777215)<<8|255;break}H=d0.blend(H,(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba&4294967040|128)>>8&16777215}else H=(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba>>8&16777215;if(_0=!0,z.selectionForeground&&(k=z.selectionForeground.rgba>>8&16777215,T0=!0),V0(e.getCode())){if(this.result.fg&67108864&&(this.result.bg&50331648)===0)k=(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba>>8&16777215;else{if(this.result.fg&67108864)switch(this.result.bg&50331648){case 16777216:case 33554432:k=this._themeService.colors.ansi[this.result.bg&255].rgba;break;case 50331648:k=(this.result.bg&16777215)<<8|255;break}else switch(this.result.fg&50331648){case 16777216:case 33554432:k=this._themeService.colors.ansi[this.result.fg&255].rgba;break;case 50331648:k=(this.result.fg&16777215)<<8|255;break;case 0:default:k=this._themeService.colors.foreground.rgba}k=d0.blend(k,(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba&4294967040|128)>>8&16777215}T0=!0}}this._decorationService.forEachDecorationAtCell(t,r,"top",n=>{n.backgroundColorRGB&&(H=n.backgroundColorRGB.rgba>>8&16777215,_0=!0),n.foregroundColorRGB&&(k=n.foregroundColorRGB.rgba>>8&16777215,T0=!0)}),_0&&($0?H=e.bg&-16777216&-134217729|H|50331648:H=e.bg&-16777216|H|50331648),T0&&(k=e.fg&-16777216&-67108865|k|50331648),this.result.fg&67108864&&(_0&&!T0&&((this.result.bg&50331648)===0?k=this.result.fg&-134217728|z.background.rgba>>8&16777215&16777215|50331648:k=this.result.fg&-134217728|this.result.bg&67108863,T0=!0),!_0&&T0&&((this.result.fg&50331648)===0?H=this.result.bg&-67108864|z.foreground.rgba>>8&16777215&16777215|50331648:H=this.result.bg&-67108864|this.result.fg&67108863,_0=!0)),z=void 0,this.result.bg=_0?H:this.result.bg,this.result.fg=T0?k:this.result.fg,this.result.ext&=536870911,this.result.ext|=x0<<29&3758096384}};var Ke=.5,K0=Be||we?"bottom":"ideographic";function qe(i,e,t,r,s,a,o,n,L,T,h,d,_=0){let p=Ve[e];if(p){let c=Array.isArray(p)?p:[p];for(let u of c)Pt(i,u,t,r,s,a,o,n,L,T,h,d,_);return!0}return!1}function Pt(i,e,t,r,s,a,o,n,L,T,h,d,_=0){let p=s,c=a,u=t,C=r;switch(e.scaleType===1&&(p=o,c=n,u=t+(s-o)/2,C=r+(a-n)/2),e.clipPath&&(i.save(),Vt(i,e.clipPath,u,C,p,c)),e.type){case 0:Bt(i,e.data,u,C,p,c);break;case 1:Ut(i,e.data,u,C,p,c,_);break;case 2:Wt(i,e.data,u,C,p,c,T,h,e.strokeWidth);break;case 3:Ht(i,e.data,u,C,p,c,T,e.strokeWidth);break;case 4:Zt(i,e.data,u,C,p,c,T,d);break;case 5:$t(i,e.data,u,C,p,c,L,T,h);break;case 6:wt(i,e.data,u,C,p,c);break}e.clipPath&&i.restore()}function Bt(i,e,t,r,s,a){for(let o=0;o{let F=parseFloat(m);return R%2===0?t+F*s:r+F*a});if(u==="M")i.moveTo(Q[0],Q[1]),T=Q[0],h=Q[1],d=T,_=h;else if(u==="L")i.lineTo(Q[0],Q[1]),T=Q[0],h=Q[1],d=T,_=h;else if(u==="Q")i.quadraticCurveTo(Q[0],Q[1],Q[2],Q[3]),d=Q[0],_=Q[1],T=Q[2],h=Q[3];else if(u==="T"){let m,R;p==="Q"||p==="T"?(m=2*T-d,R=2*h-_):(m=T,R=h),i.quadraticCurveTo(m,R,Q[0],Q[1]),d=m,_=R,T=Q[0],h=Q[1]}else u==="C"&&(i.bezierCurveTo(Q[0],Q[1],Q[2],Q[3],Q[4],Q[5]),d=Q[2],_=Q[3],T=Q[4],h=Q[5]);p=u}n!==void 0?(i.strokeStyle=i.fillStyle,i.lineWidth=o*n,i.stroke()):i.fill()}function kt(i,e,t,r,s,a,o,n,L,T){if(r===0||s===0){i.lineTo(L,T);return}r=Math.abs(r),s=Math.abs(s);let h=Math.cos(a),d=Math.sin(a),_=(e-L)/2,p=(t-T)/2,c=h*_+d*p,u=-d*_+h*p,C=r*r,Q=s*s,m=c*c,R=u*u,F=m/C+R/Q;if(F>1){let I=Math.sqrt(F);r*=I,s*=I,C=r*r,Q=s*s}let E=(C*Q-C*R-Q*m)/(C*R+Q*m);E<0&&(E=0);let y=(o===n?-1:1)*Math.sqrt(E),Y=y*(r*u/s),X=y*-(s*c/r),A0=h*Y-d*X+(e+L)/2,t0=d*Y+h*X+(t+T)/2,L0=(c-Y)/r,A=(u-X)/s,n0=(-c-Y)/r,a0=(-u-X)/s,$=Math.atan2(A,L0),q=Math.atan2(a0,n0)-$;n===0&&q>0?q-=2*Math.PI:n===1&&q<0&&(q+=2*Math.PI);let g0=$+q;i.ellipse(A0,t0,r,s,a,$,g0,n===0)}function Zt(i,e,t,r,s,a,o,n){i.save(),i.fillRect(t,r,s,a),n&&(i.fillStyle=n,i.strokeStyle=n),i.lineWidth=o,i.lineCap="square",i.beginPath();for(let L of e.d.split(" ")){let T=L[0],h=L.substring(1).split(",");if(!h[0]||!h[1]){T==="Z"&&i.closePath();continue}let d=h.map((_,p)=>{let c=parseFloat(_);return p%2===0?t+c*s:r+c*a});T==="M"?i.moveTo(d[0],d[1]):T==="L"&&i.lineTo(d[0],d[1])}e.type===1?i.stroke():i.fill(),i.restore()}var Xe=new Map;function Ut(i,e,t,r,s,a,o=0){let n=Xe.get(e);n||(n=new Map,Xe.set(e,n));let L=i.fillStyle;if(typeof L!="string")throw new Error(`Unexpected fillStyle type "${L}"`);let T=n.get(L);if(!T){let _=e[0].length,p=e.length,c=i.canvas.ownerDocument.createElement("canvas");c.width=_,c.height=p;let u=g(c.getContext("2d")),C=new ImageData(_,p),Q,m,R,F;if(L.startsWith("#"))Q=parseInt(L.slice(1,3),16),m=parseInt(L.slice(3,5),16),R=parseInt(L.slice(5,7),16),F=L.length>7&&parseInt(L.slice(7,9),16)||1;else if(L.startsWith("rgba"))[Q,m,R,F]=L.substring(5,L.length-1).split(",").map(E=>parseFloat(E));else throw new Error(`Unexpected fillStyle color format "${L}" when drawing pattern glyph`);for(let E=0;E>1&1,d=o&1;h!==0||d!==0?T.setTransform(new DOMMatrix().translateSelf(-h,-d)):T.setTransform(new DOMMatrix),i.fillStyle=T,i.fillRect(t,r,s,a)}function Wt(i,e,t,r,s,a,o,n,L){i.save(),i.beginPath(),i.rect(t,r,s,a),i.clip(),i.beginPath();let T;if(typeof e=="function"){let _=.15/a*s;T=e(.15,_)}else T=e;let h={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(let d of T.split(" ")){let _=d[0];if(_==="Z"){i.closePath(),h.lastCommand=_;continue}let p=je[_];if(!p){n.error(`Could not find drawing instructions for "${_}"`);continue}let c=d.substring(1).split(",");!c[0]||!c[1]||(p(i,Je(c,s,a,t,r,!0,o,0,0,!1),h),h.lastCommand=_)}L!==void 0?(i.strokeStyle=i.fillStyle,i.lineWidth=o*L,i.stroke()):i.fill(),i.closePath(),i.restore()}function Vt(i,e,t,r,s,a){i.beginPath();for(let o of e.split(" ")){let n=o[0];if(n==="Z"){i.closePath();continue}let L=o.substring(1).split(",");if(!L[0]||!L[1])continue;let T=t+parseFloat(L[0])*s,h=r+parseFloat(L[1])*a;n==="M"?i.moveTo(T,h):n==="L"&&i.lineTo(T,h)}i.clip()}function $t(i,e,t,r,s,a,o,n,L){let T=new Path2D;T.rect(t,r,s,a),i.clip(T),i.beginPath();let h=o/12;i.lineWidth=n*h;let d={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(let _ of e.d.split(" ")){let p=_[0];if(p==="Z"){i.closePath(),d.lastCommand=p;continue}let c=je[p];if(!c){L.error(`Could not find drawing instructions for "${p}"`);continue}let u=_.substring(1).split(",");!u[0]||!u[1]||(c(i,Je(u,s,a,t,r,!1,n,(e.leftPadding??0)*(h/2),(e.rightPadding??0)*(h/2)),d),d.lastCommand=p)}e.type===1?(i.strokeStyle=i.fillStyle,i.stroke()):i.fill(),i.closePath()}function Ye(i,e,t=0){return Math.max(Math.min(i,e),t)}var je={C:(i,e,t)=>{i.bezierCurveTo(e[0],e[1],e[2],e[3],e[4],e[5]),t.lastControlX=e[2],t.lastControlY=e[3],t.currentX=e[4],t.currentY=e[5]},L:(i,e,t)=>{i.lineTo(e[0],e[1]),t.lastControlX=t.currentX=e[0],t.lastControlY=t.currentY=e[1]},M:(i,e,t)=>{i.moveTo(e[0],e[1]),t.lastControlX=t.currentX=e[0],t.lastControlY=t.currentY=e[1]},Q:(i,e,t)=>{i.quadraticCurveTo(e[0],e[1],e[2],e[3]),t.lastControlX=e[0],t.lastControlY=e[1],t.currentX=e[2],t.currentY=e[3]},T:(i,e,t)=>{let r,s;t.lastCommand==="Q"||t.lastCommand==="T"?(r=2*t.currentX-t.lastControlX,s=2*t.currentY-t.lastControlY):(r=t.currentX,s=t.currentY),i.quadraticCurveTo(r,s,e[0],e[1]),t.lastControlX=r,t.lastControlY=s,t.currentX=e[0],t.currentY=e[1]}};function Je(i,e,t,r,s,a,o,n=0,L=0,T=!0){let h=i.map(d=>parseFloat(d)||parseInt(d));if(h.length<2)throw new Error("Too few arguments for instruction");for(let d=0;da){s-t<-20&&this._logService.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=a}this.clear()}},Ce=class extends X0{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Qe=class extends X0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},et="requestIdleCallback"in globalThis?Qe:Ce;var s0=class i{constructor(){this.fg=0;this.bg=0;this.extended=new P0}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let e=new i;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},P0=class i{constructor(e=0,t=0){this._ext=0;this._urlId=0;this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new i(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}};var U=class{constructor(){this._listeners=[];this._disposed=!1}get event(){return this._event?this._event:(this._event=(e,t,r)=>{if(this._disposed)return M(()=>{});let s={fn:e,thisArgs:t};this._listeners.push(s);let a=M(()=>{let o=this._listeners.indexOf(s);o!==-1&&this._listeners.splice(o,1)});return r&&(Array.isArray(r)?r.push(a):r.add(a)),a},this._event)}fire(e){if(!this._disposed)switch(this._listeners.length){case 0:return;case 1:{let{fn:t,thisArgs:r}=this._listeners[0];t.call(r,e);return}default:{let t=this._listeners.slice();for(let{fn:r,thisArgs:s}of t)r.call(s,e)}}}dispose(){this._disposed||(this._disposed=!0,this._listeners.length=0)}},c0;(s=>{function i(a,o){return a(n=>o.fire(n))}s.forward=i;function e(a,o){return(n,L,T)=>a(h=>n.call(L,o(h)),void 0,T)}s.map=e;function t(...a){return(o,n,L)=>{let T=new R0;for(let h of a)T.add(h(d=>o.call(n,d)));return L&&(Array.isArray(L)?L.push(T):L.add(T)),T}}s.any=t;function r(a,o,n){return o(n),a(L=>o(L))}s.runAndSubscribe=r})(c0||={});var tt={texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},offset:{x:0,y:0},size:{x:0,y:0},sizeClipSpace:{x:0,y:0}},B0=2;var w0,J=class i{constructor(e,t,r,s){this._document=e;this._config=t;this._unicodeService=r;this._logService=s;this._didWarmUp=!1;this._cacheMap=new D0;this._cacheMapCombined=new D0;this._pages=[];this._activePages=[];this._workBoundingBox={top:0,left:0,bottom:0,right:0};this._workAttributeData=new s0;this._textureSize=512;this._onAddTextureAtlasCanvas=new U;this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event;this._onRemoveTextureAtlasCanvas=new U;this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event;this._requestClearModel=!1;this._createNewPage(),this._tmpCanvas=it(e,this._config.deviceCellWidth*4+B0*2,this._config.deviceCellHeight+B0*2),this._tmpCtx=g(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:!0}))}get pages(){return this._pages}dispose(){this._tmpCanvas.remove();for(let e of this.pages)e.canvas.remove();this._onAddTextureAtlasCanvas.dispose(),this._onRemoveTextureAtlasCanvas.dispose()}warmUp(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)}_doWarmUp(){let e=new et(this._logService);for(let t=33;t<126;t++)e.enqueue(()=>{if(!this._cacheMap.get(t,0,0,0)){let r=this._drawToCache(t,0,0,0,!1,void 0);this._cacheMap.set(t,0,0,0,r)}})}beginFrame(){let e=this._requestClearModel;return this._requestClearModel=!1,e}clearTexture(){if(!(this._pages[0].currentRow.x===0&&this._pages[0].currentRow.y===0)){for(let e of this._pages)e.clear();this._cacheMap.clear(),this._cacheMapCombined.clear(),this._didWarmUp=!1}}_createNewPage(){if(i.maxAtlasPages&&this._pages.length>=Math.max(4,i.maxAtlasPages)){let t=this._pages.filter(T=>T.canvas.width*2<=(i.maxTextureSize||4096)).sort((T,h)=>h.canvas.width!==T.canvas.width?h.canvas.width-T.canvas.width:h.percentageUsed-T.percentageUsed),r=-1,s=0;for(let T=0;TT.canvas.width!==a[0].canvas.width)){let T=new u0(this._document,this._textureSize);return this._pages.push(T),this._activePages.push(T),this._onAddTextureAtlasCanvas.fire(T.canvas),T}let o=a.map(T=>T.glyphs[0].texturePage).sort((T,h)=>T-h),n=this.pages.length-a.length,L=this._mergePages(a,n);L.version=++u0.nextVersion;for(let T=o.length-1;T>=0;T--)this._deletePage(o[T]);this.pages.push(L),this._requestClearModel=!0,this._onAddTextureAtlasCanvas.fire(L.canvas)}let e=new u0(this._document,this._textureSize);return this._pages.push(e),this._activePages.push(e),this._onAddTextureAtlasCanvas.fire(e.canvas),e}_mergePages(e,t){let r=e[0].canvas.width*2,s=new u0(this._document,r,e);for(let[a,o]of e.entries()){let n=a*o.canvas.width%r,L=Math.floor(a/2)*o.canvas.height;s.ctx.drawImage(o.canvas,n,L);for(let h of o.glyphs)h.texturePage=t,h.sizeClipSpace.x=h.size.x/r,h.sizeClipSpace.y=h.size.y/r,h.texturePosition.x+=n,h.texturePosition.y+=L,h.texturePositionClipSpace.x=h.texturePosition.x/r,h.texturePositionClipSpace.y=h.texturePosition.y/r;this._onRemoveTextureAtlasCanvas.fire(o.canvas);let T=this._activePages.indexOf(o);T!==-1&&this._activePages.splice(T,1)}return s}_deletePage(e){this._pages.splice(e,1);for(let t=e;t=this._config.colors.ansi.length)throw new Error("No color found for idx "+e);return this._config.colors.ansi[e]}_getBackgroundColor(e,t,r,s){if(this._config.allowTransparency)return K;let a;switch(e){case 16777216:case 33554432:a=this._getColorFromAnsiIndex(t);break;case 50331648:let o=s0.toColorRGB(t);a=Z.toColor(o[0],o[1],o[2]);break;case 0:default:r?a=I0.opaque(this._config.colors.foreground):a=this._config.colors.background;break}return this._config.allowTransparency||(a=I0.opaque(a)),a}_getForegroundColor(e,t,r,s,a,o,n,L,T,h){let d=this._getMinimumContrastColor(e,t,r,s,a,o,n,T,L,h);if(d)return d;let _;switch(a){case 16777216:case 33554432:this._config.drawBoldTextInBrightColors&&T&&o<8&&(o+=8),_=this._getColorFromAnsiIndex(o);break;case 50331648:let p=s0.toColorRGB(o);_=Z.toColor(p[0],p[1],p[2]);break;case 0:default:n?_=this._config.colors.background:_=this._config.colors.foreground}return this._config.allowTransparency&&(_=I0.opaque(_)),L&&(_=I0.multiplyOpacity(_,Ke)),_}_resolveBackgroundRgba(e,t,r){switch(e){case 16777216:case 33554432:return this._getColorFromAnsiIndex(t).rgba;case 50331648:return t<<8;case 0:default:return r?this._config.colors.foreground.rgba:this._config.colors.background.rgba}}_resolveForegroundRgba(e,t,r,s){switch(e){case 16777216:case 33554432:return this._config.drawBoldTextInBrightColors&&s&&t<8&&(t+=8),this._getColorFromAnsiIndex(t).rgba;case 50331648:return t<<8;case 0:default:return r?this._config.colors.background.rgba:this._config.colors.foreground.rgba}}_getMinimumContrastColor(e,t,r,s,a,o,n,L,T,h){if(this._config.minimumContrastRatio===1||h)return;let d=this._getContrastCache(T),_=d.getColor(e,s);if(_!==void 0)return _??void 0;let p=this._resolveBackgroundRgba(t,r,n),c=this._resolveForegroundRgba(a,o,n,L),u=d0.ensureContrastRatio(p,c,this._config.minimumContrastRatio/(T?2:1));if(!u){d.setColor(e,s,null);return}let C=Z.toColor(u>>24&255,u>>16&255,u>>8&255);return d.setColor(e,s,C),C}_getContrastCache(e){return e?this._config.colors.halfContrastCache:this._config.colors.contrastCache}_drawToCache(e,t,r,s,a,o){let n=typeof e=="number"?String.fromCharCode(e):e;o&&this._tmpCanvas.parentElement!==o&&(this._tmpCanvas.style.display="none",o.append(this._tmpCanvas));let L=Math.min(this._config.deviceCellWidth*Math.max(n.length,2)+B0*2,this._config.deviceMaxTextureSize);this._tmpCanvas.width=b?b*2-f0:b-f0;!(f0>=b)===!1||Z0===0?(this._tmpCtx.setLineDash([Math.round(b),Math.round(b)]),this._tmpCtx.moveTo(j+Z0,G),this._tmpCtx.lineTo(Q0,G)):(this._tmpCtx.setLineDash([Math.round(b),Math.round(b)]),this._tmpCtx.moveTo(j,G),this._tmpCtx.lineTo(j+Z0,G),this._tmpCtx.moveTo(j+Z0+b,G),this._tmpCtx.lineTo(Q0,G)),f0=We(Q0-j,b,f0);break;case 5:let vt=.6,Ot=.3,de=Q0-j,Se=Math.floor(vt*de),Re=Math.floor(Ot*de),It=de-Se-Re;this._tmpCtx.setLineDash([Se,Re,It]),this._tmpCtx.moveTo(j,G),this._tmpCtx.lineTo(Q0,G);break;case 1:default:this._tmpCtx.moveTo(j,G),this._tmpCtx.lineTo(Q0,G);break}y0||this._tmpCtx.stroke(),this._tmpCtx.restore()}if(this._tmpCtx.restore(),!n0&&this._config.fontSize>=12&&!this._config.allowTransparency&&n!==" "){this._tmpCtx.save(),this._tmpCtx.textBaseline="alphabetic";let r0=this._tmpCtx.measureText(n);if(this._tmpCtx.restore(),"actualBoundingBoxDescent"in r0&&r0.actualBoundingBoxDescent>0){this._tmpCtx.save();let y0=new Path2D;y0.rect(i0,C0-Math.ceil(b/2),this._config.deviceCellWidth*$,v0-C0+Math.ceil(b/2)),this._tmpCtx.clip(y0),this._tmpCtx.lineWidth=this._config.devicePixelRatio*3,this._tmpCtx.strokeStyle=y.css,this._tmpCtx.strokeText(n,A,A+this._config.deviceCharHeight),this._tmpCtx.restore()}}}if(Q){let b=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/15)),D=b%2===1?.5:0;this._tmpCtx.lineWidth=b,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(A,A+D),this._tmpCtx.lineTo(A+this._config.deviceCharWidth*$,A+D),this._tmpCtx.stroke()}if(n0||this._tmpCtx.fillText(n,A,A+this._config.deviceCharHeight),n==="_"&&!this._config.allowTransparency){let b=fe(this._tmpCtx.getImageData(A,A,this._config.deviceCellWidth,this._config.deviceCellHeight),y,L0,a0);if(b)for(let D=1;D<=5&&(this._tmpCtx.save(),this._tmpCtx.fillStyle=y.css,this._tmpCtx.fillRect(0,0,this._tmpCanvas.width,this._tmpCanvas.height),this._tmpCtx.restore(),this._tmpCtx.fillText(n,A,A+this._config.deviceCharHeight-D),b=fe(this._tmpCtx.getImageData(A,A,this._config.deviceCellWidth,this._config.deviceCellHeight),y,L0,a0),!!b);D++);}if(C){let b=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/10)),D=this._tmpCtx.lineWidth%2===1?.5:0;this._tmpCtx.lineWidth=b,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(A,A+Math.floor(this._config.deviceCharHeight/2)-D),this._tmpCtx.lineTo(A+this._config.deviceCharWidth*$,A+Math.floor(this._config.deviceCharHeight/2)-D),this._tmpCtx.stroke()}this._tmpCtx.restore();let q=this._tmpCtx.getImageData(0,0,this._tmpCanvas.width,this._tmpCanvas.height),g0;if(this._config.allowTransparency?g0=Gt(q):g0=fe(q,y,L0,a0),g0)return tt;let I=this._findGlyphBoundingBox(q,this._workBoundingBox,L,t0,n0,A),O,v;for(;;){if(this._activePages.length===0){let b=this._createNewPage();O=b,v=b.currentRow,v.height=I.size.y;break}O=this._activePages[this._activePages.length-1],v=O.currentRow;for(let b of this._activePages)I.size.y<=b.currentRow.height&&(O=b,v=b.currentRow);for(let b=this._activePages.length-1;b>=0;b--)for(let D of this._activePages[b].fixedRows)D.height<=v.height&&I.size.y<=D.height&&(O=this._activePages[b],v=D);if(I.size.x>this._textureSize){this._overflowSizePage||(this._overflowSizePage=new u0(this._document,this._config.deviceMaxTextureSize),this.pages.push(this._overflowSizePage),this._requestClearModel=!0,this._onAddTextureAtlasCanvas.fire(this._overflowSizePage.canvas)),O=this._overflowSizePage,v=this._overflowSizePage.currentRow,v.x+I.size.x>=O.canvas.width&&(v.x=0,v.y+=v.height,v.height=0);break}if(v.y+I.size.y>=O.canvas.height||v.height>I.size.y+2){let b=!1;if(O.currentRow.y+O.currentRow.height+I.size.y>=O.canvas.height){let D;for(let i0 of this._activePages)if(i0.currentRow.y+i0.currentRow.height+I.size.y=i.maxAtlasPages&&v.y+I.size.y<=O.canvas.height&&v.height>=I.size.y&&v.x+I.size.x<=O.canvas.width)b=!0;else{let i0=this._createNewPage();O=i0,v=i0.currentRow,v.height=I.size.y,b=!0}}b||(O.currentRow.height>0&&O.fixedRows.push(O.currentRow),v={x:0,y:O.currentRow.y+O.currentRow.height,height:I.size.y},O.fixedRows.push(v),O.currentRow={x:0,y:v.y+v.height,height:0})}if(v.x+I.size.x<=O.canvas.width)break;v===O.currentRow?(v.x=0,v.y+=v.height,v.height=0):O.fixedRows.splice(O.fixedRows.indexOf(v),1)}return I.texturePage=this._pages.indexOf(O),I.texturePosition.x=v.x,I.texturePosition.y=v.y,I.texturePositionClipSpace.x=v.x/O.canvas.width,I.texturePositionClipSpace.y=v.y/O.canvas.height,I.sizeClipSpace.x/=O.canvas.width,I.sizeClipSpace.y/=O.canvas.height,v.height=Math.max(v.height,I.size.y),v.x+=I.size.x,O.ctx.putImageData(q,I.texturePosition.x-this._workBoundingBox.left,I.texturePosition.y-this._workBoundingBox.top,this._workBoundingBox.left,this._workBoundingBox.top,I.size.x,I.size.y),O.addGlyph(I),O.version=++u0.nextVersion,I}_findGlyphBoundingBox(e,t,r,s,a,o){t.top=0;let n=s?this._config.deviceCellHeight:this._tmpCanvas.height,L=s?this._config.deviceCellWidth:r,T=!1;for(let h=0;h=o;h--){for(let d=0;d=0;h--){for(let d=0;d>>24,a=e.rgba>>>16&255,o=e.rgba>>>8&255,n=t.rgba>>>24,L=t.rgba>>>16&255,T=t.rgba>>>8&255,h=Math.floor((Math.abs(s-n)+Math.abs(a-L)+Math.abs(o-T))/12),d=!0;for(let _=0;_0)return!1;return!0}function it(i,e,t){let r=i.createElement("canvas");return r.width=e,r.height=t,r}function rt(i,e,t,r,s,a,o,n,L=!0){let T={foreground:a.foreground,background:a.background,cursor:K,cursorAccent:K,selectionForeground:K,selectionBackgroundTransparent:K,selectionBackgroundOpaque:K,selectionInactiveBackgroundTransparent:K,selectionInactiveBackgroundOpaque:K,overviewRulerBorder:K,scrollbarSliderBackground:K,scrollbarSliderHoverBackground:K,scrollbarSliderActiveBackground:K,ansi:a.ansi.slice(),contrastCache:a.contrastCache,halfContrastCache:a.halfContrastCache};return{customGlyphs:L,devicePixelRatio:o,deviceMaxTextureSize:n,letterSpacing:s.letterSpacing,lineHeight:s.lineHeight,deviceCellWidth:i,deviceCellHeight:e,deviceCharWidth:t,deviceCharHeight:r,fontFamily:s.fontFamily,fontSize:s.fontSize,fontWeight:s.fontWeight,fontWeightBold:s.fontWeightBold,allowTransparency:s.allowTransparency,drawBoldTextInBrightColors:s.drawBoldTextInBrightColors,minimumContrastRatio:s.minimumContrastRatio,colors:T}}function Ee(i,e){for(let t=0;t=0){if(Ee(u.config,h))return u.atlas;u.ownedBy.length===1?(u.atlas.dispose(),e0.splice(c,1)):u.ownedBy.splice(C,1);break}}for(let c=0;c{this._renderCallback(),this._animationFrame=void 0})))}_restartInterval(e=600){this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout=this._coreBrowserService.window.setTimeout(()=>{if(this._animationTimeRestarted){let t=600-(Date.now()-this._animationTimeRestarted);if(this._animationTimeRestarted=void 0,t>0){this._restartInterval(t);return}}this.isCursorVisible=!1,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0}),this._blinkInterval=this._coreBrowserService.window.setInterval(()=>{if(this._animationTimeRestarted){let t=600-(Date.now()-this._animationTimeRestarted);this._animationTimeRestarted=void 0,this._restartInterval(t);return}this.isCursorVisible=!this.isCursorVisible,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0})},600)},e)}pause(){this.isCursorVisible=!0,this._isIdlePaused=!1,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._idleTimeout&&(this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0)}resume(){this.pause(),this._animationTimeRestarted=void 0,this._restartInterval(),this._resetIdleTimer(),this.restartBlinkAnimation()}_resetIdleTimer(){this._isIdlePaused=!1,this._idleTimeout&&this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=this._coreBrowserService.window.setTimeout(()=>{this._stopBlinkingDueToIdle()},3e5)}_stopBlinkingDueToIdle(){this.isCursorVisible=!0,this._isIdlePaused=!0,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0,this._renderCallback()}};function ve(i,e,t){let r=new e.ResizeObserver(s=>{let a=s.find(L=>L.target===i);if(!a)return;if(!("devicePixelContentBoxSize"in a)){r?.disconnect(),r=void 0;return}let o=a.devicePixelContentBoxSize[0].inlineSize,n=a.devicePixelContentBoxSize[0].blockSize;o>0&&n>0&&t(o,n)});try{r.observe(i,{box:["device-pixel-content-box"]})}catch{r.disconnect(),r=void 0}return M(()=>r?.disconnect())}function nt(i){return i>65535?(i-=65536,String.fromCharCode((i>>10)+55296)+String.fromCharCode(i%1024+56320)):String.fromCharCode(i)}var j0=class i extends s0{constructor(){super(...arguments);this.content=0;this.fg=0;this.bg=0;this.extended=new P0;this.combinedData=""}static fromCharData(t){let r=new i;return r.setFromCharData(t),r}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?nt(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let r=!1;if(t[1].length>2)r=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:r=!0}else r=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;r&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}attributesEquals(t){if(this.getFgColorMode()!==t.getFgColorMode()||this.getFgColor()!==t.getFgColor()||this.getBgColorMode()!==t.getBgColorMode()||this.getBgColor()!==t.getBgColor()||this.isInverse()!==t.isInverse()||this.isBold()!==t.isBold()||this.isUnderline()!==t.isUnderline())return!1;if(this.isUnderline()){if(this.getUnderlineStyle()!==t.getUnderlineStyle())return!1;let r=this.isUnderlineColorDefault(),s=t.isUnderlineColorDefault();if(!(r&&s)&&(r!==s||this.getUnderlineColor()!==t.getUnderlineColor()||this.getUnderlineColorMode()!==t.getUnderlineColorMode()))return!1}return!(this.isOverline()!==t.isOverline()||this.isBlink()!==t.isBlink()||this.isInvisible()!==t.isInvisible()||this.isItalic()!==t.isItalic()||this.isDim()!==t.isDim()||this.isStrikethrough()!==t.isStrikethrough())}};var J0=class extends W{constructor(t,r,s){super();this._renderCallback=t;this._coreBrowserService=r;this._optionsService=s;this._intervalDuration=0;this._blinkOn=!0;this._needsBlinkInViewport=!1;this._isViewportVisible=!0;this._register(this._optionsService.onSpecificOptionChange("blinkIntervalDuration",a=>{this.setIntervalDuration(a)})),this.setIntervalDuration(this._optionsService.rawOptions.blinkIntervalDuration),this._register(M(()=>this._clearInterval()))}get isBlinkOn(){return this._blinkOn}get isEnabled(){return this._intervalDuration>0}setNeedsBlinkInViewport(t){this._needsBlinkInViewport!==t&&(this._needsBlinkInViewport=t,this._updateIntervalState())}setViewportVisible(t){this._isViewportVisible!==t&&(this._isViewportVisible=t,this._updateIntervalState())}setIntervalDuration(t){t!==this._intervalDuration&&(this._intervalDuration=t,this._clearInterval(),this._updateIntervalState())}_updateIntervalState(){if(this._intervalDuration>0&&this._needsBlinkInViewport&&this._isViewportVisible){if(this._interval!==void 0)return;let r=this._blinkOn;this._blinkOn=!0,this._interval=this._coreBrowserService.window.setInterval(()=>{this._blinkOn=!this._blinkOn,this._renderCallback()},this._intervalDuration),r||this._renderCallback();return}this._clearInterval(),this._blinkOn||(this._blinkOn=!0,this._renderCallback())}_clearInterval(){this._interval!==void 0&&(this._coreBrowserService.window.clearInterval(this._interval),this._interval=void 0)}};var te=new Float32Array([2,0,0,0,0,-2,0,0,0,0,1,0,-1,1,0,1]);function ie(i,e,t,r){let s=g(i.createProgram());if(i.attachShader(s,g(at(i,i.VERTEX_SHADER,e,r))),i.attachShader(s,g(at(i,i.FRAGMENT_SHADER,t,r))),i.linkProgram(s),i.getProgramParameter(s,i.LINK_STATUS))return s;r.error(i.getProgramInfoLog(s)),i.deleteProgram(s)}function at(i,e,t,r){let s=g(i.createShader(e));if(i.shaderSource(s,t),i.compileShader(s),i.getShaderParameter(s,i.COMPILE_STATUS))return s;r.error(i.getShaderInfoLog(s)),i.deleteShader(s)}function ot(i,e){let t=Math.min(i.length*2,e),r=new Float32Array(t);for(let s=0;sFt(i))}var R0=class{constructor(){this._disposables=new Set;this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(e){return this._isDisposed?e.dispose():this._disposables.add(e),e}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.clear()}}clear(){for(let e of this._disposables)e.dispose();this._disposables.clear()}},W=class{constructor(){this._store=new R0}dispose(){this._store.dispose()}_register(e){return this._store.add(e)}};W.None=Object.freeze({dispose(){}});var m0=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}};var Pe=!!(typeof process<"u"&&"title"in process&&(typeof navigator>"u"||navigator.userAgent.startsWith("Node.js/"))),O0=Pe?"node":navigator.userAgent,ce=Pe?"node":navigator.platform,Be=O0.includes("Firefox"),n1=O0.includes("Chrome"),we=O0.includes("Edge"),ue=/^((?!chrome|android).)*safari/i.test(O0);function He(){if(!ue)return 0;let i=O0.match(/Version\/(\d+)/);return i===null||i.length<2?0:parseInt(i[1],10)}var a1=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(ce),o1=["Windows","Win16","Win32","WinCE"].includes(ce),T1=ce.indexOf("Linux")>=0,l1=/\bCrOS\b/.test(O0);var P=0,B=0,w=0,x=0,K={css:"#00000000",rgba:0},Z;(r=>{function i(s,a,o,n){return n!==void 0?`#${E0(s)}${E0(a)}${E0(o)}${E0(n)}`:`#${E0(s)}${E0(a)}${E0(o)}`}r.toCss=i;function e(s,a,o,n=255){return(s<<24|a<<16|o<<8|n)>>>0}r.toRgba=e;function t(s,a,o,n){return{css:r.toCss(s,a,o,n),rgba:r.toRgba(s,a,o,n)}}r.toColor=t})(Z||={});var I0;(n=>{function i(L,T){if(x=(T.rgba&255)/255,x===1)return{css:T.css,rgba:T.rgba};let h=T.rgba>>24&255,d=T.rgba>>16&255,_=T.rgba>>8&255,p=L.rgba>>24&255,c=L.rgba>>16&255,u=L.rgba>>8&255;P=p+Math.round((h-p)*x),B=c+Math.round((d-c)*x),w=u+Math.round((_-u)*x);let C=Z.toCss(P,B,w),Q=Z.toRgba(P,B,w);return{css:C,rgba:Q}}n.blend=i;function e(L){return(L.rgba&255)===255}n.isOpaque=e;function t(L,T,h){let d=d0.ensureContrastRatio(L.rgba,T.rgba,h);if(d)return Z.toColor(d>>24&255,d>>16&255,d>>8&255)}n.ensureContrastRatio=t;function r(L){let T=(L.rgba|255)>>>0;return[P,B,w]=d0.toChannels(T),{css:Z.toCss(P,B,w),rgba:T}}n.opaque=r;function s(L,T){return x=Math.round(T*255),[P,B,w]=d0.toChannels(L.rgba),{css:Z.toCss(P,B,w,x),rgba:Z.toRgba(P,B,w,x)}}n.opacity=s;function a(L,T){return x=L.rgba&255,s(L,x*T/255)}n.multiplyOpacity=a;function o(L){return[L.rgba>>24&255,L.rgba>>16&255,L.rgba>>8&255]}n.toColorRGB=o})(I0||={});var Mt;(r=>{let i,e;try{let s=document.createElement("canvas");s.width=1,s.height=1;let a=s.getContext("2d",{willReadFrequently:!0});a&&(i=a,i.globalCompositeOperation="copy",e=i.createLinearGradient(0,0,1,1))}catch{}function t(s){if(s.match(/#[\da-f]{3,8}/i))switch(s.length){case 4:return P=parseInt(s.slice(1,2).repeat(2),16),B=parseInt(s.slice(2,3).repeat(2),16),w=parseInt(s.slice(3,4).repeat(2),16),Z.toColor(P,B,w);case 5:return P=parseInt(s.slice(1,2).repeat(2),16),B=parseInt(s.slice(2,3).repeat(2),16),w=parseInt(s.slice(3,4).repeat(2),16),x=parseInt(s.slice(4,5).repeat(2),16),Z.toColor(P,B,w,x);case 7:return{css:s,rgba:(parseInt(s.slice(1),16)<<8|255)>>>0};case 9:return{css:s,rgba:parseInt(s.slice(1),16)>>>0}}let a=s.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(a)return P=parseInt(a[1],10),B=parseInt(a[2],10),w=parseInt(a[3],10),x=Math.round((a[5]===void 0?1:parseFloat(a[5]))*255),Z.toColor(P,B,w,x);if(s==="transparent")return{css:"transparent",rgba:0};if(!i||!e)throw new Error("css.toColor: Unsupported css format");if(i.fillStyle=e,i.fillStyle=s,typeof i.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(i.fillRect(0,0,1,1),[P,B,w,x]=i.getImageData(0,0,1,1).data,x!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Z.toRgba(P,B,w,x),css:s}}r.toColor=t})(Mt||={});var V;(t=>{function i(r){return e(r>>16&255,r>>8&255,r&255)}t.relativeLuminance=i;function e(r,s,a){let o=r/255,n=s/255,L=a/255,T=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),h=n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4),d=L<=.03928?L/12.92:Math.pow((L+.055)/1.055,2.4);return T*.2126+h*.7152+d*.0722}t.relativeLuminance2=e})(V||={});var d0;(a=>{function i(o,n){if(x=(n&255)/255,x===1)return n;let L=n>>24&255,T=n>>16&255,h=n>>8&255,d=o>>24&255,_=o>>16&255,p=o>>8&255;return P=d+Math.round((L-d)*x),B=_+Math.round((T-_)*x),w=p+Math.round((h-p)*x),Z.toRgba(P,B,w)}a.blend=i;function e(o,n,L){let T=V.relativeLuminance(o>>8),h=V.relativeLuminance(n>>8);if(h0(T,h)>8));if(u>8));return u>Q?c:C}return c}let _=r(o,n,L),p=h0(T,V.relativeLuminance(_>>8));if(p>8));return p>u?_:c}return _}}a.ensureContrastRatio=e;function t(o,n,L){let T=o>>24&255,h=o>>16&255,d=o>>8&255,_=n>>24&255,p=n>>16&255,c=n>>8&255,u=h0(V.relativeLuminance2(_,p,c),V.relativeLuminance2(T,h,d));for(;u0||p>0||c>0);)_-=Math.max(0,Math.ceil(_*.1)),p-=Math.max(0,Math.ceil(p*.1)),c-=Math.max(0,Math.ceil(c*.1)),u=h0(V.relativeLuminance2(_,p,c),V.relativeLuminance2(T,h,d));return(_<<24|p<<16|c<<8|255)>>>0}a.reduceLuminance=t;function r(o,n,L){let T=o>>24&255,h=o>>16&255,d=o>>8&255,_=n>>24&255,p=n>>16&255,c=n>>8&255,u=h0(V.relativeLuminance2(_,p,c),V.relativeLuminance2(T,h,d));for(;u>>0}a.increaseLuminance=r;function s(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}a.toChannels=s})(d0||={});function E0(i){let e=i.toString(16);return e.length<2?"0"+e:e}function h0(i,e){return i=128512&&i<=128591||i>=127744&&i<=128511||i>=128640&&i<=128767||i>=9728&&i<=9983||i>=9984&&i<=10175||i>=65024&&i<=65039||i>=129280&&i<=129535||i>=127462&&i<=127487}function Ze(i,e,t,r){return e===1&&t>Math.ceil(r*1.5)&&i!==void 0&&i>255&&!yt(i)&&!W0(i)&&!At(i)}function V0(i){return W0(i)||gt(i)}function Ue(){return{css:{canvas:U0(),cell:U0()},device:{canvas:U0(),cell:U0(),char:{width:0,height:0,left:0,top:0}}}}function U0(){return{width:0,height:0}}function We(i,e,t=0){return(i-(Math.round(e)*2-t))%(Math.round(e)*2)}var l;(C=>(C.LINE_H=Object.freeze({type:2,data:"M0,.5 L1,.5",strokeWidth:1}),C.LINE_V=Object.freeze({type:2,data:"M.5,0 L.5,1",strokeWidth:1}),C.FADE_RIGHT=Object.freeze({type:2,data:"M0,.5 L.28,.5 M.32,.5 L.52,.5 M.60,.5 L.72,.5 M.84,.5 L.90,.5",strokeWidth:1}),C.FADE_LEFT=Object.freeze({type:2,data:"M.10,.5 L.16,.5 M.28,.5 L.40,.5 M.48,.5 L.68,.5 M.72,.5 L1,.5",strokeWidth:1}),C.FADE_DOWN=Object.freeze({type:2,data:"M.5,0 L.5,.28 M.5,.32 L.5,.52 M.5,.60 L.5,.72 M.5,.84 L.5,.90",strokeWidth:1}),C.FADE_UP=Object.freeze({type:2,data:"M.5,.10 L.5,.16 M.5,.28 L.5,.40 M.5,.48 L.5,.68 M.5,.72 L.5,1",strokeWidth:1}),C.CURVE_DOWN_RIGHT=Object.freeze({type:2,data:(Q,m)=>`M.5,1 L.5,${.5+m/.15*.5} C.5,${.5+m/.15*.5},.5,.5,1,.5`,strokeWidth:1}),C.CURVE_DOWN_LEFT=Object.freeze({type:2,data:(Q,m)=>`M.5,1 L.5,${.5+m/.15*.5} C.5,${.5+m/.15*.5},.5,.5,0,.5`,strokeWidth:1}),C.CURVE_UP_RIGHT=Object.freeze({type:2,data:(Q,m)=>`M.5,0 L.5,${.5-m/.15*.5} C.5,${.5-m/.15*.5},.5,.5,1,.5`,strokeWidth:1}),C.CURVE_UP_LEFT=Object.freeze({type:2,data:(Q,m)=>`M.5,0 L.5,${.5-m/.15*.5} C.5,${.5-m/.15*.5},.5,.5,0,.5`,strokeWidth:1}),C.NODE_FILL=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5"}),C.NODE_STROKE=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5",strokeWidth:1}),C.NODE_LINE_RIGHT=Object.freeze({type:3,data:"M1,.5 L.85,.5",strokeWidth:1}),C.NODE_LINE_LEFT=Object.freeze({type:3,data:"M0,.5 L.15,.5",strokeWidth:1}),C.NODE_LINE_DOWN=Object.freeze({type:3,data:"M.5,1 L.5,.7",strokeWidth:1}),C.NODE_LINE_UP=Object.freeze({type:3,data:"M.5,0 L.5,.3",strokeWidth:1})))(l||={});var Ve={"\u2500":{type:2,data:"M0,.5 L1,.5",strokeWidth:1},"\u2501":{type:2,data:"M0,.5 L1,.5",strokeWidth:3},"\u2502":{type:2,data:"M.5,0 L.5,1",strokeWidth:1},"\u2503":{type:2,data:"M.5,0 L.5,1",strokeWidth:3},"\u2504":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:1},"\u2505":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:3},"\u2506":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:1},"\u2507":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:3},"\u2508":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:1},"\u2509":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:3},"\u250A":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:1},"\u250B":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:3},"\u250C":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},"\u250D":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u250E":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u250F":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3},"\u2510":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},"\u2511":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u2512":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2513":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3},"\u2514":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},"\u2515":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u2516":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2517":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3},"\u2518":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},"\u2519":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u251A":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u251B":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3},"\u251C":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},"\u251D":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u251E":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u251F":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2520":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"\u2521":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"\u2522":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"\u2523":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3},"\u2524":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},"\u2525":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u2526":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2527":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2528":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"\u2529":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"\u252A":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"\u252B":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3},"\u252C":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},"\u252D":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u252E":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u252F":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"\u2530":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2531":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"\u2532":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"\u2533":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3},"\u2534":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:1},"\u2535":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u2536":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u2537":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"\u2538":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2539":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"\u253A":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"\u253B":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:3},"\u253C":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:1},"\u253D":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u253E":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u253F":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"\u2540":[{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2541":[{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2542":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"\u2543":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"\u2544":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"\u2545":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"\u2546":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"\u2547":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:3}],"\u2548":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3}],"\u2549":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3}],"\u254A":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3}],"\u254B":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:3},"\u254C":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:1},"\u254D":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:3},"\u254E":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:1},"\u254F":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:3},"\u2550":{type:2,data:(i,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u2551":{type:2,data:(i,e)=>`M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1`,strokeWidth:1},"\u2552":{type:2,data:(i,e)=>`M.5,1 L.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u2553":{type:2,data:(i,e)=>`M${.5-i},1 L${.5-i},.5 L1,.5 M${.5+i},.5 L${.5+i},1`,strokeWidth:1},"\u2554":{type:2,data:(i,e)=>`M1,${.5-e} L${.5-i},${.5-e} L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1`,strokeWidth:1},"\u2555":{type:2,data:(i,e)=>`M0,${.5-e} L.5,${.5-e} L.5,1 M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"\u2556":{type:2,data:(i,e)=>`M${.5+i},1 L${.5+i},.5 L0,.5 M${.5-i},.5 L${.5-i},1`,strokeWidth:1},"\u2557":{type:2,data:(i,e)=>`M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M0,${.5-e} L${.5+i},${.5-e} L${.5+i},1`,strokeWidth:1},"\u2558":{type:2,data:(i,e)=>`M.5,0 L.5,${.5+e} L1,${.5+e} M.5,${.5-e} L1,${.5-e}`,strokeWidth:1},"\u2559":{type:2,data:(i,e)=>`M1,.5 L${.5-i},.5 L${.5-i},0 M${.5+i},.5 L${.5+i},0`,strokeWidth:1},"\u255A":{type:2,data:(i,e)=>`M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0 M1,${.5+e} L${.5-i},${.5+e} L${.5-i},0`,strokeWidth:1},"\u255B":{type:2,data:(i,e)=>`M0,${.5+e} L.5,${.5+e} L.5,0 M0,${.5-e} L.5,${.5-e}`,strokeWidth:1},"\u255C":{type:2,data:(i,e)=>`M0,.5 L${.5+i},.5 L${.5+i},0 M${.5-i},.5 L${.5-i},0`,strokeWidth:1},"\u255D":{type:2,data:(i,e)=>`M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0 M0,${.5+e} L${.5+i},${.5+e} L${.5+i},0`,strokeWidth:1},"\u255E":{type:2,data:(i,e)=>`M.5,0 L.5,1 M.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u255F":{type:2,data:(i,e)=>`M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1 M${.5+i},.5 L1,.5`,strokeWidth:1},"\u2560":{type:2,data:(i,e)=>`M${.5-i},0 L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1 M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0`,strokeWidth:1},"\u2561":{type:2,data:(i,e)=>`M.5,0 L.5,1 M0,${.5-e} L.5,${.5-e} M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"\u2562":{type:2,data:(i,e)=>`M0,.5 L${.5-i},.5 M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1`,strokeWidth:1},"\u2563":{type:2,data:(i,e)=>`M${.5+i},0 L${.5+i},1 M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0`,strokeWidth:1},"\u2564":{type:2,data:(i,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e} M.5,${.5+e} L.5,1`,strokeWidth:1},"\u2565":{type:2,data:(i,e)=>`M0,.5 L1,.5 M${.5-i},.5 L${.5-i},1 M${.5+i},.5 L${.5+i},1`,strokeWidth:1},"\u2566":{type:2,data:(i,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1`,strokeWidth:1},"\u2567":{type:2,data:(i,e)=>`M.5,0 L.5,${.5-e} M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u2568":{type:2,data:(i,e)=>`M0,.5 L1,.5 M${.5-i},.5 L${.5-i},0 M${.5+i},.5 L${.5+i},0`,strokeWidth:1},"\u2569":{type:2,data:(i,e)=>`M0,${.5+e} L1,${.5+e} M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0 M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0`,strokeWidth:1},"\u256A":{type:2,data:(i,e)=>`M.5,0 L.5,1 M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u256B":{type:2,data:(i,e)=>`M0,.5 L1,.5 M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1`,strokeWidth:1},"\u256C":{type:2,data:(i,e)=>`M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1 M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0 M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0`,strokeWidth:1},"\u256D":{type:2,data:(i,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"\u256E":{type:2,data:(i,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"\u256F":{type:2,data:(i,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"\u2570":{type:2,data:(i,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"\u2571":{type:2,data:"M1,0 L0,1",strokeWidth:1},"\u2572":{type:2,data:"M0,0 L1,1",strokeWidth:1},"\u2573":{type:2,data:"M1,0 L0,1 M0,0 L1,1",strokeWidth:1},"\u2574":{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},"\u2575":{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},"\u2576":{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},"\u2577":{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},"\u2578":{type:2,data:"M.5,.5 L0,.5",strokeWidth:3},"\u2579":{type:2,data:"M.5,.5 L.5,0",strokeWidth:3},"\u257A":{type:2,data:"M.5,.5 L1,.5",strokeWidth:3},"\u257B":{type:2,data:"M.5,.5 L.5,1",strokeWidth:3},"\u257C":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u257D":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u257E":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u257F":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2580":{type:0,data:[{x:0,y:0,w:8,h:4}]},"\u2581":{type:0,data:[{x:0,y:7,w:8,h:1}]},"\u2582":{type:0,data:[{x:0,y:6,w:8,h:2}]},"\u2583":{type:0,data:[{x:0,y:5,w:8,h:3}]},"\u2584":{type:0,data:[{x:0,y:4,w:8,h:4}]},"\u2585":{type:0,data:[{x:0,y:3,w:8,h:5}]},"\u2586":{type:0,data:[{x:0,y:2,w:8,h:6}]},"\u2587":{type:0,data:[{x:0,y:1,w:8,h:7}]},"\u2588":{type:0,data:[{x:0,y:0,w:8,h:8}]},"\u2589":{type:0,data:[{x:0,y:0,w:7,h:8}]},"\u258A":{type:0,data:[{x:0,y:0,w:6,h:8}]},"\u258B":{type:0,data:[{x:0,y:0,w:5,h:8}]},"\u258C":{type:0,data:[{x:0,y:0,w:4,h:8}]},"\u258D":{type:0,data:[{x:0,y:0,w:3,h:8}]},"\u258E":{type:0,data:[{x:0,y:0,w:2,h:8}]},"\u258F":{type:0,data:[{x:0,y:0,w:1,h:8}]},"\u2590":{type:0,data:[{x:4,y:0,w:4,h:8}]},"\u2591":{type:1,data:[[1,0],[0,0]]},"\u2592":{type:1,data:[[1,0],[0,1]]},"\u2593":{type:1,data:[[1,1],[1,0]]},"\u2594":{type:0,data:[{x:0,y:0,w:8,h:1}]},"\u2595":{type:0,data:[{x:7,y:0,w:1,h:8}]},"\u2596":{type:0,data:[{x:0,y:4,w:4,h:4}]},"\u2597":{type:0,data:[{x:4,y:4,w:4,h:4}]},"\u2598":{type:0,data:[{x:0,y:0,w:4,h:4}]},"\u2599":{type:0,data:[{x:0,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"\u259A":{type:0,data:[{x:0,y:0,w:4,h:4},{x:4,y:4,w:4,h:4}]},"\u259B":{type:0,data:[{x:0,y:0,w:4,h:8},{x:4,y:0,w:4,h:4}]},"\u259C":{type:0,data:[{x:0,y:0,w:8,h:4},{x:4,y:0,w:4,h:8}]},"\u259D":{type:0,data:[{x:4,y:0,w:4,h:4}]},"\u259E":{type:0,data:[{x:4,y:0,w:4,h:4},{x:0,y:4,w:4,h:4}]},"\u259F":{type:0,data:[{x:4,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"\uE0A0":{type:5,data:{d:"M.3,1 L.03,1 L.03,.88 C.03,.82,.06,.78,.11,.73 C.15,.7,.2,.68,.28,.65 L.43,.6 C.49,.58,.53,.56,.56,.53 C.59,.5,.6,.47,.6,.43 L.6,.27 L.4,.27 L.69,.1 L.98,.27 L.78,.27 L.78,.46 C.78,.52,.76,.56,.72,.61 C.68,.66,.63,.67,.56,.7 L.48,.72 C.42,.74,.38,.76,.35,.78 C.32,.8,.31,.84,.31,.88 L.31,1 M.3,.5 L.03,.59 L.03,.09 L.3,.09 L.3,.655",type:0}},"\uE0A1":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.355,.03 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"\uE0A2":{type:5,data:{d:"M.25,.94 C.16,.94,.11,.92,.11,.87 L.11,.53 C.11,.48,.15,.455,.23,.45 L.23,.3 C.23,.25,.26,.22,.31,.19 C.36,.16,.43,.15,.51,.15 C.59,.15,.66,.16,.71,.19 C.77,.22,.79,.26,.79,.3 L.79,.45 C.87,.45,.91,.48,.91,.53 L.91,.87 C.91,.92,.86,.94,.77,.94 L.24,.94 M.53,.2 C.49,.2,.45,.21,.42,.23 C.39,.25,.38,.27,.38,.3 L.38,.45 L.68,.45 L.68,.3 C.68,.27,.67,.25,.64,.23 C.61,.21,.58,.2,.53,.2 M.58,.82 L.58,.66 C.63,.65,.65,.63,.65,.6 C.65,.58,.64,.57,.61,.56 C.58,.55,.56,.54,.52,.54 C.48,.54,.46,.55,.43,.56 C.4,.57,.39,.59,.39,.6 C.39,.63,.41,.64,.46,.66 L.46,.82 L.57,.82",type:0}},"\uE0A3":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.7,.03 L.7,.1 L.355,.1 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"\uE0B0":{type:5,data:{d:"M0,0 L1,.5 L0,1",type:0,rightPadding:2}},"\uE0B1":{type:5,data:{d:"M-1,-.5 L1,.5 L-1,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0B2":{type:5,data:{d:"M1,0 L0,.5 L1,1",type:0,leftPadding:2}},"\uE0B3":{type:5,data:{d:"M2,-.5 L0,.5 L2,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0B4":{type:5,data:{d:"M0,0 L0,1 C0.552,1,1,0.776,1,.5 C1,0.224,0.552,0,0,0",type:0,rightPadding:1}},"\uE0B5":{type:5,data:{d:"M.2,1 C.422,1,.8,.826,.78,.5 C.8,.174,0.422,0,.2,0",type:1,rightPadding:1}},"\uE0B6":{type:5,data:{d:"M1,0 L1,1 C0.448,1,0,0.776,0,.5 C0,0.224,0.448,0,1,0",type:0,leftPadding:1}},"\uE0B7":{type:5,data:{d:"M.8,1 C0.578,1,0.2,.826,.22,.5 C0.2,0.174,0.578,0,0.8,0",type:1,leftPadding:1}},"\uE0B8":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L-.5,1.5",type:0}},"\uE0B9":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0BA":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L1.5,1.5",type:0}},"\uE0BB":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0BC":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L-.5,-.5",type:0}},"\uE0BD":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0BE":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L1.5,-.5",type:0}},"\uE0BF":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0C0":{type:5,data:{d:"M0.8069,0.6075 Q0.7991,0.612,0.7815,0.6218 T0.7542,0.6369 T0.7282,0.6508 T0.7016,0.6644 T0.6778,0.6758 T0.6551,0.6854 T0.637,0.6911 T0.622,0.6936 Q0.6186,0.6936,0.6128,0.6942 T0.6018,0.6952 T0.5894,0.6956 T0.5757,0.6952 T0.561,0.693 T0.5451,0.6879 Q0.5342,0.6834,0.5193,0.6756 T0.4925,0.6614 T0.4673,0.6485 T0.4436,0.6389 T0.4239,0.6363 T0.4089,0.6422 Q0.4045,0.6467,0.3958,0.6554 T0.3843,0.6669 T0.3748,0.6746 T0.3613,0.683 T0.3442,0.6903 L0.3499,0.6956 Q0.3584,0.7042,0.3679,0.7177 T0.3836,0.7403 T0.4019,0.7583 T0.4295,0.7703 Q0.4688,0.7785,0.5203,0.7605 Q0.4902,0.7817,0.449,0.7911 T0.3696,0.8001 Q0.3567,0.7997,0.341,0.7942 T0.3111,0.7813 T0.2805,0.766 T0.2493,0.753 T0.218,0.7472 T0.187,0.754 Q0.1762,0.7589,0.1653,0.7681 T0.1453,0.7895 T0.1308,0.818 T0.1264,0.8507 L0.1264,0.858 Q0.1453,0.8462,0.1607,0.8433 T0.1899,0.8452 T0.2226,0.8625 Q0.2344,0.8707,0.2485,0.8752 T0.2813,0.8831 T0.3089,0.889 Q0.2981,0.8915,0.2846,0.8956 T0.2603,0.9037 T0.2368,0.9115 T0.2129,0.9174 T0.1894,0.9194 T0.1653,0.9155 Q0.1504,0.9115,0.1328,0.9196 T0.0986,0.9421 T0.0655,0.9708 T0.0317,0.9943 T0,1 Q0.001,0.94,0.0017,0.6508 T0.0024,0.2322 Q0.002,0.2109,0.0007,0.1379 T0,0.0249 Q0.0058,0.0253,0.009,0.0257 T0.0156,0.0288 T0.0203,0.0333 T0.0264,0.0422 T0.0349,0.0539 Q0.044,0.0657,0.0542,0.072 T0.0752,0.0789 T0.096,0.0775 T0.1175,0.0694 T0.1379,0.0573 T0.1579,0.0432 Q0.2141,0,0.2673,0.0318 Q0.2588,0.0318,0.2517,0.033 T0.239,0.0361 T0.2276,0.0424 T0.218,0.0504 T0.2085,0.0612 T0.1997,0.0732 T0.1899,0.0875 T0.1795,0.1028 Q0.1748,0.1093,0.1507,0.1234 T0.1186,0.1448 Q0.0999,0.1612,0.1108,0.1783 Q0.1162,0.1877,0.1238,0.1928 T0.1404,0.1979 T0.158,0.1967 T0.1775,0.1895 T0.1963,0.1791 T0.2151,0.1663 T0.2314,0.1534 T0.2458,0.141 T0.2561,0.1322 Q0.2815,0.1106,0.3017,0.101 T0.344,0.0926 T0.3919,0.1077 Q0.4099,0.1175,0.4265,0.1206 T0.4588,0.1202 T0.488,0.1098 T0.5176,0.0914 Q0.5071,0.1032,0.4963,0.1122 T0.4722,0.1285 T0.4497,0.1401 T0.4223,0.1518 T0.3943,0.1636 Q0.374,0.1726,0.3623,0.1863 T0.3482,0.2162 Q0.3445,0.2403,0.3608,0.2605 T0.4072,0.2876 Q0.4194,0.2909,0.4326,0.2899 T0.457,0.2856 T0.4805,0.2764 T0.5032,0.264 T0.5256,0.2497 T0.5478,0.2352 T0.5698,0.2222 T0.5921,0.2118 Q0.6982,0.173,0.81,0.2436 Q0.833,0.2583,0.8496,0.2674 T0.887,0.2846 T0.925,0.294 T0.9617,0.2911 T1,0.2746 Q0.9817,0.2946,0.96,0.3056 T0.9175,0.3191 T0.8731,0.3209 T0.8277,0.3164 T0.7818,0.3109 T0.7359,0.3101 T0.6907,0.3197 T0.647,0.3448 Q0.6443,0.3472,0.6333,0.3562 T0.6194,0.3674 T0.6076,0.3766 T0.594,0.386 T0.5815,0.3931 T0.5661,0.4007 T0.5501,0.4064 L0.5556,0.4121 Q0.5627,0.4198,0.5722,0.4251 T0.5926,0.4337 T0.6131,0.439 T0.6343,0.4431 T0.6521,0.4468 Q0.6762,0.4529,0.7056,0.4463 Q0.6772,0.4623,0.6543,0.471 T0.604,0.4814 Q0.5962,0.4818,0.5815,0.4825 T0.5591,0.4835 T0.5393,0.4857 T0.519,0.4908 T0.5007,0.4996 T0.4812,0.5141 T0.4627,0.5353 L0.4549,0.5451 L0.4661,0.543 Q0.4759,0.541,0.4909,0.55 T0.5315,0.5796 T0.5684,0.6083 Q0.5799,0.6161,0.5915,0.6212 T0.6181,0.6308 L0.6331,0.6353 Q0.6514,0.6418,0.7004,0.633 T0.8069,0.6075 Z",type:0}},"\uE0C1":{type:5,data:{d:"M0.011,0.0469 Q0.0152,0.0412,0.02,0.0361 T0.0292,0.0281 T0.0365,0.0253 Q0.0426,0.0257,0.0461,0.0263 T0.0534,0.03 T0.0582,0.0345 T0.0645,0.0434 T0.0723,0.0546 Q0.0807,0.0653,0.0897,0.0712 T0.1081,0.0775 T0.1255,0.0765 T0.1438,0.0695 T0.1605,0.0593 T0.1772,0.0473 Q0.2388,0,0.2927,0.0326 L0.2614,0.0767 L0.2581,0.0767 Q0.2494,0.0767,0.2444,0.0773 T0.2359,0.0789 T0.2291,0.0842 T0.2233,0.0922 T0.2146,0.1054 T0.2026,0.1236 Q0.1943,0.1354,0.1843,0.1444 T0.1675,0.1574 T0.1526,0.1654 T0.1429,0.1701 Q0.1436,0.1717,0.1446,0.1733 Q0.1504,0.1823,0.1581,0.1866 T0.1733,0.1915 T0.1909,0.1884 T0.2085,0.1809 T0.2265,0.169 T0.2427,0.1564 T0.2575,0.1436 T0.2688,0.1338 Q0.2969,0.1101,0.3195,0.0995 T0.3643,0.0901 T0.4114,0.1048 Q0.4279,0.1138,0.4426,0.1168 T0.4705,0.117 T0.4945,0.1089 T0.5186,0.0942 L0.5211,0.0926 L0.5289,0.0922 Q0.5411,0.095,0.5189,0.1203 Q0.505,0.1358,0.4913,0.1474 T0.4634,0.167 T0.4389,0.1796 T0.4121,0.1909 T0.3866,0.2011 Q0.3782,0.2047,0.3727,0.2092 Q0.3717,0.2117,0.3714,0.2141 Q0.3695,0.2263,0.3751,0.2388 T0.394,0.2616 T0.4253,0.2761 Q0.4398,0.2785,0.4513,0.2779 T0.4756,0.2724 T0.4987,0.2616 T0.5216,0.2476 T0.5453,0.2321 T0.5703,0.217 T0.5976,0.2043 Q0.7015,0.166,0.8099,0.2345 Q0.8361,0.2512,0.8572,0.2616 T0.9006,0.2779 T0.9432,0.281 T0.9819,0.2663 L0.9887,0.2671 Q1,0.272,0.9768,0.2969 Q0.9558,0.3193,0.9319,0.333 T0.8858,0.3513 T0.8391,0.3569 T0.793,0.3546 T0.7485,0.3497 T0.7065,0.3473 T0.6681,0.3522 T0.6344,0.3699 Q0.5963,0.4005,0.5847,0.4082 Q0.595,0.4139,0.6079,0.4174 T0.6367,0.4237 T0.6586,0.4278 Q0.6793,0.4331,0.7044,0.4278 Q0.7057,0.4278,0.707,0.4274 Q0.7067,0.429,0.7062,0.4313 T0.7036,0.4398 T0.6993,0.4513 T0.6931,0.4619 T0.6851,0.4698 Q0.6573,0.4857,0.6336,0.4947 T0.5831,0.5053 Q0.577,0.5057,0.5615,0.5065 T0.5394,0.508 T0.5221,0.51 T0.5042,0.5139 T0.4905,0.5204 Q0.5008,0.5232,0.515,0.5328 T0.549,0.5585 T0.5799,0.5824 Q0.5905,0.5897,0.6013,0.5946 T0.6262,0.6036 T0.6409,0.6081 Q0.6567,0.6134,0.7035,0.605 T0.8028,0.5816 L0.7974,0.5922 T0.7867,0.6134 L0.7812,0.624 Q0.7799,0.6248,0.7786,0.6252 Q0.7709,0.6297,0.7573,0.6372 T0.7346,0.6499 T0.7123,0.6621 T0.6897,0.6741 T0.6686,0.6847 T0.648,0.6941 T0.6297,0.7013 T0.6129,0.7062 T0.5995,0.7076 Q0.5992,0.7076,0.5831,0.7092 T0.5529,0.7092 T0.525,0.7019 Q0.5105,0.6958,0.4824,0.6811 T0.4356,0.6586 T0.4079,0.6533 Q0.3872,0.6741,0.3827,0.6782 Q0.3872,0.6835,0.3934,0.6929 T0.4037,0.7078 T0.4142,0.7198 T0.4284,0.7304 T0.4466,0.7365 Q0.4824,0.7443,0.5292,0.728 L0.5292,0.7294 T0.529,0.7333 T0.5284,0.7392 T0.5266,0.7463 T0.5236,0.7539 T0.5186,0.7612 T0.5111,0.7679 Q0.5086,0.77,0.5056,0.7716 Q0.4466,0.8104,0.3591,0.8091 Q0.344,0.8091,0.3246,0.802 T0.2893,0.7863 T0.2543,0.77 T0.2206,0.76 T0.1894,0.7643 Q0.1804,0.7684,0.1733,0.7753 Q0.1591,0.7892,0.1601,0.8169 Q0.1784,0.8067,0.1938,0.8053 T0.2212,0.8087 T0.2507,0.825 Q0.2614,0.8324,0.2744,0.8365 T0.3053,0.844 T0.332,0.8499 L0.303,0.894 L0.2998,0.8948 Q0.2904,0.8968,0.278,0.9009 T0.2554,0.9086 T0.233,0.9158 T0.2099,0.9213 T0.1868,0.9229 T0.1633,0.9192 Q0.1517,0.916,0.1367,0.9241 T0.1065,0.9462 T0.0753,0.9737 T0.041,0.9955 T0.0061,1 Q0,0.9984,0.0068,0.9845 Q0.009,0.9804,0.0123,0.9755 Q0.0187,0.9666,0.0261,0.9606 T0.0374,0.9555 Q0.0481,0.958,0.0629,0.949 T0.0931,0.9262 T0.1247,0.8987 T0.1597,0.8777 T0.1949,0.8752 Q0.213,0.8805,0.2343,0.8772 Q0.2249,0.8736,0.2172,0.8683 Q0.1914,0.8511,0.1738,0.8497 T0.1349,0.8617 Q0.1304,0.865,0.1273,0.8646 T0.1242,0.8605 L0.1239,0.8536 Q0.1226,0.8295,0.1354,0.8016 T0.1723,0.7496 Q0.1914,0.7308,0.2104,0.7219 Q0.2259,0.7145,0.2425,0.7141 T0.273,0.7182 T0.3022,0.7296 T0.3301,0.7439 T0.3569,0.7571 T0.3821,0.7643 Q0.373,0.7561,0.3598,0.7367 T0.3382,0.7088 L0.3327,0.7035 Q0.3282,0.699,0.3353,0.6884 T0.3517,0.6692 L0.3611,0.6607 Q0.3711,0.657,0.3751,0.6554 T0.3837,0.6507 T0.3898,0.6458 T0.3979,0.637 T0.4111,0.6236 Q0.4172,0.6175,0.4234,0.6138 Q0.4327,0.6081,0.4439,0.6077 T0.4655,0.6105 T0.4884,0.6201 T0.5113,0.633 T0.5347,0.6468 T0.5573,0.6578 Q0.5705,0.6635,0.5833,0.665 T0.6112,0.665 T0.6286,0.6635 Q0.6421,0.6631,0.6718,0.6501 Q0.626,0.6578,0.6089,0.6517 Q0.6063,0.6509,0.6002,0.6491 T0.5884,0.6454 T0.5757,0.6409 T0.561,0.6344 T0.5466,0.6256 Q0.536,0.6183,0.5108,0.5989 T0.4722,0.5712 T0.4527,0.564 L0.4418,0.5661 Q0.4308,0.5681,0.4366,0.5563 Q0.4401,0.5485,0.4476,0.5392 L0.455,0.5298 Q0.4631,0.5188,0.4714,0.51 T0.4866,0.4947 T0.5021,0.4831 T0.516,0.4749 T0.53,0.4694 T0.5428,0.4657 T0.5558,0.4637 T0.5674,0.4629 T0.5795,0.4625 Q0.5489,0.4543,0.534,0.4384 L0.5286,0.4327 Q0.5244,0.4282,0.5318,0.4174 T0.5486,0.398 L0.5579,0.3899 Q0.567,0.387,0.5749,0.3834 T0.5878,0.3772 T0.6012,0.3687 T0.6126,0.3603 T0.6268,0.3487 T0.6421,0.3361 Q0.6567,0.3242,0.6712,0.3159 T0.7009,0.3034 T0.7277,0.2973 T0.7556,0.2961 T0.7809,0.2977 T0.8074,0.301 Q0.8096,0.3014,0.8109,0.3016 T0.8143,0.302 T0.818,0.3026 Q0.8012,0.2936,0.7767,0.2781 Q0.6718,0.2117,0.5744,0.2476 Q0.5637,0.2516,0.5492,0.2604 T0.5218,0.2779 T0.4923,0.2965 T0.461,0.3124 T0.4282,0.3216 T0.394,0.3206 Q0.3637,0.3136,0.3474,0.2936 T0.3353,0.2459 Q0.3385,0.2247,0.355,0.2023 Q0.3646,0.1892,0.3763,0.179 Q0.3898,0.1672,0.4063,0.1595 Q0.3927,0.1562,0.3785,0.1485 Q0.3604,0.1387,0.3453,0.1354 T0.3161,0.1354 T0.2899,0.1458 T0.2627,0.166 Q0.262,0.1664,0.254,0.1733 T0.2414,0.1841 T0.2267,0.196 T0.2094,0.2086 T0.1915,0.2196 T0.1725,0.2288 T0.1546,0.2337 T0.1373,0.2343 T0.1223,0.228 T0.1097,0.2145 Q0.0962,0.1929,0.1258,0.1582 Q0.131,0.1517,0.1371,0.1464 Q0.1462,0.1387,0.156,0.1321 T0.1752,0.1205 T0.1878,0.1134 Q0.1891,0.1117,0.1947,0.103 T0.2035,0.0899 T0.2125,0.0781 T0.2243,0.064 Q0.1949,0.0616,0.1672,0.0828 Q0.153,0.0934,0.1412,0.1009 T0.1146,0.1146 T0.0873,0.1213 T0.0616,0.116 T0.0374,0.0962 Q0.0339,0.0909,0.0295,0.0846 T0.024,0.0767 T0.0202,0.0728 T0.0148,0.0704 T0.0068,0.0697 Q0.0003,0.0693,0.0058,0.0567 Q0.0077,0.0522,0.011,0.0469 Z",type:0}},"\uE0C2":{type:5,data:{d:"M0.1934,0.6075 Q0.2012,0.612,0.2188,0.6218 T0.2459,0.6369 T0.2718,0.6508 T0.2983,0.6644 T0.322,0.6758 T0.3447,0.6854 T0.363,0.6911 T0.3783,0.6936 Q0.3796,0.6936,0.396,0.6952 T0.4265,0.6952 T0.4548,0.6879 Q0.4656,0.6834,0.4805,0.6756 T0.5073,0.6614 T0.5327,0.6485 T0.5564,0.6389 T0.5759,0.6363 T0.5909,0.6422 Q0.5953,0.6467,0.604,0.6554 T0.6155,0.6669 T0.6251,0.6746 T0.6387,0.683 T0.6556,0.6903 L0.6498,0.6956 Q0.6414,0.7042,0.6319,0.7177 T0.6162,0.7403 T0.5979,0.7583 T0.5703,0.7703 Q0.5313,0.7785,0.4799,0.7605 Q0.5097,0.7817,0.5508,0.7911 T0.6302,0.8001 Q0.6431,0.7997,0.659,0.7942 T0.6888,0.7813 T0.7194,0.766 T0.7506,0.753 T0.7819,0.7472 T0.8131,0.754 Q0.8239,0.7589,0.8346,0.7681 T0.8544,0.7895 T0.8689,0.818 T0.8737,0.8507 L0.8733,0.858 Q0.8591,0.849,0.8474,0.845 T0.8242,0.8421 T0.8021,0.8482 T0.7772,0.8625 Q0.7653,0.8707,0.7513,0.8752 T0.7184,0.8831 T0.6908,0.889 Q0.7017,0.8915,0.7152,0.8956 T0.7396,0.9037 T0.7633,0.9115 T0.7872,0.9174 T0.8107,0.9194 T0.8347,0.9155 Q0.8493,0.9115,0.8671,0.9196 T0.9015,0.9421 T0.9345,0.9708 T0.9682,0.9943 T0.9997,1 Q0.999,0.94,0.9983,0.6508 T0.9976,0.2322 Q0.9976,0.2109,0.9992,0.1379 T1,0.0249 Q0.9949,0.0249,0.9917,0.0257 T0.9863,0.0273 T0.9817,0.0308 T0.9776,0.0357 T0.9721,0.0437 T0.9651,0.0539 Q0.956,0.0657,0.9456,0.072 T0.9247,0.0789 T0.904,0.0775 T0.8823,0.0694 T0.862,0.0573 T0.8422,0.0432 Q0.7856,0,0.7328,0.0318 Q0.7392,0.0318,0.7452,0.0324 T0.756,0.0345 T0.7657,0.0386 T0.7741,0.0437 T0.7821,0.0506 T0.7894,0.0588 T0.7966,0.0683 T0.8039,0.0787 T0.8119,0.0904 T0.8202,0.1028 Q0.8249,0.1093,0.849,0.1234 T0.8811,0.1448 Q0.8998,0.1612,0.8893,0.1783 Q0.8835,0.1877,0.8759,0.1928 T0.8593,0.1979 T0.8417,0.1967 T0.8222,0.1895 T0.8034,0.1791 T0.7848,0.1663 T0.7687,0.1534 T0.7543,0.141 T0.744,0.1322 Q0.7186,0.1106,0.6984,0.101 T0.6559,0.0926 T0.6082,0.1077 Q0.5899,0.1175,0.5733,0.1206 T0.5411,0.1202 T0.5122,0.1098 T0.4822,0.0914 Q0.4927,0.1032,0.5036,0.1122 T0.5276,0.1285 T0.5503,0.1401 T0.5777,0.1518 T0.6055,0.1636 Q0.6258,0.1726,0.6375,0.1863 T0.6519,0.2162 Q0.6556,0.2403,0.6392,0.2605 T0.5926,0.2876 Q0.5804,0.2909,0.5672,0.2899 T0.5428,0.2856 T0.5193,0.2764 T0.4966,0.264 T0.4744,0.2497 T0.4523,0.2352 T0.4301,0.2222 T0.4077,0.2118 Q0.3021,0.173,0.1903,0.2436 Q0.1669,0.2583,0.1504,0.2674 T0.1129,0.2846 T0.075,0.294 T0.0384,0.2911 T0,0.2746 Q0.021,0.297,0.0459,0.3082 T0.0953,0.3207 T0.146,0.3193 T0.1988,0.3131 T0.2508,0.3095 T0.3029,0.3176 T0.3529,0.3448 Q0.3566,0.348,0.3652,0.355 T0.3771,0.3645 T0.3877,0.3731 T0.3993,0.3815 T0.4103,0.3884 T0.4226,0.3953 T0.4352,0.4009 T0.4497,0.4064 L0.4443,0.4121 Q0.4372,0.4198,0.4277,0.4251 T0.4072,0.4337 T0.3867,0.439 T0.3656,0.4431 T0.3481,0.4468 Q0.3241,0.4529,0.2943,0.4463 Q0.3227,0.4623,0.3458,0.471 T0.3959,0.4814 Q0.404,0.4818,0.4187,0.4825 T0.4409,0.4835 T0.4605,0.4857 T0.4809,0.4908 T0.4992,0.4996 T0.5186,0.5141 T0.5371,0.5353 L0.5449,0.5451 L0.5337,0.543 Q0.5242,0.541,0.5091,0.55 T0.4683,0.5796 T0.4314,0.6083 Q0.4203,0.6161,0.4086,0.6212 T0.382,0.6308 T0.3667,0.6353 Q0.3485,0.6418,0.2995,0.633 T0.1934,0.6075 Z",type:0}},"\uE0C3":{type:5,data:{d:"M0.989,0.0469 Q0.9829,0.0379,0.9753,0.0316 T0.9635,0.0253 Q0.9574,0.0257,0.9539,0.0263 T0.9466,0.03 T0.9418,0.0345 T0.9355,0.0434 T0.9277,0.0546 Q0.9193,0.0653,0.9103,0.0712 T0.8919,0.0775 T0.8745,0.0765 T0.8564,0.0695 T0.8396,0.0593 T0.8228,0.0473 Q0.7612,0,0.7073,0.0326 L0.7386,0.0767 L0.7419,0.0767 Q0.7506,0.0767,0.7556,0.0773 T0.7641,0.0789 T0.7709,0.0842 T0.7767,0.0922 T0.7854,0.1054 T0.7974,0.1236 Q0.8057,0.1354,0.8157,0.1444 T0.8325,0.1574 T0.8474,0.1654 T0.8571,0.1701 Q0.8564,0.1717,0.8554,0.1733 Q0.8503,0.1815,0.844,0.186 T0.8301,0.1909 T0.8153,0.1903 T0.7993,0.1845 T0.7836,0.1758 T0.768,0.1648 T0.754,0.1535 T0.741,0.1425 T0.7312,0.1338 Q0.7031,0.1101,0.6805,0.0995 T0.6357,0.0901 T0.5886,0.1048 Q0.5721,0.1138,0.5574,0.1168 T0.5295,0.117 T0.5055,0.1089 T0.4814,0.0942 L0.4789,0.0926 L0.4711,0.0922 Q0.4589,0.095,0.4811,0.1203 Q0.495,0.1358,0.5087,0.1474 T0.5366,0.167 T0.5611,0.1796 T0.5879,0.1909 T0.6134,0.2011 Q0.6218,0.2047,0.6273,0.2092 Q0.6283,0.2117,0.6286,0.2141 Q0.6305,0.2263,0.6249,0.2388 T0.606,0.2616 T0.5747,0.2761 Q0.5602,0.2785,0.5487,0.2779 T0.5245,0.2724 T0.5015,0.2616 T0.4784,0.2476 T0.4547,0.2321 T0.4297,0.217 T0.4024,0.2043 Q0.2985,0.166,0.1901,0.2345 Q0.1694,0.248,0.1523,0.2569 T0.1165,0.2726 T0.0818,0.2812 T0.0494,0.2796 T0.0181,0.2663 L0.0116,0.2671 Q0,0.272,0.0232,0.2969 Q0.0468,0.3222,0.0742,0.3365 T0.1278,0.3542 T0.1807,0.3564 T0.233,0.352 T0.2815,0.3473 T0.3269,0.3509 T0.3656,0.3699 Q0.4037,0.4005,0.4153,0.4082 Q0.405,0.4139,0.3921,0.4174 T0.3633,0.4237 T0.3414,0.4278 Q0.3207,0.4331,0.2956,0.4278 Q0.2943,0.4278,0.293,0.4274 Q0.2933,0.429,0.2938,0.4313 T0.2964,0.4398 T0.3007,0.4513 T0.3069,0.4619 T0.3149,0.4698 Q0.3427,0.4857,0.3664,0.4947 T0.4169,0.5053 Q0.423,0.5057,0.4385,0.5065 T0.4606,0.508 T0.4779,0.51 T0.4958,0.5139 T0.5095,0.5204 Q0.4992,0.5232,0.485,0.5328 T0.451,0.5585 T0.4201,0.5824 Q0.4095,0.5897,0.3987,0.5946 T0.3738,0.6036 T0.3591,0.6081 Q0.3433,0.6134,0.2965,0.605 T0.1972,0.5816 L0.2026,0.5922 T0.2133,0.6134 L0.2188,0.624 Q0.2201,0.6248,0.2214,0.6252 Q0.2291,0.6297,0.2486,0.6405 T0.2786,0.657 T0.3066,0.6721 T0.3353,0.6866 T0.3598,0.6972 T0.383,0.7051 T0.4005,0.7076 Q0.4008,0.7076,0.4169,0.7092 T0.4471,0.7092 T0.475,0.7019 Q0.4895,0.6958,0.5176,0.6811 T0.5644,0.6586 T0.5921,0.6533 Q0.6128,0.6741,0.6173,0.6782 Q0.6131,0.6835,0.6068,0.6929 T0.5963,0.7078 T0.5858,0.7198 T0.5716,0.7304 T0.5534,0.7365 Q0.5179,0.7443,0.4708,0.728 L0.4708,0.7294 T0.471,0.7333 T0.4716,0.7392 T0.4734,0.7463 T0.4764,0.7539 T0.4814,0.7612 T0.4889,0.7679 Q0.4914,0.77,0.4944,0.7716 Q0.5534,0.8104,0.6409,0.8091 Q0.6521,0.8091,0.6654,0.8053 T0.6907,0.7959 T0.7157,0.7838 T0.741,0.772 T0.7652,0.7631 T0.7888,0.7594 T0.8106,0.7643 Q0.8196,0.7684,0.8267,0.7753 Q0.8409,0.7892,0.8399,0.8169 Q0.8216,0.8067,0.8062,0.8053 T0.7788,0.8087 T0.7493,0.825 Q0.7386,0.8324,0.7256,0.8365 T0.6947,0.844 T0.668,0.8499 L0.697,0.894 L0.7002,0.8948 Q0.7099,0.8968,0.7222,0.9009 T0.7446,0.9086 T0.767,0.9158 T0.7901,0.9213 T0.8132,0.9229 T0.8367,0.9192 Q0.8483,0.916,0.8633,0.9241 T0.8937,0.9462 T0.9248,0.9737 T0.959,0.9955 T0.9939,1 Q1,0.9984,0.9932,0.9845 Q0.991,0.9804,0.9877,0.9755 Q0.9813,0.9666,0.9739,0.9606 T0.9626,0.9555 Q0.9519,0.958,0.9372,0.949 T0.9071,0.9262 T0.8753,0.8987 T0.8403,0.8777 T0.8051,0.8752 Q0.787,0.8805,0.7657,0.8772 Q0.7751,0.8736,0.7828,0.8683 Q0.8086,0.8511,0.8262,0.8497 T0.8651,0.8617 Q0.8696,0.865,0.8727,0.8646 T0.8758,0.8605 L0.8761,0.8536 Q0.8774,0.8295,0.8646,0.8016 T0.8277,0.7496 Q0.8086,0.7308,0.7896,0.7219 Q0.7741,0.7145,0.7575,0.7141 T0.727,0.7182 T0.6978,0.7296 T0.6699,0.7439 T0.6433,0.7571 T0.6179,0.7643 Q0.627,0.7561,0.6402,0.7367 T0.6618,0.7088 L0.6673,0.7035 Q0.6718,0.699,0.6647,0.6884 T0.6483,0.6692 L0.6389,0.6607 Q0.6289,0.657,0.6249,0.6554 T0.6163,0.6507 T0.6102,0.6458 T0.6021,0.637 T0.5889,0.6236 Q0.5828,0.6175,0.5766,0.6138 Q0.5673,0.6081,0.5561,0.6077 T0.5345,0.6105 T0.5116,0.6201 T0.4887,0.633 T0.4653,0.6468 T0.4427,0.6578 Q0.4295,0.6635,0.4167,0.665 T0.3888,0.665 T0.3714,0.6635 Q0.3579,0.6631,0.3282,0.6501 Q0.374,0.6578,0.3911,0.6517 Q0.3937,0.6509,0.4024,0.6482 T0.4179,0.6434 T0.4348,0.6364 T0.4534,0.6256 Q0.464,0.6183,0.4892,0.5989 T0.5278,0.5712 T0.5476,0.564 L0.5582,0.5661 Q0.5692,0.5681,0.5634,0.5563 Q0.5599,0.5485,0.5524,0.5392 L0.545,0.5298 Q0.5369,0.5188,0.5286,0.51 T0.5134,0.4947 T0.4979,0.4831 T0.484,0.4749 T0.47,0.4694 T0.4572,0.4657 T0.4442,0.4637 T0.4326,0.4629 T0.4205,0.4625 Q0.4511,0.4543,0.466,0.4384 L0.4714,0.4327 Q0.4795,0.4237,0.4469,0.394 L0.4421,0.3899 Q0.433,0.387,0.4251,0.3834 T0.4122,0.3772 T0.3988,0.3687 T0.3874,0.3603 T0.3732,0.3487 T0.3579,0.3361 Q0.3433,0.3242,0.3288,0.3159 T0.2993,0.3034 T0.2725,0.2973 T0.2446,0.2961 T0.2193,0.2977 T0.1926,0.301 Q0.1855,0.3022,0.182,0.3026 Q0.1991,0.2936,0.2233,0.2781 Q0.3282,0.2117,0.4256,0.2476 Q0.4363,0.2516,0.451,0.2604 T0.4784,0.2779 T0.5077,0.2965 T0.539,0.3124 T0.5718,0.3216 T0.606,0.3206 Q0.6363,0.3136,0.6526,0.2936 T0.6647,0.2459 Q0.6615,0.2247,0.645,0.2023 Q0.6354,0.1892,0.6237,0.179 Q0.6102,0.1672,0.5937,0.1595 Q0.6073,0.1562,0.6215,0.1485 Q0.6396,0.1387,0.6547,0.1354 T0.6839,0.1354 T0.7101,0.1458 T0.7373,0.166 Q0.738,0.1664,0.746,0.1733 T0.7586,0.1841 T0.7733,0.196 T0.7907,0.2086 T0.8086,0.2196 T0.8275,0.2288 T0.8454,0.2337 T0.8627,0.2343 T0.8777,0.228 T0.8903,0.2145 Q0.9038,0.1929,0.8742,0.1582 Q0.869,0.1517,0.8629,0.1464 Q0.8538,0.1387,0.844,0.1321 T0.8248,0.1205 T0.8122,0.1134 Q0.8109,0.1117,0.8053,0.103 T0.7965,0.0899 T0.7875,0.0781 T0.7757,0.064 Q0.8051,0.0616,0.8328,0.0828 Q0.847,0.0934,0.8588,0.1009 T0.8854,0.1146 T0.9127,0.1213 T0.9384,0.116 T0.9626,0.0962 Q0.9664,0.0909,0.9706,0.0846 T0.976,0.0767 T0.9798,0.0728 T0.9852,0.0704 T0.9932,0.0697 Q0.9997,0.0693,0.9942,0.0567 Q0.9923,0.0522,0.989,0.0469 Z",type:0}},"\uE0C4":{type:5,data:{d:"M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0.9099,0.1158 L0.9099,0.1888 L0.9951,0.1888 L0.9951,0.1158 L0.9099,0.1158 Z M0.9075,0.1116 L0.9976,0.1116 Q1,0.1116,1,0.1137 L1,0.1909 Q1,0.193,0.9976,0.193 L0.9075,0.193 Q0.905,0.193,0.905,0.1909 L0.905,0.1137 Q0.905,0.1116,0.9075,0.1116 Z M0.7852,0.6086 L0.7852,0.682 L0.8704,0.682 L0.8704,0.6086 L0.7852,0.6086 Z M0.7828,0.6044 L0.8729,0.6044 Q0.8753,0.6044,0.8753,0.6065 L0.8753,0.6841 Q0.8753,0.6862,0.8729,0.6862 L0.7828,0.6862 Q0.7803,0.6862,0.7803,0.6841 L0.7803,0.6065 Q0.7803,0.6044,0.7828,0.6044 Z M0.66,0.1137 L0.7501,0.1137 L0.7501,0.1909 L0.66,0.1909 L0.66,0.1137 Z M0.6624,0.4102 L0.6624,0.4836 L0.7477,0.4836 L0.7477,0.4102 L0.6624,0.4102 Z M0.66,0.406 L0.7501,0.406 Q0.7526,0.406,0.7526,0.4081 L0.7526,0.4857 Q0.7526,0.4878,0.7501,0.4878 L0.66,0.4878 Q0.6576,0.4878,0.6576,0.4857 L0.6576,0.4081 Q0.6576,0.406,0.66,0.406 Z M0.6624,0.7131 L0.6624,0.7865 L0.7477,0.7865 L0.7477,0.7131 L0.6624,0.7131 Z M0.66,0.7089 L0.7501,0.7089 Q0.7526,0.7089,0.7526,0.711 L0.7526,0.7886 Q0.7526,0.7907,0.7501,0.7907 L0.66,0.7907 Q0.6576,0.7907,0.6576,0.7886 L0.6576,0.711 Q0.6576,0.7089,0.66,0.7089 Z M0.5407,0.2227 L0.5407,0.2836 L0.6113,0.2836 L0.6113,0.2227 L0.5407,0.2227 Z M0.5309,0.206 L0.621,0.206 Q0.623,0.206,0.6249,0.2068 T0.6281,0.2089 T0.6301,0.2116 T0.6308,0.2143 L0.6308,0.2919 Q0.6308,0.2957,0.6276,0.298 T0.621,0.3003 L0.5309,0.3003 Q0.5265,0.3003,0.5239,0.2976 T0.5212,0.2919 L0.5212,0.2143 Q0.5212,0.211,0.5244,0.2085 T0.5309,0.206 Z M0.5407,0.3184 L0.5407,0.3792 L0.6113,0.3792 L0.6113,0.3184 L0.5407,0.3184 Z M0.5309,0.3016 L0.621,0.3016 Q0.6254,0.3016,0.6281,0.3043 T0.6308,0.31 L0.6308,0.3876 Q0.6308,0.3914,0.6276,0.3937 T0.621,0.396 L0.5309,0.396 Q0.5265,0.396,0.5239,0.3932 T0.5212,0.3876 L0.5212,0.31 Q0.5212,0.3062,0.5244,0.3039 T0.5309,0.3016 Z M0.5309,0.4081 L0.621,0.4081 L0.621,0.4857 L0.5309,0.4857 L0.5309,0.4081 Z M0.5309,0.5059 L0.621,0.5059 L0.621,0.5835 L0.5309,0.5835 L0.5309,0.5059 Z M0.5407,0.6149 L0.5407,0.6758 L0.6113,0.6758 L0.6113,0.6149 L0.5407,0.6149 Z M0.5309,0.5982 L0.621,0.5982 Q0.6254,0.5982,0.6281,0.6009 T0.6308,0.6065 L0.6308,0.6841 Q0.6308,0.6879,0.6276,0.6902 T0.621,0.6925 L0.5309,0.6925 Q0.5265,0.6925,0.5239,0.6898 T0.5212,0.6841 L0.5212,0.6065 Q0.5212,0.6028,0.5244,0.6005 T0.5309,0.5982 Z M0.4062,0.1137 L0.4963,0.1137 L0.4963,0.1909 L0.4062,0.1909 L0.4062,0.1137 Z M0.4062,0.2143 L0.4963,0.2143 L0.4963,0.2919 L0.4062,0.2919 L0.4062,0.2143 Z M0.4184,0.4186 L0.4184,0.4753 L0.4842,0.4753 L0.4842,0.4186 L0.4184,0.4186 Z M0.4062,0.3977 L0.4963,0.3977 Q0.5017,0.3977,0.5051,0.401 T0.5085,0.4081 L0.5085,0.4857 Q0.5085,0.4904,0.5046,0.4933 T0.4963,0.4962 L0.4062,0.4962 Q0.4009,0.4962,0.3975,0.4929 T0.3941,0.4857 L0.3941,0.4081 Q0.3941,0.4035,0.398,0.4006 T0.4062,0.3977 Z M0.4062,0.5059 L0.4963,0.5059 L0.4963,0.5835 L0.4062,0.5835 L0.4062,0.5059 Z M0.4087,0.7131 L0.4087,0.7865 L0.4939,0.7865 L0.4939,0.7131 L0.4087,0.7131 Z M0.4062,0.7089 L0.4963,0.7089 Q0.4988,0.7089,0.4988,0.711 L0.4988,0.7886 Q0.4988,0.7907,0.4963,0.7907 L0.4062,0.7907 Q0.4038,0.7907,0.4038,0.7886 L0.4038,0.711 Q0.4038,0.7089,0.4062,0.7089 Z M0.2689,0.1137 L0.359,0.1137 L0.359,0.1909 L0.2689,0.1909 L0.2689,0.1137 Z M0.2689,0.2143 L0.359,0.2143 L0.359,0.2919 L0.2689,0.2919 L0.2689,0.2143 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.31 L0.359,0.31 L0.359,0.3876 L0.2689,0.3876 L0.2689,0.31 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.4081 L0.359,0.4081 L0.359,0.4857 L0.2689,0.4857 L0.2689,0.4081 Z M0.2689,0.5059 L0.359,0.5059 L0.359,0.5835 L0.2689,0.5835 L0.2689,0.5059 Z M0.2689,0.711 L0.359,0.711 L0.359,0.7886 L0.2689,0.7886 L0.2689,0.711 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.1374,0.1137 L0.2275,0.1137 L0.2275,0.1909 L0.1374,0.1909 L0.1374,0.1137 Z M0.1374,0.2143 L0.2275,0.2143 L0.2275,0.2919 L0.1374,0.2919 L0.1374,0.2143 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.31 L0.2275,0.31 L0.2275,0.3876 L0.1374,0.3876 L0.1374,0.31 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.4081 L0.2275,0.4081 L0.2275,0.4857 L0.1374,0.4857 L0.1374,0.4081 Z M0.1374,0.5059 L0.2275,0.5059 L0.2275,0.5835 L0.1374,0.5835 L0.1374,0.5059 Z M0.1374,0.6065 L0.2275,0.6065 L0.2275,0.6841 L0.1374,0.6841 L0.1374,0.6065 Z M0.1374,0.711 L0.2275,0.711 L0.2275,0.7886 L0.1374,0.7886 L0.1374,0.711 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0,0.1137 L0.0901,0.1137 L0.0901,0.1909 L0,0.1909 L0,0.1137 Z M0,0.2143 L0.0901,0.2143 L0.0901,0.2919 L0,0.2919 L0,0.2143 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.31 L0.0901,0.31 L0.0901,0.3876 L0,0.3876 L0,0.31 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.4081 L0.0901,0.4081 L0.0901,0.4857 L0,0.4857 L0,0.4081 Z M0,0.5059 L0.0901,0.5059 L0.0901,0.5835 L0,0.5835 L0,0.5059 Z M0,0.6065 L0.0901,0.6065 L0.0901,0.6841 L0,0.6841 L0,0.6065 Z M0,0.711 L0.0901,0.711 L0.0901,0.7886 L0,0.7886 L0,0.711 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z",type:0}},"\uE0C5":{type:5,data:{d:"M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M0.0901,0.1158 L0.0901,0.1888 L0.0049,0.1888 L0.0049,0.1158 L0.0901,0.1158 Z M0.0925,0.1116 L0.0024,0.1116 Q0,0.1116,0,0.1137 L0,0.1909 Q0,0.193,0.0024,0.193 L0.0925,0.193 Q0.095,0.193,0.095,0.1909 L0.095,0.1137 Q0.095,0.1116,0.0925,0.1116 Z M0.2148,0.6086 L0.2148,0.682 L0.1296,0.682 L0.1296,0.6086 L0.2148,0.6086 Z M0.2172,0.6044 L0.1271,0.6044 Q0.1247,0.6044,0.1247,0.6065 L0.1247,0.6841 Q0.1247,0.6862,0.1271,0.6862 L0.2172,0.6862 Q0.2197,0.6862,0.2197,0.6841 L0.2197,0.6065 Q0.2197,0.6044,0.2172,0.6044 Z M0.34,0.1137 L0.2499,0.1137 L0.2499,0.1909 L0.34,0.1909 L0.34,0.1137 Z M0.3376,0.4102 L0.3376,0.4836 L0.2523,0.4836 L0.2523,0.4102 L0.3376,0.4102 Z M0.34,0.406 L0.2499,0.406 Q0.2474,0.406,0.2474,0.4081 L0.2474,0.4857 Q0.2474,0.4878,0.2499,0.4878 L0.34,0.4878 Q0.3424,0.4878,0.3424,0.4857 L0.3424,0.4081 Q0.3424,0.406,0.34,0.406 Z M0.3376,0.7131 L0.3376,0.7865 L0.2523,0.7865 L0.2523,0.7131 L0.3376,0.7131 Z M0.34,0.7089 L0.2499,0.7089 Q0.2474,0.7089,0.2474,0.711 L0.2474,0.7886 Q0.2474,0.7907,0.2499,0.7907 L0.34,0.7907 Q0.3424,0.7907,0.3424,0.7886 L0.3424,0.711 Q0.3424,0.7089,0.34,0.7089 Z M0.4593,0.2227 L0.4593,0.2836 L0.3887,0.2836 L0.3887,0.2227 L0.4593,0.2227 Z M0.4691,0.206 L0.379,0.206 Q0.3746,0.206,0.3719,0.2087 T0.3692,0.2143 L0.3692,0.2919 Q0.3692,0.2957,0.3724,0.298 T0.379,0.3003 L0.4691,0.3003 Q0.4735,0.3003,0.4761,0.2976 T0.4788,0.2919 L0.4788,0.2143 Q0.4788,0.211,0.4756,0.2085 T0.4691,0.206 Z M0.4593,0.3184 L0.4593,0.3792 L0.3887,0.3792 L0.3887,0.3184 L0.4593,0.3184 Z M0.4691,0.3016 L0.379,0.3016 Q0.3746,0.3016,0.3719,0.3043 T0.3692,0.31 L0.3692,0.3876 Q0.3692,0.3914,0.3724,0.3937 T0.379,0.396 L0.4691,0.396 Q0.4735,0.396,0.4761,0.3932 T0.4788,0.3876 L0.4788,0.31 Q0.4788,0.3062,0.4756,0.3039 T0.4691,0.3016 Z M0.4691,0.4081 L0.379,0.4081 L0.379,0.4857 L0.4691,0.4857 L0.4691,0.4081 Z M0.4691,0.5059 L0.379,0.5059 L0.379,0.5835 L0.4691,0.5835 L0.4691,0.5059 Z M0.4593,0.6149 L0.4593,0.6758 L0.3887,0.6758 L0.3887,0.6149 L0.4593,0.6149 Z M0.4691,0.5982 L0.379,0.5982 Q0.3746,0.5982,0.3719,0.6009 T0.3692,0.6065 L0.3692,0.6841 Q0.3692,0.6879,0.3724,0.6902 T0.379,0.6925 L0.4691,0.6925 Q0.4735,0.6925,0.4761,0.6898 T0.4788,0.6841 L0.4788,0.6065 Q0.4788,0.6028,0.4756,0.6005 T0.4691,0.5982 Z M0.5938,0.1137 L0.5037,0.1137 L0.5037,0.1909 L0.5938,0.1909 L0.5938,0.1137 Z M0.5938,0.2143 L0.5037,0.2143 L0.5037,0.2919 L0.5938,0.2919 L0.5938,0.2143 Z M0.5816,0.4186 L0.5816,0.4753 L0.5158,0.4753 L0.5158,0.4186 L0.5816,0.4186 Z M0.5938,0.3977 L0.5037,0.3977 Q0.4983,0.3977,0.4949,0.401 T0.4915,0.4081 L0.4915,0.4857 Q0.4915,0.4904,0.4954,0.4933 T0.5037,0.4962 L0.5938,0.4962 Q0.5991,0.4962,0.6025,0.4929 T0.6059,0.4857 L0.6059,0.4081 Q0.6059,0.4035,0.602,0.4006 T0.5938,0.3977 Z M0.5938,0.5059 L0.5037,0.5059 L0.5037,0.5835 L0.5938,0.5835 L0.5938,0.5059 Z M0.5913,0.7131 L0.5913,0.7865 L0.5061,0.7865 L0.5061,0.7131 L0.5913,0.7131 Z M0.5938,0.7089 L0.5037,0.7089 Q0.5012,0.7089,0.5012,0.711 L0.5012,0.7886 Q0.5012,0.7907,0.5037,0.7907 L0.5938,0.7907 Q0.5962,0.7907,0.5962,0.7886 L0.5962,0.711 Q0.5962,0.7089,0.5938,0.7089 Z M0.7311,0.1137 L0.641,0.1137 L0.641,0.1909 L0.7311,0.1909 L0.7311,0.1137 Z M0.7311,0.2143 L0.641,0.2143 L0.641,0.2919 L0.7311,0.2919 L0.7311,0.2143 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.31 L0.641,0.31 L0.641,0.3876 L0.7311,0.3876 L0.7311,0.31 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.4081 L0.641,0.4081 L0.641,0.4857 L0.7311,0.4857 L0.7311,0.4081 Z M0.7311,0.5059 L0.641,0.5059 L0.641,0.5835 L0.7311,0.5835 L0.7311,0.5059 Z M0.7311,0.711 L0.641,0.711 L0.641,0.7886 L0.7311,0.7886 L0.7311,0.711 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.8626,0.1137 L0.7725,0.1137 L0.7725,0.1909 L0.8626,0.1909 L0.8626,0.1137 Z M0.8626,0.2143 L0.7725,0.2143 L0.7725,0.2919 L0.8626,0.2919 L0.8626,0.2143 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.31 L0.7725,0.31 L0.7725,0.3876 L0.8626,0.3876 L0.8626,0.31 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.4081 L0.7725,0.4081 L0.7725,0.4857 L0.8626,0.4857 L0.8626,0.4081 Z M0.8626,0.5059 L0.7725,0.5059 L0.7725,0.5835 L0.8626,0.5835 L0.8626,0.5059 Z M0.8626,0.6065 L0.7725,0.6065 L0.7725,0.6841 L0.8626,0.6841 L0.8626,0.6065 Z M0.8626,0.711 L0.7725,0.711 L0.7725,0.7886 L0.8626,0.7886 L0.8626,0.711 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M1,0.1137 L0.9099,0.1137 L0.9099,0.1909 L1,0.1909 L1,0.1137 Z M1,0.2143 L0.9099,0.2143 L0.9099,0.2919 L1,0.2919 L1,0.2143 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.31 L0.9099,0.31 L0.9099,0.3876 L1,0.3876 L1,0.31 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.4081 L0.9099,0.4081 L0.9099,0.4857 L1,0.4857 L1,0.4081 Z M1,0.5059 L0.9099,0.5059 L0.9099,0.5835 L1,0.5835 L1,0.5059 Z M1,0.6065 L0.9099,0.6065 L0.9099,0.6841 L1,0.6841 L1,0.6065 Z M1,0.711 L0.9099,0.711 L0.9099,0.7886 L1,0.7886 L1,0.711 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z",type:0}},"\uE0C6":{type:5,data:{d:"M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0.8574,0.3217 L0.8574,0.4098 L0.9691,0.4098 L0.9691,0.3217 L0.8574,0.3217 Z M0.8419,0.2978 L0.9846,0.2978 Q0.9892,0.2978,0.9928,0.2997 T0.9982,0.3043 T1,0.31 L1,0.4216 Q1,0.427,0.9951,0.4304 T0.9846,0.4337 L0.8419,0.4337 Q0.8352,0.4337,0.8308,0.4299 T0.8265,0.4216 L0.8265,0.31 Q0.8265,0.3062,0.829,0.3035 T0.835,0.2993 T0.8419,0.2978 Z M0.8574,0.888 L0.8574,0.9757 L0.9691,0.9757 L0.9691,0.888 L0.8574,0.888 Z M0.8419,0.8637 L0.9846,0.8637 Q0.9892,0.8637,0.9928,0.8658 T0.9982,0.8706 T1,0.8758 L1,0.9878 Q1,0.9929,0.9951,0.9964 T0.9846,1 L0.8419,1 Q0.8352,1,0.8308,0.996 T0.8265,0.9878 L0.8265,0.8758 Q0.8265,0.8708,0.8314,0.8672 T0.8419,0.8637 Z M0.6509,0.169 L0.6509,0.2706 L0.7806,0.2706 L0.7806,0.169 L0.6509,0.169 Z M0.6442,0.159 L0.7868,0.159 Q0.7899,0.159,0.7917,0.1604 T0.7935,0.164 L0.7935,0.2756 Q0.7935,0.2781,0.7915,0.2796 T0.7868,0.281 L0.6442,0.281 Q0.6416,0.281,0.6395,0.2794 T0.6375,0.2756 L0.6375,0.164 Q0.6375,0.1619,0.6398,0.1604 T0.6442,0.159 Z M0.6632,0.6044 L0.6632,0.6858 L0.7678,0.6858 L0.7678,0.6044 L0.6632,0.6044 Z M0.6442,0.5742 L0.7868,0.5742 Q0.7951,0.5742,0.8007,0.5791 T0.8064,0.5893 L0.8064,0.7013 Q0.8064,0.7076,0.8002,0.712 T0.7868,0.7164 L0.6442,0.7164 Q0.6359,0.7164,0.6305,0.7114 T0.6251,0.7013 L0.6251,0.5893 Q0.6251,0.5847,0.6282,0.5812 T0.6357,0.5759 T0.6442,0.5742 Z M0.4264,0.164 L0.5695,0.164 L0.5695,0.2756 L0.4264,0.2756 L0.4264,0.164 Z M0.4325,0.315 L0.4325,0.4165 L0.5628,0.4165 L0.5628,0.315 L0.4325,0.315 Z M0.4264,0.3049 L0.5695,0.3049 Q0.5721,0.3049,0.5739,0.3064 T0.5757,0.31 L0.5757,0.4216 Q0.5757,0.4237,0.5736,0.4251 T0.5695,0.4266 L0.4264,0.4266 Q0.4238,0.4266,0.422,0.4251 T0.4202,0.4216 L0.4202,0.31 Q0.4202,0.3087,0.4207,0.3077 T0.4222,0.306 T0.4243,0.3052 T0.4264,0.3049 Z M0.4264,0.4476 L0.5695,0.4476 L0.5695,0.5596 L0.4264,0.5596 L0.4264,0.4476 Z M0.4392,0.7408 L0.4392,0.8326 L0.5561,0.8326 L0.5561,0.7408 L0.4392,0.7408 Z M0.4264,0.7206 L0.5695,0.7206 Q0.5747,0.7206,0.5783,0.724 T0.5819,0.7307 L0.5819,0.8427 Q0.5819,0.8469,0.5778,0.8498 T0.5695,0.8528 L0.4264,0.8528 Q0.4207,0.8528,0.4171,0.8496 T0.4135,0.8427 L0.4135,0.7307 Q0.4135,0.7265,0.4176,0.7236 T0.4264,0.7206 Z M0.2178,0.164 L0.3605,0.164 L0.3605,0.2756 L0.2178,0.2756 L0.2178,0.164 Z M0.2178,0.31 L0.3605,0.31 L0.3605,0.4216 L0.2178,0.4216 L0.2178,0.31 Z M0.2178,0.5893 L0.3605,0.5893 L0.3605,0.7013 L0.2178,0.7013 L0.2178,0.5893 Z M0.2178,0.7307 L0.3605,0.7307 L0.3605,0.8427 L0.2178,0.8427 L0.2178,0.7307 Z M0.2178,0.8758 L0.3605,0.8758 L0.3605,0.9878 L0.2178,0.9878 L0.2178,0.8758 Z M0,0.164 L0.1432,0.164 L0.1432,0.2756 L0,0.2756 L0,0.164 Z M0,0.31 L0.1432,0.31 L0.1432,0.4216 L0,0.4216 L0,0.31 Z M0,0.4476 L0.1432,0.4476 L0.1432,0.5596 L0,0.5596 L0,0.4476 Z M0,0.5893 L0.1432,0.5893 L0.1432,0.7013 L0,0.7013 L0,0.5893 Z M0,0.7307 L0.1432,0.7307 L0.1432,0.8427 L0,0.8427 L0,0.7307 Z M0,0.8758 L0.1432,0.8758 L0.1432,0.9878 L0,0.9878 L0,0.8758 Z",type:0}},"\uE0C7":{type:5,data:{d:"M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M0.1432,0.3217 L0.1432,0.4098 L0.0309,0.4098 L0.0309,0.3217 L0.1432,0.3217 Z M0.1586,0.2978 L0.0154,0.2978 Q0.0088,0.2978,0.0044,0.3016 T0,0.31 L0,0.4216 Q0,0.427,0.0049,0.4304 T0.0154,0.4337 L0.1586,0.4337 Q0.1648,0.4337,0.1694,0.4299 T0.174,0.4216 L0.174,0.31 Q0.174,0.3062,0.1715,0.3035 T0.1653,0.2993 T0.1586,0.2978 Z M0.1432,0.888 L0.1432,0.9757 L0.0309,0.9757 L0.0309,0.888 L0.1432,0.888 Z M0.1586,0.8637 L0.0154,0.8637 Q0.0108,0.8637,0.0072,0.8658 T0.0018,0.8706 T0,0.8758 L0,0.9878 Q0,0.9929,0.0049,0.9964 T0.0154,1 L0.1586,1 Q0.1648,1,0.1694,0.996 T0.174,0.9878 L0.174,0.8758 Q0.174,0.8725,0.1715,0.8695 T0.1653,0.8651 T0.1586,0.8637 Z M0.3496,0.169 L0.3496,0.2706 L0.2194,0.2706 L0.2194,0.169 L0.3496,0.169 Z M0.3563,0.159 L0.2132,0.159 Q0.2106,0.159,0.2088,0.1604 T0.207,0.164 L0.207,0.2756 Q0.207,0.2781,0.2091,0.2796 T0.2132,0.281 L0.3563,0.281 Q0.3589,0.281,0.3607,0.2794 T0.3625,0.2756 L0.3625,0.164 Q0.3625,0.1619,0.3605,0.1604 T0.3563,0.159 Z M0.3368,0.6044 L0.3368,0.6858 L0.2327,0.6858 L0.2327,0.6044 L0.3368,0.6044 Z M0.3563,0.5742 L0.2132,0.5742 Q0.2049,0.5742,0.1993,0.5791 T0.1936,0.5893 L0.1936,0.7013 Q0.1936,0.7076,0.2001,0.712 T0.2132,0.7164 L0.3563,0.7164 Q0.3641,0.7164,0.3697,0.7114 T0.3754,0.7013 L0.3754,0.5893 Q0.3754,0.5847,0.3723,0.5812 T0.3648,0.5759 T0.3563,0.5742 Z M0.5736,0.164 L0.431,0.164 L0.431,0.2756 L0.5736,0.2756 L0.5736,0.164 Z M0.5675,0.315 L0.5675,0.4165 L0.4377,0.4165 L0.4377,0.315 L0.5675,0.315 Z M0.5736,0.3049 L0.431,0.3049 Q0.4284,0.3049,0.4264,0.3064 T0.4243,0.31 L0.4243,0.4216 Q0.4243,0.4237,0.4266,0.4251 T0.431,0.4266 L0.5736,0.4266 Q0.5767,0.4266,0.5785,0.4251 T0.5803,0.4216 L0.5803,0.31 Q0.5803,0.3087,0.5798,0.3077 T0.5783,0.306 T0.5762,0.3052 T0.5736,0.3049 Z M0.5736,0.4476 L0.431,0.4476 L0.431,0.5596 L0.5736,0.5596 L0.5736,0.4476 Z M0.5613,0.7408 L0.5613,0.8326 L0.4439,0.8326 L0.4439,0.7408 L0.5613,0.7408 Z M0.5736,0.7206 L0.431,0.7206 Q0.4253,0.7206,0.4217,0.724 T0.4181,0.7307 L0.4181,0.8427 Q0.4181,0.8469,0.4222,0.8498 T0.431,0.8528 L0.5736,0.8528 Q0.5778,0.8528,0.5808,0.8511 T0.5855,0.8471 T0.587,0.8427 L0.587,0.7307 Q0.587,0.7265,0.5826,0.7236 T0.5736,0.7206 Z M0.7827,0.164 L0.6395,0.164 L0.6395,0.2756 L0.7827,0.2756 L0.7827,0.164 Z M0.7827,0.31 L0.6395,0.31 L0.6395,0.4216 L0.7827,0.4216 L0.7827,0.31 Z M0.7827,0.5893 L0.6395,0.5893 L0.6395,0.7013 L0.7827,0.7013 L0.7827,0.5893 Z M0.7827,0.7307 L0.6395,0.7307 L0.6395,0.8427 L0.7827,0.8427 L0.7827,0.7307 Z M0.7827,0.8758 L0.6395,0.8758 L0.6395,0.9878 L0.7827,0.9878 L0.7827,0.8758 Z M1,0.164 L0.8574,0.164 L0.8574,0.2756 L1,0.2756 L1,0.164 Z M1,0.31 L0.8574,0.31 L0.8574,0.4216 L1,0.4216 L1,0.31 Z M1,0.4476 L0.8574,0.4476 L0.8574,0.5596 L1,0.5596 L1,0.4476 Z M1,0.5893 L0.8574,0.5893 L0.8574,0.7013 L1,0.7013 L1,0.5893 Z M1,0.7307 L0.8574,0.7307 L0.8574,0.8427 L1,0.8427 L1,0.7307 Z M1,0.8758 L0.8574,0.8758 L0.8574,0.9878 L1,0.9878 L1,0.8758 Z",type:0}},"\uE0C8":{type:5,data:{d:"M0.0008,0.9979 Q0.0008,1,0.0032,1 Q0.0482,1,0.0602,0.9975 Q0.0667,0.9963,0.0847,0.9917 T0.1084,0.9859 Q0.1124,0.9851,0.1221,0.9851 L0.1253,0.9851 L0.1285,0.9851 Q0.1518,0.9851,0.1655,0.9809 Q0.1695,0.9801,0.1731,0.9788 T0.1791,0.9766 T0.1839,0.9747 T0.1888,0.9732 L0.1936,0.972 T0.1988,0.9712 T0.2048,0.971 L0.2096,0.971 Q0.2201,0.9714,0.2233,0.9714 T0.2345,0.9693 Q0.2386,0.9685,0.2502,0.9674 T0.2715,0.966 L0.2811,0.9656 Q0.2916,0.9647,0.2916,0.9573 Q0.2916,0.954,0.2892,0.9515 T0.2819,0.9486 Q0.2755,0.9482,0.2683,0.9482 Q0.2643,0.9482,0.2582,0.9484 T0.2498,0.9486 Q0.2426,0.9486,0.2402,0.9473 Q0.2386,0.9469,0.2317,0.943 T0.2161,0.937 Q0.2104,0.9357,0.1992,0.933 T0.1831,0.9291 Q0.1807,0.9287,0.1783,0.9285 T0.1739,0.928 T0.1703,0.9276 T0.1675,0.9272 T0.1655,0.9266 T0.1639,0.9253 Q0.1598,0.9216,0.1462,0.9216 L0.143,0.9216 L0.1398,0.9216 L0.1365,0.9216 Q0.1197,0.9195,0.1197,0.9154 L0.1197,0.9154 Q0.1205,0.9121,0.1373,0.9088 T0.1703,0.9054 Q0.1791,0.9054,0.1863,0.904 T0.1984,0.9011 T0.2064,0.8992 Q0.2402,0.8967,0.2506,0.8934 Q0.2538,0.8926,0.2602,0.8899 T0.2707,0.8872 Q0.2715,0.8872,0.2731,0.8876 Q0.2795,0.8884,0.2884,0.8884 Q0.3068,0.8884,0.3092,0.8826 L0.3092,0.8797 Q0.3092,0.8772,0.3076,0.8747 T0.3044,0.8706 T0.3028,0.8681 Q0.3076,0.8656,0.3237,0.8656 Q0.3317,0.8656,0.3622,0.8623 Q0.3655,0.8623,0.3867,0.8617 T0.4217,0.8602 Q0.4241,0.8598,0.4289,0.8598 L0.4345,0.8598 L0.441,0.8598 Q0.4578,0.8598,0.4667,0.8586 Q0.4739,0.8573,0.4851,0.8567 T0.5004,0.8552 Q0.5012,0.8552,0.5108,0.855 T0.5269,0.853 T0.5333,0.8461 Q0.5333,0.8445,0.5325,0.8432 T0.5309,0.8409 T0.5289,0.8391 T0.5261,0.8378 L0.5229,0.837 T0.5185,0.8362 T0.5133,0.8355 T0.5076,0.8349 T0.502,0.8341 Q0.4932,0.8324,0.4859,0.8324 Q0.4827,0.8324,0.4787,0.8328 T0.4731,0.8333 Q0.4707,0.8333,0.4683,0.8324 Q0.4482,0.825,0.4394,0.825 Q0.4369,0.825,0.4345,0.8254 Q0.4225,0.827,0.4153,0.827 Q0.4088,0.827,0.4064,0.8258 Q0.3976,0.8204,0.3751,0.8204 Q0.3703,0.8204,0.3667,0.8214 T0.3622,0.8225 Q0.3598,0.8225,0.3558,0.82 Q0.351,0.8175,0.3402,0.8167 T0.3177,0.8156 T0.3028,0.8146 L0.2956,0.8121 T0.2871,0.8094 T0.2771,0.8073 T0.2635,0.8063 Q0.261,0.8063,0.2586,0.8067 Q0.2378,0.8071,0.2273,0.8071 Q0.2072,0.8071,0.2024,0.8051 Q0.1976,0.8034,0.1932,0.8026 T0.1867,0.8013 T0.1847,0.8001 L0.1847,0.7993 Q0.1855,0.7984,0.1855,0.7978 T0.1859,0.7966 T0.1867,0.7959 T0.188,0.7955 T0.1896,0.7951 T0.1916,0.7949 T0.1944,0.7945 T0.1984,0.7941 T0.2032,0.7939 Q0.212,0.7926,0.2325,0.7918 T0.2562,0.7905 Q0.2691,0.7893,0.2787,0.7847 Q0.2835,0.7827,0.2968,0.7791 T0.3149,0.7756 Q0.3189,0.7756,0.3305,0.7733 T0.3446,0.771 L0.3454,0.771 Q0.3462,0.771,0.3498,0.7721 T0.3574,0.774 T0.3655,0.7748 Q0.3703,0.7748,0.3743,0.7731 T0.3823,0.7708 T0.3916,0.77 T0.3992,0.7694 Q0.4008,0.7694,0.4076,0.7688 T0.4205,0.7675 L0.4305,0.7665 Q0.4345,0.7657,0.4402,0.7617 T0.4458,0.7545 Q0.4458,0.7503,0.4353,0.7487 Q0.4297,0.7478,0.4209,0.7462 T0.4044,0.7433 T0.3904,0.7416 L0.3847,0.7416 Q0.3807,0.7416,0.3747,0.7422 T0.3663,0.7428 T0.3606,0.7424 Q0.3582,0.742,0.3562,0.7418 T0.3522,0.7412 T0.3482,0.7406 T0.3446,0.7401 T0.341,0.7397 T0.3373,0.7393 T0.3341,0.7391 L0.3293,0.7391 Q0.3277,0.7395,0.3253,0.7395 Q0.3205,0.7395,0.3052,0.7387 T0.2835,0.7379 Q0.2755,0.7379,0.253,0.7325 Q0.2506,0.7316,0.2462,0.731 T0.2382,0.7296 T0.2305,0.7271 T0.2181,0.7234 T0.2048,0.7196 T0.2,0.7155 Q0.2,0.7142,0.2016,0.713 Q0.208,0.7059,0.2285,0.6978 T0.2618,0.6898 Q0.2739,0.6898,0.2831,0.6848 T0.2956,0.6794 Q0.3028,0.6786,0.3289,0.6765 T0.3566,0.674 Q0.3582,0.674,0.3855,0.6723 T0.4406,0.6688 T0.4755,0.6653 Q0.5004,0.6607,0.5124,0.6599 L0.5165,0.6599 Q0.5213,0.6599,0.5277,0.6605 T0.5373,0.6611 Q0.543,0.6611,0.5494,0.6599 Q0.592,0.6524,0.6,0.6524 Q0.6064,0.6524,0.61,0.6499 T0.6161,0.6474 Q0.6177,0.6474,0.6261,0.6495 T0.6418,0.6516 L0.6482,0.6516 Q0.653,0.6512,0.6651,0.6506 T0.6876,0.6493 T0.7084,0.6477 T0.7229,0.645 Q0.7269,0.6437,0.7333,0.6437 Q0.7373,0.6437,0.7458,0.6443 T0.7574,0.645 Q0.7614,0.645,0.7631,0.6445 T0.7655,0.6441 Q0.7671,0.6441,0.7723,0.6448 T0.7823,0.6454 Q0.788,0.6454,0.7952,0.6445 Q0.8233,0.6408,0.8723,0.6367 Q0.9012,0.6342,0.9092,0.6342 L0.9165,0.6342 L0.9205,0.6342 Q0.9277,0.6342,0.9382,0.6323 T0.9526,0.6304 Q0.9534,0.6304,0.9594,0.6307 T0.9695,0.6309 Q0.9976,0.6309,0.9992,0.6234 Q1,0.6201,1,0.618 Q1,0.6089,0.9775,0.608 Q0.9703,0.6076,0.9582,0.6076 Q0.9518,0.6076,0.9394,0.6078 T0.9213,0.608 Q0.9036,0.608,0.8972,0.6072 Q0.894,0.6068,0.8871,0.6058 T0.8751,0.6039 T0.8627,0.6024 T0.8506,0.6018 L0.8474,0.6018 Q0.841,0.6022,0.8281,0.6041 T0.8112,0.606 Q0.8096,0.606,0.808,0.6056 Q0.7783,0.6002,0.7647,0.6002 Q0.7598,0.6002,0.7454,0.6006 T0.7261,0.601 Q0.7221,0.601,0.7145,0.6022 T0.7036,0.6035 Q0.6996,0.6035,0.6964,0.6022 Q0.6723,0.5902,0.6442,0.5902 Q0.6426,0.5902,0.6386,0.5904 T0.6337,0.5906 Q0.6273,0.5906,0.6249,0.5894 L0.6177,0.5856 T0.6116,0.5838 T0.6016,0.5825 T0.5855,0.5823 Q0.5719,0.5823,0.5574,0.5798 T0.5373,0.5774 L0.5341,0.5774 Q0.5293,0.5778,0.5213,0.5786 T0.51,0.5794 Q0.5036,0.5794,0.4988,0.5769 Q0.4932,0.574,0.4771,0.574 Q0.4723,0.574,0.4631,0.5745 T0.4498,0.5749 Q0.4418,0.5749,0.4394,0.5736 Q0.4353,0.5724,0.4305,0.5715 T0.4225,0.5707 T0.4145,0.5705 T0.4056,0.5699 Q0.4008,0.5691,0.398,0.5689 T0.394,0.5689 T0.3908,0.5686 T0.3855,0.5674 Q0.3831,0.567,0.3811,0.5662 T0.3779,0.5645 T0.3743,0.563 T0.3695,0.5624 Q0.3655,0.5624,0.3594,0.5635 T0.3494,0.5645 T0.3406,0.5635 T0.3325,0.5624 Q0.3309,0.5624,0.3301,0.5628 L0.3141,0.5628 Q0.2635,0.5628,0.2506,0.5612 Q0.2474,0.5608,0.2434,0.5608 Q0.2402,0.5608,0.2349,0.561 T0.2273,0.5612 Q0.2209,0.5612,0.2177,0.5595 Q0.2145,0.557,0.2145,0.5558 Q0.2169,0.5537,0.2345,0.5521 Q0.2876,0.5475,0.3028,0.5425 Q0.3068,0.5413,0.3149,0.5396 T0.3309,0.5367 T0.3478,0.5338 T0.3606,0.5309 Q0.3631,0.5305,0.3755,0.5259 T0.3968,0.5214 Q0.3992,0.5214,0.4024,0.5218 T0.4096,0.5222 Q0.4161,0.5222,0.4213,0.5209 T0.4313,0.5185 T0.4402,0.5172 Q0.4418,0.5168,0.447,0.5168 L0.4558,0.5168 T0.4639,0.5162 T0.4707,0.5141 T0.4731,0.5102 Q0.4731,0.5089,0.4723,0.5081 Q0.4699,0.5019,0.4627,0.4994 T0.4369,0.4965 Q0.4273,0.4961,0.4193,0.4946 T0.4048,0.4915 T0.3952,0.4894 Q0.392,0.4886,0.388,0.4886 Q0.3847,0.4886,0.3775,0.4892 T0.3647,0.4898 Q0.3598,0.4898,0.355,0.4894 Q0.3165,0.4861,0.3141,0.4853 Q0.2779,0.4774,0.2715,0.4774 Q0.2699,0.4774,0.2683,0.4776 T0.2627,0.4778 Q0.2498,0.4778,0.2281,0.4762 Q0.2241,0.4749,0.2233,0.4737 Q0.2249,0.472,0.2321,0.4708 Q0.2402,0.4695,0.2554,0.4695 L0.2675,0.4695 L0.2795,0.4695 Q0.294,0.4695,0.2996,0.4679 Q0.3141,0.4629,0.3373,0.4616 Q0.3414,0.4612,0.3466,0.4606 T0.3582,0.4589 T0.3687,0.4562 T0.3727,0.4525 Q0.3727,0.4509,0.3703,0.4492 Q0.3639,0.4455,0.3474,0.4419 T0.3213,0.4384 L0.3157,0.4384 L0.31,0.4384 Q0.294,0.4384,0.2859,0.4363 Q0.2795,0.4347,0.2691,0.4347 L0.2618,0.4347 L0.2546,0.4347 Q0.2458,0.4347,0.2394,0.4338 Q0.2257,0.4318,0.2193,0.4303 T0.2092,0.4266 T0.2052,0.4224 T0.2024,0.4154 T0.196,0.4052 Q0.1912,0.3994,0.1867,0.3949 T0.1807,0.3884 T0.1791,0.3849 Q0.1791,0.3824,0.1839,0.3745 Q0.1871,0.3687,0.1944,0.3637 T0.2072,0.3561 T0.2221,0.3501 T0.2321,0.3463 Q0.2353,0.3455,0.241,0.3445 T0.2522,0.3428 T0.2639,0.3411 T0.2731,0.3384 T0.2956,0.3351 T0.3197,0.3326 Q0.3213,0.3322,0.3237,0.3322 T0.3325,0.3331 T0.3414,0.3339 Q0.3478,0.3339,0.3518,0.3314 Q0.3606,0.3264,0.3703,0.3264 Q0.3775,0.3264,0.3847,0.3293 Q0.3888,0.331,0.396,0.331 Q0.4024,0.331,0.4116,0.3295 T0.4265,0.3266 T0.4414,0.3227 T0.4514,0.3202 Q0.4578,0.3181,0.4839,0.3152 T0.5112,0.3123 T0.5177,0.3119 T0.5285,0.3111 T0.5398,0.3096 T0.549,0.3065 T0.5526,0.3015 Q0.5526,0.2999,0.5518,0.2982 Q0.547,0.2903,0.5386,0.2883 T0.5165,0.2862 Q0.5116,0.2862,0.5056,0.2866 T0.4972,0.287 Q0.4884,0.287,0.4787,0.2833 Q0.4594,0.2758,0.4265,0.2758 Q0.4169,0.2758,0.4129,0.2766 Q0.4112,0.2771,0.4104,0.2771 Q0.4088,0.2771,0.4056,0.2748 T0.3968,0.2721 Q0.3695,0.2696,0.359,0.2659 Q0.355,0.2646,0.351,0.2646 T0.3426,0.2661 T0.3365,0.2675 T0.3333,0.2659 Q0.3277,0.2605,0.3116,0.2553 T0.2859,0.2501 L0.2843,0.2501 L0.2819,0.2501 Q0.2779,0.2501,0.2723,0.2493 T0.2586,0.2472 T0.2474,0.2455 Q0.1799,0.236,0.1719,0.236 Q0.1663,0.236,0.1606,0.235 T0.1502,0.2316 T0.1454,0.2265 Q0.1454,0.2223,0.1558,0.2173 Q0.1679,0.2115,0.1859,0.2092 T0.2185,0.207 T0.2353,0.2057 Q0.2369,0.2049,0.2502,0.2041 T0.2799,0.2022 T0.302,0.2007 Q0.3084,0.1999,0.3245,0.1954 T0.347,0.1908 Q0.3502,0.1908,0.3534,0.1916 Q0.3663,0.197,0.388,0.197 Q0.404,0.197,0.4088,0.1929 Q0.4096,0.192,0.4108,0.192 T0.4177,0.1945 T0.4277,0.197 T0.4369,0.1949 Q0.4442,0.1908,0.4843,0.1875 Q0.4892,0.1871,0.4968,0.1839 T0.5084,0.1808 L0.5108,0.1808 Q0.5213,0.1825,0.5454,0.1825 Q0.5823,0.1825,0.5992,0.1779 Q0.6096,0.1746,0.6217,0.1746 Q0.6249,0.1746,0.6309,0.1748 T0.6394,0.175 Q0.6434,0.175,0.6466,0.1746 Q0.6474,0.1746,0.6594,0.1738 T0.6787,0.1713 T0.6892,0.1659 Q0.6924,0.1634,0.6924,0.1593 Q0.6924,0.1547,0.6888,0.151 T0.6795,0.1472 Q0.6779,0.1472,0.6763,0.1477 Q0.6699,0.1493,0.6667,0.1493 Q0.661,0.1493,0.6506,0.1456 Q0.6329,0.1394,0.6129,0.1394 Q0.6048,0.1394,0.5992,0.1377 T0.5888,0.136 T0.5803,0.1377 T0.5751,0.1394 Q0.5711,0.1394,0.5639,0.1369 Q0.5365,0.1273,0.5116,0.1273 Q0.4876,0.1273,0.4667,0.1253 Q0.4627,0.1248,0.4542,0.1211 T0.4337,0.1174 L0.4305,0.1174 Q0.4217,0.1178,0.4153,0.119 T0.408,0.1203 Q0.4056,0.1203,0.4,0.117 Q0.3976,0.1153,0.396,0.1136 T0.3932,0.1112 T0.39,0.1099 T0.3847,0.1095 Q0.3799,0.1095,0.3687,0.1103 Q0.355,0.1112,0.3434,0.1141 T0.3301,0.117 Q0.3261,0.117,0.3229,0.1145 Q0.3181,0.1116,0.3052,0.1087 T0.2787,0.1043 T0.2546,0.1029 Q0.2506,0.1029,0.2474,0.1033 Q0.2418,0.1037,0.2349,0.1054 T0.2249,0.107 Q0.2225,0.107,0.2193,0.1066 Q0.2024,0.1024,0.1863,0.1024 Q0.1823,0.1024,0.1562,0.0971 T0.1269,0.0917 T0.1161,0.0896 T0.106,0.0854 Q0.1076,0.0846,0.11,0.0842 Q0.1173,0.0821,0.1261,0.0821 Q0.1301,0.0821,0.1369,0.0825 T0.1462,0.083 Q0.1494,0.083,0.151,0.0825 T0.1831,0.0813 T0.2201,0.0784 T0.243,0.074 T0.2667,0.0718 Q0.2707,0.0718,0.2755,0.0724 T0.2843,0.073 T0.2936,0.0724 T0.3024,0.0705 T0.3072,0.068 T0.3092,0.0657 T0.3108,0.0647 Q0.3116,0.0643,0.3133,0.0643 L0.3157,0.0643 L0.3181,0.0643 Q0.3446,0.0643,0.3446,0.0556 T0.3205,0.0469 L0.3189,0.0469 Q0.3157,0.0469,0.3157,0.0465 Q0.3084,0.0427,0.2835,0.0386 Q0.2739,0.0369,0.2675,0.0342 T0.2538,0.0299 Q0.249,0.029,0.245,0.029 T0.2378,0.0303 T0.2321,0.0315 Q0.2305,0.0315,0.2273,0.0307 Q0.2201,0.0286,0.2004,0.0272 T0.1775,0.0245 Q0.1735,0.0228,0.1663,0.0226 T0.1522,0.0197 T0.1345,0.0145 T0.1124,0.0079 Q0.0996,0.0033,0.0671,0.0044 T0.0297,0.0041 Q0.0169,0,0.0024,0.0017 Q0,0.0021,0,0.0037 Z M0.0064,0.9954 L0.0056,0.0058 Q0.0177,0.005,0.0281,0.0083 Q0.0345,0.01,0.0675,0.0089 T0.1108,0.012 Q0.1221,0.0162,0.1329,0.0187 T0.1498,0.0236 T0.1606,0.0268 T0.1691,0.0274 T0.1759,0.0286 Q0.1807,0.0303,0.2,0.0315 T0.2257,0.0348 Q0.2305,0.0361,0.2337,0.0361 Q0.2361,0.0361,0.2398,0.0348 T0.2466,0.0336 Q0.249,0.0336,0.2522,0.034 Q0.2586,0.0353,0.2655,0.0382 T0.2827,0.0427 Q0.3068,0.0469,0.3124,0.0502 Q0.3157,0.0523,0.3237,0.0523 L0.3277,0.0523 L0.3309,0.0523 Q0.3398,0.0523,0.3398,0.0556 Q0.3398,0.0581,0.3341,0.0587 T0.3205,0.0593 T0.3092,0.0603 T0.3036,0.0643 T0.2932,0.068 Q0.2884,0.0684,0.2843,0.0684 Q0.2811,0.0684,0.2763,0.0678 T0.2667,0.0672 Q0.2586,0.0672,0.2422,0.0697 T0.2177,0.0747 Q0.2137,0.0759,0.1831,0.0767 T0.1494,0.0784 L0.1474,0.0784 T0.1398,0.078 T0.1285,0.0776 Q0.1173,0.0776,0.1084,0.08 Q0.1004,0.0817,0.1004,0.0846 Q0.1004,0.0867,0.104,0.0888 T0.1124,0.0923 T0.1213,0.0948 T0.1269,0.0958 T0.155,0.1014 T0.1863,0.107 Q0.2016,0.107,0.2185,0.1107 Q0.2217,0.1116,0.2257,0.1116 Q0.2289,0.1116,0.2365,0.1099 T0.2482,0.1074 L0.2538,0.1074 Q0.2683,0.1074,0.2912,0.1107 T0.3197,0.1182 Q0.3245,0.1215,0.3301,0.1215 Q0.3333,0.1215,0.3454,0.1184 T0.3687,0.1145 Q0.3735,0.1141,0.3779,0.1139 T0.3843,0.1134 T0.3871,0.1132 Q0.3896,0.1132,0.39,0.1136 T0.392,0.1161 T0.3968,0.1203 Q0.404,0.1248,0.408,0.1248 Q0.4096,0.1248,0.4165,0.1234 T0.4305,0.1215 L0.4337,0.1215 Q0.4442,0.1215,0.4518,0.1251 T0.4659,0.1294 Q0.4876,0.1319,0.5116,0.1319 T0.5622,0.141 Q0.5703,0.1439,0.5751,0.1439 Q0.5791,0.1439,0.5831,0.1423 T0.5888,0.1406 Q0.592,0.1406,0.5944,0.1412 T0.6012,0.1427 T0.6129,0.1435 Q0.6313,0.1435,0.649,0.1497 Q0.6602,0.1535,0.6667,0.1535 Q0.6715,0.1535,0.6779,0.1522 Q0.6787,0.1518,0.6795,0.1518 Q0.6827,0.1518,0.6847,0.1541 T0.6867,0.1593 Q0.6867,0.1618,0.6851,0.1634 Q0.6835,0.1655,0.6775,0.1667 T0.6598,0.169 T0.6458,0.1705 T0.6402,0.1709 Q0.6378,0.1709,0.6321,0.1705 T0.6225,0.1701 Q0.6096,0.1701,0.5968,0.1738 Q0.5823,0.1779,0.5446,0.1779 Q0.5205,0.1779,0.5116,0.1767 Q0.51,0.1763,0.5084,0.1763 Q0.5028,0.1763,0.4944,0.1796 T0.4835,0.1829 L0.4771,0.1833 T0.4659,0.1844 L0.4546,0.1858 T0.443,0.1881 T0.4337,0.1912 Q0.4321,0.1916,0.4305,0.1916 Q0.4273,0.1916,0.4209,0.1895 T0.412,0.1875 Q0.408,0.1875,0.4056,0.19 Q0.4024,0.1925,0.388,0.1925 Q0.3663,0.1925,0.3558,0.1879 Q0.3518,0.1862,0.3462,0.1862 Q0.3373,0.1862,0.3213,0.191 T0.3012,0.1962 Q0.2964,0.1966,0.2799,0.1976 T0.2494,0.1997 T0.2313,0.2024 L0.2313,0.2024 L0.2293,0.2024 L0.2261,0.2024 L0.2217,0.2024 Q0.204,0.2024,0.1851,0.2047 T0.1526,0.2136 Q0.1406,0.2198,0.1406,0.226 Q0.1406,0.2319,0.1518,0.2362 T0.1719,0.2406 Q0.1791,0.2406,0.2466,0.2497 Q0.2498,0.2501,0.2574,0.2516 T0.2711,0.2538 T0.2819,0.2547 L0.2851,0.2547 Q0.2851,0.2543,0.2859,0.2543 Q0.294,0.2543,0.3096,0.2592 T0.3285,0.2684 Q0.3317,0.2721,0.3373,0.2721 Q0.3406,0.2721,0.3462,0.2708 T0.3542,0.2696 Q0.3558,0.2696,0.3574,0.27 Q0.3679,0.2737,0.3968,0.2762 Q0.3984,0.2766,0.4004,0.2779 L0.4044,0.2804 T0.4096,0.2816 Q0.412,0.2816,0.4145,0.2808 Q0.4177,0.2804,0.4249,0.2804 Q0.4586,0.2804,0.4763,0.287 Q0.4867,0.2912,0.4972,0.2912 Q0.5004,0.2912,0.5064,0.2908 T0.5165,0.2903 Q0.5293,0.2903,0.5361,0.2922 T0.547,0.3003 L0.547,0.3011 Q0.547,0.3036,0.5414,0.3049 T0.5249,0.3067 T0.51,0.3082 Q0.5092,0.3082,0.4831,0.3111 T0.4498,0.3161 Q0.408,0.3264,0.3952,0.3264 Q0.3896,0.3264,0.3863,0.3252 Q0.3783,0.3223,0.3703,0.3223 Q0.359,0.3223,0.3494,0.3277 Q0.347,0.3293,0.343,0.3293 Q0.3414,0.3293,0.3353,0.3285 T0.3253,0.3277 T0.3181,0.3285 Q0.3149,0.3289,0.2952,0.3306 T0.2699,0.3347 Q0.2675,0.3364,0.2598,0.3372 T0.2434,0.3395 T0.2297,0.3426 L0.2205,0.3461 T0.2048,0.3523 T0.1908,0.3606 T0.1791,0.3725 Q0.1743,0.3803,0.1743,0.3845 Q0.1743,0.3874,0.1763,0.3901 T0.1827,0.3976 T0.1912,0.4073 T0.198,0.4189 T0.2032,0.4276 T0.2137,0.4326 T0.2386,0.438 Q0.2458,0.4392,0.2562,0.4392 L0.2639,0.4392 L0.2699,0.4392 Q0.2795,0.4392,0.2843,0.4405 Q0.2932,0.443,0.3092,0.443 L0.3157,0.443 L0.3213,0.443 Q0.3293,0.443,0.3458,0.4463 T0.3671,0.4525 Q0.3598,0.4558,0.3373,0.4571 Q0.3124,0.4587,0.298,0.4637 Q0.294,0.465,0.2811,0.465 L0.2703,0.465 L0.2586,0.465 Q0.241,0.465,0.2305,0.4666 Q0.2185,0.4687,0.2185,0.4728 Q0.2185,0.4745,0.2205,0.4764 T0.2241,0.4791 L0.2265,0.4803 L0.2273,0.4803 Q0.2506,0.4824,0.261,0.4824 Q0.2675,0.4824,0.2699,0.482 Q0.2699,0.4815,0.2707,0.4815 Q0.2771,0.4815,0.3124,0.4898 Q0.3173,0.4907,0.3229,0.4913 T0.3386,0.4925 T0.3542,0.4936 T0.3663,0.494 Q0.3711,0.494,0.3787,0.4936 T0.3888,0.4932 Q0.392,0.4932,0.3944,0.4936 T0.4032,0.4959 T0.4181,0.499 T0.4369,0.5006 Q0.449,0.501,0.455,0.5021 T0.4639,0.5048 T0.4675,0.5093 L0.4675,0.5097 Q0.4675,0.5106,0.4663,0.511 T0.4622,0.5116 L0.4566,0.512 T0.4486,0.5124 T0.4402,0.5127 Q0.4345,0.5131,0.4257,0.5153 T0.4096,0.5176 Q0.4064,0.5176,0.4024,0.5172 L0.3968,0.5172 Q0.3863,0.5172,0.3731,0.522 T0.359,0.5268 Q0.355,0.528,0.3317,0.5321 T0.3004,0.5388 Q0.2867,0.5433,0.2337,0.5479 Q0.2096,0.55,0.2096,0.5562 Q0.2096,0.5591,0.2145,0.5628 Q0.2193,0.5662,0.2289,0.5662 Q0.2313,0.5662,0.2373,0.5657 T0.2458,0.5653 L0.2498,0.5653 Q0.2635,0.5674,0.3124,0.5674 Q0.3261,0.5674,0.3301,0.567 L0.3317,0.567 Q0.3341,0.567,0.3394,0.568 T0.3486,0.5691 Q0.3542,0.5691,0.3606,0.5678 T0.3699,0.5666 T0.3759,0.5686 T0.3839,0.5718 T0.3908,0.573 T0.3964,0.5734 T0.4048,0.5742 T0.4165,0.5751 T0.4277,0.5757 T0.4369,0.5778 Q0.4426,0.5794,0.4538,0.5794 Q0.4586,0.5794,0.4679,0.5792 T0.4811,0.579 Q0.4924,0.579,0.4956,0.5807 Q0.502,0.584,0.5108,0.584 L0.5137,0.584 T0.5173,0.5838 L0.5205,0.5834 L0.5237,0.583 L0.5269,0.5825 T0.5305,0.5821 T0.5341,0.5819 L0.5365,0.5819 Q0.5414,0.5819,0.5562,0.5842 T0.5855,0.5865 Q0.5912,0.5865,0.5948,0.5867 T0.6012,0.5869 T0.6064,0.5873 T0.61,0.5877 T0.6133,0.5886 T0.6157,0.5896 L0.6185,0.591 T0.6217,0.5931 Q0.6265,0.5952,0.6369,0.5952 L0.6418,0.5952 L0.6466,0.5952 Q0.6723,0.5952,0.6932,0.606 Q0.698,0.608,0.7044,0.608 Q0.7084,0.608,0.7161,0.6068 T0.7261,0.6056 Q0.7309,0.6056,0.7454,0.6051 T0.7647,0.6047 Q0.7775,0.6047,0.8072,0.6101 Q0.8096,0.6105,0.812,0.6105 Q0.8177,0.6105,0.8297,0.6085 T0.8474,0.606 L0.8506,0.606 Q0.8562,0.606,0.8647,0.607 T0.8831,0.6095 T0.8964,0.6118 Q0.9036,0.6122,0.9221,0.6122 L0.9406,0.6122 L0.959,0.6122 L0.9767,0.6122 Q0.9952,0.613,0.9952,0.6172 Q0.9952,0.6176,0.9944,0.6221 Q0.9936,0.6259,0.9574,0.6259 L0.955,0.6259 L0.9526,0.6259 Q0.9478,0.6259,0.9373,0.628 T0.9205,0.63 L0.9173,0.63 Q0.9133,0.6296,0.9084,0.6296 Q0.9004,0.6296,0.8715,0.6321 Q0.8233,0.6367,0.7944,0.64 Q0.7888,0.6408,0.7839,0.6408 T0.7739,0.6402 T0.7671,0.6396 Q0.7639,0.6396,0.7622,0.64 Q0.7614,0.6404,0.759,0.6404 Q0.7574,0.6404,0.749,0.6398 T0.7357,0.6392 Q0.7261,0.6392,0.7213,0.6412 Q0.7173,0.6425,0.7032,0.6437 T0.6711,0.6458 T0.6474,0.647 Q0.645,0.6474,0.6418,0.6474 Q0.6353,0.6474,0.6277,0.6454 T0.6161,0.6433 Q0.6104,0.6433,0.6072,0.6456 T0.6,0.6479 Q0.5912,0.6479,0.5486,0.6557 Q0.5422,0.657,0.5373,0.657 Q0.5349,0.657,0.5289,0.6564 T0.5173,0.6557 L0.5124,0.6557 Q0.4996,0.6562,0.4739,0.6611 Q0.4675,0.6624,0.4398,0.6645 T0.3851,0.668 T0.3558,0.6698 Q0.355,0.6698,0.3285,0.6721 T0.2948,0.6752 Q0.2892,0.6761,0.2843,0.6786 T0.2747,0.6831 T0.2618,0.6852 Q0.253,0.6852,0.2394,0.6893 T0.2141,0.6993 T0.1968,0.7105 Q0.1944,0.713,0.1944,0.7155 Q0.1944,0.7196,0.2012,0.7229 T0.2177,0.7285 T0.2281,0.7308 Q0.2321,0.7329,0.2365,0.7339 T0.245,0.7356 T0.2514,0.7366 Q0.2522,0.737,0.2554,0.7379 T0.2614,0.7393 T0.2679,0.7406 T0.2755,0.7416 T0.2835,0.742 Q0.29,0.742,0.3048,0.7428 T0.3253,0.7437 L0.3301,0.7437 L0.3333,0.7437 Q0.3341,0.7437,0.3598,0.7466 Q0.3639,0.7474,0.3671,0.7474 T0.3759,0.7466 T0.3855,0.7457 Q0.388,0.7457,0.3904,0.7462 Q0.3984,0.7466,0.4137,0.7495 T0.4349,0.7532 T0.441,0.7557 Q0.441,0.7599,0.4289,0.7619 Q0.4257,0.7628,0.4197,0.7634 T0.4072,0.7644 T0.3984,0.7652 Q0.3968,0.7652,0.3912,0.7655 T0.3811,0.7665 T0.3719,0.7694 Q0.3695,0.7702,0.3655,0.7702 T0.3546,0.7686 T0.3462,0.7665 L0.3446,0.7665 Q0.3406,0.7665,0.3293,0.769 T0.3149,0.7715 Q0.3084,0.7715,0.2952,0.7748 T0.2763,0.781 Q0.2675,0.7847,0.2554,0.7864 Q0.253,0.7864,0.2325,0.7874 T0.2024,0.7893 Q0.2008,0.7893,0.1984,0.7897 T0.1948,0.7901 T0.1916,0.7903 T0.1888,0.7908 T0.1867,0.7914 T0.1847,0.7922 L0.1831,0.793 T0.1819,0.7943 L0.1811,0.7959 T0.1799,0.7976 Q0.1791,0.7993,0.1791,0.8001 Q0.1791,0.8034,0.1831,0.8051 T0.1932,0.8078 T0.2,0.8092 Q0.2072,0.8117,0.2257,0.8117 Q0.2337,0.8117,0.2586,0.8109 L0.2635,0.8109 Q0.2707,0.8109,0.2767,0.8117 T0.2859,0.8136 T0.2936,0.8163 T0.3012,0.8187 Q0.3068,0.82,0.3277,0.8206 T0.3526,0.8237 Q0.3582,0.8266,0.3622,0.8266 Q0.3647,0.8266,0.3687,0.8258 T0.3751,0.825 Q0.396,0.825,0.404,0.8291 Q0.408,0.8316,0.4161,0.8316 Q0.4217,0.8316,0.4353,0.8295 L0.4394,0.8295 Q0.4466,0.8295,0.4659,0.8366 Q0.4699,0.8378,0.4747,0.8378 Q0.4763,0.8378,0.4807,0.8374 T0.4884,0.837 Q0.494,0.837,0.5004,0.8382 Q0.5052,0.8391,0.5124,0.8399 Q0.5221,0.8411,0.5249,0.8422 T0.5277,0.8461 Q0.5277,0.8482,0.5233,0.849 T0.5112,0.8501 T0.4996,0.8511 Q0.4964,0.8519,0.4851,0.8523 T0.4659,0.8544 Q0.4578,0.8557,0.4402,0.8557 L0.4349,0.8557 L0.4297,0.8557 L0.4209,0.8557 Q0.408,0.8565,0.3867,0.8571 T0.3614,0.8582 Q0.3317,0.8611,0.3237,0.8611 L0.3225,0.8611 L0.3213,0.8611 Q0.2972,0.8611,0.2972,0.8681 Q0.2972,0.8714,0.3008,0.8747 T0.3044,0.8805 Q0.3044,0.881,0.3036,0.8814 Q0.3012,0.8839,0.2851,0.8839 Q0.2779,0.8839,0.2739,0.883 Q0.2723,0.8826,0.2699,0.8826 T0.2643,0.8835 T0.259,0.8853 T0.2542,0.8876 T0.249,0.8893 Q0.2386,0.8922,0.2056,0.8946 Q0.2016,0.8951,0.1916,0.898 T0.1703,0.9009 Q0.1518,0.9009,0.1337,0.9044 T0.1149,0.9146 L0.1149,0.9158 Q0.1149,0.9175,0.1157,0.9187 T0.1173,0.921 T0.1201,0.9226 T0.1233,0.9237 T0.1269,0.9245 L0.1305,0.9251 T0.1337,0.9255 L0.1357,0.9258 Q0.139,0.9262,0.1446,0.9262 T0.1542,0.9266 T0.1598,0.9282 Q0.1614,0.9303,0.1647,0.9314 T0.1739,0.9328 T0.1815,0.9336 Q0.1863,0.9345,0.1976,0.9372 T0.2145,0.9415 Q0.2225,0.9432,0.2285,0.9467 T0.2378,0.9515 Q0.2426,0.9531,0.2514,0.9531 Q0.2538,0.9531,0.2602,0.9529 T0.2707,0.9527 Q0.2763,0.9527,0.2815,0.9531 T0.2867,0.9569 T0.2811,0.9614 Q0.2434,0.9627,0.2329,0.9652 Q0.2249,0.9672,0.2241,0.9672 L0.2096,0.9668 L0.2056,0.9668 Q0.2,0.9668,0.196,0.9672 T0.1884,0.9687 T0.1815,0.9708 T0.1731,0.9737 T0.1639,0.9772 Q0.1518,0.9805,0.1285,0.9805 L0.1253,0.9805 Q0.1124,0.9805,0.1076,0.9818 Q0.1012,0.983,0.0831,0.9876 T0.0594,0.9934 Q0.049,0.9954,0.0064,0.9954 Z M0.0032,0.9979 L0.0024,0.0037 Q0.0161,0.0021,0.0289,0.0062 Q0.0337,0.0075,0.0671,0.0066 T0.1116,0.01 T0.1337,0.0166 T0.151,0.022 Q0.1582,0.0249,0.1659,0.0251 T0.1767,0.0265 Q0.1807,0.0278,0.2,0.0292 T0.2265,0.0328 Q0.2305,0.034,0.2329,0.034 T0.239,0.0326 T0.2458,0.0311 T0.253,0.0319 Q0.2578,0.0332,0.2614,0.0342 T0.2667,0.0363 T0.2723,0.0384 T0.2827,0.0406 Q0.3084,0.0448,0.3141,0.0485 Q0.3149,0.0494,0.3225,0.0494 T0.3361,0.0504 T0.3422,0.0554 T0.3357,0.0606 T0.3205,0.0618 T0.31,0.0626 Q0.3092,0.0626,0.3056,0.0659 T0.2932,0.0701 Q0.2884,0.0709,0.2843,0.0709 Q0.2811,0.0709,0.2759,0.0701 T0.2667,0.0693 Q0.2586,0.0693,0.2422,0.0718 T0.2193,0.0763 Q0.2137,0.0784,0.1831,0.079 T0.1502,0.0805 Q0.1494,0.0809,0.147,0.0809 Q0.1454,0.0809,0.1386,0.0803 T0.1277,0.0796 Q0.1173,0.0796,0.1092,0.0821 Q0.1036,0.0834,0.1036,0.0854 Q0.1036,0.0879,0.1129,0.0908 T0.1269,0.0937 Q0.1293,0.0937,0.1558,0.0991 T0.1863,0.1045 Q0.2016,0.1045,0.2193,0.1087 Q0.2225,0.1091,0.2249,0.1091 Q0.2289,0.1091,0.2357,0.1076 T0.2482,0.1054 Q0.2506,0.1049,0.2546,0.1049 Q0.2699,0.1049,0.2924,0.1085 T0.3213,0.1165 Q0.3253,0.119,0.3301,0.119 Q0.3325,0.119,0.3446,0.1161 T0.3687,0.1124 Q0.3831,0.1112,0.3863,0.1112 T0.3908,0.1118 T0.3936,0.1145 T0.3984,0.1186 Q0.4048,0.1228,0.408,0.1228 Q0.4096,0.1228,0.4161,0.1213 T0.4305,0.1195 L0.4337,0.1195 Q0.4426,0.1195,0.4474,0.1211 T0.4566,0.1246 T0.4667,0.1273 Q0.4876,0.1298,0.5116,0.1298 Q0.5365,0.1298,0.5631,0.1389 Q0.5703,0.1414,0.5751,0.1414 Q0.5783,0.1414,0.5819,0.1398 T0.5888,0.1381 Q0.5928,0.1381,0.5984,0.1398 T0.6129,0.1414 Q0.6321,0.1414,0.6498,0.1477 Q0.661,0.1514,0.6667,0.1514 Q0.6707,0.1514,0.6771,0.1501 Q0.6787,0.1497,0.6795,0.1497 Q0.6835,0.1497,0.6863,0.1526 T0.6892,0.1593 Q0.6892,0.1626,0.6876,0.1647 Q0.6851,0.1672,0.6799,0.1686 T0.6695,0.1705 T0.6566,0.1715 T0.6458,0.1725 Q0.6434,0.173,0.6402,0.173 Q0.6378,0.173,0.6317,0.1727 T0.6225,0.1725 Q0.6096,0.1725,0.5984,0.1759 Q0.5823,0.1804,0.5454,0.1804 Q0.5205,0.1804,0.5116,0.1788 L0.5084,0.1788 Q0.5036,0.1788,0.4956,0.1819 T0.4843,0.185 Q0.4434,0.1887,0.4353,0.1929 Q0.4321,0.1945,0.4289,0.1945 T0.4197,0.1922 T0.4112,0.19 T0.4072,0.1912 Q0.4032,0.1949,0.388,0.1949 Q0.3663,0.1949,0.3542,0.19 Q0.351,0.1883,0.3462,0.1883 Q0.3406,0.1883,0.3321,0.1906 T0.3153,0.1954 T0.302,0.1983 Q0.2972,0.1991,0.2859,0.1997 T0.2643,0.201 T0.245,0.2024 T0.2337,0.2041 Q0.2321,0.2045,0.2181,0.2045 T0.1851,0.207 T0.1542,0.2157 Q0.143,0.2211,0.143,0.226 Q0.143,0.2314,0.153,0.2348 T0.1719,0.2381 Q0.1791,0.2381,0.2474,0.2476 Q0.2506,0.248,0.2558,0.2489 T0.2651,0.2505 T0.2739,0.252 T0.2819,0.2526 Q0.2835,0.2526,0.2851,0.2522 L0.2859,0.2522 Q0.2948,0.2522,0.3104,0.2574 T0.3309,0.2671 Q0.3333,0.2696,0.3365,0.2696 Q0.339,0.2696,0.3442,0.2684 T0.3526,0.2671 T0.3582,0.2679 Q0.3687,0.2717,0.3968,0.2742 Q0.4,0.2746,0.4036,0.2771 T0.4096,0.2796 Q0.4112,0.2796,0.4137,0.2787 Q0.4169,0.2779,0.4257,0.2779 Q0.4594,0.2779,0.4779,0.2849 Q0.4876,0.2891,0.4972,0.2891 Q0.4996,0.2891,0.506,0.2887 T0.5165,0.2883 Q0.5253,0.2883,0.5305,0.2889 T0.541,0.292 T0.5494,0.299 L0.5494,0.3015 Q0.5494,0.3036,0.5466,0.3051 T0.5386,0.3073 T0.5285,0.3086 T0.5181,0.3094 T0.5108,0.3102 Q0.5068,0.3107,0.494,0.3121 L0.4683,0.315 T0.4506,0.3181 Q0.449,0.3181,0.4426,0.32 T0.4313,0.3229 T0.4197,0.3256 T0.4064,0.3281 T0.3952,0.3289 Q0.3888,0.3289,0.3855,0.3273 Q0.3783,0.3243,0.3703,0.3243 Q0.3598,0.3243,0.351,0.3297 Q0.3478,0.3314,0.3422,0.3314 Q0.3398,0.3314,0.3337,0.3306 T0.3245,0.3297 T0.3189,0.3306 Q0.3149,0.3314,0.2956,0.3328 T0.2715,0.3368 Q0.2691,0.338,0.2635,0.3391 T0.2522,0.3407 T0.2406,0.3424 T0.2313,0.3447 Q0.2305,0.3447,0.2213,0.348 T0.206,0.354 T0.1924,0.3621 T0.1815,0.3733 Q0.1767,0.3816,0.1767,0.3849 Q0.1767,0.387,0.1783,0.3893 T0.1847,0.3961 T0.1936,0.4063 T0.2004,0.4181 T0.2052,0.4264 T0.2145,0.4309 T0.2386,0.4359 Q0.2458,0.4372,0.2554,0.4372 Q0.2578,0.4372,0.2627,0.437 T0.2699,0.4367 Q0.2795,0.4367,0.2851,0.4384 Q0.294,0.4409,0.3092,0.4409 Q0.3116,0.4409,0.3157,0.4407 T0.3213,0.4405 Q0.3301,0.4405,0.3466,0.444 T0.3687,0.4509 Q0.3703,0.4517,0.3703,0.4525 Q0.3703,0.4575,0.3373,0.4596 Q0.3133,0.4608,0.2988,0.4658 Q0.294,0.4674,0.2803,0.4674 Q0.2763,0.4674,0.2687,0.4672 T0.257,0.467 Q0.2402,0.467,0.2313,0.4687 Q0.2209,0.4708,0.2209,0.4737 Q0.2209,0.4741,0.2213,0.4749 T0.2229,0.4764 L0.2249,0.4774 T0.2265,0.4778 L0.2273,0.4782 Q0.2498,0.4803,0.2618,0.4803 Q0.2667,0.4803,0.2691,0.4799 Q0.2699,0.4795,0.2715,0.4795 Q0.2779,0.4795,0.3133,0.4873 Q0.3181,0.4886,0.3233,0.4892 T0.3386,0.4905 T0.3542,0.4915 T0.3655,0.4919 Q0.3703,0.4919,0.3779,0.4915 T0.3888,0.4911 T0.3952,0.4915 Q0.3976,0.4919,0.4008,0.4927 L0.4072,0.4944 T0.4149,0.4961 T0.4249,0.4975 T0.4369,0.4985 Q0.449,0.499,0.4554,0.5 T0.4651,0.5031 T0.4699,0.5085 Q0.4707,0.5093,0.4707,0.5097 Q0.4707,0.5114,0.4687,0.5124 T0.4631,0.5139 T0.4562,0.5145 T0.4478,0.5147 L0.4402,0.5147 Q0.4353,0.5151,0.4265,0.5174 T0.4096,0.5197 L0.4024,0.5197 Q0.4,0.5193,0.3968,0.5193 Q0.3896,0.5193,0.3831,0.5209 T0.3703,0.5253 T0.3598,0.5288 Q0.3558,0.5301,0.3321,0.5342 T0.302,0.5409 Q0.2876,0.5454,0.2337,0.55 Q0.2112,0.5521,0.2112,0.5558 Q0.2112,0.5574,0.2161,0.5612 Q0.2201,0.5637,0.2281,0.5637 Q0.2305,0.5637,0.2361,0.5633 T0.2442,0.5628 Q0.2474,0.5628,0.2498,0.5633 Q0.2635,0.5653,0.3133,0.5653 Q0.3261,0.5653,0.3301,0.5649 L0.3325,0.5649 Q0.3349,0.5649,0.3402,0.5657 T0.3494,0.5666 Q0.3542,0.5666,0.3598,0.5657 Q0.3663,0.5645,0.3695,0.5645 Q0.3735,0.5645,0.3775,0.5666 T0.3847,0.5695 Q0.3888,0.5707,0.3912,0.5709 T0.3968,0.5711 T0.4048,0.572 Q0.4096,0.5724,0.4165,0.5726 T0.4281,0.5734 T0.4378,0.5757 Q0.4418,0.5774,0.4522,0.5774 Q0.4562,0.5774,0.4655,0.5769 T0.4795,0.5765 Q0.4932,0.5765,0.4972,0.579 Q0.5028,0.5819,0.51,0.5819 Q0.5141,0.5819,0.5221,0.5809 T0.5341,0.5798 L0.5373,0.5798 Q0.5422,0.5798,0.557,0.5821 T0.5855,0.5844 L0.5936,0.5844 L0.5992,0.5844 T0.604,0.5848 T0.6076,0.5852 T0.6108,0.5859 T0.6137,0.5865 T0.6161,0.5873 T0.6181,0.5881 T0.6209,0.5896 L0.6233,0.591 Q0.6265,0.5927,0.6353,0.5927 L0.6402,0.5927 L0.645,0.5927 Q0.6723,0.5927,0.6948,0.6039 Q0.6988,0.606,0.7036,0.606 Q0.7076,0.606,0.7153,0.6045 T0.7261,0.6031 Q0.7309,0.6031,0.7454,0.6027 T0.7647,0.6022 Q0.7783,0.6022,0.808,0.608 L0.812,0.608 Q0.8169,0.608,0.8293,0.6062 T0.8474,0.6039 L0.8506,0.6039 Q0.857,0.6039,0.8655,0.6049 T0.8835,0.6074 T0.8972,0.6093 Q0.9036,0.6101,0.9213,0.6101 L0.9398,0.6101 L0.959,0.6101 L0.9767,0.6101 Q0.9976,0.6109,0.9976,0.6176 Q0.9976,0.6188,0.9968,0.6226 Q0.9952,0.6284,0.9671,0.6284 L0.959,0.6284 L0.9526,0.6284 Q0.9486,0.6284,0.9382,0.6302 T0.9205,0.6321 L0.9173,0.6321 Q0.9133,0.6317,0.9092,0.6317 Q0.9012,0.6317,0.8715,0.6346 Q0.8233,0.6387,0.7944,0.6421 Q0.7888,0.6429,0.7831,0.6429 Q0.7783,0.6429,0.7731,0.6425 T0.7663,0.6421 L0.7622,0.6421 Q0.7614,0.6425,0.7586,0.6425 T0.7474,0.6421 T0.7349,0.6416 Q0.7261,0.6416,0.7221,0.6429 Q0.7173,0.645,0.7032,0.646 T0.6711,0.6479 T0.6482,0.6491 Q0.645,0.6495,0.6418,0.6495 Q0.6353,0.6495,0.6273,0.6474 T0.6161,0.6454 Q0.612,0.6454,0.6088,0.6477 T0.6,0.6499 Q0.5912,0.6499,0.5494,0.6578 Q0.5422,0.6591,0.5373,0.6591 Q0.5341,0.6591,0.5281,0.6584 T0.5173,0.6578 L0.5124,0.6578 Q0.5004,0.6582,0.4747,0.6632 Q0.4675,0.6649,0.4398,0.6667 T0.3851,0.6703 T0.3566,0.6719 Q0.3534,0.6723,0.3406,0.6734 T0.3141,0.6757 T0.2948,0.6773 Q0.2908,0.6781,0.2819,0.6829 T0.2618,0.6877 Q0.2482,0.6877,0.2273,0.6958 T0.1992,0.7117 Q0.1976,0.7138,0.1976,0.7155 Q0.1976,0.7188,0.2032,0.7213 T0.2181,0.7258 T0.2289,0.7292 Q0.2337,0.7308,0.2378,0.7316 L0.2458,0.7333 T0.2522,0.7345 Q0.2747,0.7399,0.2835,0.7399 Q0.29,0.7399,0.3048,0.7408 T0.3253,0.7416 Q0.3277,0.7416,0.3297,0.7414 T0.3341,0.7412 L0.3598,0.7445 Q0.3639,0.7449,0.3663,0.7449 Q0.3695,0.7449,0.3751,0.7443 T0.3855,0.7437 L0.3904,0.7437 Q0.3984,0.7441,0.4141,0.7472 T0.4353,0.7507 Q0.4434,0.752,0.4434,0.7553 Q0.4434,0.7578,0.439,0.7605 T0.4297,0.764 Q0.4257,0.7648,0.4201,0.7655 T0.4076,0.7665 T0.3984,0.7673 Q0.3968,0.7673,0.3912,0.7677 T0.3815,0.7688 T0.3735,0.771 T0.3655,0.7727 Q0.3606,0.7727,0.3534,0.7708 T0.3458,0.769 L0.3446,0.769 Q0.3414,0.769,0.3297,0.7713 T0.3149,0.7735 Q0.3092,0.7735,0.296,0.7771 T0.2771,0.7831 Q0.2683,0.7872,0.2554,0.7885 Q0.253,0.7889,0.2325,0.7897 T0.2032,0.7914 Q0.2008,0.7918,0.198,0.792 T0.194,0.7924 T0.1912,0.7928 T0.1888,0.793 T0.1867,0.7934 T0.1851,0.7943 T0.1843,0.7953 T0.1835,0.7968 T0.1823,0.7984 T0.1815,0.8001 Q0.1815,0.8022,0.1847,0.8032 T0.1932,0.8053 T0.2008,0.8071 Q0.2072,0.8092,0.2265,0.8092 Q0.2361,0.8092,0.2586,0.8088 L0.2635,0.8088 Q0.2731,0.8088,0.2795,0.8098 T0.2928,0.8134 T0.302,0.8167 Q0.306,0.8179,0.3277,0.8183 T0.3542,0.8221 Q0.359,0.8246,0.3622,0.8246 Q0.3639,0.8246,0.3675,0.8237 T0.3751,0.8229 Q0.3968,0.8229,0.4048,0.8275 Q0.4088,0.8291,0.4161,0.8291 Q0.4225,0.8291,0.4353,0.8275 Q0.4369,0.827,0.4394,0.827 Q0.4474,0.827,0.4675,0.8345 Q0.4707,0.8358,0.4739,0.8358 Q0.4755,0.8358,0.4799,0.8353 T0.4876,0.8349 Q0.494,0.8349,0.5012,0.8362 L0.5076,0.837 T0.5133,0.8376 T0.5181,0.8382 T0.5221,0.8391 L0.5253,0.8399 T0.5277,0.8409 L0.5293,0.8422 T0.5301,0.8438 L0.5301,0.8461 Q0.5301,0.8499,0.5249,0.8511 T0.5112,0.8526 T0.5004,0.8532 Q0.4964,0.854,0.4851,0.8546 T0.4667,0.8565 Q0.4578,0.8577,0.441,0.8577 L0.4345,0.8577 L0.4289,0.8577 L0.4209,0.8577 Q0.4153,0.8582,0.4088,0.8586 T0.3968,0.8592 T0.3855,0.8594 T0.3755,0.8596 T0.3675,0.86 T0.3622,0.8602 Q0.3317,0.8635,0.3237,0.8635 Q0.2996,0.8635,0.2996,0.8681 Q0.2996,0.8698,0.3032,0.8733 T0.3068,0.8797 L0.3068,0.8822 Q0.3052,0.8859,0.2859,0.8859 Q0.2787,0.8859,0.2739,0.8851 L0.2699,0.8851 Q0.2659,0.8851,0.259,0.888 T0.2498,0.8913 Q0.2394,0.8946,0.2056,0.8971 Q0.2032,0.8971,0.1928,0.9002 T0.1703,0.9034 Q0.1526,0.9034,0.1353,0.9067 T0.1173,0.915 L0.1173,0.9158 Q0.1173,0.9166,0.1177,0.9175 T0.1189,0.9191 T0.1205,0.9204 T0.1229,0.9212 T0.1257,0.922 T0.1285,0.9226 T0.1309,0.9231 T0.1337,0.9235 T0.1365,0.9237 L0.1446,0.9237 T0.1554,0.9243 T0.1614,0.9268 T0.1659,0.9293 T0.1743,0.9303 T0.1823,0.9316 Q0.1863,0.932,0.1912,0.9332 T0.2028,0.9361 T0.2153,0.939 Q0.2233,0.9411,0.2297,0.9448 T0.2386,0.9494 Q0.2426,0.9506,0.2506,0.9506 Q0.253,0.9506,0.2594,0.9504 T0.2699,0.9502 Q0.2763,0.9502,0.2819,0.9511 Q0.2851,0.9511,0.2871,0.9529 T0.2892,0.9573 Q0.2892,0.9627,0.2811,0.9635 Q0.2434,0.9652,0.2337,0.9672 Q0.2257,0.9693,0.2241,0.9693 Q0.2217,0.9693,0.2096,0.9689 L0.2056,0.9689 Q0.1976,0.9689,0.1924,0.9699 T0.1787,0.9741 L0.1647,0.9793 Q0.1518,0.983,0.1285,0.983 L0.1261,0.983 L0.1237,0.983 Q0.1124,0.983,0.1076,0.9838 Q0.102,0.9851,0.0839,0.9896 T0.0602,0.9954 T0.0406,0.9971 T0.0153,0.9979 L0.0032,0.9979 Z",type:0}},"\uE0CA":{type:5,data:{d:"M0.9992,0.998 Q0.9992,1,0.9968,1 Q0.9521,1,0.9392,0.998 Q0.9335,0.997,0.9152,0.9921 T0.8913,0.9862 Q0.8873,0.9852,0.8783,0.9852 L0.8747,0.9852 L0.871,0.9852 Q0.8483,0.9852,0.8345,0.9812 Q0.8289,0.9792,0.8228,0.9773 T0.8135,0.9743 T0.8054,0.9723 T0.7948,0.9713 L0.7908,0.9713 L0.777,0.9713 T0.7656,0.9693 Q0.7616,0.9683,0.7498,0.9674 T0.7283,0.9664 L0.7186,0.9654 Q0.708,0.9644,0.708,0.9575 Q0.708,0.9545,0.7109,0.952 T0.7178,0.9486 L0.7315,0.9486 L0.7417,0.9486 L0.7502,0.9486 Q0.7575,0.9486,0.7599,0.9476 Q0.7616,0.9466,0.7685,0.9426 T0.7843,0.9377 Q0.7899,0.9357,0.8009,0.9332 T0.8175,0.9298 Q0.82,0.9288,0.8228,0.9283 T0.8277,0.9278 T0.8313,0.9273 T0.8341,0.9263 T0.8362,0.9258 Q0.8402,0.9219,0.854,0.9219 L0.8569,0.9219 L0.8597,0.9219 L0.8637,0.9219 Q0.88,0.9199,0.88,0.9159 L0.88,0.9149 Q0.88,0.913,0.8719,0.911 T0.852,0.9075 T0.8297,0.906 Q0.8224,0.906,0.8167,0.905 T0.8074,0.9031 T0.8001,0.9006 T0.794,0.8991 Q0.7599,0.8971,0.7494,0.8942 Q0.7461,0.8932,0.7397,0.8902 T0.7299,0.8872 L0.7267,0.8872 Q0.721,0.8882,0.7121,0.8882 Q0.6926,0.8882,0.691,0.8833 L0.691,0.8803 Q0.691,0.8773,0.6922,0.8749 T0.6955,0.8704 L0.6975,0.8684 Q0.6926,0.8655,0.6764,0.8655 Q0.6683,0.8655,0.6375,0.8625 Q0.6358,0.8625,0.629,0.862 T0.6148,0.8615 T0.5973,0.861 T0.5791,0.8605 L0.5718,0.8605 L0.5661,0.8605 L0.5596,0.8605 Q0.5426,0.8605,0.5337,0.8586 Q0.5264,0.8576,0.515,0.8571 T0.4996,0.8556 Q0.498,0.8556,0.4947,0.8551 T0.4882,0.8546 T0.4809,0.8541 T0.474,0.8531 T0.4692,0.8506 T0.4672,0.8467 Q0.4672,0.8437,0.468,0.8422 T0.4704,0.8398 T0.4736,0.8383 T0.4781,0.8368 T0.4838,0.8358 T0.4911,0.8353 T0.4988,0.8338 Q0.5069,0.8328,0.5142,0.8328 Q0.5174,0.8328,0.5215,0.8333 T0.5264,0.8338 Q0.5296,0.8338,0.532,0.8328 Q0.5523,0.8249,0.5604,0.8249 L0.5653,0.8249 Q0.5775,0.8269,0.5848,0.8269 Q0.5912,0.8269,0.5937,0.8259 Q0.6026,0.821,0.6253,0.821 Q0.6294,0.821,0.6334,0.822 T0.6383,0.8229 Q0.6399,0.8229,0.644,0.82 Q0.6504,0.817,0.6723,0.816 T0.6975,0.814 Q0.6999,0.814,0.7048,0.8121 T0.7129,0.8091 T0.7226,0.8071 T0.7372,0.8061 L0.7421,0.8061 Q0.7624,0.8071,0.7721,0.8071 Q0.7924,0.8071,0.7981,0.8051 Q0.8021,0.8032,0.807,0.8027 T0.8135,0.8017 T0.8151,0.8002 L0.8151,0.7992 Q0.8143,0.7962,0.8127,0.7957 T0.8045,0.7943 Q0.7997,0.7943,0.7964,0.7933 Q0.7883,0.7933,0.7676,0.7923 T0.7437,0.7903 Q0.7307,0.7893,0.7218,0.7844 Q0.7194,0.7834,0.7141,0.7819 L0.7036,0.7789 T0.693,0.7765 T0.6853,0.7755 Q0.6805,0.7755,0.6691,0.773 T0.6553,0.7705 Q0.6545,0.7705,0.6545,0.7715 Q0.6537,0.7715,0.65,0.7725 T0.6423,0.774 T0.635,0.7745 Q0.6294,0.7745,0.6257,0.773 T0.618,0.771 T0.6083,0.77 T0.601,0.7695 Q0.5985,0.7695,0.5921,0.769 T0.5795,0.7676 T0.5702,0.7666 Q0.5653,0.7656,0.5596,0.7616 T0.5539,0.7547 Q0.5539,0.7498,0.5645,0.7488 Q0.5693,0.7478,0.5852,0.7448 T0.6099,0.7418 L0.6148,0.7418 Q0.6196,0.7418,0.6253,0.7423 T0.6338,0.7428 L0.6399,0.7428 Q0.6431,0.7418,0.6488,0.7409 T0.6586,0.7394 T0.6659,0.7389 L0.6707,0.7389 Q0.6723,0.7399,0.6748,0.7399 Q0.6796,0.7399,0.6946,0.7389 T0.7161,0.7379 Q0.7251,0.7379,0.7478,0.7319 Q0.7494,0.7319,0.7539,0.7315 T0.762,0.73 T0.7697,0.727 T0.7818,0.723 T0.7948,0.7196 T0.7997,0.7151 Q0.7997,0.7141,0.7989,0.7132 Q0.7924,0.7062,0.7717,0.6978 T0.738,0.6894 Q0.7267,0.6894,0.717,0.6845 T0.7048,0.6795 Q0.6975,0.6785,0.6711,0.6766 T0.6431,0.6746 Q0.6415,0.6736,0.6144,0.6721 T0.5596,0.6686 T0.5247,0.6657 Q0.4996,0.6607,0.4874,0.6597 L0.4834,0.6597 Q0.4785,0.6597,0.4724,0.6607 T0.4631,0.6617 Q0.4574,0.6617,0.4501,0.6597 Q0.4088,0.6518,0.4006,0.6518 Q0.3933,0.6518,0.3901,0.6499 T0.3844,0.6479 T0.3739,0.6499 T0.3585,0.6518 L0.352,0.6518 Q0.3471,0.6508,0.335,0.6503 T0.3122,0.6494 T0.2912,0.6479 T0.2766,0.6449 Q0.2733,0.6439,0.2668,0.6439 Q0.2628,0.6439,0.2543,0.6444 T0.2425,0.6449 T0.2368,0.6439 L0.2344,0.6439 Q0.2336,0.6439,0.2283,0.6444 T0.2182,0.6449 Q0.2117,0.6449,0.2052,0.6439 Q0.1768,0.6409,0.1281,0.637 Q0.0989,0.634,0.0916,0.634 L0.0835,0.634 L0.0795,0.634 Q0.0722,0.634,0.0616,0.632 T0.0479,0.6301 Q0.0462,0.6301,0.0406,0.6306 T0.0308,0.6311 Q0.0032,0.6311,0.0008,0.6231 Q0,0.6202,0,0.6182 Q0,0.6083,0.0227,0.6083 Q0.03,0.6073,0.0422,0.6073 Q0.0487,0.6073,0.0608,0.6078 T0.0787,0.6083 Q0.0973,0.6083,0.103,0.6073 Q0.1062,0.6063,0.1131,0.6053 T0.1253,0.6039 T0.1375,0.6024 T0.1492,0.6014 L0.1533,0.6014 Q0.1598,0.6024,0.1723,0.6044 T0.189,0.6063 Q0.1906,0.6063,0.1922,0.6053 Q0.2214,0.6004,0.236,0.6004 Q0.2409,0.6004,0.2551,0.6009 T0.2741,0.6014 Q0.2782,0.6014,0.2859,0.6024 T0.2968,0.6034 Q0.3009,0.6034,0.3041,0.6024 Q0.3277,0.5905,0.356,0.5905 L0.3613,0.5905 L0.3666,0.5905 Q0.3731,0.5905,0.3755,0.5895 Q0.382,0.5856,0.3844,0.5846 T0.3938,0.5831 T0.4144,0.5826 T0.4428,0.5801 T0.4631,0.5776 L0.4663,0.5776 Q0.4704,0.5776,0.4785,0.5786 T0.4899,0.5796 Q0.4964,0.5796,0.5012,0.5767 Q0.5069,0.5737,0.5223,0.5737 Q0.5272,0.5737,0.5369,0.5742 T0.5499,0.5747 Q0.558,0.5747,0.5612,0.5737 Q0.5661,0.5717,0.5714,0.5712 T0.5835,0.5702 T0.5945,0.5692 T0.6018,0.5687 L0.6062,0.5687 T0.6095,0.5682 T0.6148,0.5678 Q0.6172,0.5668,0.6196,0.5653 T0.6245,0.5633 T0.631,0.5628 T0.6407,0.5638 T0.6504,0.5648 T0.6594,0.5638 T0.6675,0.5628 L0.6707,0.5628 L0.6861,0.5628 Q0.7364,0.5628,0.7494,0.5608 L0.7567,0.5608 L0.7652,0.5608 L0.7729,0.5608 Q0.7794,0.5608,0.7818,0.5589 Q0.7851,0.5569,0.7859,0.5559 Q0.7835,0.5539,0.7656,0.5519 Q0.7121,0.547,0.6975,0.543 Q0.6934,0.541,0.6853,0.5396 L0.6691,0.5366 T0.6525,0.5336 T0.6391,0.5312 Q0.6367,0.5302,0.6245,0.5257 T0.6034,0.5213 L0.5977,0.5213 Q0.5945,0.5223,0.5904,0.5223 Q0.5839,0.5223,0.5787,0.5208 T0.5685,0.5183 T0.5596,0.5173 Q0.558,0.5173,0.5552,0.5168 T0.5495,0.5163 L0.5434,0.5163 T0.5373,0.5158 T0.532,0.5148 T0.5284,0.5129 T0.5272,0.5104 L0.5272,0.5074 Q0.5304,0.5015,0.5377,0.499 T0.5629,0.4965 Q0.5734,0.4955,0.5811,0.4946 T0.5953,0.4916 T0.605,0.4896 Q0.6083,0.4886,0.6123,0.4886 Q0.6148,0.4886,0.6225,0.4891 T0.635,0.4896 L0.6456,0.4896 Q0.6837,0.4857,0.6861,0.4857 Q0.7226,0.4768,0.7283,0.4768 Q0.7307,0.4768,0.732,0.4773 T0.7372,0.4777 Q0.7502,0.4777,0.7721,0.4758 Q0.7753,0.4748,0.777,0.4738 Q0.7745,0.4718,0.768,0.4708 Q0.7599,0.4688,0.7445,0.4688 Q0.7405,0.4688,0.7324,0.4693 T0.721,0.4698 Q0.7056,0.4698,0.6999,0.4679 Q0.6861,0.4629,0.6626,0.4619 Q0.6586,0.4609,0.6533,0.4604 T0.6419,0.459 T0.6314,0.456 T0.6269,0.452 Q0.6269,0.451,0.6302,0.4491 Q0.6358,0.4451,0.6525,0.4416 T0.6788,0.4382 L0.6845,0.4382 L0.6902,0.4382 Q0.7064,0.4382,0.7145,0.4362 Q0.7202,0.4342,0.7307,0.4342 L0.7356,0.4342 L0.7409,0.4342 L0.7453,0.4342 Q0.7543,0.4342,0.7607,0.4332 Q0.7778,0.4313,0.7847,0.4288 T0.7932,0.4248 T0.7972,0.4169 T0.8045,0.4045 L0.8094,0.3986 T0.8135,0.3942 L0.8167,0.3912 T0.8191,0.3887 T0.8204,0.3867 T0.8208,0.3848 Q0.8208,0.3818,0.8167,0.3739 Q0.8127,0.3689,0.8054,0.3635 T0.7924,0.3556 T0.7778,0.3497 T0.768,0.3462 Q0.764,0.3442,0.7478,0.3427 T0.7267,0.3383 Q0.7234,0.3363,0.7044,0.3348 T0.6805,0.3323 L0.6764,0.3323 T0.6679,0.3328 T0.6586,0.3333 Q0.6521,0.3333,0.648,0.3314 Q0.6391,0.3264,0.6294,0.3264 Q0.6229,0.3264,0.6156,0.3294 Q0.6115,0.3304,0.6042,0.3304 Q0.5977,0.3304,0.5888,0.3289 T0.5738,0.3264 T0.5584,0.3225 L0.5491,0.3195 Q0.5418,0.3185,0.5162,0.3155 T0.4895,0.3121 T0.4826,0.3116 T0.4716,0.3111 T0.4607,0.3096 T0.4513,0.3066 T0.4477,0.3017 Q0.4477,0.2997,0.4485,0.2977 Q0.4526,0.2898,0.4611,0.2878 T0.4842,0.2859 Q0.4882,0.2859,0.4943,0.2864 T0.5028,0.2868 Q0.5118,0.2868,0.5215,0.2829 Q0.5401,0.276,0.5734,0.276 Q0.5831,0.276,0.5872,0.277 L0.5904,0.277 T0.5949,0.2745 T0.6034,0.272 Q0.631,0.269,0.6407,0.2661 Q0.6448,0.2641,0.6488,0.2641 T0.6573,0.2656 T0.6634,0.2671 Q0.6659,0.2671,0.6675,0.2651 Q0.6723,0.2601,0.6886,0.2552 T0.7137,0.2502 L0.7153,0.2502 L0.7178,0.2502 Q0.7218,0.2502,0.7279,0.2493 T0.7417,0.2468 T0.7526,0.2453 Q0.8208,0.2354,0.8281,0.2354 Q0.8337,0.2354,0.8394,0.2344 T0.8496,0.2315 T0.854,0.2265 Q0.854,0.2216,0.8443,0.2176 Q0.8354,0.2127,0.8216,0.2102 T0.7972,0.2072 T0.777,0.2067 T0.7648,0.2057 Q0.7632,0.2047,0.7498,0.2038 T0.7202,0.2018 T0.6983,0.1998 Q0.6918,0.1998,0.676,0.1949 T0.6537,0.1899 Q0.6496,0.1899,0.6472,0.1919 Q0.6342,0.1968,0.6123,0.1968 Q0.5961,0.1968,0.5912,0.1929 Q0.5904,0.1919,0.5892,0.1919 T0.5823,0.1944 T0.5722,0.1968 T0.5637,0.1949 Q0.5556,0.1909,0.5158,0.1869 Q0.5109,0.1869,0.5032,0.1835 T0.4915,0.18 Q0.4907,0.18,0.4891,0.181 Q0.4793,0.182,0.455,0.182 Q0.4177,0.182,0.4015,0.1771 Q0.3901,0.1741,0.3779,0.1741 Q0.3747,0.1741,0.369,0.1746 T0.3609,0.1751 Q0.3569,0.1751,0.3536,0.1741 Q0.3512,0.1741,0.3459,0.1736 T0.3358,0.1726 T0.3256,0.1716 T0.3167,0.1696 T0.3106,0.1662 Q0.3082,0.1632,0.3082,0.1592 Q0.3082,0.1543,0.3114,0.1508 T0.3204,0.1474 L0.3236,0.1474 Q0.3301,0.1494,0.3333,0.1494 Q0.339,0.1494,0.3496,0.1454 Q0.3674,0.1385,0.3869,0.1385 Q0.395,0.1385,0.4011,0.137 T0.4116,0.1355 T0.4197,0.1375 T0.425,0.1395 Q0.429,0.1395,0.4355,0.1365 Q0.4631,0.1266,0.4882,0.1266 Q0.5126,0.1266,0.5337,0.1246 Q0.5369,0.1246,0.5458,0.1207 T0.5661,0.1167 L0.5693,0.1167 Q0.5791,0.1177,0.5852,0.1187 T0.5921,0.1197 Q0.5945,0.1197,0.6002,0.1167 Q0.6026,0.1147,0.605,0.1123 T0.6091,0.1093 T0.6156,0.1088 T0.6318,0.1098 Q0.6456,0.1108,0.6569,0.1137 T0.6707,0.1167 Q0.674,0.1167,0.6772,0.1147 Q0.6821,0.1108,0.6946,0.1083 T0.721,0.1044 T0.7453,0.1029 L0.7526,0.1029 Q0.7583,0.1039,0.7652,0.1053 T0.7753,0.1068 Q0.7778,0.1068,0.7802,0.1058 Q0.7981,0.1019,0.8143,0.1019 Q0.8175,0.1019,0.8439,0.0964 T0.8735,0.091 Q0.8759,0.091,0.8836,0.089 T0.8938,0.0851 Q0.8929,0.0841,0.8905,0.0841 Q0.8832,0.0821,0.8735,0.0821 Q0.8694,0.0821,0.8629,0.0826 T0.854,0.0831 Q0.8508,0.0831,0.8491,0.0821 Q0.8475,0.0821,0.8171,0.0811 T0.7802,0.0781 T0.7571,0.0737 T0.7332,0.0712 Q0.7299,0.0712,0.7247,0.0717 T0.7161,0.0722 L0.7064,0.0722 Q0.7032,0.0712,0.7003,0.0707 T0.6959,0.0692 T0.693,0.0678 T0.6914,0.0663 T0.6902,0.0648 T0.689,0.0643 L0.6869,0.0643 L0.6845,0.0643 L0.6821,0.0643 Q0.6553,0.0643,0.6553,0.0554 T0.6796,0.0465 L0.6813,0.0465 L0.6845,0.0465 Q0.6918,0.0425,0.717,0.0376 Q0.7226,0.0366,0.7267,0.0356 T0.7324,0.0336 T0.7376,0.0317 T0.747,0.0297 Q0.7518,0.0287,0.7551,0.0287 T0.762,0.0297 T0.768,0.0307 L0.7729,0.0307 Q0.7802,0.0277,0.7997,0.0267 T0.8224,0.0237 Q0.8273,0.0227,0.8341,0.0223 T0.8475,0.0193 T0.8654,0.0143 T0.8873,0.0079 Q0.9002,0.003,0.9331,0.004 T0.97,0.004 Q0.9838,0,0.9976,0.001 Q1,0.001,1,0.003 Z M0.9935,0.996 L0.9951,0.0049 Q0.9822,0.0049,0.9716,0.0079 Q0.9659,0.0099,0.9327,0.0089 T0.8897,0.0119 Q0.8775,0.0158,0.8666,0.0183 T0.85,0.0237 Q0.8418,0.0267,0.8341,0.0272 T0.8248,0.0277 Q0.82,0.0297,0.8001,0.0312 T0.7745,0.0346 Q0.7697,0.0356,0.7664,0.0356 Q0.764,0.0356,0.7603,0.0341 T0.7534,0.0326 Q0.751,0.0326,0.7478,0.0336 Q0.7429,0.0346,0.7397,0.0356 T0.7344,0.0376 T0.7283,0.0401 T0.7178,0.0425 Q0.6926,0.0465,0.6878,0.0495 Q0.6845,0.0514,0.6764,0.0514 L0.6723,0.0514 L0.6691,0.0514 Q0.6602,0.0514,0.6602,0.0554 Q0.6602,0.0574,0.6659,0.0579 T0.6796,0.0589 T0.691,0.0603 T0.6967,0.0643 T0.7072,0.0673 Q0.7121,0.0682,0.7153,0.0682 T0.7238,0.0678 T0.7332,0.0673 Q0.7413,0.0673,0.7579,0.0692 T0.7818,0.0742 Q0.7867,0.0752,0.8171,0.0762 T0.8508,0.0781 L0.852,0.0781 T0.8601,0.0776 T0.8719,0.0772 Q0.8832,0.0772,0.8921,0.0791 Q0.8994,0.0811,0.8994,0.0841 T0.8933,0.0895 T0.8812,0.094 T0.8735,0.0959 T0.8451,0.1014 T0.8143,0.1068 Q0.7989,0.1068,0.7818,0.1098 Q0.7778,0.1108,0.7745,0.1108 T0.768,0.1103 T0.7603,0.1088 T0.7518,0.1068 L0.7461,0.1068 Q0.7315,0.1068,0.7088,0.1103 T0.6805,0.1177 Q0.6756,0.1207,0.6699,0.1207 Q0.6667,0.1207,0.6545,0.1177 T0.631,0.1147 Q0.6269,0.1137,0.6225,0.1133 T0.616,0.1128 L0.6123,0.1128 T0.6103,0.1133 L0.6083,0.1157 T0.6034,0.1197 Q0.5961,0.1246,0.5921,0.1246 Q0.5904,0.1246,0.5835,0.1231 T0.5693,0.1217 L0.5661,0.1217 Q0.558,0.1217,0.5535,0.1231 T0.5446,0.1266 T0.5345,0.1296 Q0.5126,0.1316,0.4882,0.1316 T0.438,0.1405 Q0.4298,0.1434,0.425,0.1434 Q0.4209,0.1434,0.4173,0.1419 T0.4112,0.1405 T0.4027,0.1419 T0.3869,0.1434 Q0.3682,0.1434,0.3512,0.1494 Q0.3398,0.1533,0.3333,0.1533 Q0.3285,0.1533,0.3228,0.1513 L0.3212,0.1513 Q0.3179,0.1513,0.3155,0.1538 T0.3131,0.1592 Q0.3131,0.1612,0.3147,0.1632 Q0.3171,0.1652,0.3232,0.1667 T0.3406,0.1691 T0.3544,0.1701 L0.3601,0.1701 L0.3678,0.1701 L0.3771,0.1701 Q0.3909,0.1701,0.4031,0.1731 Q0.4177,0.178,0.4558,0.178 Q0.4793,0.178,0.4882,0.1761 L0.4915,0.1761 Q0.498,0.1761,0.5061,0.179 T0.5158,0.183 Q0.5166,0.183,0.5231,0.1835 T0.5341,0.1845 T0.545,0.1855 T0.5572,0.1874 T0.5661,0.1909 Q0.5677,0.1919,0.5702,0.1919 T0.5791,0.1894 T0.588,0.1869 Q0.5921,0.1869,0.5945,0.1899 Q0.5977,0.1919,0.6123,0.1919 Q0.6334,0.1919,0.6448,0.1879 Q0.6488,0.186,0.6537,0.186 Q0.6626,0.186,0.6784,0.1909 T0.6983,0.1958 Q0.704,0.1968,0.7206,0.1973 T0.7506,0.1993 T0.7689,0.2018 L0.7705,0.2018 L0.7741,0.2018 L0.7786,0.2018 Q0.8248,0.2018,0.8475,0.2136 Q0.8597,0.2196,0.8597,0.2255 T0.8483,0.2359 T0.8281,0.2404 Q0.8208,0.2404,0.7534,0.2493 Q0.7502,0.2502,0.7425,0.2512 T0.7287,0.2532 T0.7178,0.2542 L0.7153,0.2542 L0.7137,0.2542 Q0.7064,0.2542,0.6906,0.2591 T0.6715,0.2681 T0.6626,0.272 Q0.6594,0.272,0.6541,0.2705 T0.6464,0.269 T0.6431,0.27 Q0.6318,0.273,0.6034,0.276 Q0.6018,0.276,0.5998,0.2774 T0.5957,0.2799 T0.5904,0.2809 L0.5856,0.2809 Q0.5823,0.2799,0.575,0.2799 Q0.541,0.2799,0.5239,0.2868 Q0.5134,0.2908,0.5028,0.2908 Q0.4996,0.2908,0.4935,0.2903 T0.4842,0.2898 Q0.4704,0.2898,0.4635,0.2918 T0.4534,0.2997 L0.4534,0.3007 Q0.4534,0.3037,0.459,0.3046 T0.4753,0.3066 T0.4899,0.3076 Q0.4907,0.3076,0.5166,0.3106 T0.5507,0.3155 Q0.5921,0.3264,0.605,0.3264 Q0.6107,0.3264,0.6131,0.3254 Q0.6212,0.3225,0.6294,0.3225 Q0.6407,0.3225,0.6513,0.3274 Q0.6529,0.3294,0.6569,0.3294 Q0.6594,0.3294,0.665,0.3284 T0.6748,0.3274 T0.6821,0.3284 Q0.6861,0.3294,0.6967,0.3299 T0.7165,0.3314 T0.7299,0.3343 Q0.7324,0.3363,0.7486,0.3383 T0.7697,0.3422 Q0.7713,0.3432,0.7774,0.3452 T0.7887,0.3492 T0.8005,0.3546 T0.8127,0.3625 T0.8208,0.3719 Q0.8256,0.3798,0.8256,0.3848 Q0.8256,0.3877,0.8236,0.3902 T0.8171,0.3976 T0.809,0.4075 T0.8021,0.4189 T0.7968,0.4273 T0.7867,0.4322 T0.7616,0.4382 Q0.7543,0.4392,0.7437,0.4392 L0.7364,0.4392 L0.7299,0.4392 Q0.7202,0.4392,0.7161,0.4402 Q0.7072,0.4431,0.691,0.4431 L0.6845,0.4431 L0.6788,0.4431 Q0.6707,0.4431,0.6545,0.4461 T0.6334,0.452 Q0.6399,0.456,0.6626,0.457 Q0.6878,0.458,0.7024,0.4639 Q0.7064,0.4649,0.7186,0.4649 L0.7295,0.4649 L0.7413,0.4649 Q0.7591,0.4649,0.7697,0.4669 Q0.7818,0.4688,0.7818,0.4728 Q0.7818,0.4748,0.7798,0.4763 T0.7753,0.4787 L0.7737,0.4797 L0.7729,0.4797 Q0.7494,0.4827,0.7388,0.4827 Q0.7332,0.4827,0.7307,0.4817 L0.7291,0.4817 Q0.7226,0.4817,0.6878,0.4896 Q0.6829,0.4906,0.6772,0.4911 T0.6618,0.4921 T0.646,0.4931 T0.6342,0.4936 T0.6212,0.4931 T0.6115,0.4926 Q0.6083,0.4926,0.6058,0.4931 T0.5969,0.4955 T0.5819,0.499 T0.5629,0.5005 Q0.5572,0.5005,0.5527,0.501 T0.545,0.502 T0.5397,0.503 T0.5361,0.5045 T0.5337,0.5064 T0.5328,0.5094 L0.532,0.5094 Q0.532,0.5104,0.5337,0.5109 T0.5381,0.5114 T0.5438,0.5119 T0.5515,0.5124 L0.5604,0.5124 Q0.5661,0.5134,0.5746,0.5153 T0.5912,0.5173 L0.5977,0.5173 L0.6026,0.5173 Q0.6139,0.5173,0.6273,0.5218 T0.6407,0.5272 Q0.6448,0.5282,0.6683,0.5321 T0.6991,0.5381 Q0.7137,0.543,0.7664,0.548 Q0.7908,0.55,0.7908,0.5559 Q0.7908,0.5589,0.7859,0.5628 Q0.781,0.5658,0.7713,0.5658 Q0.7689,0.5658,0.7628,0.5653 T0.7543,0.5648 T0.7502,0.5658 Q0.7364,0.5678,0.6878,0.5678 Q0.674,0.5678,0.6699,0.5668 L0.6683,0.5668 Q0.6659,0.5668,0.6606,0.5678 T0.6513,0.5687 Q0.6464,0.5687,0.6391,0.5678 Q0.6334,0.5668,0.6302,0.5668 T0.6241,0.5687 T0.6164,0.5717 Q0.6123,0.5727,0.6099,0.5727 L0.6062,0.5727 T0.6022,0.5732 T0.5953,0.5737 Q0.5904,0.5747,0.5839,0.5747 T0.5726,0.5752 T0.5629,0.5776 T0.5458,0.5796 Q0.5418,0.5796,0.5324,0.5791 T0.5191,0.5786 Q0.5077,0.5786,0.5045,0.5806 Q0.498,0.5836,0.4899,0.5836 Q0.4858,0.5836,0.4777,0.5826 T0.4655,0.5816 L0.4631,0.5816 Q0.4582,0.5816,0.4436,0.5841 T0.4144,0.5865 L0.4051,0.5865 L0.3986,0.5865 T0.3933,0.587 T0.3897,0.5875 T0.3869,0.5885 T0.3844,0.5895 T0.3812,0.591 T0.3779,0.5925 Q0.3739,0.5955,0.3633,0.5955 L0.3585,0.5955 L0.3536,0.5955 Q0.3277,0.5955,0.3066,0.6053 Q0.3017,0.6083,0.296,0.6083 Q0.2912,0.6083,0.2839,0.6068 T0.2741,0.6053 Q0.2693,0.6053,0.2547,0.6048 T0.236,0.6044 Q0.2222,0.6044,0.193,0.6103 L0.1882,0.6103 Q0.1825,0.6103,0.1703,0.6083 T0.1525,0.6063 L0.15,0.6063 Q0.1436,0.6063,0.135,0.6073 T0.1168,0.6098 T0.1038,0.6113 Q0.0973,0.6123,0.0787,0.6123 L0.06,0.6123 L0.0414,0.6123 L0.0235,0.6123 Q0.0049,0.6133,0.0049,0.6172 L0.0057,0.6222 Q0.0073,0.6261,0.043,0.6261 L0.0454,0.6261 L0.0479,0.6261 Q0.0527,0.6261,0.0633,0.6281 T0.0803,0.6301 L0.0835,0.6301 L0.0916,0.6301 Q0.0998,0.6301,0.129,0.632 Q0.1768,0.636,0.206,0.64 Q0.2117,0.6409,0.2165,0.6409 Q0.2206,0.6409,0.2263,0.6405 T0.2336,0.64 L0.2384,0.64 L0.2409,0.64 T0.251,0.6395 T0.2644,0.639 Q0.2741,0.639,0.279,0.6409 Q0.283,0.6429,0.2972,0.6439 T0.3293,0.6459 T0.3528,0.6469 L0.3577,0.6469 Q0.3642,0.6469,0.3723,0.6449 T0.3844,0.6429 Q0.3901,0.6429,0.3933,0.6454 T0.4006,0.6479 Q0.4088,0.6479,0.4517,0.6558 Q0.4582,0.6568,0.4623,0.6568 Q0.4655,0.6568,0.4716,0.6563 T0.4826,0.6558 L0.4882,0.6558 Q0.5004,0.6558,0.5255,0.6607 Q0.5328,0.6627,0.5604,0.6647 T0.6152,0.6682 T0.644,0.6696 T0.6719,0.6721 T0.7056,0.6756 Q0.7113,0.6756,0.7198,0.6805 T0.738,0.6855 Q0.7453,0.6855,0.7551,0.6879 T0.7741,0.6939 T0.7912,0.7018 T0.8029,0.7102 Q0.8054,0.7132,0.8054,0.7151 Q0.8054,0.7191,0.8009,0.7216 T0.7908,0.7255 T0.779,0.7285 T0.7721,0.731 Q0.7672,0.7329,0.7632,0.7339 T0.7551,0.7354 T0.7486,0.7369 Q0.7478,0.7369,0.7445,0.7379 T0.7388,0.7394 T0.7324,0.7404 L0.7242,0.7413 T0.7161,0.7418 Q0.7105,0.7418,0.6955,0.7428 T0.6748,0.7438 L0.6699,0.7438 L0.6667,0.7438 Q0.6659,0.7438,0.6407,0.7468 Q0.6367,0.7478,0.6334,0.7478 T0.6245,0.7468 T0.6148,0.7458 L0.6099,0.7458 Q0.6018,0.7468,0.5864,0.7498 T0.5653,0.7532 T0.5596,0.7557 Q0.5596,0.7596,0.571,0.7616 Q0.5742,0.7626,0.5803,0.7631 T0.5929,0.7641 T0.6018,0.7656 L0.6087,0.7656 T0.6192,0.7666 T0.6277,0.7695 Q0.631,0.7705,0.6342,0.7705 Q0.6383,0.7705,0.6452,0.7685 T0.6537,0.7666 L0.6553,0.7666 Q0.6602,0.7666,0.6711,0.769 T0.6853,0.7715 Q0.691,0.7715,0.7048,0.775 T0.7242,0.7814 Q0.7324,0.7854,0.7445,0.7864 Q0.7478,0.7864,0.768,0.7873 T0.7972,0.7893 Q0.7989,0.7893,0.8017,0.7898 T0.8054,0.7903 L0.8082,0.7903 T0.811,0.7908 T0.8131,0.7913 T0.8151,0.7918 L0.8167,0.7928 T0.8179,0.7943 T0.8191,0.7957 T0.8204,0.7977 T0.8208,0.8002 Q0.8208,0.8032,0.8171,0.8051 T0.8074,0.8081 T0.7997,0.8091 Q0.7932,0.8121,0.7737,0.8121 Q0.7664,0.8121,0.7413,0.8111 L0.7364,0.8111 Q0.7275,0.8111,0.7214,0.8121 T0.7084,0.8155 T0.6991,0.819 Q0.6934,0.82,0.6723,0.8205 T0.6472,0.8239 Q0.6423,0.8269,0.6375,0.8269 Q0.6358,0.8269,0.6338,0.8264 T0.6294,0.8254 T0.6253,0.8249 Q0.6042,0.8249,0.5961,0.8289 Q0.5921,0.8318,0.5839,0.8318 Q0.5783,0.8318,0.5645,0.8299 L0.5604,0.8299 Q0.5531,0.8299,0.5337,0.8368 Q0.5296,0.8378,0.5255,0.8378 Q0.5239,0.8378,0.5195,0.8373 T0.5118,0.8368 Q0.5061,0.8368,0.4996,0.8388 Q0.4947,0.8388,0.4882,0.8398 Q0.4777,0.8417,0.4753,0.8427 T0.4728,0.8467 Q0.4728,0.8487,0.4769,0.8492 T0.4886,0.8501 T0.5004,0.8516 Q0.5036,0.8516,0.515,0.8521 T0.5345,0.8546 Q0.5426,0.8556,0.5596,0.8556 L0.5649,0.8556 L0.5702,0.8556 L0.5791,0.8556 Q0.5921,0.8566,0.6135,0.8571 T0.6383,0.8586 Q0.6683,0.8615,0.6764,0.8615 L0.6776,0.8615 L0.6788,0.8615 Q0.7032,0.8615,0.7032,0.8684 Q0.7032,0.8714,0.6995,0.8749 T0.6959,0.8803 L0.6959,0.8813 Q0.6991,0.8843,0.7153,0.8843 Q0.7218,0.8843,0.7259,0.8833 L0.7299,0.8833 Q0.7324,0.8833,0.7348,0.8838 T0.7393,0.8848 T0.7433,0.8863 L0.7474,0.8882 T0.751,0.8892 Q0.7616,0.8922,0.7948,0.8952 Q0.7981,0.8952,0.8082,0.8981 T0.8297,0.9011 T0.8528,0.9026 T0.8747,0.907 T0.8856,0.9149 L0.8856,0.9159 Q0.8856,0.9179,0.8848,0.9189 T0.8828,0.9209 T0.88,0.9228 T0.8767,0.9243 T0.8731,0.9248 T0.8698,0.9253 T0.8666,0.9258 L0.8646,0.9258 Q0.8621,0.9258,0.8577,0.9263 T0.85,0.9268 T0.8439,0.9273 T0.8402,0.9278 Q0.8386,0.9298,0.8358,0.9308 T0.8305,0.9322 T0.8244,0.9332 T0.8183,0.9337 Q0.8135,0.9347,0.8025,0.9372 T0.7859,0.9416 Q0.7778,0.9436,0.7717,0.9471 T0.7624,0.9515 Q0.7575,0.9535,0.7486,0.9535 Q0.7461,0.9535,0.7397,0.953 T0.7291,0.9525 Q0.7234,0.9525,0.7186,0.953 T0.7137,0.957 T0.7194,0.9614 Q0.7567,0.9634,0.7664,0.9654 Q0.7745,0.9674,0.7762,0.9674 L0.7908,0.9674 Q0.7924,0.9664,0.7948,0.9664 Q0.8029,0.9664,0.8082,0.9679 T0.8224,0.9723 T0.8362,0.9773 Q0.8483,0.9812,0.871,0.9812 L0.8751,0.9812 Q0.8873,0.9812,0.8929,0.9822 T0.9165,0.9876 T0.9408,0.9931 Q0.9513,0.996,0.9935,0.996 Z M0.9968,0.998 L0.9976,0.003 Q0.9838,0.002,0.9708,0.0059 Q0.9659,0.0069,0.9327,0.0059 T0.8881,0.0099 Q0.8767,0.0138,0.8658,0.0163 T0.8491,0.0218 Q0.8418,0.0247,0.8341,0.0247 T0.8232,0.0257 Q0.8191,0.0277,0.7997,0.0292 T0.7737,0.0326 Q0.7697,0.0336,0.7672,0.0336 T0.7612,0.0321 T0.7543,0.0307 T0.747,0.0317 Q0.7397,0.0326,0.7336,0.0356 T0.717,0.0406 Q0.6918,0.0445,0.6861,0.0475 Q0.6845,0.0485,0.6772,0.0485 T0.6638,0.05 T0.6577,0.0549 T0.6642,0.0598 T0.6796,0.0613 T0.6902,0.0623 Q0.691,0.0623,0.6946,0.0658 T0.7064,0.0702 L0.7161,0.0702 Q0.7194,0.0702,0.7242,0.0697 T0.7332,0.0692 Q0.7413,0.0692,0.7579,0.0717 T0.781,0.0762 Q0.7867,0.0781,0.8171,0.0786 T0.85,0.0801 L0.8532,0.0801 Q0.8548,0.0801,0.8613,0.0796 T0.8727,0.0791 Q0.8832,0.0791,0.8913,0.0811 Q0.897,0.0831,0.897,0.0851 Q0.897,0.088,0.8873,0.0905 T0.8735,0.093 Q0.871,0.093,0.8447,0.0984 T0.8143,0.1039 Q0.7981,0.1039,0.781,0.1078 Q0.7778,0.1088,0.7745,0.1088 T0.7644,0.1073 T0.7518,0.1048 L0.7453,0.1048 Q0.7299,0.1048,0.7076,0.1083 T0.6788,0.1157 Q0.6748,0.1187,0.6699,0.1187 Q0.6675,0.1187,0.6557,0.1157 T0.6318,0.1118 Q0.6164,0.1108,0.6135,0.1108 T0.6095,0.1113 T0.6067,0.1142 T0.6018,0.1187 Q0.5953,0.1227,0.5921,0.1227 Q0.5904,0.1227,0.5839,0.1212 T0.5693,0.1187 L0.5661,0.1187 Q0.558,0.1187,0.5527,0.1207 T0.5434,0.1246 T0.5337,0.1266 Q0.5126,0.1296,0.4882,0.1296 T0.4371,0.1385 Q0.4298,0.1414,0.425,0.1414 Q0.4225,0.1414,0.4189,0.1395 T0.4112,0.1375 Q0.4079,0.1375,0.4019,0.1395 T0.3869,0.1414 Q0.3682,0.1414,0.3504,0.1474 Q0.3398,0.1513,0.3333,0.1513 Q0.3293,0.1513,0.3228,0.1494 L0.3204,0.1494 Q0.3179,0.1494,0.3155,0.1508 T0.3118,0.1543 T0.3106,0.1592 T0.3127,0.1642 T0.32,0.1677 T0.3305,0.1701 T0.3435,0.1716 T0.3544,0.1721 Q0.3569,0.1731,0.3601,0.1731 Q0.3625,0.1731,0.3686,0.1726 T0.3779,0.1721 Q0.3901,0.1721,0.4023,0.1751 Q0.4177,0.18,0.455,0.18 Q0.4793,0.18,0.4882,0.178 L0.4915,0.178 Q0.4964,0.178,0.5045,0.1815 T0.5158,0.185 Q0.5564,0.1889,0.5645,0.1929 Q0.5677,0.1939,0.571,0.1939 Q0.575,0.1939,0.5807,0.1919 T0.5888,0.1899 T0.5929,0.1909 Q0.5969,0.1949,0.6123,0.1949 Q0.6334,0.1949,0.6456,0.1899 Q0.6488,0.1879,0.6537,0.1879 Q0.661,0.1879,0.6772,0.1929 T0.6983,0.1978 Q0.704,0.1988,0.7206,0.1998 T0.7502,0.2018 T0.7664,0.2038 Q0.7672,0.2038,0.7818,0.2043 T0.8151,0.2067 T0.8459,0.2156 Q0.8573,0.2206,0.8573,0.2255 Q0.8573,0.2295,0.8516,0.2324 T0.8394,0.2369 T0.8281,0.2384 Q0.8208,0.2384,0.7526,0.2473 Q0.7494,0.2483,0.7421,0.2493 T0.7287,0.2512 T0.7178,0.2522 L0.7153,0.2522 L0.7137,0.2522 Q0.7056,0.2522,0.6898,0.2572 T0.6691,0.2671 Q0.6667,0.269,0.6634,0.269 Q0.661,0.269,0.6557,0.2681 T0.6472,0.2671 Q0.6448,0.2671,0.6415,0.2681 Q0.631,0.271,0.6034,0.274 Q0.5994,0.274,0.5961,0.2765 T0.5904,0.2789 L0.5864,0.2789 Q0.5831,0.2779,0.5742,0.2779 Q0.541,0.2779,0.5223,0.2849 Q0.5126,0.2888,0.5028,0.2888 Q0.5004,0.2888,0.4943,0.2883 T0.4842,0.2878 Q0.4704,0.2878,0.4627,0.2898 T0.4509,0.2987 Q0.4501,0.2997,0.4501,0.3007 Q0.4501,0.3046,0.4574,0.3066 T0.4765,0.3091 T0.4899,0.3096 Q0.4931,0.3106,0.5061,0.3121 T0.5316,0.315 T0.5499,0.3175 Q0.5507,0.3175,0.5572,0.3195 T0.5685,0.3225 T0.5803,0.3254 T0.5933,0.3279 T0.605,0.3284 T0.6148,0.3274 Q0.6221,0.3244,0.6294,0.3244 Q0.6399,0.3244,0.6496,0.3294 Q0.6529,0.3314,0.6577,0.3314 Q0.6602,0.3314,0.6663,0.3304 T0.6756,0.3294 T0.6813,0.3304 Q0.6837,0.3304,0.6873,0.3309 L0.6946,0.3318 T0.7024,0.3323 T0.7105,0.3328 T0.7178,0.3338 T0.7238,0.3348 T0.7283,0.3363 Q0.7324,0.3383,0.7482,0.3403 T0.7689,0.3442 Q0.7697,0.3442,0.779,0.3477 T0.794,0.3536 T0.8074,0.3615 T0.8183,0.3729 Q0.8232,0.3808,0.8232,0.3848 Q0.8232,0.3867,0.8216,0.3892 T0.8151,0.3961 T0.8062,0.406 T0.7997,0.4179 T0.7952,0.4263 T0.7855,0.4308 T0.7616,0.4362 Q0.7543,0.4372,0.7445,0.4372 L0.7372,0.4372 L0.7307,0.4372 Q0.7202,0.4372,0.7153,0.4382 Q0.7064,0.4402,0.691,0.4402 L0.6845,0.4402 L0.6788,0.4402 Q0.6699,0.4402,0.6533,0.4436 T0.6318,0.451 Q0.6302,0.451,0.6302,0.452 Q0.6302,0.457,0.6626,0.459 Q0.6869,0.4609,0.7015,0.4659 Q0.7064,0.4669,0.7202,0.4669 L0.7311,0.4669 L0.7429,0.4669 Q0.7599,0.4669,0.7689,0.4688 Q0.7794,0.4708,0.7794,0.4738 L0.7786,0.4748 T0.777,0.4763 T0.7749,0.4773 L0.7737,0.4777 L0.7729,0.4777 Q0.7502,0.4797,0.738,0.4797 L0.7315,0.4797 L0.7291,0.4797 Q0.7226,0.4797,0.6869,0.4876 Q0.6821,0.4886,0.6768,0.4891 T0.6614,0.4901 T0.6456,0.4916 L0.6342,0.4916 Q0.6294,0.4916,0.6217,0.4911 T0.6115,0.4906 Q0.6083,0.4906,0.6054,0.4911 T0.5961,0.4936 T0.5815,0.4965 T0.5629,0.4985 Q0.5507,0.4985,0.5442,0.4995 T0.5345,0.5025 T0.5304,0.5084 L0.5296,0.5094 Q0.5296,0.5114,0.5316,0.5124 T0.5373,0.5138 T0.5442,0.5143 L0.5523,0.5143 L0.5604,0.5143 Q0.5637,0.5153,0.5677,0.5158 T0.5742,0.5173 T0.5811,0.5188 T0.5904,0.5193 L0.5977,0.5193 L0.6026,0.5193 Q0.6107,0.5193,0.6168,0.5208 T0.6294,0.5252 T0.6399,0.5292 Q0.6448,0.5302,0.6679,0.5341 T0.6983,0.541 Q0.7129,0.545,0.7664,0.55 Q0.7883,0.5519,0.7883,0.5559 Q0.7883,0.5579,0.7843,0.5608 T0.7721,0.5638 Q0.7697,0.5638,0.764,0.5633 T0.7559,0.5628 L0.7502,0.5628 Q0.7364,0.5648,0.6869,0.5648 L0.6699,0.5648 L0.6675,0.5648 Q0.665,0.5648,0.6602,0.5658 T0.6513,0.5668 Q0.6464,0.5668,0.6399,0.5658 Q0.6342,0.5648,0.6302,0.5648 T0.6225,0.5668 T0.6156,0.5697 Q0.6107,0.5707,0.6087,0.5707 T0.6034,0.5712 T0.5953,0.5717 Q0.5904,0.5727,0.5835,0.5727 T0.5718,0.5732 T0.562,0.5757 Q0.558,0.5767,0.5483,0.5767 L0.5349,0.5767 L0.5207,0.5767 Q0.5069,0.5767,0.5028,0.5786 Q0.4972,0.5816,0.4899,0.5816 Q0.4858,0.5816,0.4781,0.5806 T0.4663,0.5796 L0.4631,0.5796 Q0.4582,0.5796,0.4432,0.5821 T0.4144,0.5846 L0.4071,0.5846 L0.4011,0.5846 T0.3958,0.5851 T0.3921,0.5856 T0.3889,0.5861 T0.3865,0.5865 T0.384,0.5875 L0.382,0.5885 L0.3796,0.5895 L0.3771,0.5905 Q0.3731,0.5925,0.365,0.5925 L0.3601,0.5925 L0.3552,0.5925 Q0.3277,0.5925,0.3049,0.6044 Q0.3017,0.6053,0.296,0.6053 Q0.292,0.6053,0.2847,0.6044 T0.2741,0.6034 Q0.2693,0.6034,0.2547,0.6029 T0.236,0.6024 Q0.2222,0.6024,0.1922,0.6073 Q0.1906,0.6083,0.1882,0.6083 Q0.1833,0.6083,0.1711,0.6063 T0.1533,0.6044 Q0.1517,0.6034,0.1492,0.6034 Q0.1436,0.6034,0.135,0.6048 T0.1168,0.6078 T0.103,0.6093 Q0.0973,0.6103,0.0787,0.6103 L0.0604,0.6103 L0.0414,0.6103 L0.0235,0.6103 Q0.0024,0.6113,0.0024,0.6172 Q0.0024,0.6192,0.0032,0.6231 Q0.0049,0.6281,0.0333,0.6281 L0.0414,0.6281 L0.0479,0.6281 Q0.0519,0.6281,0.0624,0.6301 T0.0803,0.632 L0.0835,0.632 L0.0916,0.632 Q0.0989,0.632,0.1281,0.634 L0.206,0.6419 Q0.2117,0.6429,0.2174,0.6429 Q0.2214,0.6429,0.2271,0.6424 T0.2344,0.6419 L0.2376,0.6419 Q0.2393,0.6429,0.2417,0.6429 T0.2526,0.6419 T0.2652,0.6409 Q0.2741,0.6409,0.2782,0.6429 T0.2968,0.6459 T0.3293,0.6479 T0.352,0.6489 Q0.3552,0.6499,0.3585,0.6499 Q0.365,0.6499,0.3731,0.6474 T0.3844,0.6449 Q0.3885,0.6449,0.3917,0.6474 T0.4006,0.6499 Q0.4088,0.6499,0.4509,0.6578 Q0.4574,0.6588,0.4631,0.6588 Q0.4655,0.6588,0.4716,0.6583 T0.4834,0.6578 L0.4874,0.6578 Q0.5004,0.6588,0.5255,0.6637 Q0.532,0.6647,0.56,0.6667 T0.6148,0.6701 T0.644,0.6716 Q0.6464,0.6726,0.6594,0.6736 T0.6861,0.6756 T0.7048,0.6775 Q0.7097,0.6775,0.7186,0.6825 T0.738,0.6874 Q0.7518,0.6874,0.7729,0.6958 T0.8005,0.7122 Q0.8029,0.7141,0.8029,0.7151 Q0.8029,0.7191,0.7968,0.7216 T0.7818,0.726 T0.7705,0.729 L0.764,0.731 T0.7583,0.7324 T0.753,0.7334 T0.7486,0.7349 Q0.7251,0.7399,0.7161,0.7399 Q0.7097,0.7399,0.6951,0.7409 T0.6748,0.7418 L0.6703,0.7418 L0.6667,0.7418 Q0.6659,0.7418,0.6399,0.7448 L0.6334,0.7448 Q0.631,0.7448,0.6249,0.7443 T0.6148,0.7438 L0.6099,0.7438 Q0.601,0.7448,0.5856,0.7473 T0.5645,0.7507 Q0.5572,0.7517,0.5572,0.7547 T0.5616,0.7606 T0.5702,0.7646 Q0.5734,0.7646,0.5779,0.7651 T0.5864,0.7661 T0.5949,0.7671 T0.6018,0.7676 L0.6071,0.7676 T0.6135,0.7681 T0.62,0.769 T0.6269,0.771 T0.6342,0.7725 Q0.6391,0.7725,0.6464,0.7705 T0.6541,0.7685 L0.6553,0.7685 Q0.6586,0.7685,0.6699,0.771 T0.6853,0.7735 Q0.6902,0.7735,0.704,0.777 T0.7226,0.7834 Q0.7315,0.7873,0.7445,0.7883 Q0.747,0.7883,0.7676,0.7893 T0.7972,0.7913 Q0.7989,0.7913,0.8017,0.7918 T0.8058,0.7923 T0.809,0.7928 T0.8114,0.7933 T0.8131,0.7938 T0.8147,0.7943 T0.8159,0.7953 L0.8171,0.7967 T0.8175,0.7982 Q0.8183,0.7992,0.8183,0.8002 Q0.8183,0.8022,0.8155,0.8032 T0.807,0.8051 T0.7989,0.8071 Q0.7932,0.8091,0.7737,0.8091 L0.7413,0.8091 L0.7372,0.8091 Q0.7275,0.8091,0.721,0.8101 T0.7072,0.8136 T0.6983,0.817 Q0.6942,0.818,0.6825,0.818 T0.6602,0.819 T0.6456,0.822 Q0.6415,0.8249,0.6375,0.8249 Q0.6367,0.8249,0.6326,0.8239 T0.6253,0.8229 Q0.6034,0.8229,0.5953,0.8279 Q0.5912,0.8289,0.5848,0.8289 Q0.5775,0.8289,0.5645,0.8279 Q0.5629,0.8269,0.5604,0.8269 Q0.5523,0.8269,0.5328,0.8348 Q0.5296,0.8358,0.5264,0.8358 Q0.5247,0.8358,0.5203,0.8353 T0.5126,0.8348 Q0.5061,0.8348,0.4988,0.8358 Q0.4947,0.8368,0.4882,0.8378 Q0.4826,0.8388,0.4797,0.8388 T0.474,0.8398 T0.4704,0.8422 T0.4696,0.8462 T0.472,0.8501 T0.4781,0.8521 T0.4854,0.8526 L0.4935,0.8526 T0.4996,0.8536 Q0.5036,0.8536,0.515,0.8546 T0.5337,0.8566 Q0.5426,0.8576,0.5596,0.8576 L0.5657,0.8576 L0.571,0.8576 L0.5791,0.8576 Q0.5921,0.8586,0.6135,0.8591 T0.6383,0.8605 Q0.6683,0.8635,0.6764,0.8635 Q0.6999,0.8635,0.6999,0.8684 Q0.6999,0.8694,0.6967,0.8734 T0.6934,0.8803 L0.6934,0.8823 Q0.6951,0.8863,0.7137,0.8863 Q0.7218,0.8863,0.7267,0.8853 L0.7299,0.8853 Q0.734,0.8853,0.7409,0.8882 T0.7502,0.8912 Q0.7607,0.8942,0.794,0.8971 Q0.7972,0.8971,0.8078,0.9001 T0.8297,0.9031 Q0.8475,0.9031,0.8646,0.9065 T0.8824,0.9149 L0.8824,0.9159 Q0.8824,0.9169,0.882,0.9179 T0.8808,0.9194 L0.8792,0.9204 T0.8767,0.9214 T0.8743,0.9224 T0.8715,0.9228 L0.8686,0.9228 T0.8662,0.9233 T0.8637,0.9238 L0.8556,0.9238 T0.8447,0.9243 T0.8386,0.9268 Q0.837,0.9278,0.835,0.9288 T0.8305,0.9303 T0.8244,0.9308 T0.8175,0.9318 Q0.8127,0.9327,0.8017,0.9352 T0.7851,0.9397 Q0.777,0.9416,0.7705,0.9451 T0.7616,0.9496 Q0.7575,0.9505,0.7494,0.9505 L0.7405,0.9505 L0.7307,0.9505 Q0.7234,0.9505,0.7178,0.9515 Q0.7145,0.9515,0.7125,0.9535 T0.7105,0.9575 Q0.7105,0.9624,0.7194,0.9634 Q0.7567,0.9654,0.7664,0.9674 Q0.7745,0.9693,0.7762,0.9693 L0.7908,0.9693 L0.7948,0.9693 Q0.8005,0.9693,0.8058,0.9698 T0.8143,0.9718 T0.824,0.9753 T0.8354,0.9792 Q0.8483,0.9832,0.871,0.9832 L0.8739,0.9832 L0.8767,0.9832 Q0.8873,0.9832,0.8921,0.9842 Q0.8978,0.9852,0.9157,0.9896 T0.94,0.996 Q0.9424,0.996,0.9469,0.9965 T0.9566,0.997 T0.9676,0.9975 T0.9781,0.998 L0.9874,0.998 L0.9943,0.998 L0.9968,0.998 Z",type:0}},"\uE0CC":{type:5,data:{d:"M1,0.5071 L0.8623,0.7102 L0.5865,0.7102 L0.4489,0.5071 L0.5865,0.3045 L0.8623,0.3045 Z M0.4135,0.7974 L0.2758,1 L0,1 L0,0.5944 L0.2758,0.5944 Z M0.4135,0.2026 L0.2758,0.4056 L0,0.4056 L0,0 L0.2758,0 Z",type:0}},"\uE0CD":{type:5,data:{d:"M0.9726,0.5071 L0.8451,0.3184 L0.59,0.3184 L0.4624,0.5071 L0.59,0.6955 L0.8451,0.6955 Z M1,0.5071 L0.8588,0.716 L0.5768,0.716 L0.4355,0.5071 L0.5768,0.2982 L0.8588,0.2982 Z M0.401,0.7911 L0.2735,0.6028 L0.0236,0.6028 L0.0236,0.9799 L0.2735,0.9799 Z M0.4284,0.7911 L0.2872,1 L0,1 L0,0.5826 L0.2872,0.5826 Z M0.401,0.2089 L0.2735,0.0201 L0.0236,0.0201 L0.0236,0.3972 L0.2735,0.3972 Z M0.4284,0.2089 L0.2872,0.4174 L0,0.4174 L0,0 L0.2872,0 Z",type:0}},"\uE0CE":{type:5,data:{d:"M1,0.4996 Q1,0.5365,0.9924,0.568 T0.9718,0.6177 T0.9433,0.6363 L0.9425,0.6367 Q0.9355,0.6367,0.9285,0.6326 L0.9308,0.6326 Q0.9129,0.6195,0.9013,0.587 T0.8871,0.5164 T0.8943,0.4373 T0.9254,0.3687 L0.9254,0.3691 Q0.9339,0.3628,0.9425,0.3628 Q0.9584,0.3628,0.9716,0.3811 T0.9924,0.431 T1,0.4996 Z M0.9234,0.6321 L0.8776,0.7169 Q0.8791,0.732,0.8791,0.7441 Q0.8791,0.781,0.8716,0.8123 T0.8508,0.862 T0.8224,0.8809 L0.8216,0.8809 Q0.8154,0.8809,0.8092,0.8775 L0.8088,0.8775 Q0.7905,0.8633,0.7792,0.8297 T0.766,0.7571 T0.775,0.6768 T0.8088,0.6086 L0.7431,0.6065 Q0.719,0.6313,0.7072,0.6705 T0.6965,0.7487 T0.7097,0.823 T0.7423,0.8763 L0.7913,0.8775 L0.7314,0.9895 L0.4648,0.5038 L0.7299,0.0176 L0.7882,0.1229 L0.7404,0.1212 Q0.7244,0.138,0.7136,0.1617 T0.6982,0.2108 T0.6943,0.2632 T0.7003,0.3144 T0.7159,0.3586 T0.7396,0.3909 L0.8072,0.3926 Q0.7894,0.3796,0.7777,0.3479 T0.7635,0.2789 T0.7697,0.2011 T0.7987,0.1326 Q0.8092,0.1225,0.8204,0.1225 Q0.8321,0.1225,0.8426,0.1332 T0.8609,0.1623 T0.8731,0.2062 T0.8776,0.2592 Q0.8776,0.268,0.8768,0.2815 L0.9219,0.3628 L0.8644,0.3612 Q0.8403,0.3855,0.8284,0.4247 T0.8177,0.5029 T0.8309,0.5772 T0.8632,0.6305 Z M0.6759,0.6384 Q0.6576,0.625,0.6457,0.5914 T0.6319,0.5185 T0.6407,0.4375 T0.6751,0.3691 L0.609,0.367 Q0.5849,0.3918,0.5731,0.431 T0.5626,0.509 T0.5758,0.5833 T0.6082,0.6367 Z M0.6459,0.0025 L0.391,0.4551 L0.0035,0.4551 L0.246,0 Z M0.6553,1 L0.2421,1 L0,0.5449 L0.3875,0.5449 Z",type:0}},"\uE0CF":{type:5,data:{d:"M0.4996,0 Q0.5562,0,0.5961,0.0166 T0.6364,0.0566 L0.6368,0.0575 Q0.6368,0.0646,0.6324,0.0713 L0.6324,0.0692 Q0.6196,0.0868,0.5872,0.0986 T0.5166,0.1128 T0.4373,0.1057 T0.3689,0.0747 L0.3694,0.0747 Q0.3627,0.0663,0.3627,0.0575 Q0.3627,0.0336,0.4028,0.0168 T0.4996,0 Z M0.6324,0.0768 L0.717,0.1225 Q0.7321,0.1212,0.744,0.1212 Q0.8007,0.1212,0.8406,0.1378 T0.8809,0.1779 L0.8813,0.1783 Q0.8813,0.1846,0.8778,0.1909 Q0.8636,0.2093,0.8299,0.2208 T0.7573,0.2343 T0.6769,0.2253 T0.6089,0.1913 L0.6067,0.2567 Q0.6315,0.281,0.6707,0.2928 T0.7489,0.3035 T0.8231,0.2903 T0.8764,0.258 L0.8778,0.2085 L0.9898,0.2685 L0.504,0.5352 L0.0177,0.2701 L0.1227,0.2118 L0.1213,0.2596 Q0.1457,0.2836,0.1851,0.2955 T0.2635,0.3062 T0.3377,0.293 T0.3911,0.2605 L0.3928,0.193 Q0.38,0.2106,0.3483,0.2221 T0.2792,0.2364 T0.2013,0.2303 T0.1324,0.2013 Q0.1222,0.1909,0.1222,0.1795 Q0.1222,0.156,0.1623,0.1393 T0.2591,0.1225 Q0.2679,0.1225,0.2817,0.1233 L0.3627,0.078 L0.3609,0.1359 Q0.3857,0.1598,0.4249,0.1718 T0.5031,0.1825 T0.5773,0.1693 T0.6306,0.1367 Z M0.6386,0.3242 Q0.6253,0.3427,0.5917,0.3544 T0.5186,0.3683 T0.4376,0.3595 T0.3689,0.3251 L0.3671,0.3909 Q0.3915,0.4148,0.4309,0.4268 T0.5093,0.4375 T0.5835,0.4243 T0.6368,0.3918 Z M0.0027,0.354 L0.4553,0.6091 L0.4553,0.9962 L0,0.7542 Z M1,0.3448 L1,0.7576 L0.5447,1 L0.5447,0.6128 Z",type:0}},"\uE0D0":{type:5,data:{d:"M0,0.7699 Q0,0.7172,0.0277,0.6731 T0.103,0.6032 T0.2066,0.5774 Q0.2487,0.5774,0.2865,0.5922 T0.3526,0.6339 L0.3935,0.6715 Q0.4218,0.6984,0.438,0.7336 T0.4541,0.8075 Q0.4541,0.8602,0.4264,0.9046 T0.3511,0.9745 T0.2475,1 Q0.2054,1,0.1676,0.9852 T0.1016,0.9435 L0.0606,0.9059 Q0.0317,0.879,0.0159,0.8438 T0,0.7699 Z M0.5459,0.7699 Q0.5459,0.7172,0.5736,0.6731 T0.6489,0.6032 T0.7525,0.5774 Q0.7946,0.5774,0.8324,0.5922 T0.8984,0.6339 L0.9394,0.6715 Q0.9579,0.6892,0.9714,0.7105 T0.9925,0.7567 T1,0.8075 Q1,0.8602,0.9723,0.9046 T0.897,0.9745 T0.7934,1 Q0.7513,1,0.7135,0.9852 T0.6474,0.9435 L0.6065,0.9059 Q0.5776,0.879,0.5617,0.8438 T0.5459,0.7699 Z M0,0.1925 Q0,0.1398,0.0277,0.0957 T0.103,0.0258 T0.2066,0 Q0.2487,0,0.2865,0.0148 T0.3526,0.0565 L0.3935,0.0941 Q0.4218,0.121,0.438,0.1562 T0.4541,0.2301 Q0.4541,0.2828,0.4264,0.3269 T0.3511,0.3968 T0.2475,0.4226 Q0.2054,0.4226,0.1676,0.4078 T0.1016,0.3661 L0.0606,0.3285 Q0.0317,0.3016,0.0159,0.2664 T0,0.1925 Z M0.5459,0.1925 Q0.5459,0.1398,0.5736,0.0957 T0.6489,0.0258 T0.7525,0 Q0.7946,0,0.8324,0.0148 T0.8984,0.0565 L0.9394,0.0941 Q0.9677,0.121,0.9838,0.1562 T1,0.2301 Q1,0.2828,0.9723,0.3269 T0.897,0.3968 T0.7934,0.4226 Q0.7513,0.4226,0.7135,0.4078 T0.6474,0.3661 L0.6065,0.3285 Q0.5874,0.3108,0.5741,0.2895 T0.5534,0.2433 T0.5459,0.1925 Z M0.3301,0.6403 Q0.3306,0.6403,0.3312,0.6409 L0.3272,0.6371 L0.3272,0.6371 Z M0.8759,0.6403 Q0.8765,0.6403,0.8771,0.6409 Q0.8748,0.6387,0.8725,0.6371 L0.8731,0.6371 Z M0.3301,0.0629 Q0.3306,0.0629,0.3312,0.0634 L0.3272,0.0597 L0.3272,0.0602 Z M0.8759,0.0629 Q0.8765,0.0629,0.8771,0.0634 Q0.8748,0.0613,0.8725,0.0597 Q0.8731,0.0597,0.8731,0.0602 Z M0.779,0.4113 L0.7501,0.3849 Q0.7046,0.3844,0.6636,0.3661 Q0.7132,0.407,0.779,0.4113 Z M0.7957,0.4118 Q0.8477,0.4113,0.8918,0.3874 T0.9619,0.3223 T0.9885,0.2323 L0.9585,0.2048 Q0.9538,0.2769,0.8987,0.3282 T0.7657,0.3844 Z M0.9879,0.2167 Q0.9827,0.1554,0.9388,0.1097 Q0.9585,0.1478,0.959,0.1898 Z M0.2331,0.4113 L0.2043,0.3849 Q0.1587,0.3844,0.1177,0.3661 Q0.1673,0.407,0.2331,0.4113 Z M0.2499,0.4118 Q0.2885,0.4118,0.324,0.3973 T0.3852,0.3589 T0.4264,0.3019 T0.4426,0.2323 L0.4126,0.2048 Q0.408,0.2769,0.3529,0.3282 T0.2198,0.3844 Z M0.442,0.2167 Q0.4368,0.1554,0.393,0.1097 Q0.4126,0.1478,0.4132,0.1903 Z M0.779,0.9887 L0.7501,0.9624 Q0.7046,0.9618,0.6636,0.9435 Q0.7132,0.9844,0.779,0.9887 Z M0.7957,0.9892 Q0.8477,0.9887,0.8918,0.9648 T0.9619,0.8997 T0.9885,0.8097 L0.9585,0.7823 Q0.9538,0.8543,0.8987,0.9056 T0.7657,0.9618 Z M0.9879,0.7941 Q0.9827,0.7328,0.9388,0.6871 Q0.9585,0.7253,0.959,0.7672 Z M0.2331,0.9887 L0.2043,0.9624 Q0.1587,0.9618,0.1177,0.9435 Q0.1673,0.9844,0.2331,0.9887 Z M0.2499,0.9892 Q0.3018,0.9887,0.3459,0.9648 T0.416,0.8997 T0.4426,0.8102 L0.4126,0.7823 Q0.408,0.8543,0.3529,0.9056 T0.2198,0.9618 Z M0.442,0.7941 Q0.4368,0.7328,0.393,0.6871 Q0.4126,0.7253,0.4132,0.7672 Z M0.3191,0.6452 Q0.2943,0.622,0.2643,0.6091 T0.2066,0.5962 Q0.1795,0.5962,0.1497,0.6091 T0.0949,0.6441 T0.0537,0.6995 T0.0375,0.7699 Q0.0375,0.8419,0.0941,0.8941 Q0.1189,0.9172,0.1489,0.9304 T0.2066,0.9435 Q0.2337,0.9435,0.2634,0.9304 T0.3182,0.8952 T0.3595,0.8398 T0.3756,0.7699 Q0.3756,0.6978,0.3191,0.6452 Z M0.026,0.7731 L0.026,0.7699 Q0.026,0.6935,0.0854,0.6376 Q0.0658,0.6538,0.0514,0.6739 T0.0289,0.718 T0.0202,0.7677 Z M0.0271,0.7892 L0.0208,0.7833 Q0.0254,0.8419,0.0681,0.886 Q0.0664,0.8828,0.0646,0.879 Q0.0329,0.8382,0.0271,0.7892 Z M0.3866,0.7823 Q0.382,0.8511,0.3278,0.9016 Q0.3843,0.8565,0.3918,0.7871 Z M0.3872,0.7677 L0.393,0.7726 L0.393,0.7699 Q0.393,0.7349,0.3791,0.7038 Q0.3739,0.6973,0.3681,0.6914 Q0.3866,0.7274,0.3872,0.7677 Z M0.865,0.6452 Q0.8402,0.622,0.8102,0.6091 T0.7525,0.5962 Q0.7305,0.5962,0.7072,0.6043 T0.6619,0.628 T0.6223,0.6642 T0.5941,0.7124 T0.5834,0.7699 Q0.5834,0.8419,0.6399,0.8941 Q0.6561,0.9097,0.6757,0.9207 T0.7149,0.9376 T0.7525,0.9435 Q0.7796,0.9435,0.8093,0.9304 T0.8641,0.8952 T0.9054,0.8398 T0.9215,0.7699 Q0.9215,0.6978,0.865,0.6452 Z M0.5718,0.7731 L0.5718,0.7699 Q0.5718,0.6935,0.6313,0.6376 Q0.6013,0.6618,0.584,0.6954 T0.5661,0.7677 Z M0.573,0.7892 L0.5666,0.7833 Q0.5713,0.8419,0.614,0.886 Q0.6122,0.8828,0.6105,0.879 Q0.5788,0.8382,0.573,0.7892 Z M0.9325,0.7823 Q0.9279,0.8511,0.8736,0.9016 Q0.9308,0.8565,0.9377,0.7871 Z M0.9331,0.7672 L0.9388,0.7726 L0.9388,0.7699 Q0.9388,0.7349,0.925,0.7038 Q0.9198,0.6973,0.914,0.6914 Q0.9325,0.7274,0.9331,0.7672 Z M0.3191,0.0677 Q0.2943,0.0446,0.2643,0.0317 T0.2066,0.0188 Q0.1795,0.0188,0.1497,0.0317 T0.0949,0.0667 T0.0537,0.122 T0.0375,0.1925 Q0.0375,0.2645,0.0941,0.3167 Q0.1189,0.3398,0.1489,0.353 T0.2066,0.3661 Q0.2337,0.3661,0.2634,0.353 T0.3182,0.3177 T0.3595,0.2624 T0.3756,0.1925 Q0.3756,0.1204,0.3191,0.0677 Z M0.026,0.1957 L0.026,0.1925 Q0.026,0.1161,0.0854,0.0602 Q0.0554,0.0844,0.0381,0.118 T0.0202,0.1903 Z M0.0271,0.2118 L0.0208,0.2059 Q0.0254,0.2645,0.0681,0.3086 Q0.0664,0.3054,0.0646,0.3016 Q0.0329,0.2608,0.0271,0.2118 Z M0.3866,0.2048 Q0.382,0.2737,0.3278,0.3242 Q0.3849,0.279,0.3918,0.2097 Z M0.3872,0.1903 L0.393,0.1952 L0.393,0.1925 Q0.393,0.1581,0.3791,0.1263 Q0.3739,0.1199,0.3681,0.114 Q0.3866,0.15,0.3872,0.1903 Z M0.865,0.0677 Q0.8402,0.0446,0.8102,0.0317 T0.7525,0.0188 Q0.7253,0.0188,0.6956,0.0317 T0.6408,0.0667 T0.5995,0.122 T0.5834,0.1925 Q0.5834,0.2645,0.6399,0.3167 Q0.6647,0.3398,0.6947,0.353 T0.7525,0.3661 Q0.7796,0.3661,0.8093,0.353 T0.8641,0.3177 T0.9054,0.2624 T0.9215,0.1925 Q0.9215,0.1204,0.865,0.0677 Z M0.5718,0.1957 L0.5718,0.1925 Q0.5718,0.1161,0.6313,0.0602 Q0.6013,0.0844,0.584,0.118 T0.5661,0.1903 Z M0.573,0.2118 L0.5666,0.2059 Q0.5713,0.2645,0.614,0.3086 Q0.6122,0.3054,0.6105,0.3016 Q0.5788,0.2608,0.573,0.2118 Z M0.9325,0.2048 Q0.9279,0.2737,0.8736,0.3242 Q0.9308,0.279,0.9377,0.2097 Z M0.9331,0.1898 L0.9388,0.1952 L0.9388,0.1925 Q0.9388,0.1575,0.925,0.1263 Q0.9198,0.1199,0.914,0.114 Q0.9325,0.15,0.9331,0.1898 Z",type:0}},"\uE0D1":{type:5,data:{d:"M0.7639,0.1974 L0.9593,0.1974 L0.9593,0.1443 L0.7639,0.1443 L0.7639,0.1974 Z M0.7586,0.109 L0.9727,0.109 Q0.9839,0.109,0.992,0.1153 T1,0.1291 L1,0.382 Q1,0.3906,0.9912,0.3964 T0.9727,0.4021 L0.7586,0.4021 Q0.7468,0.4021,0.739,0.3956 T0.7313,0.382 L0.7313,0.1291 Q0.7313,0.1246,0.7339,0.1207 T0.7406,0.1143 T0.7495,0.1104 T0.7586,0.109 Z M0.7639,0.6575 L0.9593,0.6575 L0.9593,0.6044 L0.7639,0.6044 L0.7639,0.6575 Z M0.7313,0.8347 L0.7313,0.5843 Q0.7313,0.5757,0.7401,0.5699 T0.7586,0.5641 L0.9706,0.5641 Q0.9818,0.5641,0.9898,0.5705 T0.9979,0.5843 L0.9979,0.8347 Q0.9979,0.8433,0.989,0.8491 T0.9706,0.8549 L0.7586,0.8549 Q0.7468,0.8549,0.739,0.8483 T0.7313,0.8347 Z M0,1 L0,0 L0.7607,0 L0.7607,1 L0,1 Z",type:0}},"\uE0D2":{type:5,data:{d:"M0.9764,0.0029 L0.3179,0.4552 L0,0.4552 L0,0 Z M1,1 L0,1 L0,0.5448 L0.3091,0.5448 Z",type:0}},"\uE0D4":{type:5,data:{d:"M0.0236,0.0029 L0.6824,0.4552 L1,0.4552 L1,0 Z M0,1 L1,1 L1,0.5448 L0.6912,0.5448 Z",type:0}},"\uEE00":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z"},"\uEE01":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z"},"\uEE02":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z"},"\uEE03":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z M.25,.15 L1,.15 L1,.85 L.25,.85 Z"},"\uEE04":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z M0,.15 L1,.15 L1,.85 L0,.85 Z"},"\uEE05":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z M0,.15 L.75,.15 L.75,.85 L0,.85 Z"},"\uEE06":{type:5,data:{d:"M0.6574,0.303 Q0.623,0.291,0.5852,0.285 T0.5082,0.279 T0.4311,0.285 T0.359,0.303 L0.3082,0.248 Q0.3525,0.232,0.4041,0.2235 T0.5082,0.215 T0.6123,0.2235 T0.7082,0.248 Z",type:0},scaleType:1},"\uEE07":{type:5,data:{d:"M0.8557,0.582 L0.7656,0.551 Q0.7852,0.53,0.7951,0.507 T0.8049,0.46 Q0.8049,0.424,0.782,0.3905 T0.718,0.332 T0.6221,0.293 T0.5082,0.279 L0.5082,0.215 Q0.5607,0.215,0.6123,0.2235 T0.709,0.248 T0.7918,0.287 T0.8557,0.3375 T0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.582 Z",type:0},scaleType:1},"\uEE08":{type:5,data:{d:"M0.5082,0.705 Q0.482,0.705,0.4557,0.703 T0.4049,0.697 L0.4311,0.635 Q0.4508,0.638,0.4697,0.6395 T0.5082,0.641 Q0.5672,0.641,0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 Q0.8049,0.436,0.7951,0.413 T0.7656,0.369 L0.8557,0.338 Q0.882,0.365,0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"\uEE09":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 L0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 T0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 L0.9098,0.46 Q0.9098,0.492,0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"\uEE0A":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.338 L0.2508,0.369 Q0.2311,0.39,0.2213,0.413 T0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 Q0.5279,0.641,0.5467,0.6395 T0.5852,0.635 L0.6115,0.697 Q0.5869,0.701,0.5607,0.703 T0.5082,0.705 Z",type:0},scaleType:1},"\uEE0B":{type:5,data:{d:"M0.1607,0.582 Q0.1344,0.555,0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.3375 T0.2246,0.287 T0.3074,0.248 T0.4041,0.2235 T0.5082,0.215 L0.5082,0.279 Q0.4492,0.279,0.3943,0.293 T0.2984,0.332 T0.2344,0.3905 T0.2115,0.46 Q0.2115,0.484,0.2213,0.507 T0.2508,0.551 Z",type:0},scaleType:1},"\uF5D0":l.LINE_H,"\uF5D1":l.LINE_V,"\uF5D2":l.FADE_RIGHT,"\uF5D3":l.FADE_LEFT,"\uF5D4":l.FADE_DOWN,"\uF5D5":l.FADE_UP,"\uF5D6":l.CURVE_DOWN_RIGHT,"\uF5D7":l.CURVE_DOWN_LEFT,"\uF5D8":l.CURVE_UP_RIGHT,"\uF5D9":l.CURVE_UP_LEFT,"\uF5DA":[l.LINE_V,l.CURVE_UP_RIGHT],"\uF5DB":[l.LINE_V,l.CURVE_DOWN_RIGHT],"\uF5DC":[l.CURVE_DOWN_RIGHT,l.CURVE_UP_RIGHT],"\uF5DD":[l.LINE_V,l.CURVE_UP_LEFT],"\uF5DE":[l.LINE_V,l.CURVE_DOWN_LEFT],"\uF5DF":[l.CURVE_DOWN_LEFT,l.CURVE_UP_LEFT],"\uF5E0":[l.LINE_H,l.CURVE_DOWN_LEFT],"\uF5E1":[l.LINE_H,l.CURVE_DOWN_RIGHT],"\uF5E2":[l.CURVE_DOWN_LEFT,l.CURVE_DOWN_RIGHT],"\uF5E3":[l.LINE_H,l.CURVE_UP_LEFT],"\uF5E4":[l.LINE_H,l.CURVE_UP_RIGHT],"\uF5E5":[l.CURVE_UP_LEFT,l.CURVE_UP_RIGHT],"\uF5E6":[l.LINE_V,l.CURVE_UP_LEFT,l.CURVE_UP_RIGHT],"\uF5E7":[l.LINE_V,l.CURVE_DOWN_LEFT,l.CURVE_DOWN_RIGHT],"\uF5E8":[l.LINE_H,l.CURVE_DOWN_LEFT,l.CURVE_UP_LEFT],"\uF5E9":[l.LINE_H,l.CURVE_DOWN_RIGHT,l.CURVE_UP_RIGHT],"\uF5EA":[l.LINE_V,l.CURVE_DOWN_RIGHT,l.CURVE_UP_LEFT],"\uF5EB":[l.LINE_V,l.CURVE_DOWN_LEFT,l.CURVE_UP_RIGHT],"\uF5EC":[l.LINE_H,l.CURVE_DOWN_RIGHT,l.CURVE_UP_LEFT],"\uF5ED":[l.LINE_H,l.CURVE_DOWN_LEFT,l.CURVE_UP_RIGHT],"\uF5EE":[l.NODE_FILL,l.NODE_STROKE],"\uF5EF":l.NODE_STROKE,"\uF5F0":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_RIGHT],"\uF5F1":[l.NODE_STROKE,l.NODE_LINE_RIGHT],"\uF5F2":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_LEFT],"\uF5F3":[l.NODE_STROKE,l.NODE_LINE_LEFT],"\uF5F4":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF5F5":[l.NODE_STROKE,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF5F6":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN],"\uF5F7":[l.NODE_STROKE,l.NODE_LINE_DOWN],"\uF5F8":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP],"\uF5F9":[l.NODE_STROKE,l.NODE_LINE_UP],"\uF5FA":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_UP],"\uF5FB":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_UP],"\uF5FC":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF5FD":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF5FE":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF5FF":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF600":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_RIGHT],"\uF601":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_RIGHT],"\uF602":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT],"\uF603":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT],"\uF604":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF605":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF606":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF607":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF608":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF609":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60A":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60B":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60C":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60D":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\u{1FB00}":f(1),"\u{1FB01}":f(2),"\u{1FB02}":f(3),"\u{1FB03}":f(4),"\u{1FB04}":f(5),"\u{1FB05}":f(6),"\u{1FB06}":f(7),"\u{1FB07}":f(8),"\u{1FB08}":f(9),"\u{1FB09}":f(10),"\u{1FB0A}":f(11),"\u{1FB0B}":f(12),"\u{1FB0C}":f(13),"\u{1FB0D}":f(14),"\u{1FB0E}":f(15),"\u{1FB0F}":f(16),"\u{1FB10}":f(17),"\u{1FB11}":f(18),"\u{1FB12}":f(19),"\u{1FB13}":f(20),"\u{1FB14}":f(22),"\u{1FB15}":f(23),"\u{1FB16}":f(24),"\u{1FB17}":f(25),"\u{1FB18}":f(26),"\u{1FB19}":f(27),"\u{1FB1A}":f(28),"\u{1FB1B}":f(29),"\u{1FB1C}":f(30),"\u{1FB1D}":f(31),"\u{1FB1E}":f(32),"\u{1FB1F}":f(33),"\u{1FB20}":f(34),"\u{1FB21}":f(35),"\u{1FB22}":f(36),"\u{1FB23}":f(37),"\u{1FB24}":f(38),"\u{1FB25}":f(39),"\u{1FB26}":f(40),"\u{1FB27}":f(41),"\u{1FB28}":f(43),"\u{1FB29}":f(44),"\u{1FB2A}":f(45),"\u{1FB2B}":f(46),"\u{1FB2C}":f(47),"\u{1FB2D}":f(48),"\u{1FB2E}":f(49),"\u{1FB2F}":f(50),"\u{1FB30}":f(51),"\u{1FB31}":f(52),"\u{1FB32}":f(53),"\u{1FB33}":f(54),"\u{1FB34}":f(55),"\u{1FB35}":f(56),"\u{1FB36}":f(57),"\u{1FB37}":f(58),"\u{1FB38}":f(59),"\u{1FB39}":f(60),"\u{1FB3A}":f(61),"\u{1FB3B}":f(62),"\u{1FB3C}":{type:3,data:"M0,0.6667 L0,1 L0.5,1 Z"},"\u{1FB3D}":{type:3,data:"M0,0.6667 L0,1 L1,1 Z"},"\u{1FB3E}":{type:3,data:"M0,0.3333 L0,1 L0.5,1 Z"},"\u{1FB3F}":{type:3,data:"M0,0.3333 L0,1 L1,1 Z"},"\u{1FB40}":{type:3,data:"M0,0 L0,1 L0.5,1 Z"},"\u{1FB41}":{type:3,data:"M0,0.3333 L0.5,0 L1,0 L1,1 L0,1 Z"},"\u{1FB42}":{type:3,data:"M0,0.3333 L1,0 L1,1 L0,1 Z"},"\u{1FB43}":{type:3,data:"M0,0.6667 L0.5,0 L1,0 L1,1 L0,1 Z"},"\u{1FB44}":{type:3,data:"M0,0.6667 L1,0 L1,1 L0,1 Z"},"\u{1FB45}":{type:3,data:"M0,1 L0.5,0 L1,0 L1,1 Z"},"\u{1FB46}":{type:3,data:"M0,0.6667 L1,0.3333 L1,1 L0,1 Z"},"\u{1FB47}":{type:3,data:"M0.5,1 L1,0.6667 L1,1 Z"},"\u{1FB48}":{type:3,data:"M0,1 L1,0.6667 L1,1 Z"},"\u{1FB49}":{type:3,data:"M0.5,1 L1,0.3333 L1,1 Z"},"\u{1FB4A}":{type:3,data:"M0,1 L1,0.3333 L1,1 Z"},"\u{1FB4B}":{type:3,data:"M0.5,1 L1,0 L1,1 Z"},"\u{1FB4C}":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.3333 Z"},"\u{1FB4D}":{type:3,data:"M0,0 L0,1 L1,1 L1,0.3333 Z"},"\u{1FB4E}":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.6667 Z"},"\u{1FB4F}":{type:3,data:"M0,0 L0,1 L1,1 L1,0.6667 Z"},"\u{1FB50}":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 Z"},"\u{1FB51}":{type:3,data:"M0,0.3333 L0,1 L1,1 L1,0.6667 Z"},"\u{1FB52}":{type:3,data:"M0,0.6667 L0.5,1 L1,1 L1,0 L0,0 Z"},"\u{1FB53}":{type:3,data:"M0,0.6667 L1,1 L1,0 L0,0 Z"},"\u{1FB54}":{type:3,data:"M0,0.3333 L0.5,1 L1,1 L1,0 L0,0 Z"},"\u{1FB55}":{type:3,data:"M0,0.3333 L1,1 L1,0 L0,0 Z"},"\u{1FB56}":{type:3,data:"M0,0 L0.5,1 L1,1 L1,0 Z"},"\u{1FB57}":{type:3,data:"M0,0.3333 L0,0 L0.5,0 Z"},"\u{1FB58}":{type:3,data:"M0,0.3333 L0,0 L1,0 Z"},"\u{1FB59}":{type:3,data:"M0,0.6667 L0,0 L0.5,0 Z"},"\u{1FB5A}":{type:3,data:"M0,0.6667 L0,0 L1,0 Z"},"\u{1FB5B}":{type:3,data:"M0,1 L0,0 L0.5,0 Z"},"\u{1FB5C}":{type:3,data:"M0,0.6667 L0,0 L1,0 L1,0.3333 Z"},"\u{1FB5D}":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.6667 Z"},"\u{1FB5E}":{type:3,data:"M0,1 L0,0 L1,0 L1,0.6667 Z"},"\u{1FB5F}":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.3333 Z"},"\u{1FB60}":{type:3,data:"M0,1 L0,0 L1,0 L1,0.3333 Z"},"\u{1FB61}":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 Z"},"\u{1FB62}":{type:3,data:"M0.5,0 L1,0 L1,0.3333 Z"},"\u{1FB63}":{type:3,data:"M0,0 L1,0 L1,0.3333 Z"},"\u{1FB64}":{type:3,data:"M0.5,0 L1,0 L1,0.6667 Z"},"\u{1FB65}":{type:3,data:"M0,0 L1,0 L1,0.6667 Z"},"\u{1FB66}":{type:3,data:"M0.5,0 L1,0 L1,1 Z"},"\u{1FB67}":{type:3,data:"M0,0.3333 L1,0.6667 L1,0 L0,0 Z"},"\u{1FB68}":{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0.5,0.5 Z"},"\u{1FB69}":{type:3,data:"M0,0 L0.5,0.5 L1,0 L1,1 L0,1 Z"},"\u{1FB6A}":{type:3,data:"M0,0 L1,0 L0.5,0.5 L1,1 L0,1 Z"},"\u{1FB6B}":{type:3,data:"M0,0 L1,0 L1,1 L0.5,0.5 L0,1 Z"},"\u{1FB6C}":{type:3,data:"M0,0 L0.5,0.5 L0,1 Z"},"\u{1FB6D}":{type:3,data:"M0,0 L1,0 L0.5,0.5 Z"},"\u{1FB6E}":{type:3,data:"M1,0 L1,1 L0.5,0.5 Z"},"\u{1FB6F}":{type:3,data:"M0,1 L1,1 L0.5,0.5 Z"},"\u{1FB70}":{type:0,data:[{x:1,y:0,w:1,h:8}]},"\u{1FB71}":{type:0,data:[{x:2,y:0,w:1,h:8}]},"\u{1FB72}":{type:0,data:[{x:3,y:0,w:1,h:8}]},"\u{1FB73}":{type:0,data:[{x:4,y:0,w:1,h:8}]},"\u{1FB74}":{type:0,data:[{x:5,y:0,w:1,h:8}]},"\u{1FB75}":{type:0,data:[{x:6,y:0,w:1,h:8}]},"\u{1FB76}":{type:0,data:[{x:0,y:1,w:8,h:1}]},"\u{1FB77}":{type:0,data:[{x:0,y:2,w:8,h:1}]},"\u{1FB78}":{type:0,data:[{x:0,y:3,w:8,h:1}]},"\u{1FB79}":{type:0,data:[{x:0,y:4,w:8,h:1}]},"\u{1FB7A}":{type:0,data:[{x:0,y:5,w:8,h:1}]},"\u{1FB7B}":{type:0,data:[{x:0,y:6,w:8,h:1}]},"\u{1FB7C}":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"\u{1FB7D}":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"\u{1FB7E}":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"\u{1FB7F}":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"\u{1FB80}":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:7,w:8,h:1}]},"\u{1FB81}":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:2,w:8,h:1},{x:0,y:4,w:8,h:1},{x:0,y:7,w:8,h:1}]},"\u{1FB82}":{type:0,data:[{x:0,y:0,w:8,h:2}]},"\u{1FB83}":{type:0,data:[{x:0,y:0,w:8,h:3}]},"\u{1FB84}":{type:0,data:[{x:0,y:0,w:8,h:5}]},"\u{1FB85}":{type:0,data:[{x:0,y:0,w:8,h:6}]},"\u{1FB86}":{type:0,data:[{x:0,y:0,w:8,h:7}]},"\u{1FB87}":{type:0,data:[{x:6,y:0,w:2,h:8}]},"\u{1FB88}":{type:0,data:[{x:5,y:0,w:3,h:8}]},"\u{1FB89}":{type:0,data:[{x:3,y:0,w:5,h:8}]},"\u{1FB8A}":{type:0,data:[{x:2,y:0,w:6,h:8}]},"\u{1FB8B}":{type:0,data:[{x:1,y:0,w:7,h:8}]},"\u{1FB8C}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},"\u{1FB8D}":{type:1,data:[[1,0],[0,1]],clipPath:"M0.5,0 L1,0 L1,1 L0.5,1 Z"},"\u{1FB8E}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},"\u{1FB8F}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},"\u{1FB90}":{type:1,data:[[0,1],[1,0]]},"\u{1FB91}":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},{type:0,data:[{x:0,y:0,w:8,h:4}]}],"\u{1FB92}":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},{type:0,data:[{x:0,y:4,w:8,h:4}]}],"\u{1FB94}":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},{type:0,data:[{x:4,y:0,w:4,h:8}]}],"\u{1FB95}":{type:0,data:[{x:0,y:0,w:2,h:2},{x:4,y:0,w:2,h:2},{x:2,y:2,w:2,h:2},{x:6,y:2,w:2,h:2},{x:0,y:4,w:2,h:2},{x:4,y:4,w:2,h:2},{x:2,y:6,w:2,h:2},{x:6,y:6,w:2,h:2}]},"\u{1FB96}":{type:0,data:[{x:2,y:0,w:2,h:2},{x:6,y:0,w:2,h:2},{x:0,y:2,w:2,h:2},{x:4,y:2,w:2,h:2},{x:2,y:4,w:2,h:2},{x:6,y:4,w:2,h:2},{x:0,y:6,w:2,h:2},{x:4,y:6,w:2,h:2}]},"\u{1FB97}":{type:0,data:[{x:0,y:2,w:8,h:2},{x:0,y:6,w:8,h:2}]},"\u{1FB98}":{type:2,data:"M-0.25,-0.25 L1.25,1.25 M-0.25,0 L1,1.25 M-0.25,0.25 L0.75,1.25 M-0.25,0.5 L0.5,1.25 M0,-0.25 L1.25,1 M0.25,-0.25 L1.25,0.75 M0.5,-0.25 L1.25,0.5 M-0.25,0.75 L0.25,1.25 M0.75,-0.25 L1.25,0.25",strokeWidth:1},"\u{1FB99}":{type:2,data:"M-0.25,0.5 L0.5,-0.25 M-0.25,0.75 L0.75,-0.25 M-0.25,1 L1,-0.25 M-0.25,1.25 L1.25,-0.25 M0,1.25 L1.25,0 M0.25,1.25 L1.25,0.25 M0.5,1.25 L1.25,0.5 M-0.25,0.25 L0.25,-0.25 M0.75,1.25 L1.25,0.75",strokeWidth:1},"\u{1FB9A}":{type:5,data:{d:"M0,0 L.5,.5 L0,1 L1,1 L.5,.5 L1,0",type:0}},"\u{1FB9B}":{type:5,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1",type:0}},"\u{1FB9C}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L0,1 Z"},"\u{1FB9D}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,1 Z"},"\u{1FB9E}":{type:1,data:[[1,0],[0,1]],clipPath:"M1,0 L1,1 L0,1 Z"},"\u{1FB9F}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,1 L0,1 Z"},"\u{1FBA0}":{type:2,data:"M.5,0 L0,.5",strokeWidth:1},"\u{1FBA1}":{type:2,data:"M.5,0 L1,.5",strokeWidth:1},"\u{1FBA2}":{type:2,data:"M0,.5 L.5,1",strokeWidth:1},"\u{1FBA3}":{type:2,data:"M1,.5 L.5,1",strokeWidth:1},"\u{1FBA4}":{type:2,data:"M.5,0 L0,.5 L.5,1",strokeWidth:1},"\u{1FBA5}":{type:2,data:"M.5,0 L1,.5 L.5,1",strokeWidth:1},"\u{1FBA6}":{type:2,data:"M0,.5 L.5,1 L1,.5",strokeWidth:1},"\u{1FBA7}":{type:2,data:"M0,.5 L.5,0 L1,.5",strokeWidth:1},"\u{1FBA8}":{type:2,data:"M.5,0 L0,.5 M1,.5 L.5,1",strokeWidth:1},"\u{1FBA9}":{type:2,data:"M.5,0 L1,.5 M0,.5 L.5,1",strokeWidth:1},"\u{1FBAA}":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5",strokeWidth:1},"\u{1FBAB}":{type:2,data:"M.5,0 L0,.5 L.5,1 L1,.5",strokeWidth:1},"\u{1FBAC}":{type:2,data:"M0,.5 L.5,0 L1,.5 L.5,1",strokeWidth:1},"\u{1FBAD}":{type:2,data:"M1,.5 L.5,0 L0,.5 L.5,1",strokeWidth:1},"\u{1FBAE}":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5 Z",strokeWidth:1},"\u{1FBAF}":{type:2,data:"M0,.5 L1,.5 M.5,.35 L.5,.65",strokeWidth:1},"\u{1FBB0}":{type:3,data:"M0.1,0.2 L0.1,.8 L.4,.6 L.9,0.6 Z",scaleType:1},"\u{1FBB1}":{type:4,data:{d:"M.1,.525 L.35,.675 L.9,.35",type:1},scaleType:1},"\u{1FBB2}":{type:3,data:"M.29,.27 L0.13,.56 L.22,.59 L.35,0.35 L.67,.35 L.57,.57 L.71,.76 L.22,.76 L.42,1 L.53,.98 L.43,.86 L.9,.86 L.71,.6 L1,.6 L1,.52 L.83,.52 L.92,.36 L1,.36 L1,.27Z M.99,.13 A.12,.12,0,1,1,.75,.13 A.12,.12,0,1,1,.99,.13"},"\u{1FBB3}":{type:3,data:"M0,.27 L.3,.27 L.55,.12 L.63,.18 L.33,.36 L0,.36 M0,.52 L.33,.52 L.59,.89 L.73,.89 L.73,.98 L.53,.98 L.28,.6 L0,.6"},"\u{1FBB4}":{type:4,data:{d:"M.15,.55 L.5,.4 L.5,.45 L.65,.45 L.65,.35 L.85,.35 L.85,.625 L.5,.625 L.5,.7 Z",type:0},scaleType:1},"\u{1FBB5}":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.15,.5 L.5,.35 L.5,.425 L.85,.425 L.85,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"\u{1FBB6}":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.85,.5 L.5,.35 L.5,.425 L.15,.425 L.15,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"\u{1FBB7}":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.675 L.2,.5 L.35,.5 L.35,.325 L.65,.325 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"\u{1FBB8}":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.325 L.2,.5 L.35,.5 L.35,.675 L.65,.675 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"\u{1FBB9}":{type:5,data:{d:"M1,.89 L.11,.89 L.11,.37 L.36,.12 L.74,.12 L.96,.34 L1,.34 L1,.405 L.92,.405 L.69,.185 L.41,.185 L.21,.42 L.21,.825 L1,.825 Z",type:0}},"\u{1FBBA}":{type:5,data:{d:"M0,.89 L0,.825 L.78,.825 L.78,.53 L.7,.415 L0,.415 L0,.35 L.75,.35 L.88,.48 L.88,.89 Z",type:0}},"\u{1FBBB}":{type:5,data:{d:"M.31,.275 L.44,.275 L.44,.47 L.05,.47 L.05,.405 L.31,.405 Z M.56,.275 L.69,.275 L.69,.405 L.95,.405 L.95,.47 L.56,.47 Z M.05,.53 L.44,.53 L.44,.725 L.31,.725 L.31,.595 L.05,.595 Z M.56,.53 L.95,.53 L.95,.595 L.69,.595 L.69,.725 L.56,.725 Z",type:0},scaleType:1},"\u{1FBBC}":[{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0,.935 L.885,.935 L.885,.065 L0,.065 Z"},{type:3,data:"M.67,.5 A.17,.085,0,1,1,.33,.5 A.17,.085,0,1,1,.67,.5",scaleType:1}],"\u{1FBBD}":{type:4,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1 Z",type:1}},"\u{1FBBE}":{type:4,data:{d:"M1,.5 L.5,1",type:1}},"\u{1FBBF}":{type:4,data:{d:"M.5,0 L1,.5 L.5,1 L0,.5 Z",type:1}},"\u{1FBC0}":{type:3,data:"M.16,.445 A.02,.01,0,0,1,.39,.33 L.5,.375 L.61,.33 A.02,.01,0,0,1,.84,.445 L.75,.5 L.84,.555 A.02,.01,0,0,1,.61,.67 L.5,.625 L.39,.67 A.02,.01,0,0,1,.16,.555 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",scaleType:1},"\u{1FBC1}":{type:3,data:"M0.142308,0.924 Q0.130770,0.924,0.120193,0.922 T0.101924,0.916 T0.089424,0.9065 T0.084616,0.895 V0.025 Q0.084616,0.019,0.089424,0.0135 T0.101924,0.004 T0.120193,-0.002 T0.142308,-0.004 Q0.150000,-0.004,0.157693,-0.003 T0.173078,0.000 L0.430770,0.085 Q0.451924,0.059,0.494232,0.041 T0.587501,0.013 T0.692309,-0.0005 T0.800001,-0.004 H1 V0.055 H0.800001 Q0.771155,0.055,0.742309,0.056 T0.685578,0.060 T0.630770,0.0685 T0.580770,0.0825 T0.543270,0.1045 T0.528847,0.133 V0.647 H0.530770 Q0.596155,0.645,0.659616,0.638 T0.782693,0.6165 T0.893270,0.5805 T1,0.531 V0.623 Q0.934616,0.644,0.880770,0.6595 T0.769232,0.685 T0.650963,0.700 T0.528847,0.707 V0.787 Q0.528847,0.802,0.543270,0.8155 T0.580770,0.8375 T0.630770,0.8515 T0.685578,0.860 T0.742309,0.864 T0.800001,0.865 H1 V0.924 H0.800001 Q0.746155,0.924,0.692309,0.9205 T0.587501,0.907 T0.494232,0.879 T0.430770,0.835 L0.173078,0.920 Q0.165386,0.922,0.157693,0.923 T0.142308,0.924 Z M0.2,0.841 L0.415385,0.770 V0.150 L0.2,0.079 V0.841 Z M1,0.698 Q0.973077,0.694,0.969231,0.6885 T0.965385,0.677 Q0.965385,0.672,0.969231,0.6665 T1,0.657 V0.698 Z"},"\u{1FBC2}":{type:3,data:"M0,0.623 V0.531 Q0.044231,0.512,0.0625,0.4905 T0.092308,0.4465 T0.108654,0.4005 T0.113462,0.354 V0.351 Q0.113462,0.345,0.117308,0.3395 T0.129808,0.3305 T0.148846,0.3245 T0.171154,0.323 H0.501923 Q0.532692,0.323,0.563462,0.3185 T0.617308,0.303 T0.651923,0.2765 T0.663462,0.2435 V0.241 Q0.663462,0.219,0.657692,0.197 T0.639423,0.1545 T0.604808,0.115 T0.549615,0.082 T0.475577,0.0615 T0.392308,0.055 H0 V-0.004 H1 V0.055 H0.667308 Q0.694231,0.071,0.713462,0.09 T0.746154,0.129 T0.766346,0.1705 T0.775,0.213 H1 V0.316 Q0.971154,0.305,0.955769,0.2965 T0.920192,0.2825 T0.876923,0.2745 T0.830769,0.272 H0.773077 Q0.767308,0.297,0.743269,0.319 T0.680769,0.355 T0.595192,0.375 T0.501923,0.381 H0.227308 Q0.223462,0.415,0.211,0.4485 T0.172692,0.5135 T0.108269,0.573 T0,0.623 Z M0.611538,0.924 H0 V0.865 H0.611538 Q0.642308,0.865,0.673077,0.8605 T0.727885,0.845 T0.762308,0.8185 T0.773077,0.787 V0.785 Q0.773077,0.769,0.762308,0.7535 T0.727885,0.727 T0.673077,0.7115 T0.611538,0.707 H0.059615 Q0.048077,0.707,0.037115,0.7045 T0,0.694 V0.653 Q0.026923,0.648,0.037115,0.646 T0.059615,0.644 H0.722692 Q0.753462,0.644,0.784231,0.6395 T0.839038,0.624 T0.873846,0.5975 T0.884615,0.566 V0.564 Q0.884615,0.548,0.873846,0.532 T0.839038,0.5055 T0.784231,0.49 T0.722692,0.4855 H0.392308 Q0.380769,0.4855,0.370192,0.483 T0.351923,0.4765 T0.339423,0.467 T0.334615,0.4555 T0.339423,0.444 T0.351923,0.4345 T0.370192,0.428 T0.392308,0.4255 H0.832692 Q0.855769,0.4255,0.878846,0.4235 T0.922115,0.416 T0.957692,0.4015 T1,0.3815 V0.4685 Q0.975,0.4705,0.966346,0.4725 T0.95,0.4765 Q0.961538,0.4835,0.969231,0.4915 T1,0.5075 V0.6205 Q0.965385,0.6455,0.926923,0.665 T0.84,0.6935 Q0.866923,0.7115,0.877596,0.7345 T0.894231,0.7855 V0.787 Q0.894231,0.815,0.876923,0.8425 T0.820192,0.8895 T0.726923,0.916 T0.611538,0.924 Z"},"\u{1FBC3}":{type:3,data:"M0,0.473 V0.386 Q0.025490,0.378,0.028431,0.3695 T0.031373,0.352 V0.35 Q0.031373,0.342,0.028431,0.333 T0,0.316 V0.213 H0.652941 Q0.684314,0.213,0.715686,0.2085 T0.770588,0.193 T0.804902,0.1665 T0.815686,0.135 V0.133 Q0.815686,0.117,0.804902,0.101 T0.770588,0.0745 T0.715686,0.0595 T0.652941,0.055 H0 V-0.004 H0.652941 Q0.707843,-0.004,0.761765,0.004 T0.856863,0.031 T0.915686,0.0775 T0.933333,0.133 V0.135 Q0.933333,0.163,0.915686,0.1905 T0.856863,0.237 T0.761765,0.264 T0.652941,0.272 H0.109804 Q0.131373,0.29,0.140196,0.31 T0.149020,0.35 V0.352 Q0.149020,0.37,0.142157,0.388 T0.118627,0.4225 T0.076471,0.452 T0,0.473 Z M0,0.625 V0.513 Q0.029412,0.526,0.032353,0.54 T0.035294,0.568 V0.57 Q0.035294,0.584,0.032353,0.598 T0,0.625 Z"},"\u{1FBC4}":{type:3,data:"M0.019231,1.085 V-0.165 H0.980769 V1.085 H0.019231 Z M0.446154,0.527 H0.553846 Q0.553846,0.511,0.5625,0.495 T0.591346,0.466 T0.631731,0.4405 T0.666346,0.4135 T0.688462,0.3825 T0.696154,0.35 Q0.696154,0.33,0.682692,0.311 T0.641346,0.2785 T0.575,0.259 T0.498077,0.253 T0.421154,0.259 T0.356731,0.279 T0.315385,0.3125 T0.301923,0.352 V0.357 H0.409615 V0.354 Q0.409615,0.345,0.414423,0.335 T0.431731,0.318 T0.4625,0.3075 T0.498077,0.304 Q0.517308,0.304,0.534615,0.307 T0.564423,0.3165 T0.582692,0.332 T0.588462,0.35 Q0.588462,0.366,0.572115,0.3805 T0.535577,0.4075 T0.496154,0.4335 T0.465385,0.4625 T0.45,0.4945 T0.446154,0.527 Z M0.5,0.667 Q0.519231,0.667,0.5375,0.664 T0.569231,0.654 T0.588462,0.637 T0.594231,0.617 T0.588462,0.5975 T0.569231,0.581 T0.5375,0.571 T0.5,0.568 T0.4625,0.571 T0.430769,0.581 T0.411538,0.5975 T0.405769,0.617 T0.411538,0.637 T0.430769,0.654 T0.4625,0.664 T0.5,0.667 Z",scaleType:1},"\u{1FBC5}":{type:5,data:{d:"M.44,.425 L.44,.51 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.51 L.56,.425 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC6}":{type:5,data:{d:"M.44,.425 L.44,.46 L.23,.385 L.19,.43 L.44,.51 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.61,.735 L.7,.71 L.56,.56 L.56,.51 L.81,.43 L.77,.385 L.56,.46 L.56,.425 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC7}":{type:5,data:{d:"M.44,.425 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.425 Z M.18,.53 L.23,.575 L.81,.43 L.77,.385 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC8}":{type:5,data:{d:"M.44,.425 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.62,.735 L.71,.71 L.56,.56 L.56,.425 Z M.23,.385 L.18,.43 L.77,.575 L.81,.53 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC9}":{type:5,data:{d:"M.44,.425 L.45,.495 L.15,.645 L.34,.645 L.34,.7 L.44,.7 L.44,.645 L.56,.645 L.56,.7 L.66,.7 L.66,.645 L.84,.645 L.54,.495 L.56,.425 Z M.39,.6 L.5,.55 L.60,.6 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBCA}":{type:5,data:{d:"M.26,.375 L.5,.255 L.74,.375 L.74,.665 L.5,.55 L.26,.665 Z M.37,.395 L.37,.54 L.5,.475 L.63,.54 L.63,.395 L.5,.33 Z",type:0},scaleType:1},"\u{1FBCB}":{type:5,data:{d:"M.09,.41 L.32,.295 L.5,.375 L.68,.295 L.91,.41 L.75,.5 L.91,.59 L.68,.705 L.5,.625 L.32,.705 L.09,.59 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",type:0},scaleType:1},"\u{1FBCC}":{type:5,data:{d:"M.55,.305 L.88,.305 L.88,.355 L.65,.355 L.65,.47 L.88,.47 L.88,.52 L.55,.52 Z",type:0},scaleType:1},"\u{1FBCD}":{type:5,data:{d:"M.38,.39 L.5,.33 L.62,.39 L.62,.53 L.5,.47 L.38,.53 Z",type:0},scaleType:1},"\u{1FBCE}":{type:3,data:"M0,0 L0.6667,0 L0.6667,1 L0,1 Z"},"\u{1FBCF}":{type:3,data:"M0,0 L0.3333,0 L0.3333,1 L0,1 Z"},"\u{1FBD0}":{type:2,data:"M1,.5 L0,1",strokeWidth:1},"\u{1FBD1}":{type:2,data:"M1,0 L0,.5",strokeWidth:1},"\u{1FBD2}":{type:2,data:"M0,0 L1,.5",strokeWidth:1},"\u{1FBD3}":{type:2,data:"M0,.5 L1,1",strokeWidth:1},"\u{1FBD4}":{type:2,data:"M0,0 L.5,1",strokeWidth:1},"\u{1FBD5}":{type:2,data:"M.5,0 L1,1",strokeWidth:1},"\u{1FBD6}":{type:2,data:"M1,0 L.5,1",strokeWidth:1},"\u{1FBD7}":{type:2,data:"M.5,0 L0,1",strokeWidth:1},"\u{1FBD8}":{type:2,data:"M0,0 L.5,.5 L1,0",strokeWidth:1},"\u{1FBD9}":{type:2,data:"M1,0 L.5,.5 L1,1",strokeWidth:1},"\u{1FBDA}":{type:2,data:"M0,1 L.5,.5 L1,1",strokeWidth:1},"\u{1FBDB}":{type:2,data:"M0,0 L.5,.5 L0,1",strokeWidth:1},"\u{1FBDC}":{type:2,data:"M0,0 L.5,1 L1,0",strokeWidth:1},"\u{1FBDD}":{type:2,data:"M1,0 L0,.5 L1,1",strokeWidth:1},"\u{1FBDE}":{type:2,data:"M0,1 L.5,0 L1,1",strokeWidth:1},"\u{1FBDF}":{type:2,data:"M0,0 L1,.5 L0,1",strokeWidth:1},"\u{1FBE0}":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0",type:1}},"\u{1FBE1}":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1",type:1}},"\u{1FBE2}":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1",type:1}},"\u{1FBE3}":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1",type:1}},"\u{1FBE4}":{type:0,data:[{x:2,y:0,w:4,h:4}]},"\u{1FBE5}":{type:0,data:[{x:2,y:4,w:4,h:4}]},"\u{1FBE6}":{type:0,data:[{x:0,y:2,w:4,h:4}]},"\u{1FBE7}":{type:0,data:[{x:4,y:2,w:4,h:4}]},"\u{1FBE8}":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0 Z",type:0}},"\u{1FBE9}":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1 Z",type:0}},"\u{1FBEA}":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1 Z",type:0}},"\u{1FBEB}":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1 Z",type:0}},"\u{1FBEC}":{type:5,data:{d:"M1,0 L.5,0 C.5,.276,.724,.5,1,.5 Z",type:0}},"\u{1FBED}":{type:5,data:{d:"M0,1 L.5,1 C.5,.724,.276,.5,0,.5 Z",type:0}},"\u{1FBEE}":{type:5,data:{d:"M1,1 L1,.5 C.724,.5,.5,.724,.5,1 Z",type:0}},"\u{1FBEF}":{type:5,data:{d:"M0,0 L0,.5 C.276,.5,.5,.276,.5,0 Z",type:0}},"\u{1FBF0}":{type:5,data:{d:o0(126),type:0},scaleType:1},"\u{1FBF1}":{type:5,data:{d:o0(48),type:0},scaleType:1},"\u{1FBF2}":{type:5,data:{d:o0(109),type:0},scaleType:1},"\u{1FBF3}":{type:5,data:{d:o0(121),type:0},scaleType:1},"\u{1FBF4}":{type:5,data:{d:o0(51),type:0},scaleType:1},"\u{1FBF5}":{type:5,data:{d:o0(91),type:0},scaleType:1},"\u{1FBF6}":{type:5,data:{d:o0(95),type:0},scaleType:1},"\u{1FBF7}":{type:5,data:{d:o0(114),type:0},scaleType:1},"\u{1FBF8}":{type:5,data:{d:o0(127),type:0},scaleType:1},"\u{1FBF9}":{type:5,data:{d:o0(123),type:0},scaleType:1},"\u{1FBFA}":{type:5,data:{d:"M.5,.175 C.2,.175,.15,.305,.15,.435 L.05,.63 L.35,.63 C.35,.682,.42,.76,.5,.76 C.58,.76,.65,.682,.65,.63 L.95,.63 L.85,.435 C.85,.305,.8,.175,.5,.175 Z",type:0},scaleType:1},...Object.fromEntries(Array.from({length:256},(i,e)=>[String.fromCodePoint(10240+e),{type:6,data:e}]))},$e=new Set([9617,9618,9619,129932,129933,129934,129935,129936,129937,129938,129940,129948,129949,129950,129951]);function f(i){return{type:2,data:()=>{let e=[],r=[.375,.25,.375],s=[0,3/8,5/8];for(let a=0;a<3;a++){let o=i>>a*2&1,n=i>>a*2+1&1;o&&n?e.push(`M0,${s[a]} L1,${s[a]} L1,${s[a]+r[a]} L0,${s[a]+r[a]} Z`):o?e.push(`M0,${s[a]} L${.5},${s[a]} L${.5},${s[a]+r[a]} L0,${s[a]+r[a]} Z`):n&&e.push(`M${.5},${s[a]} L1,${s[a]} L1,${s[a]+r[a]} L${.5},${s[a]+r[a]} Z`)}return e.join(" ")}}}function o0(i){let e=[];if(i&64){let Q=.21500000000000002,m=.95-.15-.015;e.push(`M${Q},${.2125} L${Q+.075},${.175} L${m-.075},${.175} L${m},${.2125} L${m-.075},${.25} L${Q+.075},${.25} Z`)}if(i&32){let c=.7999999999999999,u=.95-.15/2,C=.95,Q=.175+.075+.015,m=.5-.015;e.push(`M${u},${Q} L${C},${Q+.0375} L${C},${m-.0375} L${u},${m} L${c},${m-.0375} L${c},${Q+.0375} Z`)}if(i&16){let c=.7999999999999999,u=.95-.15/2,C=.95,Q=.5+.015,m=.825-.075-.015;e.push(`M${u},${Q} L${C},${Q+.0375} L${C},${m-.0375} L${u},${m} L${c},${m-.0375} L${c},${Q+.0375} Z`)}if(i&8){let Q=.21500000000000002,m=.95-.15-.015;e.push(`M${Q},${.7875} L${Q+.075},${.75} L${m-.075},${.75} L${m},${.7875} L${m-.075},${.825} L${Q+.075},${.825} Z`)}if(i&4&&e.push(`M${.125},${.515} L${.2},${.515+.0375} L${.2},${.735-.0375} L${.125},${.735} L${.05},${.735-.0375} L${.05},${.515+.0375} Z`),i&2&&e.push(`M${.125},${.265} L${.2},${.265+.0375} L${.2},${.485-.0375} L${.125},${.485} L${.05},${.485-.0375} L${.05},${.265+.0375} Z`),i&1){let Q=.21500000000000002,m=.95-.15-.015;e.push(`M${Q},${.5} L${Q+.075},${.4625} L${m-.075},${.4625} L${m},${.5} L${m-.075},${.5375} L${Q+.075},${.5375} Z`)}return e.join(" ")}var k=0,H=0,T0=!1,_0=!1,$0=!1,z,x0=0,G0=class{constructor(e,t,r,s,a,o){this._terminal=e;this._optionService=t;this._selectionRenderModel=r;this._decorationService=s;this._coreBrowserService=a;this._themeService=o;this.result={fg:0,bg:0,ext:0}}resolve(e,t,r,s,a){this.result.bg=e.bg,this.result.fg=e.fg,this.result.ext=e.bg&268435456?e.extended.ext:0,H=0,k=0,_0=!1,T0=!1,$0=!1,z=this._themeService.colors,x0=0;let o=e.getCode();if(o!==0&&e.extended.underlineStyle===4){let n=Math.max(1,Math.floor(this._optionService.rawOptions.fontSize*this._coreBrowserService.dpr/15));x0=t*s%(Math.round(n)*2)}if(x0===0&&$e.has(o)&&(x0=t*s%2*2+r*a%2),this._decorationService.forEachDecorationAtCell(t,r,"bottom",n=>{n.backgroundColorRGB&&(H=n.backgroundColorRGB.rgba>>8&16777215,_0=!0),n.foregroundColorRGB&&(k=n.foregroundColorRGB.rgba>>8&16777215,T0=!0)}),$0=this._selectionRenderModel.isCellSelected(this._terminal,t,r),$0){if(this.result.fg&67108864||(this.result.bg&50331648)!==0){if(this.result.fg&67108864)switch(this.result.fg&50331648){case 16777216:case 33554432:H=this._themeService.colors.ansi[this.result.fg&255].rgba;break;case 50331648:H=(this.result.fg&16777215)<<8|255;break;case 0:default:H=this._themeService.colors.foreground.rgba}else switch(this.result.bg&50331648){case 16777216:case 33554432:H=this._themeService.colors.ansi[this.result.bg&255].rgba;break;case 50331648:H=(this.result.bg&16777215)<<8|255;break}H=d0.blend(H,(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba&4294967040|128)>>8&16777215}else H=(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba>>8&16777215;if(_0=!0,z.selectionForeground&&(k=z.selectionForeground.rgba>>8&16777215,T0=!0),V0(e.getCode())){if(this.result.fg&67108864&&(this.result.bg&50331648)===0)k=(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba>>8&16777215;else{if(this.result.fg&67108864)switch(this.result.bg&50331648){case 16777216:case 33554432:k=this._themeService.colors.ansi[this.result.bg&255].rgba;break;case 50331648:k=(this.result.bg&16777215)<<8|255;break}else switch(this.result.fg&50331648){case 16777216:case 33554432:k=this._themeService.colors.ansi[this.result.fg&255].rgba;break;case 50331648:k=(this.result.fg&16777215)<<8|255;break;case 0:default:k=this._themeService.colors.foreground.rgba}k=d0.blend(k,(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba&4294967040|128)>>8&16777215}T0=!0}}this._decorationService.forEachDecorationAtCell(t,r,"top",n=>{n.backgroundColorRGB&&(H=n.backgroundColorRGB.rgba>>8&16777215,_0=!0),n.foregroundColorRGB&&(k=n.foregroundColorRGB.rgba>>8&16777215,T0=!0)}),_0&&($0?H=e.bg&-16777216&-134217729|H|50331648:H=e.bg&-16777216|H|50331648),T0&&(k=e.fg&-16777216&-67108865|k|50331648),this.result.fg&67108864&&(_0&&!T0&&((this.result.bg&50331648)===0?k=this.result.fg&-134217728|z.background.rgba>>8&16777215&16777215|50331648:k=this.result.fg&-134217728|this.result.bg&67108863,T0=!0),!_0&&T0&&((this.result.fg&50331648)===0?H=this.result.bg&-67108864|z.foreground.rgba>>8&16777215&16777215|50331648:H=this.result.bg&-67108864|this.result.fg&67108863,_0=!0)),z=void 0,this.result.bg=_0?H:this.result.bg,this.result.fg=T0?k:this.result.fg,this.result.ext&=536870911,this.result.ext|=x0<<29&3758096384}};var Ke=.5,K0=Be||we?"bottom":"ideographic";function qe(i,e,t,r,s,a,o,n,L,T,h,d,_=0){let p=Ve[e];if(p){let c=Array.isArray(p)?p:[p];for(let u of c)Pt(i,u,t,r,s,a,o,n,L,T,h,d,_);return!0}return!1}function Pt(i,e,t,r,s,a,o,n,L,T,h,d,_=0){let p=s,c=a,u=t,C=r;switch(e.scaleType===1&&(p=o,c=n,u=t+(s-o)/2,C=r+(a-n)/2),e.clipPath&&(i.save(),Vt(i,e.clipPath,u,C,p,c)),e.type){case 0:Bt(i,e.data,u,C,p,c);break;case 1:Ut(i,e.data,u,C,p,c,_);break;case 2:Wt(i,e.data,u,C,p,c,T,h,e.strokeWidth);break;case 3:Ht(i,e.data,u,C,p,c,T,e.strokeWidth);break;case 4:Zt(i,e.data,u,C,p,c,T,d);break;case 5:$t(i,e.data,u,C,p,c,L,T,h);break;case 6:wt(i,e.data,u,C,p,c);break}e.clipPath&&i.restore()}function Bt(i,e,t,r,s,a){for(let o=0;o{let F=parseFloat(m);return R%2===0?t+F*s:r+F*a});if(u==="M")i.moveTo(Q[0],Q[1]),T=Q[0],h=Q[1],d=T,_=h;else if(u==="L")i.lineTo(Q[0],Q[1]),T=Q[0],h=Q[1],d=T,_=h;else if(u==="Q")i.quadraticCurveTo(Q[0],Q[1],Q[2],Q[3]),d=Q[0],_=Q[1],T=Q[2],h=Q[3];else if(u==="T"){let m,R;p==="Q"||p==="T"?(m=2*T-d,R=2*h-_):(m=T,R=h),i.quadraticCurveTo(m,R,Q[0],Q[1]),d=m,_=R,T=Q[0],h=Q[1]}else u==="C"&&(i.bezierCurveTo(Q[0],Q[1],Q[2],Q[3],Q[4],Q[5]),d=Q[2],_=Q[3],T=Q[4],h=Q[5]);p=u}n!==void 0?(i.strokeStyle=i.fillStyle,i.lineWidth=o*n,i.stroke()):i.fill()}function kt(i,e,t,r,s,a,o,n,L,T){if(r===0||s===0){i.lineTo(L,T);return}r=Math.abs(r),s=Math.abs(s);let h=Math.cos(a),d=Math.sin(a),_=(e-L)/2,p=(t-T)/2,c=h*_+d*p,u=-d*_+h*p,C=r*r,Q=s*s,m=c*c,R=u*u,F=m/C+R/Q;if(F>1){let I=Math.sqrt(F);r*=I,s*=I,C=r*r,Q=s*s}let E=(C*Q-C*R-Q*m)/(C*R+Q*m);E<0&&(E=0);let y=(o===n?-1:1)*Math.sqrt(E),Y=y*(r*u/s),X=y*-(s*c/r),A0=h*Y-d*X+(e+L)/2,t0=d*Y+h*X+(t+T)/2,L0=(c-Y)/r,A=(u-X)/s,n0=(-c-Y)/r,a0=(-u-X)/s,$=Math.atan2(A,L0),q=Math.atan2(a0,n0)-$;n===0&&q>0?q-=2*Math.PI:n===1&&q<0&&(q+=2*Math.PI);let g0=$+q;i.ellipse(A0,t0,r,s,a,$,g0,n===0)}function Zt(i,e,t,r,s,a,o,n){i.save(),i.fillRect(t,r,s,a),n&&(i.fillStyle=n,i.strokeStyle=n),i.lineWidth=o,i.lineCap="square",i.beginPath();for(let L of e.d.split(" ")){let T=L[0],h=L.substring(1).split(",");if(!h[0]||!h[1]){T==="Z"&&i.closePath();continue}let d=h.map((_,p)=>{let c=parseFloat(_);return p%2===0?t+c*s:r+c*a});T==="M"?i.moveTo(d[0],d[1]):T==="L"&&i.lineTo(d[0],d[1])}e.type===1?i.stroke():i.fill(),i.restore()}var Xe=new Map;function Ut(i,e,t,r,s,a,o=0){let n=Xe.get(e);n||(n=new Map,Xe.set(e,n));let L=i.fillStyle;if(typeof L!="string")throw new Error(`Unexpected fillStyle type "${L}"`);let T=n.get(L);if(!T){let _=e[0].length,p=e.length,c=i.canvas.ownerDocument.createElement("canvas");c.width=_,c.height=p;let u=g(c.getContext("2d")),C=new ImageData(_,p),Q,m,R,F;if(L.startsWith("#"))Q=parseInt(L.slice(1,3),16),m=parseInt(L.slice(3,5),16),R=parseInt(L.slice(5,7),16),F=L.length>7&&parseInt(L.slice(7,9),16)||1;else if(L.startsWith("rgba"))[Q,m,R,F]=L.substring(5,L.length-1).split(",").map(E=>parseFloat(E));else throw new Error(`Unexpected fillStyle color format "${L}" when drawing pattern glyph`);for(let E=0;E>1&1,d=o&1;h!==0||d!==0?T.setTransform(new DOMMatrix().translateSelf(-h,-d)):T.setTransform(new DOMMatrix),i.fillStyle=T,i.fillRect(t,r,s,a)}function Wt(i,e,t,r,s,a,o,n,L){i.save(),i.beginPath(),i.rect(t,r,s,a),i.clip(),i.beginPath();let T;if(typeof e=="function"){let _=.15/a*s;T=e(.15,_)}else T=e;let h={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(let d of T.split(" ")){let _=d[0];if(_==="Z"){i.closePath(),h.lastCommand=_;continue}let p=je[_];if(!p){n.error(`Could not find drawing instructions for "${_}"`);continue}let c=d.substring(1).split(",");!c[0]||!c[1]||(p(i,Je(c,s,a,t,r,!0,o,0,0,!1),h),h.lastCommand=_)}L!==void 0?(i.strokeStyle=i.fillStyle,i.lineWidth=o*L,i.stroke()):i.fill(),i.closePath(),i.restore()}function Vt(i,e,t,r,s,a){i.beginPath();for(let o of e.split(" ")){let n=o[0];if(n==="Z"){i.closePath();continue}let L=o.substring(1).split(",");if(!L[0]||!L[1])continue;let T=t+parseFloat(L[0])*s,h=r+parseFloat(L[1])*a;n==="M"?i.moveTo(T,h):n==="L"&&i.lineTo(T,h)}i.clip()}function $t(i,e,t,r,s,a,o,n,L){let T=new Path2D;T.rect(t,r,s,a),i.clip(T),i.beginPath();let h=o/12;i.lineWidth=n*h;let d={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(let _ of e.d.split(" ")){let p=_[0];if(p==="Z"){i.closePath(),d.lastCommand=p;continue}let c=je[p];if(!c){L.error(`Could not find drawing instructions for "${p}"`);continue}let u=_.substring(1).split(",");!u[0]||!u[1]||(c(i,Je(u,s,a,t,r,!1,n,(e.leftPadding??0)*(h/2),(e.rightPadding??0)*(h/2)),d),d.lastCommand=p)}e.type===1?(i.strokeStyle=i.fillStyle,i.stroke()):i.fill(),i.closePath()}function Ye(i,e,t=0){return Math.max(Math.min(i,e),t)}var je={C:(i,e,t)=>{i.bezierCurveTo(e[0],e[1],e[2],e[3],e[4],e[5]),t.lastControlX=e[2],t.lastControlY=e[3],t.currentX=e[4],t.currentY=e[5]},L:(i,e,t)=>{i.lineTo(e[0],e[1]),t.lastControlX=t.currentX=e[0],t.lastControlY=t.currentY=e[1]},M:(i,e,t)=>{i.moveTo(e[0],e[1]),t.lastControlX=t.currentX=e[0],t.lastControlY=t.currentY=e[1]},Q:(i,e,t)=>{i.quadraticCurveTo(e[0],e[1],e[2],e[3]),t.lastControlX=e[0],t.lastControlY=e[1],t.currentX=e[2],t.currentY=e[3]},T:(i,e,t)=>{let r,s;t.lastCommand==="Q"||t.lastCommand==="T"?(r=2*t.currentX-t.lastControlX,s=2*t.currentY-t.lastControlY):(r=t.currentX,s=t.currentY),i.quadraticCurveTo(r,s,e[0],e[1]),t.lastControlX=r,t.lastControlY=s,t.currentX=e[0],t.currentY=e[1]}};function Je(i,e,t,r,s,a,o,n=0,L=0,T=!0){let h=i.map(d=>parseFloat(d)||parseInt(d));if(h.length<2)throw new Error("Too few arguments for instruction");for(let d=0;da){s-t<-20&&this._logService.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=a}this.clear()}},Ce=class extends X0{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Qe=class extends X0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},et="requestIdleCallback"in globalThis?Qe:Ce;var s0=class i{constructor(){this.fg=0;this.bg=0;this.extended=new P0}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let e=new i;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},P0=class i{constructor(e=0,t=0){this._ext=0;this._urlId=0;this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new i(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}};var U=class{constructor(){this._listeners=[];this._disposed=!1}get event(){return this._event?this._event:(this._event=(e,t,r)=>{if(this._disposed)return M(()=>{});let s={fn:e,thisArgs:t};this._listeners.push(s);let a=M(()=>{let o=this._listeners.indexOf(s);o!==-1&&this._listeners.splice(o,1)});return r&&(Array.isArray(r)?r.push(a):r.add(a)),a},this._event)}fire(e){if(!this._disposed)switch(this._listeners.length){case 0:return;case 1:{let{fn:t,thisArgs:r}=this._listeners[0];t.call(r,e);return}default:{let t=this._listeners.slice();for(let{fn:r,thisArgs:s}of t)r.call(s,e)}}}dispose(){this._disposed||(this._disposed=!0,this._listeners.length=0)}},c0;(s=>{function i(a,o){return a(n=>o.fire(n))}s.forward=i;function e(a,o){return(n,L,T)=>a(h=>n.call(L,o(h)),void 0,T)}s.map=e;function t(...a){return(o,n,L)=>{let T=new R0;for(let h of a)T.add(h(d=>o.call(n,d)));return L&&(Array.isArray(L)?L.push(T):L.add(T)),T}}s.any=t;function r(a,o,n){return o(n),a(L=>o(L))}s.runAndSubscribe=r})(c0||={});var tt={texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},offset:{x:0,y:0},size:{x:0,y:0},sizeClipSpace:{x:0,y:0}},B0=2;var w0,J=class i{constructor(e,t,r,s){this._document=e;this._config=t;this._unicodeService=r;this._logService=s;this._didWarmUp=!1;this._cacheMap=new D0;this._cacheMapCombined=new D0;this._pages=[];this._activePages=[];this._workBoundingBox={top:0,left:0,bottom:0,right:0};this._workAttributeData=new s0;this._textureSize=512;this._onAddTextureAtlasCanvas=new U;this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event;this._onRemoveTextureAtlasCanvas=new U;this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event;this._requestClearModel=!1;this._clearModelGeneration=0;this._createNewPage(),this._tmpCanvas=it(e,this._config.deviceCellWidth*4+B0*2,this._config.deviceCellHeight+B0*2),this._tmpCtx=g(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:!0}))}get pages(){return this._pages}dispose(){this._tmpCanvas.remove();for(let e of this.pages)e.canvas.remove();this._onAddTextureAtlasCanvas.dispose(),this._onRemoveTextureAtlasCanvas.dispose()}warmUp(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)}_doWarmUp(){let e=new et(this._logService);for(let t=33;t<126;t++)e.enqueue(()=>{if(!this._cacheMap.get(t,0,0,0)){let r=this._drawToCache(t,0,0,0,!1,void 0);this._cacheMap.set(t,0,0,0,r)}})}beginFrame(){let e=this._requestClearModel;return this._requestClearModel=!1,e}clearTexture(){if(!(this._pages[0].currentRow.x===0&&this._pages[0].currentRow.y===0)){for(let e of this._pages)e.clear();this._cacheMap.clear(),this._cacheMapCombined.clear(),this._didWarmUp=!1,this._requestClearModel=!0,this._clearModelGeneration++}}_createNewPage(){if(i.maxAtlasPages&&this._pages.length>=Math.max(4,i.maxAtlasPages)){let t=this._pages.filter(T=>T.canvas.width*2<=(i.maxTextureSize||4096)).sort((T,h)=>h.canvas.width!==T.canvas.width?h.canvas.width-T.canvas.width:h.percentageUsed-T.percentageUsed),r=-1,s=0;for(let T=0;TT.canvas.width!==a[0].canvas.width)){let T=new u0(this._document,this._textureSize);return this._pages.push(T),this._activePages.push(T),this._onAddTextureAtlasCanvas.fire(T.canvas),T}let o=a.map(T=>T.glyphs[0].texturePage).sort((T,h)=>T-h),n=this.pages.length-a.length,L=this._mergePages(a,n);L.version=++u0.nextVersion;for(let T=o.length-1;T>=0;T--)this._deletePage(o[T]);this.pages.push(L),this._requestClearModel=!0,this._clearModelGeneration++,this._onAddTextureAtlasCanvas.fire(L.canvas)}let e=new u0(this._document,this._textureSize);return this._pages.push(e),this._activePages.push(e),this._onAddTextureAtlasCanvas.fire(e.canvas),e}_mergePages(e,t){let r=e[0].canvas.width*2,s=new u0(this._document,r,e);for(let[a,o]of e.entries()){let n=a*o.canvas.width%r,L=Math.floor(a/2)*o.canvas.height;s.ctx.drawImage(o.canvas,n,L);for(let h of o.glyphs)h.texturePage=t,h.sizeClipSpace.x=h.size.x/r,h.sizeClipSpace.y=h.size.y/r,h.texturePosition.x+=n,h.texturePosition.y+=L,h.texturePositionClipSpace.x=h.texturePosition.x/r,h.texturePositionClipSpace.y=h.texturePosition.y/r;this._onRemoveTextureAtlasCanvas.fire(o.canvas);let T=this._activePages.indexOf(o);T!==-1&&this._activePages.splice(T,1)}return s}_deletePage(e){this._pages.splice(e,1);for(let t=e;t=this._config.colors.ansi.length)throw new Error("No color found for idx "+e);return this._config.colors.ansi[e]}_getBackgroundColor(e,t,r,s){if(this._config.allowTransparency)return K;let a;switch(e){case 16777216:case 33554432:a=this._getColorFromAnsiIndex(t);break;case 50331648:let o=s0.toColorRGB(t);a=Z.toColor(o[0],o[1],o[2]);break;case 0:default:r?a=I0.opaque(this._config.colors.foreground):a=this._config.colors.background;break}return this._config.allowTransparency||(a=I0.opaque(a)),a}_getForegroundColor(e,t,r,s,a,o,n,L,T,h){let d=this._getMinimumContrastColor(e,t,r,s,a,o,n,T,L,h);if(d)return d;let _;switch(a){case 16777216:case 33554432:this._config.drawBoldTextInBrightColors&&T&&o<8&&(o+=8),_=this._getColorFromAnsiIndex(o);break;case 50331648:let p=s0.toColorRGB(o);_=Z.toColor(p[0],p[1],p[2]);break;case 0:default:n?_=this._config.colors.background:_=this._config.colors.foreground}return this._config.allowTransparency&&(_=I0.opaque(_)),L&&(_=I0.multiplyOpacity(_,Ke)),_}_resolveBackgroundRgba(e,t,r){switch(e){case 16777216:case 33554432:return this._getColorFromAnsiIndex(t).rgba;case 50331648:return t<<8;case 0:default:return r?this._config.colors.foreground.rgba:this._config.colors.background.rgba}}_resolveForegroundRgba(e,t,r,s){switch(e){case 16777216:case 33554432:return this._config.drawBoldTextInBrightColors&&s&&t<8&&(t+=8),this._getColorFromAnsiIndex(t).rgba;case 50331648:return t<<8;case 0:default:return r?this._config.colors.background.rgba:this._config.colors.foreground.rgba}}_getMinimumContrastColor(e,t,r,s,a,o,n,L,T,h){if(this._config.minimumContrastRatio===1||h)return;let d=this._getContrastCache(T),_=d.getColor(e,s);if(_!==void 0)return _??void 0;let p=this._resolveBackgroundRgba(t,r,n),c=this._resolveForegroundRgba(a,o,n,L),u=d0.ensureContrastRatio(p,c,this._config.minimumContrastRatio/(T?2:1));if(!u){d.setColor(e,s,null);return}let C=Z.toColor(u>>24&255,u>>16&255,u>>8&255);return d.setColor(e,s,C),C}_getContrastCache(e){return e?this._config.colors.halfContrastCache:this._config.colors.contrastCache}_drawToCache(e,t,r,s,a,o){let n=typeof e=="number"?String.fromCharCode(e):e;o&&this._tmpCanvas.parentElement!==o&&(this._tmpCanvas.style.display="none",o.append(this._tmpCanvas));let L=Math.min(this._config.deviceCellWidth*Math.max(n.length,2)+B0*2,this._config.deviceMaxTextureSize);this._tmpCanvas.width=b?b*2-f0:b-f0;!(f0>=b)===!1||Z0===0?(this._tmpCtx.setLineDash([Math.round(b),Math.round(b)]),this._tmpCtx.moveTo(j+Z0,G),this._tmpCtx.lineTo(Q0,G)):(this._tmpCtx.setLineDash([Math.round(b),Math.round(b)]),this._tmpCtx.moveTo(j,G),this._tmpCtx.lineTo(j+Z0,G),this._tmpCtx.moveTo(j+Z0+b,G),this._tmpCtx.lineTo(Q0,G)),f0=We(Q0-j,b,f0);break;case 5:let vt=.6,Ot=.3,de=Q0-j,Se=Math.floor(vt*de),Re=Math.floor(Ot*de),It=de-Se-Re;this._tmpCtx.setLineDash([Se,Re,It]),this._tmpCtx.moveTo(j,G),this._tmpCtx.lineTo(Q0,G);break;case 1:default:this._tmpCtx.moveTo(j,G),this._tmpCtx.lineTo(Q0,G);break}y0||this._tmpCtx.stroke(),this._tmpCtx.restore()}if(this._tmpCtx.restore(),!n0&&this._config.fontSize>=12&&!this._config.allowTransparency&&n!==" "){this._tmpCtx.save(),this._tmpCtx.textBaseline="alphabetic";let r0=this._tmpCtx.measureText(n);if(this._tmpCtx.restore(),"actualBoundingBoxDescent"in r0&&r0.actualBoundingBoxDescent>0){this._tmpCtx.save();let y0=new Path2D;y0.rect(i0,C0-Math.ceil(b/2),this._config.deviceCellWidth*$,v0-C0+Math.ceil(b/2)),this._tmpCtx.clip(y0),this._tmpCtx.lineWidth=this._config.devicePixelRatio*3,this._tmpCtx.strokeStyle=y.css,this._tmpCtx.strokeText(n,A,A+this._config.deviceCharHeight),this._tmpCtx.restore()}}}if(Q){let b=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/15)),D=b%2===1?.5:0;this._tmpCtx.lineWidth=b,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(A,A+D),this._tmpCtx.lineTo(A+this._config.deviceCharWidth*$,A+D),this._tmpCtx.stroke()}if(n0||this._tmpCtx.fillText(n,A,A+this._config.deviceCharHeight),n==="_"&&!this._config.allowTransparency){let b=fe(this._tmpCtx.getImageData(A,A,this._config.deviceCellWidth,this._config.deviceCellHeight),y,L0,a0);if(b)for(let D=1;D<=5&&(this._tmpCtx.save(),this._tmpCtx.fillStyle=y.css,this._tmpCtx.fillRect(0,0,this._tmpCanvas.width,this._tmpCanvas.height),this._tmpCtx.restore(),this._tmpCtx.fillText(n,A,A+this._config.deviceCharHeight-D),b=fe(this._tmpCtx.getImageData(A,A,this._config.deviceCellWidth,this._config.deviceCellHeight),y,L0,a0),!!b);D++);}if(C){let b=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/10)),D=this._tmpCtx.lineWidth%2===1?.5:0;this._tmpCtx.lineWidth=b,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(A,A+Math.floor(this._config.deviceCharHeight/2)-D),this._tmpCtx.lineTo(A+this._config.deviceCharWidth*$,A+Math.floor(this._config.deviceCharHeight/2)-D),this._tmpCtx.stroke()}this._tmpCtx.restore();let q=this._tmpCtx.getImageData(0,0,this._tmpCanvas.width,this._tmpCanvas.height),g0;if(this._config.allowTransparency?g0=Gt(q):g0=fe(q,y,L0,a0),g0)return tt;let I=this._findGlyphBoundingBox(q,this._workBoundingBox,L,t0,n0,A),O,v;for(;;){if(this._activePages.length===0){let b=this._createNewPage();O=b,v=b.currentRow,v.height=I.size.y;break}O=this._activePages[this._activePages.length-1],v=O.currentRow;for(let b of this._activePages)I.size.y<=b.currentRow.height&&(O=b,v=b.currentRow);for(let b=this._activePages.length-1;b>=0;b--)for(let D of this._activePages[b].fixedRows)D.height<=v.height&&I.size.y<=D.height&&(O=this._activePages[b],v=D);if(I.size.x>this._textureSize){this._overflowSizePage||(this._overflowSizePage=new u0(this._document,this._config.deviceMaxTextureSize),this.pages.push(this._overflowSizePage),this._requestClearModel=!0,this._clearModelGeneration++,this._onAddTextureAtlasCanvas.fire(this._overflowSizePage.canvas)),O=this._overflowSizePage,v=this._overflowSizePage.currentRow,v.x+I.size.x>=O.canvas.width&&(v.x=0,v.y+=v.height,v.height=0);break}if(v.y+I.size.y>=O.canvas.height||v.height>I.size.y+2){let b=!1;if(O.currentRow.y+O.currentRow.height+I.size.y>=O.canvas.height){let D;for(let i0 of this._activePages)if(i0.currentRow.y+i0.currentRow.height+I.size.y=i.maxAtlasPages&&v.y+I.size.y<=O.canvas.height&&v.height>=I.size.y&&v.x+I.size.x<=O.canvas.width)b=!0;else{let i0=this._createNewPage();O=i0,v=i0.currentRow,v.height=I.size.y,b=!0}}b||(O.currentRow.height>0&&O.fixedRows.push(O.currentRow),v={x:0,y:O.currentRow.y+O.currentRow.height,height:I.size.y},O.fixedRows.push(v),O.currentRow={x:0,y:v.y+v.height,height:0})}if(v.x+I.size.x<=O.canvas.width)break;v===O.currentRow?(v.x=0,v.y+=v.height,v.height=0):O.fixedRows.splice(O.fixedRows.indexOf(v),1)}return I.texturePage=this._pages.indexOf(O),I.texturePosition.x=v.x,I.texturePosition.y=v.y,I.texturePositionClipSpace.x=v.x/O.canvas.width,I.texturePositionClipSpace.y=v.y/O.canvas.height,I.sizeClipSpace.x/=O.canvas.width,I.sizeClipSpace.y/=O.canvas.height,v.height=Math.max(v.height,I.size.y),v.x+=I.size.x,O.ctx.putImageData(q,I.texturePosition.x-this._workBoundingBox.left,I.texturePosition.y-this._workBoundingBox.top,this._workBoundingBox.left,this._workBoundingBox.top,I.size.x,I.size.y),O.addGlyph(I),O.version=++u0.nextVersion,I}_findGlyphBoundingBox(e,t,r,s,a,o){t.top=0;let n=s?this._config.deviceCellHeight:this._tmpCanvas.height,L=s?this._config.deviceCellWidth:r,T=!1;for(let h=0;h=o;h--){for(let d=0;d=0;h--){for(let d=0;d>>24,a=e.rgba>>>16&255,o=e.rgba>>>8&255,n=t.rgba>>>24,L=t.rgba>>>16&255,T=t.rgba>>>8&255,h=Math.floor((Math.abs(s-n)+Math.abs(a-L)+Math.abs(o-T))/12),d=!0;for(let _=0;_0)return!1;return!0}function it(i,e,t){let r=i.createElement("canvas");return r.width=e,r.height=t,r}function rt(i,e,t,r,s,a,o,n,L=!0){let T={foreground:a.foreground,background:a.background,cursor:K,cursorAccent:K,selectionForeground:K,selectionBackgroundTransparent:K,selectionBackgroundOpaque:K,selectionInactiveBackgroundTransparent:K,selectionInactiveBackgroundOpaque:K,overviewRulerBorder:K,scrollbarSliderBackground:K,scrollbarSliderHoverBackground:K,scrollbarSliderActiveBackground:K,ansi:a.ansi.slice(),contrastCache:a.contrastCache,halfContrastCache:a.halfContrastCache};return{customGlyphs:L,devicePixelRatio:o,deviceMaxTextureSize:n,letterSpacing:s.letterSpacing,lineHeight:s.lineHeight,deviceCellWidth:i,deviceCellHeight:e,deviceCharWidth:t,deviceCharHeight:r,fontFamily:s.fontFamily,fontSize:s.fontSize,fontWeight:s.fontWeight,fontWeightBold:s.fontWeightBold,allowTransparency:s.allowTransparency,drawBoldTextInBrightColors:s.drawBoldTextInBrightColors,minimumContrastRatio:s.minimumContrastRatio,colors:T}}function Ee(i,e){for(let t=0;t=0){if(Ee(u.config,h))return u.atlas;u.ownedBy.length===1?(u.atlas.dispose(),e0.splice(c,1)):u.ownedBy.splice(C,1);break}}for(let c=0;c{this._renderCallback(),this._animationFrame=void 0})))}_restartInterval(e=600){this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout=this._coreBrowserService.window.setTimeout(()=>{if(this._animationTimeRestarted){let t=600-(Date.now()-this._animationTimeRestarted);if(this._animationTimeRestarted=void 0,t>0){this._restartInterval(t);return}}this.isCursorVisible=!1,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0}),this._blinkInterval=this._coreBrowserService.window.setInterval(()=>{if(this._animationTimeRestarted){let t=600-(Date.now()-this._animationTimeRestarted);this._animationTimeRestarted=void 0,this._restartInterval(t);return}this.isCursorVisible=!this.isCursorVisible,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0})},600)},e)}pause(){this.isCursorVisible=!0,this._isIdlePaused=!1,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._idleTimeout&&(this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0)}resume(){this.pause(),this._animationTimeRestarted=void 0,this._restartInterval(),this._resetIdleTimer(),this.restartBlinkAnimation()}_resetIdleTimer(){this._isIdlePaused=!1,this._idleTimeout&&this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=this._coreBrowserService.window.setTimeout(()=>{this._stopBlinkingDueToIdle()},3e5)}_stopBlinkingDueToIdle(){this.isCursorVisible=!0,this._isIdlePaused=!0,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0,this._renderCallback()}};function ve(i,e,t){let r=new e.ResizeObserver(s=>{let a=s.find(L=>L.target===i);if(!a)return;if(!("devicePixelContentBoxSize"in a)){r?.disconnect(),r=void 0;return}let o=a.devicePixelContentBoxSize[0].inlineSize,n=a.devicePixelContentBoxSize[0].blockSize;o>0&&n>0&&t(o,n)});try{r.observe(i,{box:["device-pixel-content-box"]})}catch{r.disconnect(),r=void 0}return M(()=>r?.disconnect())}function nt(i){return i>65535?(i-=65536,String.fromCharCode((i>>10)+55296)+String.fromCharCode(i%1024+56320)):String.fromCharCode(i)}var j0=class i extends s0{constructor(){super(...arguments);this.content=0;this.fg=0;this.bg=0;this.extended=new P0;this.combinedData=""}static fromCharData(t){let r=new i;return r.setFromCharData(t),r}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?nt(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let r=!1;if(t[1].length>2)r=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:r=!0}else r=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;r&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}attributesEquals(t){if(this.getFgColorMode()!==t.getFgColorMode()||this.getFgColor()!==t.getFgColor()||this.getBgColorMode()!==t.getBgColorMode()||this.getBgColor()!==t.getBgColor()||this.isInverse()!==t.isInverse()||this.isBold()!==t.isBold()||this.isUnderline()!==t.isUnderline())return!1;if(this.isUnderline()){if(this.getUnderlineStyle()!==t.getUnderlineStyle())return!1;let r=this.isUnderlineColorDefault(),s=t.isUnderlineColorDefault();if(!(r&&s)&&(r!==s||this.getUnderlineColor()!==t.getUnderlineColor()||this.getUnderlineColorMode()!==t.getUnderlineColorMode()))return!1}return!(this.isOverline()!==t.isOverline()||this.isBlink()!==t.isBlink()||this.isInvisible()!==t.isInvisible()||this.isItalic()!==t.isItalic()||this.isDim()!==t.isDim()||this.isStrikethrough()!==t.isStrikethrough())}};var J0=class extends W{constructor(t,r,s){super();this._renderCallback=t;this._coreBrowserService=r;this._optionsService=s;this._intervalDuration=0;this._blinkOn=!0;this._needsBlinkInViewport=!1;this._isViewportVisible=!0;this._register(this._optionsService.onSpecificOptionChange("blinkIntervalDuration",a=>{this.setIntervalDuration(a)})),this.setIntervalDuration(this._optionsService.rawOptions.blinkIntervalDuration),this._register(M(()=>this._clearInterval()))}get isBlinkOn(){return this._blinkOn}get isEnabled(){return this._intervalDuration>0}setNeedsBlinkInViewport(t){this._needsBlinkInViewport!==t&&(this._needsBlinkInViewport=t,this._updateIntervalState())}setViewportVisible(t){this._isViewportVisible!==t&&(this._isViewportVisible=t,this._updateIntervalState())}setIntervalDuration(t){t!==this._intervalDuration&&(this._intervalDuration=t,this._clearInterval(),this._updateIntervalState())}_updateIntervalState(){if(this._intervalDuration>0&&this._needsBlinkInViewport&&this._isViewportVisible){if(this._interval!==void 0)return;let r=this._blinkOn;this._blinkOn=!0,this._interval=this._coreBrowserService.window.setInterval(()=>{this._blinkOn=!this._blinkOn,this._renderCallback()},this._intervalDuration),r||this._renderCallback();return}this._clearInterval(),this._blinkOn||(this._blinkOn=!0,this._renderCallback())}_clearInterval(){this._interval!==void 0&&(this._coreBrowserService.window.clearInterval(this._interval),this._interval=void 0)}};var te=new Float32Array([2,0,0,0,0,-2,0,0,0,0,1,0,-1,1,0,1]);function ie(i,e,t,r){let s=g(i.createProgram());if(i.attachShader(s,g(at(i,i.VERTEX_SHADER,e,r))),i.attachShader(s,g(at(i,i.FRAGMENT_SHADER,t,r))),i.linkProgram(s),i.getProgramParameter(s,i.LINK_STATUS))return s;r.error(i.getProgramInfoLog(s)),i.deleteProgram(s)}function at(i,e,t,r){let s=g(i.createShader(e));if(i.shaderSource(s,t),i.compileShader(s),i.getShaderParameter(s,i.COMPILE_STATUS))return s;r.error(i.getShaderInfoLog(s)),i.deleteShader(s)}function ot(i,e){let t=Math.min(i.length*2,e),r=new Float32Array(t);for(let s=0;sFt(i))}var R0=class{constructor(){this._disposables=new Set;this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(e){return this._isDisposed?e.dispose():this._disposables.add(e),e}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.clear()}}clear(){for(let e of this._disposables)e.dispose();this._disposables.clear()}},W=class{constructor(){this._store=new R0}dispose(){this._store.dispose()}_register(e){return this._store.add(e)}};W.None=Object.freeze({dispose(){}});var m0=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}};var Pe=!!(typeof process<"u"&&"title"in process&&(typeof navigator>"u"||navigator.userAgent.startsWith("Node.js/"))),O0=Pe?"node":navigator.userAgent,ce=Pe?"node":navigator.platform,Be=O0.includes("Firefox"),n1=O0.includes("Chrome"),we=O0.includes("Edge"),ue=/^((?!chrome|android).)*safari/i.test(O0);function He(){if(!ue)return 0;let i=O0.match(/Version\/(\d+)/);return i===null||i.length<2?0:parseInt(i[1],10)}var a1=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(ce),o1=["Windows","Win16","Win32","WinCE"].includes(ce),T1=ce.indexOf("Linux")>=0,l1=/\bCrOS\b/.test(O0);var P=0,B=0,w=0,x=0,K={css:"#00000000",rgba:0},Z;(r=>{function i(s,a,o,n){return n!==void 0?`#${E0(s)}${E0(a)}${E0(o)}${E0(n)}`:`#${E0(s)}${E0(a)}${E0(o)}`}r.toCss=i;function e(s,a,o,n=255){return(s<<24|a<<16|o<<8|n)>>>0}r.toRgba=e;function t(s,a,o,n){return{css:r.toCss(s,a,o,n),rgba:r.toRgba(s,a,o,n)}}r.toColor=t})(Z||={});var I0;(n=>{function i(L,T){if(x=(T.rgba&255)/255,x===1)return{css:T.css,rgba:T.rgba};let h=T.rgba>>24&255,d=T.rgba>>16&255,_=T.rgba>>8&255,p=L.rgba>>24&255,c=L.rgba>>16&255,u=L.rgba>>8&255;P=p+Math.round((h-p)*x),B=c+Math.round((d-c)*x),w=u+Math.round((_-u)*x);let C=Z.toCss(P,B,w),Q=Z.toRgba(P,B,w);return{css:C,rgba:Q}}n.blend=i;function e(L){return(L.rgba&255)===255}n.isOpaque=e;function t(L,T,h){let d=d0.ensureContrastRatio(L.rgba,T.rgba,h);if(d)return Z.toColor(d>>24&255,d>>16&255,d>>8&255)}n.ensureContrastRatio=t;function r(L){let T=(L.rgba|255)>>>0;return[P,B,w]=d0.toChannels(T),{css:Z.toCss(P,B,w),rgba:T}}n.opaque=r;function s(L,T){return x=Math.round(T*255),[P,B,w]=d0.toChannels(L.rgba),{css:Z.toCss(P,B,w,x),rgba:Z.toRgba(P,B,w,x)}}n.opacity=s;function a(L,T){return x=L.rgba&255,s(L,x*T/255)}n.multiplyOpacity=a;function o(L){return[L.rgba>>24&255,L.rgba>>16&255,L.rgba>>8&255]}n.toColorRGB=o})(I0||={});var Mt;(r=>{let i,e;try{let s=document.createElement("canvas");s.width=1,s.height=1;let a=s.getContext("2d",{willReadFrequently:!0});a&&(i=a,i.globalCompositeOperation="copy",e=i.createLinearGradient(0,0,1,1))}catch{}function t(s){if(s.match(/#[\da-f]{3,8}/i))switch(s.length){case 4:return P=parseInt(s.slice(1,2).repeat(2),16),B=parseInt(s.slice(2,3).repeat(2),16),w=parseInt(s.slice(3,4).repeat(2),16),Z.toColor(P,B,w);case 5:return P=parseInt(s.slice(1,2).repeat(2),16),B=parseInt(s.slice(2,3).repeat(2),16),w=parseInt(s.slice(3,4).repeat(2),16),x=parseInt(s.slice(4,5).repeat(2),16),Z.toColor(P,B,w,x);case 7:return{css:s,rgba:(parseInt(s.slice(1),16)<<8|255)>>>0};case 9:return{css:s,rgba:parseInt(s.slice(1),16)>>>0}}let a=s.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(a)return P=parseInt(a[1],10),B=parseInt(a[2],10),w=parseInt(a[3],10),x=Math.round((a[5]===void 0?1:parseFloat(a[5]))*255),Z.toColor(P,B,w,x);if(s==="transparent")return{css:"transparent",rgba:0};if(!i||!e)throw new Error("css.toColor: Unsupported css format");if(i.fillStyle=e,i.fillStyle=s,typeof i.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(i.fillRect(0,0,1,1),[P,B,w,x]=i.getImageData(0,0,1,1).data,x!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Z.toRgba(P,B,w,x),css:s}}r.toColor=t})(Mt||={});var V;(t=>{function i(r){return e(r>>16&255,r>>8&255,r&255)}t.relativeLuminance=i;function e(r,s,a){let o=r/255,n=s/255,L=a/255,T=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),h=n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4),d=L<=.03928?L/12.92:Math.pow((L+.055)/1.055,2.4);return T*.2126+h*.7152+d*.0722}t.relativeLuminance2=e})(V||={});var d0;(a=>{function i(o,n){if(x=(n&255)/255,x===1)return n;let L=n>>24&255,T=n>>16&255,h=n>>8&255,d=o>>24&255,_=o>>16&255,p=o>>8&255;return P=d+Math.round((L-d)*x),B=_+Math.round((T-_)*x),w=p+Math.round((h-p)*x),Z.toRgba(P,B,w)}a.blend=i;function e(o,n,L){let T=V.relativeLuminance(o>>8),h=V.relativeLuminance(n>>8);if(h0(T,h)>8));if(u>8));return u>Q?c:C}return c}let _=r(o,n,L),p=h0(T,V.relativeLuminance(_>>8));if(p>8));return p>u?_:c}return _}}a.ensureContrastRatio=e;function t(o,n,L){let T=o>>24&255,h=o>>16&255,d=o>>8&255,_=n>>24&255,p=n>>16&255,c=n>>8&255,u=h0(V.relativeLuminance2(_,p,c),V.relativeLuminance2(T,h,d));for(;u0||p>0||c>0);)_-=Math.max(0,Math.ceil(_*.1)),p-=Math.max(0,Math.ceil(p*.1)),c-=Math.max(0,Math.ceil(c*.1)),u=h0(V.relativeLuminance2(_,p,c),V.relativeLuminance2(T,h,d));return(_<<24|p<<16|c<<8|255)>>>0}a.reduceLuminance=t;function r(o,n,L){let T=o>>24&255,h=o>>16&255,d=o>>8&255,_=n>>24&255,p=n>>16&255,c=n>>8&255,u=h0(V.relativeLuminance2(_,p,c),V.relativeLuminance2(T,h,d));for(;u>>0}a.increaseLuminance=r;function s(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}a.toChannels=s})(d0||={});function E0(i){let e=i.toString(16);return e.length<2?"0"+e:e}function h0(i,e){return i=128512&&i<=128591||i>=127744&&i<=128511||i>=128640&&i<=128767||i>=9728&&i<=9983||i>=9984&&i<=10175||i>=65024&&i<=65039||i>=129280&&i<=129535||i>=127462&&i<=127487}function Ze(i,e,t,r){return e===1&&t>Math.ceil(r*1.5)&&i!==void 0&&i>255&&!yt(i)&&!W0(i)&&!At(i)}function V0(i){return W0(i)||gt(i)}function Ue(){return{css:{canvas:U0(),cell:U0()},device:{canvas:U0(),cell:U0(),char:{width:0,height:0,left:0,top:0}}}}function U0(){return{width:0,height:0}}function We(i,e,t=0){return(i-(Math.round(e)*2-t))%(Math.round(e)*2)}var l;(C=>(C.LINE_H=Object.freeze({type:2,data:"M0,.5 L1,.5",strokeWidth:1}),C.LINE_V=Object.freeze({type:2,data:"M.5,0 L.5,1",strokeWidth:1}),C.FADE_RIGHT=Object.freeze({type:2,data:"M0,.5 L.28,.5 M.32,.5 L.52,.5 M.60,.5 L.72,.5 M.84,.5 L.90,.5",strokeWidth:1}),C.FADE_LEFT=Object.freeze({type:2,data:"M.10,.5 L.16,.5 M.28,.5 L.40,.5 M.48,.5 L.68,.5 M.72,.5 L1,.5",strokeWidth:1}),C.FADE_DOWN=Object.freeze({type:2,data:"M.5,0 L.5,.28 M.5,.32 L.5,.52 M.5,.60 L.5,.72 M.5,.84 L.5,.90",strokeWidth:1}),C.FADE_UP=Object.freeze({type:2,data:"M.5,.10 L.5,.16 M.5,.28 L.5,.40 M.5,.48 L.5,.68 M.5,.72 L.5,1",strokeWidth:1}),C.CURVE_DOWN_RIGHT=Object.freeze({type:2,data:(Q,m)=>`M.5,1 L.5,${.5+m/.15*.5} C.5,${.5+m/.15*.5},.5,.5,1,.5`,strokeWidth:1}),C.CURVE_DOWN_LEFT=Object.freeze({type:2,data:(Q,m)=>`M.5,1 L.5,${.5+m/.15*.5} C.5,${.5+m/.15*.5},.5,.5,0,.5`,strokeWidth:1}),C.CURVE_UP_RIGHT=Object.freeze({type:2,data:(Q,m)=>`M.5,0 L.5,${.5-m/.15*.5} C.5,${.5-m/.15*.5},.5,.5,1,.5`,strokeWidth:1}),C.CURVE_UP_LEFT=Object.freeze({type:2,data:(Q,m)=>`M.5,0 L.5,${.5-m/.15*.5} C.5,${.5-m/.15*.5},.5,.5,0,.5`,strokeWidth:1}),C.NODE_FILL=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5"}),C.NODE_STROKE=Object.freeze({type:3,data:"M.85,.5 A.35,.175,0,1,1,.15,.5 A.35,.175,0,1,1,.85,.5",strokeWidth:1}),C.NODE_LINE_RIGHT=Object.freeze({type:3,data:"M1,.5 L.85,.5",strokeWidth:1}),C.NODE_LINE_LEFT=Object.freeze({type:3,data:"M0,.5 L.15,.5",strokeWidth:1}),C.NODE_LINE_DOWN=Object.freeze({type:3,data:"M.5,1 L.5,.7",strokeWidth:1}),C.NODE_LINE_UP=Object.freeze({type:3,data:"M.5,0 L.5,.3",strokeWidth:1})))(l||={});var Ve={"\u2500":{type:2,data:"M0,.5 L1,.5",strokeWidth:1},"\u2501":{type:2,data:"M0,.5 L1,.5",strokeWidth:3},"\u2502":{type:2,data:"M.5,0 L.5,1",strokeWidth:1},"\u2503":{type:2,data:"M.5,0 L.5,1",strokeWidth:3},"\u2504":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:1},"\u2505":{type:2,data:"M.0667,.5 L.2667,.5 M.4,.5 L.6,.5 M.7333,.5 L.9333,.5",strokeWidth:3},"\u2506":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:1},"\u2507":{type:2,data:"M.5,.0667 L.5,.2667 M.5,.4 L.5,.6 M.5,.7333 L.5,.9333",strokeWidth:3},"\u2508":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:1},"\u2509":{type:2,data:"M.05,.5 L.2,.5 M.3,.5 L.45,.5 M.55,.5 L.7,.5 M.8,.5 L.95,.5",strokeWidth:3},"\u250A":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:1},"\u250B":{type:2,data:"M.5,.05 L.5,.2 M.5,.3 L.5,.45 L.5,.55 M.5,.7 L.5,.95",strokeWidth:3},"\u250C":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},"\u250D":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u250E":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u250F":{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3},"\u2510":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},"\u2511":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u2512":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2513":{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3},"\u2514":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},"\u2515":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u2516":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2517":{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3},"\u2518":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},"\u2519":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u251A":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u251B":{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3},"\u251C":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},"\u251D":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u251E":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u251F":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2520":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"\u2521":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"\u2522":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"\u2523":{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3},"\u2524":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},"\u2525":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u2526":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2527":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2528":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"\u2529":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"\u252A":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"\u252B":{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3},"\u252C":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},"\u252D":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u252E":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u252F":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"\u2530":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2531":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"\u2532":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"\u2533":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3},"\u2534":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:1},"\u2535":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u2536":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u2537":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"\u2538":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2539":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"\u253A":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"\u253B":{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,0",strokeWidth:3},"\u253C":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:1},"\u253D":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u253E":[{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u253F":[{type:2,data:"M.5,0 L.5,1",strokeWidth:1},{type:2,data:"M0,.5 L1,.5",strokeWidth:3}],"\u2540":[{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2541":[{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u2542":[{type:2,data:"M0,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1",strokeWidth:3}],"\u2543":[{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:3}],"\u2544":[{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:3}],"\u2545":[{type:2,data:"M.5,0 L.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M0,.5 L.5,.5 L.5,1",strokeWidth:3}],"\u2546":[{type:2,data:"M.5,0 L.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M0.5,1 L.5,.5 L1,.5",strokeWidth:3}],"\u2547":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0 M0,.5 L1,.5",strokeWidth:3}],"\u2548":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M0,.5 L1,.5 M.5,.5 L.5,1",strokeWidth:3}],"\u2549":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L0,.5",strokeWidth:3}],"\u254A":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,0 L.5,1 M.5,.5 L1,.5",strokeWidth:3}],"\u254B":{type:2,data:"M0,.5 L1,.5 M.5,0 L.5,1",strokeWidth:3},"\u254C":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:1},"\u254D":{type:2,data:"M.1,.5 L.4,.5 M.6,.5 L.9,.5",strokeWidth:3},"\u254E":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:1},"\u254F":{type:2,data:"M.5,.1 L.5,.4 M.5,.6 L.5,.9",strokeWidth:3},"\u2550":{type:2,data:(i,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u2551":{type:2,data:(i,e)=>`M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1`,strokeWidth:1},"\u2552":{type:2,data:(i,e)=>`M.5,1 L.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u2553":{type:2,data:(i,e)=>`M${.5-i},1 L${.5-i},.5 L1,.5 M${.5+i},.5 L${.5+i},1`,strokeWidth:1},"\u2554":{type:2,data:(i,e)=>`M1,${.5-e} L${.5-i},${.5-e} L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1`,strokeWidth:1},"\u2555":{type:2,data:(i,e)=>`M0,${.5-e} L.5,${.5-e} L.5,1 M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"\u2556":{type:2,data:(i,e)=>`M${.5+i},1 L${.5+i},.5 L0,.5 M${.5-i},.5 L${.5-i},1`,strokeWidth:1},"\u2557":{type:2,data:(i,e)=>`M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M0,${.5-e} L${.5+i},${.5-e} L${.5+i},1`,strokeWidth:1},"\u2558":{type:2,data:(i,e)=>`M.5,0 L.5,${.5+e} L1,${.5+e} M.5,${.5-e} L1,${.5-e}`,strokeWidth:1},"\u2559":{type:2,data:(i,e)=>`M1,.5 L${.5-i},.5 L${.5-i},0 M${.5+i},.5 L${.5+i},0`,strokeWidth:1},"\u255A":{type:2,data:(i,e)=>`M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0 M1,${.5+e} L${.5-i},${.5+e} L${.5-i},0`,strokeWidth:1},"\u255B":{type:2,data:(i,e)=>`M0,${.5+e} L.5,${.5+e} L.5,0 M0,${.5-e} L.5,${.5-e}`,strokeWidth:1},"\u255C":{type:2,data:(i,e)=>`M0,.5 L${.5+i},.5 L${.5+i},0 M${.5-i},.5 L${.5-i},0`,strokeWidth:1},"\u255D":{type:2,data:(i,e)=>`M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0 M0,${.5+e} L${.5+i},${.5+e} L${.5+i},0`,strokeWidth:1},"\u255E":{type:2,data:(i,e)=>`M.5,0 L.5,1 M.5,${.5-e} L1,${.5-e} M.5,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u255F":{type:2,data:(i,e)=>`M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1 M${.5+i},.5 L1,.5`,strokeWidth:1},"\u2560":{type:2,data:(i,e)=>`M${.5-i},0 L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1 M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0`,strokeWidth:1},"\u2561":{type:2,data:(i,e)=>`M.5,0 L.5,1 M0,${.5-e} L.5,${.5-e} M0,${.5+e} L.5,${.5+e}`,strokeWidth:1},"\u2562":{type:2,data:(i,e)=>`M0,.5 L${.5-i},.5 M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1`,strokeWidth:1},"\u2563":{type:2,data:(i,e)=>`M${.5+i},0 L${.5+i},1 M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0`,strokeWidth:1},"\u2564":{type:2,data:(i,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e} M.5,${.5+e} L.5,1`,strokeWidth:1},"\u2565":{type:2,data:(i,e)=>`M0,.5 L1,.5 M${.5-i},.5 L${.5-i},1 M${.5+i},.5 L${.5+i},1`,strokeWidth:1},"\u2566":{type:2,data:(i,e)=>`M0,${.5-e} L1,${.5-e} M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1`,strokeWidth:1},"\u2567":{type:2,data:(i,e)=>`M.5,0 L.5,${.5-e} M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u2568":{type:2,data:(i,e)=>`M0,.5 L1,.5 M${.5-i},.5 L${.5-i},0 M${.5+i},.5 L${.5+i},0`,strokeWidth:1},"\u2569":{type:2,data:(i,e)=>`M0,${.5+e} L1,${.5+e} M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0 M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0`,strokeWidth:1},"\u256A":{type:2,data:(i,e)=>`M.5,0 L.5,1 M0,${.5-e} L1,${.5-e} M0,${.5+e} L1,${.5+e}`,strokeWidth:1},"\u256B":{type:2,data:(i,e)=>`M0,.5 L1,.5 M${.5-i},0 L${.5-i},1 M${.5+i},0 L${.5+i},1`,strokeWidth:1},"\u256C":{type:2,data:(i,e)=>`M0,${.5+e} L${.5-i},${.5+e} L${.5-i},1 M1,${.5+e} L${.5+i},${.5+e} L${.5+i},1 M0,${.5-e} L${.5-i},${.5-e} L${.5-i},0 M1,${.5-e} L${.5+i},${.5-e} L${.5+i},0`,strokeWidth:1},"\u256D":{type:2,data:(i,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"\u256E":{type:2,data:(i,e)=>`M.5,1 L.5,${.5+e/.15*.5} C.5,${.5+e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"\u256F":{type:2,data:(i,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,0,.5`,strokeWidth:1},"\u2570":{type:2,data:(i,e)=>`M.5,0 L.5,${.5-e/.15*.5} C.5,${.5-e/.15*.5},.5,.5,1,.5`,strokeWidth:1},"\u2571":{type:2,data:"M1,0 L0,1",strokeWidth:1},"\u2572":{type:2,data:"M0,0 L1,1",strokeWidth:1},"\u2573":{type:2,data:"M1,0 L0,1 M0,0 L1,1",strokeWidth:1},"\u2574":{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},"\u2575":{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},"\u2576":{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},"\u2577":{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},"\u2578":{type:2,data:"M.5,.5 L0,.5",strokeWidth:3},"\u2579":{type:2,data:"M.5,.5 L.5,0",strokeWidth:3},"\u257A":{type:2,data:"M.5,.5 L1,.5",strokeWidth:3},"\u257B":{type:2,data:"M.5,.5 L.5,1",strokeWidth:3},"\u257C":[{type:2,data:"M.5,.5 L0,.5",strokeWidth:1},{type:2,data:"M.5,.5 L1,.5",strokeWidth:3}],"\u257D":[{type:2,data:"M.5,.5 L.5,0",strokeWidth:1},{type:2,data:"M.5,.5 L.5,1",strokeWidth:3}],"\u257E":[{type:2,data:"M.5,.5 L1,.5",strokeWidth:1},{type:2,data:"M.5,.5 L0,.5",strokeWidth:3}],"\u257F":[{type:2,data:"M.5,.5 L.5,1",strokeWidth:1},{type:2,data:"M.5,.5 L.5,0",strokeWidth:3}],"\u2580":{type:0,data:[{x:0,y:0,w:8,h:4}]},"\u2581":{type:0,data:[{x:0,y:7,w:8,h:1}]},"\u2582":{type:0,data:[{x:0,y:6,w:8,h:2}]},"\u2583":{type:0,data:[{x:0,y:5,w:8,h:3}]},"\u2584":{type:0,data:[{x:0,y:4,w:8,h:4}]},"\u2585":{type:0,data:[{x:0,y:3,w:8,h:5}]},"\u2586":{type:0,data:[{x:0,y:2,w:8,h:6}]},"\u2587":{type:0,data:[{x:0,y:1,w:8,h:7}]},"\u2588":{type:0,data:[{x:0,y:0,w:8,h:8}]},"\u2589":{type:0,data:[{x:0,y:0,w:7,h:8}]},"\u258A":{type:0,data:[{x:0,y:0,w:6,h:8}]},"\u258B":{type:0,data:[{x:0,y:0,w:5,h:8}]},"\u258C":{type:0,data:[{x:0,y:0,w:4,h:8}]},"\u258D":{type:0,data:[{x:0,y:0,w:3,h:8}]},"\u258E":{type:0,data:[{x:0,y:0,w:2,h:8}]},"\u258F":{type:0,data:[{x:0,y:0,w:1,h:8}]},"\u2590":{type:0,data:[{x:4,y:0,w:4,h:8}]},"\u2591":{type:1,data:[[1,0],[0,0]]},"\u2592":{type:1,data:[[1,0],[0,1]]},"\u2593":{type:1,data:[[1,1],[1,0]]},"\u2594":{type:0,data:[{x:0,y:0,w:8,h:1}]},"\u2595":{type:0,data:[{x:7,y:0,w:1,h:8}]},"\u2596":{type:0,data:[{x:0,y:4,w:4,h:4}]},"\u2597":{type:0,data:[{x:4,y:4,w:4,h:4}]},"\u2598":{type:0,data:[{x:0,y:0,w:4,h:4}]},"\u2599":{type:0,data:[{x:0,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"\u259A":{type:0,data:[{x:0,y:0,w:4,h:4},{x:4,y:4,w:4,h:4}]},"\u259B":{type:0,data:[{x:0,y:0,w:4,h:8},{x:4,y:0,w:4,h:4}]},"\u259C":{type:0,data:[{x:0,y:0,w:8,h:4},{x:4,y:0,w:4,h:8}]},"\u259D":{type:0,data:[{x:4,y:0,w:4,h:4}]},"\u259E":{type:0,data:[{x:4,y:0,w:4,h:4},{x:0,y:4,w:4,h:4}]},"\u259F":{type:0,data:[{x:4,y:0,w:4,h:8},{x:0,y:4,w:8,h:4}]},"\uE0A0":{type:5,data:{d:"M.3,1 L.03,1 L.03,.88 C.03,.82,.06,.78,.11,.73 C.15,.7,.2,.68,.28,.65 L.43,.6 C.49,.58,.53,.56,.56,.53 C.59,.5,.6,.47,.6,.43 L.6,.27 L.4,.27 L.69,.1 L.98,.27 L.78,.27 L.78,.46 C.78,.52,.76,.56,.72,.61 C.68,.66,.63,.67,.56,.7 L.48,.72 C.42,.74,.38,.76,.35,.78 C.32,.8,.31,.84,.31,.88 L.31,1 M.3,.5 L.03,.59 L.03,.09 L.3,.09 L.3,.655",type:0}},"\uE0A1":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.355,.03 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"\uE0A2":{type:5,data:{d:"M.25,.94 C.16,.94,.11,.92,.11,.87 L.11,.53 C.11,.48,.15,.455,.23,.45 L.23,.3 C.23,.25,.26,.22,.31,.19 C.36,.16,.43,.15,.51,.15 C.59,.15,.66,.16,.71,.19 C.77,.22,.79,.26,.79,.3 L.79,.45 C.87,.45,.91,.48,.91,.53 L.91,.87 C.91,.92,.86,.94,.77,.94 L.24,.94 M.53,.2 C.49,.2,.45,.21,.42,.23 C.39,.25,.38,.27,.38,.3 L.38,.45 L.68,.45 L.68,.3 C.68,.27,.67,.25,.64,.23 C.61,.21,.58,.2,.53,.2 M.58,.82 L.58,.66 C.63,.65,.65,.63,.65,.6 C.65,.58,.64,.57,.61,.56 C.58,.55,.56,.54,.52,.54 C.48,.54,.46,.55,.43,.56 C.4,.57,.39,.59,.39,.6 C.39,.63,.41,.64,.46,.66 L.46,.82 L.57,.82",type:0}},"\uE0A3":{type:5,data:{d:"M.7,.4 L.7,.47 L.2,.47 L.2,.03 L.7,.03 L.7,.1 L.355,.1 L.355,.4 L.705,.4 M.7,.5 L.86,.5 L.86,.95 L.69,.95 L.44,.66 L.46,.86 L.46,.95 L.3,.95 L.3,.49 L.46,.49 L.71,.78 L.69,.565 L.69,.5",type:0}},"\uE0B0":{type:5,data:{d:"M0,0 L1,.5 L0,1",type:0,rightPadding:2}},"\uE0B1":{type:5,data:{d:"M-1,-.5 L1,.5 L-1,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0B2":{type:5,data:{d:"M1,0 L0,.5 L1,1",type:0,leftPadding:2}},"\uE0B3":{type:5,data:{d:"M2,-.5 L0,.5 L2,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0B4":{type:5,data:{d:"M0,0 L0,1 C0.552,1,1,0.776,1,.5 C1,0.224,0.552,0,0,0",type:0,rightPadding:1}},"\uE0B5":{type:5,data:{d:"M.2,1 C.422,1,.8,.826,.78,.5 C.8,.174,0.422,0,.2,0",type:1,rightPadding:1}},"\uE0B6":{type:5,data:{d:"M1,0 L1,1 C0.448,1,0,0.776,0,.5 C0,0.224,0.448,0,1,0",type:0,leftPadding:1}},"\uE0B7":{type:5,data:{d:"M.8,1 C0.578,1,0.2,.826,.22,.5 C0.2,0.174,0.578,0,0.8,0",type:1,leftPadding:1}},"\uE0B8":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L-.5,1.5",type:0}},"\uE0B9":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0BA":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L1.5,1.5",type:0}},"\uE0BB":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0BC":{type:5,data:{d:"M1.5,-.5 L-.5,1.5 L-.5,-.5",type:0}},"\uE0BD":{type:5,data:{d:"M1.5,-.5 L-.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0BE":{type:5,data:{d:"M-.5,-.5 L1.5,1.5 L1.5,-.5",type:0}},"\uE0BF":{type:5,data:{d:"M-.5,-.5 L1.5,1.5",type:1,leftPadding:1,rightPadding:1}},"\uE0C0":{type:5,data:{d:"M0.8069,0.6075 Q0.7991,0.612,0.7815,0.6218 T0.7542,0.6369 T0.7282,0.6508 T0.7016,0.6644 T0.6778,0.6758 T0.6551,0.6854 T0.637,0.6911 T0.622,0.6936 Q0.6186,0.6936,0.6128,0.6942 T0.6018,0.6952 T0.5894,0.6956 T0.5757,0.6952 T0.561,0.693 T0.5451,0.6879 Q0.5342,0.6834,0.5193,0.6756 T0.4925,0.6614 T0.4673,0.6485 T0.4436,0.6389 T0.4239,0.6363 T0.4089,0.6422 Q0.4045,0.6467,0.3958,0.6554 T0.3843,0.6669 T0.3748,0.6746 T0.3613,0.683 T0.3442,0.6903 L0.3499,0.6956 Q0.3584,0.7042,0.3679,0.7177 T0.3836,0.7403 T0.4019,0.7583 T0.4295,0.7703 Q0.4688,0.7785,0.5203,0.7605 Q0.4902,0.7817,0.449,0.7911 T0.3696,0.8001 Q0.3567,0.7997,0.341,0.7942 T0.3111,0.7813 T0.2805,0.766 T0.2493,0.753 T0.218,0.7472 T0.187,0.754 Q0.1762,0.7589,0.1653,0.7681 T0.1453,0.7895 T0.1308,0.818 T0.1264,0.8507 L0.1264,0.858 Q0.1453,0.8462,0.1607,0.8433 T0.1899,0.8452 T0.2226,0.8625 Q0.2344,0.8707,0.2485,0.8752 T0.2813,0.8831 T0.3089,0.889 Q0.2981,0.8915,0.2846,0.8956 T0.2603,0.9037 T0.2368,0.9115 T0.2129,0.9174 T0.1894,0.9194 T0.1653,0.9155 Q0.1504,0.9115,0.1328,0.9196 T0.0986,0.9421 T0.0655,0.9708 T0.0317,0.9943 T0,1 Q0.001,0.94,0.0017,0.6508 T0.0024,0.2322 Q0.002,0.2109,0.0007,0.1379 T0,0.0249 Q0.0058,0.0253,0.009,0.0257 T0.0156,0.0288 T0.0203,0.0333 T0.0264,0.0422 T0.0349,0.0539 Q0.044,0.0657,0.0542,0.072 T0.0752,0.0789 T0.096,0.0775 T0.1175,0.0694 T0.1379,0.0573 T0.1579,0.0432 Q0.2141,0,0.2673,0.0318 Q0.2588,0.0318,0.2517,0.033 T0.239,0.0361 T0.2276,0.0424 T0.218,0.0504 T0.2085,0.0612 T0.1997,0.0732 T0.1899,0.0875 T0.1795,0.1028 Q0.1748,0.1093,0.1507,0.1234 T0.1186,0.1448 Q0.0999,0.1612,0.1108,0.1783 Q0.1162,0.1877,0.1238,0.1928 T0.1404,0.1979 T0.158,0.1967 T0.1775,0.1895 T0.1963,0.1791 T0.2151,0.1663 T0.2314,0.1534 T0.2458,0.141 T0.2561,0.1322 Q0.2815,0.1106,0.3017,0.101 T0.344,0.0926 T0.3919,0.1077 Q0.4099,0.1175,0.4265,0.1206 T0.4588,0.1202 T0.488,0.1098 T0.5176,0.0914 Q0.5071,0.1032,0.4963,0.1122 T0.4722,0.1285 T0.4497,0.1401 T0.4223,0.1518 T0.3943,0.1636 Q0.374,0.1726,0.3623,0.1863 T0.3482,0.2162 Q0.3445,0.2403,0.3608,0.2605 T0.4072,0.2876 Q0.4194,0.2909,0.4326,0.2899 T0.457,0.2856 T0.4805,0.2764 T0.5032,0.264 T0.5256,0.2497 T0.5478,0.2352 T0.5698,0.2222 T0.5921,0.2118 Q0.6982,0.173,0.81,0.2436 Q0.833,0.2583,0.8496,0.2674 T0.887,0.2846 T0.925,0.294 T0.9617,0.2911 T1,0.2746 Q0.9817,0.2946,0.96,0.3056 T0.9175,0.3191 T0.8731,0.3209 T0.8277,0.3164 T0.7818,0.3109 T0.7359,0.3101 T0.6907,0.3197 T0.647,0.3448 Q0.6443,0.3472,0.6333,0.3562 T0.6194,0.3674 T0.6076,0.3766 T0.594,0.386 T0.5815,0.3931 T0.5661,0.4007 T0.5501,0.4064 L0.5556,0.4121 Q0.5627,0.4198,0.5722,0.4251 T0.5926,0.4337 T0.6131,0.439 T0.6343,0.4431 T0.6521,0.4468 Q0.6762,0.4529,0.7056,0.4463 Q0.6772,0.4623,0.6543,0.471 T0.604,0.4814 Q0.5962,0.4818,0.5815,0.4825 T0.5591,0.4835 T0.5393,0.4857 T0.519,0.4908 T0.5007,0.4996 T0.4812,0.5141 T0.4627,0.5353 L0.4549,0.5451 L0.4661,0.543 Q0.4759,0.541,0.4909,0.55 T0.5315,0.5796 T0.5684,0.6083 Q0.5799,0.6161,0.5915,0.6212 T0.6181,0.6308 L0.6331,0.6353 Q0.6514,0.6418,0.7004,0.633 T0.8069,0.6075 Z",type:0}},"\uE0C1":{type:5,data:{d:"M0.011,0.0469 Q0.0152,0.0412,0.02,0.0361 T0.0292,0.0281 T0.0365,0.0253 Q0.0426,0.0257,0.0461,0.0263 T0.0534,0.03 T0.0582,0.0345 T0.0645,0.0434 T0.0723,0.0546 Q0.0807,0.0653,0.0897,0.0712 T0.1081,0.0775 T0.1255,0.0765 T0.1438,0.0695 T0.1605,0.0593 T0.1772,0.0473 Q0.2388,0,0.2927,0.0326 L0.2614,0.0767 L0.2581,0.0767 Q0.2494,0.0767,0.2444,0.0773 T0.2359,0.0789 T0.2291,0.0842 T0.2233,0.0922 T0.2146,0.1054 T0.2026,0.1236 Q0.1943,0.1354,0.1843,0.1444 T0.1675,0.1574 T0.1526,0.1654 T0.1429,0.1701 Q0.1436,0.1717,0.1446,0.1733 Q0.1504,0.1823,0.1581,0.1866 T0.1733,0.1915 T0.1909,0.1884 T0.2085,0.1809 T0.2265,0.169 T0.2427,0.1564 T0.2575,0.1436 T0.2688,0.1338 Q0.2969,0.1101,0.3195,0.0995 T0.3643,0.0901 T0.4114,0.1048 Q0.4279,0.1138,0.4426,0.1168 T0.4705,0.117 T0.4945,0.1089 T0.5186,0.0942 L0.5211,0.0926 L0.5289,0.0922 Q0.5411,0.095,0.5189,0.1203 Q0.505,0.1358,0.4913,0.1474 T0.4634,0.167 T0.4389,0.1796 T0.4121,0.1909 T0.3866,0.2011 Q0.3782,0.2047,0.3727,0.2092 Q0.3717,0.2117,0.3714,0.2141 Q0.3695,0.2263,0.3751,0.2388 T0.394,0.2616 T0.4253,0.2761 Q0.4398,0.2785,0.4513,0.2779 T0.4756,0.2724 T0.4987,0.2616 T0.5216,0.2476 T0.5453,0.2321 T0.5703,0.217 T0.5976,0.2043 Q0.7015,0.166,0.8099,0.2345 Q0.8361,0.2512,0.8572,0.2616 T0.9006,0.2779 T0.9432,0.281 T0.9819,0.2663 L0.9887,0.2671 Q1,0.272,0.9768,0.2969 Q0.9558,0.3193,0.9319,0.333 T0.8858,0.3513 T0.8391,0.3569 T0.793,0.3546 T0.7485,0.3497 T0.7065,0.3473 T0.6681,0.3522 T0.6344,0.3699 Q0.5963,0.4005,0.5847,0.4082 Q0.595,0.4139,0.6079,0.4174 T0.6367,0.4237 T0.6586,0.4278 Q0.6793,0.4331,0.7044,0.4278 Q0.7057,0.4278,0.707,0.4274 Q0.7067,0.429,0.7062,0.4313 T0.7036,0.4398 T0.6993,0.4513 T0.6931,0.4619 T0.6851,0.4698 Q0.6573,0.4857,0.6336,0.4947 T0.5831,0.5053 Q0.577,0.5057,0.5615,0.5065 T0.5394,0.508 T0.5221,0.51 T0.5042,0.5139 T0.4905,0.5204 Q0.5008,0.5232,0.515,0.5328 T0.549,0.5585 T0.5799,0.5824 Q0.5905,0.5897,0.6013,0.5946 T0.6262,0.6036 T0.6409,0.6081 Q0.6567,0.6134,0.7035,0.605 T0.8028,0.5816 L0.7974,0.5922 T0.7867,0.6134 L0.7812,0.624 Q0.7799,0.6248,0.7786,0.6252 Q0.7709,0.6297,0.7573,0.6372 T0.7346,0.6499 T0.7123,0.6621 T0.6897,0.6741 T0.6686,0.6847 T0.648,0.6941 T0.6297,0.7013 T0.6129,0.7062 T0.5995,0.7076 Q0.5992,0.7076,0.5831,0.7092 T0.5529,0.7092 T0.525,0.7019 Q0.5105,0.6958,0.4824,0.6811 T0.4356,0.6586 T0.4079,0.6533 Q0.3872,0.6741,0.3827,0.6782 Q0.3872,0.6835,0.3934,0.6929 T0.4037,0.7078 T0.4142,0.7198 T0.4284,0.7304 T0.4466,0.7365 Q0.4824,0.7443,0.5292,0.728 L0.5292,0.7294 T0.529,0.7333 T0.5284,0.7392 T0.5266,0.7463 T0.5236,0.7539 T0.5186,0.7612 T0.5111,0.7679 Q0.5086,0.77,0.5056,0.7716 Q0.4466,0.8104,0.3591,0.8091 Q0.344,0.8091,0.3246,0.802 T0.2893,0.7863 T0.2543,0.77 T0.2206,0.76 T0.1894,0.7643 Q0.1804,0.7684,0.1733,0.7753 Q0.1591,0.7892,0.1601,0.8169 Q0.1784,0.8067,0.1938,0.8053 T0.2212,0.8087 T0.2507,0.825 Q0.2614,0.8324,0.2744,0.8365 T0.3053,0.844 T0.332,0.8499 L0.303,0.894 L0.2998,0.8948 Q0.2904,0.8968,0.278,0.9009 T0.2554,0.9086 T0.233,0.9158 T0.2099,0.9213 T0.1868,0.9229 T0.1633,0.9192 Q0.1517,0.916,0.1367,0.9241 T0.1065,0.9462 T0.0753,0.9737 T0.041,0.9955 T0.0061,1 Q0,0.9984,0.0068,0.9845 Q0.009,0.9804,0.0123,0.9755 Q0.0187,0.9666,0.0261,0.9606 T0.0374,0.9555 Q0.0481,0.958,0.0629,0.949 T0.0931,0.9262 T0.1247,0.8987 T0.1597,0.8777 T0.1949,0.8752 Q0.213,0.8805,0.2343,0.8772 Q0.2249,0.8736,0.2172,0.8683 Q0.1914,0.8511,0.1738,0.8497 T0.1349,0.8617 Q0.1304,0.865,0.1273,0.8646 T0.1242,0.8605 L0.1239,0.8536 Q0.1226,0.8295,0.1354,0.8016 T0.1723,0.7496 Q0.1914,0.7308,0.2104,0.7219 Q0.2259,0.7145,0.2425,0.7141 T0.273,0.7182 T0.3022,0.7296 T0.3301,0.7439 T0.3569,0.7571 T0.3821,0.7643 Q0.373,0.7561,0.3598,0.7367 T0.3382,0.7088 L0.3327,0.7035 Q0.3282,0.699,0.3353,0.6884 T0.3517,0.6692 L0.3611,0.6607 Q0.3711,0.657,0.3751,0.6554 T0.3837,0.6507 T0.3898,0.6458 T0.3979,0.637 T0.4111,0.6236 Q0.4172,0.6175,0.4234,0.6138 Q0.4327,0.6081,0.4439,0.6077 T0.4655,0.6105 T0.4884,0.6201 T0.5113,0.633 T0.5347,0.6468 T0.5573,0.6578 Q0.5705,0.6635,0.5833,0.665 T0.6112,0.665 T0.6286,0.6635 Q0.6421,0.6631,0.6718,0.6501 Q0.626,0.6578,0.6089,0.6517 Q0.6063,0.6509,0.6002,0.6491 T0.5884,0.6454 T0.5757,0.6409 T0.561,0.6344 T0.5466,0.6256 Q0.536,0.6183,0.5108,0.5989 T0.4722,0.5712 T0.4527,0.564 L0.4418,0.5661 Q0.4308,0.5681,0.4366,0.5563 Q0.4401,0.5485,0.4476,0.5392 L0.455,0.5298 Q0.4631,0.5188,0.4714,0.51 T0.4866,0.4947 T0.5021,0.4831 T0.516,0.4749 T0.53,0.4694 T0.5428,0.4657 T0.5558,0.4637 T0.5674,0.4629 T0.5795,0.4625 Q0.5489,0.4543,0.534,0.4384 L0.5286,0.4327 Q0.5244,0.4282,0.5318,0.4174 T0.5486,0.398 L0.5579,0.3899 Q0.567,0.387,0.5749,0.3834 T0.5878,0.3772 T0.6012,0.3687 T0.6126,0.3603 T0.6268,0.3487 T0.6421,0.3361 Q0.6567,0.3242,0.6712,0.3159 T0.7009,0.3034 T0.7277,0.2973 T0.7556,0.2961 T0.7809,0.2977 T0.8074,0.301 Q0.8096,0.3014,0.8109,0.3016 T0.8143,0.302 T0.818,0.3026 Q0.8012,0.2936,0.7767,0.2781 Q0.6718,0.2117,0.5744,0.2476 Q0.5637,0.2516,0.5492,0.2604 T0.5218,0.2779 T0.4923,0.2965 T0.461,0.3124 T0.4282,0.3216 T0.394,0.3206 Q0.3637,0.3136,0.3474,0.2936 T0.3353,0.2459 Q0.3385,0.2247,0.355,0.2023 Q0.3646,0.1892,0.3763,0.179 Q0.3898,0.1672,0.4063,0.1595 Q0.3927,0.1562,0.3785,0.1485 Q0.3604,0.1387,0.3453,0.1354 T0.3161,0.1354 T0.2899,0.1458 T0.2627,0.166 Q0.262,0.1664,0.254,0.1733 T0.2414,0.1841 T0.2267,0.196 T0.2094,0.2086 T0.1915,0.2196 T0.1725,0.2288 T0.1546,0.2337 T0.1373,0.2343 T0.1223,0.228 T0.1097,0.2145 Q0.0962,0.1929,0.1258,0.1582 Q0.131,0.1517,0.1371,0.1464 Q0.1462,0.1387,0.156,0.1321 T0.1752,0.1205 T0.1878,0.1134 Q0.1891,0.1117,0.1947,0.103 T0.2035,0.0899 T0.2125,0.0781 T0.2243,0.064 Q0.1949,0.0616,0.1672,0.0828 Q0.153,0.0934,0.1412,0.1009 T0.1146,0.1146 T0.0873,0.1213 T0.0616,0.116 T0.0374,0.0962 Q0.0339,0.0909,0.0295,0.0846 T0.024,0.0767 T0.0202,0.0728 T0.0148,0.0704 T0.0068,0.0697 Q0.0003,0.0693,0.0058,0.0567 Q0.0077,0.0522,0.011,0.0469 Z",type:0}},"\uE0C2":{type:5,data:{d:"M0.1934,0.6075 Q0.2012,0.612,0.2188,0.6218 T0.2459,0.6369 T0.2718,0.6508 T0.2983,0.6644 T0.322,0.6758 T0.3447,0.6854 T0.363,0.6911 T0.3783,0.6936 Q0.3796,0.6936,0.396,0.6952 T0.4265,0.6952 T0.4548,0.6879 Q0.4656,0.6834,0.4805,0.6756 T0.5073,0.6614 T0.5327,0.6485 T0.5564,0.6389 T0.5759,0.6363 T0.5909,0.6422 Q0.5953,0.6467,0.604,0.6554 T0.6155,0.6669 T0.6251,0.6746 T0.6387,0.683 T0.6556,0.6903 L0.6498,0.6956 Q0.6414,0.7042,0.6319,0.7177 T0.6162,0.7403 T0.5979,0.7583 T0.5703,0.7703 Q0.5313,0.7785,0.4799,0.7605 Q0.5097,0.7817,0.5508,0.7911 T0.6302,0.8001 Q0.6431,0.7997,0.659,0.7942 T0.6888,0.7813 T0.7194,0.766 T0.7506,0.753 T0.7819,0.7472 T0.8131,0.754 Q0.8239,0.7589,0.8346,0.7681 T0.8544,0.7895 T0.8689,0.818 T0.8737,0.8507 L0.8733,0.858 Q0.8591,0.849,0.8474,0.845 T0.8242,0.8421 T0.8021,0.8482 T0.7772,0.8625 Q0.7653,0.8707,0.7513,0.8752 T0.7184,0.8831 T0.6908,0.889 Q0.7017,0.8915,0.7152,0.8956 T0.7396,0.9037 T0.7633,0.9115 T0.7872,0.9174 T0.8107,0.9194 T0.8347,0.9155 Q0.8493,0.9115,0.8671,0.9196 T0.9015,0.9421 T0.9345,0.9708 T0.9682,0.9943 T0.9997,1 Q0.999,0.94,0.9983,0.6508 T0.9976,0.2322 Q0.9976,0.2109,0.9992,0.1379 T1,0.0249 Q0.9949,0.0249,0.9917,0.0257 T0.9863,0.0273 T0.9817,0.0308 T0.9776,0.0357 T0.9721,0.0437 T0.9651,0.0539 Q0.956,0.0657,0.9456,0.072 T0.9247,0.0789 T0.904,0.0775 T0.8823,0.0694 T0.862,0.0573 T0.8422,0.0432 Q0.7856,0,0.7328,0.0318 Q0.7392,0.0318,0.7452,0.0324 T0.756,0.0345 T0.7657,0.0386 T0.7741,0.0437 T0.7821,0.0506 T0.7894,0.0588 T0.7966,0.0683 T0.8039,0.0787 T0.8119,0.0904 T0.8202,0.1028 Q0.8249,0.1093,0.849,0.1234 T0.8811,0.1448 Q0.8998,0.1612,0.8893,0.1783 Q0.8835,0.1877,0.8759,0.1928 T0.8593,0.1979 T0.8417,0.1967 T0.8222,0.1895 T0.8034,0.1791 T0.7848,0.1663 T0.7687,0.1534 T0.7543,0.141 T0.744,0.1322 Q0.7186,0.1106,0.6984,0.101 T0.6559,0.0926 T0.6082,0.1077 Q0.5899,0.1175,0.5733,0.1206 T0.5411,0.1202 T0.5122,0.1098 T0.4822,0.0914 Q0.4927,0.1032,0.5036,0.1122 T0.5276,0.1285 T0.5503,0.1401 T0.5777,0.1518 T0.6055,0.1636 Q0.6258,0.1726,0.6375,0.1863 T0.6519,0.2162 Q0.6556,0.2403,0.6392,0.2605 T0.5926,0.2876 Q0.5804,0.2909,0.5672,0.2899 T0.5428,0.2856 T0.5193,0.2764 T0.4966,0.264 T0.4744,0.2497 T0.4523,0.2352 T0.4301,0.2222 T0.4077,0.2118 Q0.3021,0.173,0.1903,0.2436 Q0.1669,0.2583,0.1504,0.2674 T0.1129,0.2846 T0.075,0.294 T0.0384,0.2911 T0,0.2746 Q0.021,0.297,0.0459,0.3082 T0.0953,0.3207 T0.146,0.3193 T0.1988,0.3131 T0.2508,0.3095 T0.3029,0.3176 T0.3529,0.3448 Q0.3566,0.348,0.3652,0.355 T0.3771,0.3645 T0.3877,0.3731 T0.3993,0.3815 T0.4103,0.3884 T0.4226,0.3953 T0.4352,0.4009 T0.4497,0.4064 L0.4443,0.4121 Q0.4372,0.4198,0.4277,0.4251 T0.4072,0.4337 T0.3867,0.439 T0.3656,0.4431 T0.3481,0.4468 Q0.3241,0.4529,0.2943,0.4463 Q0.3227,0.4623,0.3458,0.471 T0.3959,0.4814 Q0.404,0.4818,0.4187,0.4825 T0.4409,0.4835 T0.4605,0.4857 T0.4809,0.4908 T0.4992,0.4996 T0.5186,0.5141 T0.5371,0.5353 L0.5449,0.5451 L0.5337,0.543 Q0.5242,0.541,0.5091,0.55 T0.4683,0.5796 T0.4314,0.6083 Q0.4203,0.6161,0.4086,0.6212 T0.382,0.6308 T0.3667,0.6353 Q0.3485,0.6418,0.2995,0.633 T0.1934,0.6075 Z",type:0}},"\uE0C3":{type:5,data:{d:"M0.989,0.0469 Q0.9829,0.0379,0.9753,0.0316 T0.9635,0.0253 Q0.9574,0.0257,0.9539,0.0263 T0.9466,0.03 T0.9418,0.0345 T0.9355,0.0434 T0.9277,0.0546 Q0.9193,0.0653,0.9103,0.0712 T0.8919,0.0775 T0.8745,0.0765 T0.8564,0.0695 T0.8396,0.0593 T0.8228,0.0473 Q0.7612,0,0.7073,0.0326 L0.7386,0.0767 L0.7419,0.0767 Q0.7506,0.0767,0.7556,0.0773 T0.7641,0.0789 T0.7709,0.0842 T0.7767,0.0922 T0.7854,0.1054 T0.7974,0.1236 Q0.8057,0.1354,0.8157,0.1444 T0.8325,0.1574 T0.8474,0.1654 T0.8571,0.1701 Q0.8564,0.1717,0.8554,0.1733 Q0.8503,0.1815,0.844,0.186 T0.8301,0.1909 T0.8153,0.1903 T0.7993,0.1845 T0.7836,0.1758 T0.768,0.1648 T0.754,0.1535 T0.741,0.1425 T0.7312,0.1338 Q0.7031,0.1101,0.6805,0.0995 T0.6357,0.0901 T0.5886,0.1048 Q0.5721,0.1138,0.5574,0.1168 T0.5295,0.117 T0.5055,0.1089 T0.4814,0.0942 L0.4789,0.0926 L0.4711,0.0922 Q0.4589,0.095,0.4811,0.1203 Q0.495,0.1358,0.5087,0.1474 T0.5366,0.167 T0.5611,0.1796 T0.5879,0.1909 T0.6134,0.2011 Q0.6218,0.2047,0.6273,0.2092 Q0.6283,0.2117,0.6286,0.2141 Q0.6305,0.2263,0.6249,0.2388 T0.606,0.2616 T0.5747,0.2761 Q0.5602,0.2785,0.5487,0.2779 T0.5245,0.2724 T0.5015,0.2616 T0.4784,0.2476 T0.4547,0.2321 T0.4297,0.217 T0.4024,0.2043 Q0.2985,0.166,0.1901,0.2345 Q0.1694,0.248,0.1523,0.2569 T0.1165,0.2726 T0.0818,0.2812 T0.0494,0.2796 T0.0181,0.2663 L0.0116,0.2671 Q0,0.272,0.0232,0.2969 Q0.0468,0.3222,0.0742,0.3365 T0.1278,0.3542 T0.1807,0.3564 T0.233,0.352 T0.2815,0.3473 T0.3269,0.3509 T0.3656,0.3699 Q0.4037,0.4005,0.4153,0.4082 Q0.405,0.4139,0.3921,0.4174 T0.3633,0.4237 T0.3414,0.4278 Q0.3207,0.4331,0.2956,0.4278 Q0.2943,0.4278,0.293,0.4274 Q0.2933,0.429,0.2938,0.4313 T0.2964,0.4398 T0.3007,0.4513 T0.3069,0.4619 T0.3149,0.4698 Q0.3427,0.4857,0.3664,0.4947 T0.4169,0.5053 Q0.423,0.5057,0.4385,0.5065 T0.4606,0.508 T0.4779,0.51 T0.4958,0.5139 T0.5095,0.5204 Q0.4992,0.5232,0.485,0.5328 T0.451,0.5585 T0.4201,0.5824 Q0.4095,0.5897,0.3987,0.5946 T0.3738,0.6036 T0.3591,0.6081 Q0.3433,0.6134,0.2965,0.605 T0.1972,0.5816 L0.2026,0.5922 T0.2133,0.6134 L0.2188,0.624 Q0.2201,0.6248,0.2214,0.6252 Q0.2291,0.6297,0.2486,0.6405 T0.2786,0.657 T0.3066,0.6721 T0.3353,0.6866 T0.3598,0.6972 T0.383,0.7051 T0.4005,0.7076 Q0.4008,0.7076,0.4169,0.7092 T0.4471,0.7092 T0.475,0.7019 Q0.4895,0.6958,0.5176,0.6811 T0.5644,0.6586 T0.5921,0.6533 Q0.6128,0.6741,0.6173,0.6782 Q0.6131,0.6835,0.6068,0.6929 T0.5963,0.7078 T0.5858,0.7198 T0.5716,0.7304 T0.5534,0.7365 Q0.5179,0.7443,0.4708,0.728 L0.4708,0.7294 T0.471,0.7333 T0.4716,0.7392 T0.4734,0.7463 T0.4764,0.7539 T0.4814,0.7612 T0.4889,0.7679 Q0.4914,0.77,0.4944,0.7716 Q0.5534,0.8104,0.6409,0.8091 Q0.6521,0.8091,0.6654,0.8053 T0.6907,0.7959 T0.7157,0.7838 T0.741,0.772 T0.7652,0.7631 T0.7888,0.7594 T0.8106,0.7643 Q0.8196,0.7684,0.8267,0.7753 Q0.8409,0.7892,0.8399,0.8169 Q0.8216,0.8067,0.8062,0.8053 T0.7788,0.8087 T0.7493,0.825 Q0.7386,0.8324,0.7256,0.8365 T0.6947,0.844 T0.668,0.8499 L0.697,0.894 L0.7002,0.8948 Q0.7099,0.8968,0.7222,0.9009 T0.7446,0.9086 T0.767,0.9158 T0.7901,0.9213 T0.8132,0.9229 T0.8367,0.9192 Q0.8483,0.916,0.8633,0.9241 T0.8937,0.9462 T0.9248,0.9737 T0.959,0.9955 T0.9939,1 Q1,0.9984,0.9932,0.9845 Q0.991,0.9804,0.9877,0.9755 Q0.9813,0.9666,0.9739,0.9606 T0.9626,0.9555 Q0.9519,0.958,0.9372,0.949 T0.9071,0.9262 T0.8753,0.8987 T0.8403,0.8777 T0.8051,0.8752 Q0.787,0.8805,0.7657,0.8772 Q0.7751,0.8736,0.7828,0.8683 Q0.8086,0.8511,0.8262,0.8497 T0.8651,0.8617 Q0.8696,0.865,0.8727,0.8646 T0.8758,0.8605 L0.8761,0.8536 Q0.8774,0.8295,0.8646,0.8016 T0.8277,0.7496 Q0.8086,0.7308,0.7896,0.7219 Q0.7741,0.7145,0.7575,0.7141 T0.727,0.7182 T0.6978,0.7296 T0.6699,0.7439 T0.6433,0.7571 T0.6179,0.7643 Q0.627,0.7561,0.6402,0.7367 T0.6618,0.7088 L0.6673,0.7035 Q0.6718,0.699,0.6647,0.6884 T0.6483,0.6692 L0.6389,0.6607 Q0.6289,0.657,0.6249,0.6554 T0.6163,0.6507 T0.6102,0.6458 T0.6021,0.637 T0.5889,0.6236 Q0.5828,0.6175,0.5766,0.6138 Q0.5673,0.6081,0.5561,0.6077 T0.5345,0.6105 T0.5116,0.6201 T0.4887,0.633 T0.4653,0.6468 T0.4427,0.6578 Q0.4295,0.6635,0.4167,0.665 T0.3888,0.665 T0.3714,0.6635 Q0.3579,0.6631,0.3282,0.6501 Q0.374,0.6578,0.3911,0.6517 Q0.3937,0.6509,0.4024,0.6482 T0.4179,0.6434 T0.4348,0.6364 T0.4534,0.6256 Q0.464,0.6183,0.4892,0.5989 T0.5278,0.5712 T0.5476,0.564 L0.5582,0.5661 Q0.5692,0.5681,0.5634,0.5563 Q0.5599,0.5485,0.5524,0.5392 L0.545,0.5298 Q0.5369,0.5188,0.5286,0.51 T0.5134,0.4947 T0.4979,0.4831 T0.484,0.4749 T0.47,0.4694 T0.4572,0.4657 T0.4442,0.4637 T0.4326,0.4629 T0.4205,0.4625 Q0.4511,0.4543,0.466,0.4384 L0.4714,0.4327 Q0.4795,0.4237,0.4469,0.394 L0.4421,0.3899 Q0.433,0.387,0.4251,0.3834 T0.4122,0.3772 T0.3988,0.3687 T0.3874,0.3603 T0.3732,0.3487 T0.3579,0.3361 Q0.3433,0.3242,0.3288,0.3159 T0.2993,0.3034 T0.2725,0.2973 T0.2446,0.2961 T0.2193,0.2977 T0.1926,0.301 Q0.1855,0.3022,0.182,0.3026 Q0.1991,0.2936,0.2233,0.2781 Q0.3282,0.2117,0.4256,0.2476 Q0.4363,0.2516,0.451,0.2604 T0.4784,0.2779 T0.5077,0.2965 T0.539,0.3124 T0.5718,0.3216 T0.606,0.3206 Q0.6363,0.3136,0.6526,0.2936 T0.6647,0.2459 Q0.6615,0.2247,0.645,0.2023 Q0.6354,0.1892,0.6237,0.179 Q0.6102,0.1672,0.5937,0.1595 Q0.6073,0.1562,0.6215,0.1485 Q0.6396,0.1387,0.6547,0.1354 T0.6839,0.1354 T0.7101,0.1458 T0.7373,0.166 Q0.738,0.1664,0.746,0.1733 T0.7586,0.1841 T0.7733,0.196 T0.7907,0.2086 T0.8086,0.2196 T0.8275,0.2288 T0.8454,0.2337 T0.8627,0.2343 T0.8777,0.228 T0.8903,0.2145 Q0.9038,0.1929,0.8742,0.1582 Q0.869,0.1517,0.8629,0.1464 Q0.8538,0.1387,0.844,0.1321 T0.8248,0.1205 T0.8122,0.1134 Q0.8109,0.1117,0.8053,0.103 T0.7965,0.0899 T0.7875,0.0781 T0.7757,0.064 Q0.8051,0.0616,0.8328,0.0828 Q0.847,0.0934,0.8588,0.1009 T0.8854,0.1146 T0.9127,0.1213 T0.9384,0.116 T0.9626,0.0962 Q0.9664,0.0909,0.9706,0.0846 T0.976,0.0767 T0.9798,0.0728 T0.9852,0.0704 T0.9932,0.0697 Q0.9997,0.0693,0.9942,0.0567 Q0.9923,0.0522,0.989,0.0469 Z",type:0}},"\uE0C4":{type:5,data:{d:"M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.4116,0.0126 L0.4116,0.0776 L0.4871,0.0776 L0.4871,0.0126 L0.4116,0.0126 Z M0.4043,0 L0.4944,0 Q0.4973,0,0.4995,0.0021 T0.5017,0.0063 L0.5017,0.0839 Q0.5017,0.0864,0.4993,0.0883 T0.4944,0.0902 L0.4043,0.0902 Q0.4014,0.0902,0.3992,0.0881 T0.397,0.0839 L0.397,0.0063 Q0.397,0.0038,0.3994,0.0019 T0.4043,0 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.9099,0.0084 L0.9099,0.0818 L0.9951,0.0818 L0.9951,0.0084 L0.9099,0.0084 Z M0.9075,0.0042 L0.9976,0.0042 Q1,0.0042,1,0.0063 L1,0.0839 Q1,0.086,0.9976,0.086 L0.9075,0.086 Q0.905,0.086,0.905,0.0839 L0.905,0.0063 Q0.905,0.0042,0.9075,0.0042 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.66,0.0063 L0.7501,0.0063 L0.7501,0.0839 L0.66,0.0839 L0.66,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.5309,0.0063 L0.621,0.0063 L0.621,0.0839 L0.5309,0.0839 L0.5309,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.2689,0.0063 L0.359,0.0063 L0.359,0.0839 L0.2689,0.0839 L0.2689,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0.1374,0.0063 L0.2275,0.0063 L0.2275,0.0839 L0.1374,0.0839 L0.1374,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0,0.0063 L0.0901,0.0063 L0.0901,0.0839 L0,0.0839 L0,0.0063 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.4087,0.9224 L0.4087,0.9958 L0.4939,0.9958 L0.4939,0.9224 L0.4087,0.9224 Z M0.4062,0.9182 L0.4963,0.9182 Q0.4988,0.9182,0.4988,0.9203 L0.4988,0.9979 Q0.4988,1,0.4963,1 L0.4062,1 Q0.4038,1,0.4038,0.9979 L0.4038,0.9203 Q0.4038,0.9182,0.4062,0.9182 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0.1374,0.9203 L0.2275,0.9203 L0.2275,0.9979 L0.1374,0.9979 L0.1374,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0,0.9203 L0.0901,0.9203 L0.0901,0.9979 L0,0.9979 L0,0.9203 Z M0.9099,0.1158 L0.9099,0.1888 L0.9951,0.1888 L0.9951,0.1158 L0.9099,0.1158 Z M0.9075,0.1116 L0.9976,0.1116 Q1,0.1116,1,0.1137 L1,0.1909 Q1,0.193,0.9976,0.193 L0.9075,0.193 Q0.905,0.193,0.905,0.1909 L0.905,0.1137 Q0.905,0.1116,0.9075,0.1116 Z M0.7852,0.6086 L0.7852,0.682 L0.8704,0.682 L0.8704,0.6086 L0.7852,0.6086 Z M0.7828,0.6044 L0.8729,0.6044 Q0.8753,0.6044,0.8753,0.6065 L0.8753,0.6841 Q0.8753,0.6862,0.8729,0.6862 L0.7828,0.6862 Q0.7803,0.6862,0.7803,0.6841 L0.7803,0.6065 Q0.7803,0.6044,0.7828,0.6044 Z M0.66,0.1137 L0.7501,0.1137 L0.7501,0.1909 L0.66,0.1909 L0.66,0.1137 Z M0.6624,0.4102 L0.6624,0.4836 L0.7477,0.4836 L0.7477,0.4102 L0.6624,0.4102 Z M0.66,0.406 L0.7501,0.406 Q0.7526,0.406,0.7526,0.4081 L0.7526,0.4857 Q0.7526,0.4878,0.7501,0.4878 L0.66,0.4878 Q0.6576,0.4878,0.6576,0.4857 L0.6576,0.4081 Q0.6576,0.406,0.66,0.406 Z M0.6624,0.7131 L0.6624,0.7865 L0.7477,0.7865 L0.7477,0.7131 L0.6624,0.7131 Z M0.66,0.7089 L0.7501,0.7089 Q0.7526,0.7089,0.7526,0.711 L0.7526,0.7886 Q0.7526,0.7907,0.7501,0.7907 L0.66,0.7907 Q0.6576,0.7907,0.6576,0.7886 L0.6576,0.711 Q0.6576,0.7089,0.66,0.7089 Z M0.5407,0.2227 L0.5407,0.2836 L0.6113,0.2836 L0.6113,0.2227 L0.5407,0.2227 Z M0.5309,0.206 L0.621,0.206 Q0.623,0.206,0.6249,0.2068 T0.6281,0.2089 T0.6301,0.2116 T0.6308,0.2143 L0.6308,0.2919 Q0.6308,0.2957,0.6276,0.298 T0.621,0.3003 L0.5309,0.3003 Q0.5265,0.3003,0.5239,0.2976 T0.5212,0.2919 L0.5212,0.2143 Q0.5212,0.211,0.5244,0.2085 T0.5309,0.206 Z M0.5407,0.3184 L0.5407,0.3792 L0.6113,0.3792 L0.6113,0.3184 L0.5407,0.3184 Z M0.5309,0.3016 L0.621,0.3016 Q0.6254,0.3016,0.6281,0.3043 T0.6308,0.31 L0.6308,0.3876 Q0.6308,0.3914,0.6276,0.3937 T0.621,0.396 L0.5309,0.396 Q0.5265,0.396,0.5239,0.3932 T0.5212,0.3876 L0.5212,0.31 Q0.5212,0.3062,0.5244,0.3039 T0.5309,0.3016 Z M0.5309,0.4081 L0.621,0.4081 L0.621,0.4857 L0.5309,0.4857 L0.5309,0.4081 Z M0.5309,0.5059 L0.621,0.5059 L0.621,0.5835 L0.5309,0.5835 L0.5309,0.5059 Z M0.5407,0.6149 L0.5407,0.6758 L0.6113,0.6758 L0.6113,0.6149 L0.5407,0.6149 Z M0.5309,0.5982 L0.621,0.5982 Q0.6254,0.5982,0.6281,0.6009 T0.6308,0.6065 L0.6308,0.6841 Q0.6308,0.6879,0.6276,0.6902 T0.621,0.6925 L0.5309,0.6925 Q0.5265,0.6925,0.5239,0.6898 T0.5212,0.6841 L0.5212,0.6065 Q0.5212,0.6028,0.5244,0.6005 T0.5309,0.5982 Z M0.4062,0.1137 L0.4963,0.1137 L0.4963,0.1909 L0.4062,0.1909 L0.4062,0.1137 Z M0.4062,0.2143 L0.4963,0.2143 L0.4963,0.2919 L0.4062,0.2919 L0.4062,0.2143 Z M0.4184,0.4186 L0.4184,0.4753 L0.4842,0.4753 L0.4842,0.4186 L0.4184,0.4186 Z M0.4062,0.3977 L0.4963,0.3977 Q0.5017,0.3977,0.5051,0.401 T0.5085,0.4081 L0.5085,0.4857 Q0.5085,0.4904,0.5046,0.4933 T0.4963,0.4962 L0.4062,0.4962 Q0.4009,0.4962,0.3975,0.4929 T0.3941,0.4857 L0.3941,0.4081 Q0.3941,0.4035,0.398,0.4006 T0.4062,0.3977 Z M0.4062,0.5059 L0.4963,0.5059 L0.4963,0.5835 L0.4062,0.5835 L0.4062,0.5059 Z M0.4087,0.7131 L0.4087,0.7865 L0.4939,0.7865 L0.4939,0.7131 L0.4087,0.7131 Z M0.4062,0.7089 L0.4963,0.7089 Q0.4988,0.7089,0.4988,0.711 L0.4988,0.7886 Q0.4988,0.7907,0.4963,0.7907 L0.4062,0.7907 Q0.4038,0.7907,0.4038,0.7886 L0.4038,0.711 Q0.4038,0.7089,0.4062,0.7089 Z M0.2689,0.1137 L0.359,0.1137 L0.359,0.1909 L0.2689,0.1909 L0.2689,0.1137 Z M0.2689,0.2143 L0.359,0.2143 L0.359,0.2919 L0.2689,0.2919 L0.2689,0.2143 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.31 L0.359,0.31 L0.359,0.3876 L0.2689,0.3876 L0.2689,0.31 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.2689,0.4081 L0.359,0.4081 L0.359,0.4857 L0.2689,0.4857 L0.2689,0.4081 Z M0.2689,0.5059 L0.359,0.5059 L0.359,0.5835 L0.2689,0.5835 L0.2689,0.5059 Z M0.2689,0.711 L0.359,0.711 L0.359,0.7886 L0.2689,0.7886 L0.2689,0.711 Z M0.2689,0.8154 L0.359,0.8154 L0.359,0.8926 L0.2689,0.8926 L0.2689,0.8154 Z M0.1374,0.1137 L0.2275,0.1137 L0.2275,0.1909 L0.1374,0.1909 L0.1374,0.1137 Z M0.1374,0.2143 L0.2275,0.2143 L0.2275,0.2919 L0.1374,0.2919 L0.1374,0.2143 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.31 L0.2275,0.31 L0.2275,0.3876 L0.1374,0.3876 L0.1374,0.31 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0.1374,0.4081 L0.2275,0.4081 L0.2275,0.4857 L0.1374,0.4857 L0.1374,0.4081 Z M0.1374,0.5059 L0.2275,0.5059 L0.2275,0.5835 L0.1374,0.5835 L0.1374,0.5059 Z M0.1374,0.6065 L0.2275,0.6065 L0.2275,0.6841 L0.1374,0.6841 L0.1374,0.6065 Z M0.1374,0.711 L0.2275,0.711 L0.2275,0.7886 L0.1374,0.7886 L0.1374,0.711 Z M0.1374,0.8154 L0.2275,0.8154 L0.2275,0.8926 L0.1374,0.8926 L0.1374,0.8154 Z M0,0.1137 L0.0901,0.1137 L0.0901,0.1909 L0,0.1909 L0,0.1137 Z M0,0.2143 L0.0901,0.2143 L0.0901,0.2919 L0,0.2919 L0,0.2143 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.31 L0.0901,0.31 L0.0901,0.3876 L0,0.3876 L0,0.31 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z M0,0.4081 L0.0901,0.4081 L0.0901,0.4857 L0,0.4857 L0,0.4081 Z M0,0.5059 L0.0901,0.5059 L0.0901,0.5835 L0,0.5835 L0,0.5059 Z M0,0.6065 L0.0901,0.6065 L0.0901,0.6841 L0,0.6841 L0,0.6065 Z M0,0.711 L0.0901,0.711 L0.0901,0.7886 L0,0.7886 L0,0.711 Z M0,0.8154 L0.0901,0.8154 L0.0901,0.8926 L0,0.8926 L0,0.8154 Z",type:0}},"\uE0C5":{type:5,data:{d:"M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.5884,0.0126 L0.5884,0.0776 L0.5129,0.0776 L0.5129,0.0126 L0.5884,0.0126 Z M0.5957,0 L0.5056,0 Q0.5027,0,0.5005,0.0021 T0.4983,0.0063 L0.4983,0.0839 Q0.4983,0.0864,0.5007,0.0883 T0.5056,0.0902 L0.5957,0.0902 Q0.5986,0.0902,0.6008,0.0881 T0.603,0.0839 L0.603,0.0063 Q0.603,0.0038,0.6006,0.0019 T0.5957,0 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.0901,0.0084 L0.0901,0.0818 L0.0049,0.0818 L0.0049,0.0084 L0.0901,0.0084 Z M0.0925,0.0042 L0.0024,0.0042 Q0,0.0042,0,0.0063 L0,0.0839 Q0,0.086,0.0024,0.086 L0.0925,0.086 Q0.095,0.086,0.095,0.0839 L0.095,0.0063 Q0.095,0.0042,0.0925,0.0042 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.34,0.0063 L0.2499,0.0063 L0.2499,0.0839 L0.34,0.0839 L0.34,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.4691,0.0063 L0.379,0.0063 L0.379,0.0839 L0.4691,0.0839 L0.4691,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.7311,0.0063 L0.641,0.0063 L0.641,0.0839 L0.7311,0.0839 L0.7311,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M0.8626,0.0063 L0.7725,0.0063 L0.7725,0.0839 L0.8626,0.0839 L0.8626,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M1,0.0063 L0.9099,0.0063 L0.9099,0.0839 L1,0.0839 L1,0.0063 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.5913,0.9224 L0.5913,0.9958 L0.5061,0.9958 L0.5061,0.9224 L0.5913,0.9224 Z M0.5938,0.9182 L0.5037,0.9182 Q0.5012,0.9182,0.5012,0.9203 L0.5012,0.9979 Q0.5012,1,0.5037,1 L0.5938,1 Q0.5962,1,0.5962,0.9979 L0.5962,0.9203 Q0.5962,0.9182,0.5938,0.9182 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M0.8626,0.9203 L0.7725,0.9203 L0.7725,0.9979 L0.8626,0.9979 L0.8626,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M1,0.9203 L0.9099,0.9203 L0.9099,0.9979 L1,0.9979 L1,0.9203 Z M0.0901,0.1158 L0.0901,0.1888 L0.0049,0.1888 L0.0049,0.1158 L0.0901,0.1158 Z M0.0925,0.1116 L0.0024,0.1116 Q0,0.1116,0,0.1137 L0,0.1909 Q0,0.193,0.0024,0.193 L0.0925,0.193 Q0.095,0.193,0.095,0.1909 L0.095,0.1137 Q0.095,0.1116,0.0925,0.1116 Z M0.2148,0.6086 L0.2148,0.682 L0.1296,0.682 L0.1296,0.6086 L0.2148,0.6086 Z M0.2172,0.6044 L0.1271,0.6044 Q0.1247,0.6044,0.1247,0.6065 L0.1247,0.6841 Q0.1247,0.6862,0.1271,0.6862 L0.2172,0.6862 Q0.2197,0.6862,0.2197,0.6841 L0.2197,0.6065 Q0.2197,0.6044,0.2172,0.6044 Z M0.34,0.1137 L0.2499,0.1137 L0.2499,0.1909 L0.34,0.1909 L0.34,0.1137 Z M0.3376,0.4102 L0.3376,0.4836 L0.2523,0.4836 L0.2523,0.4102 L0.3376,0.4102 Z M0.34,0.406 L0.2499,0.406 Q0.2474,0.406,0.2474,0.4081 L0.2474,0.4857 Q0.2474,0.4878,0.2499,0.4878 L0.34,0.4878 Q0.3424,0.4878,0.3424,0.4857 L0.3424,0.4081 Q0.3424,0.406,0.34,0.406 Z M0.3376,0.7131 L0.3376,0.7865 L0.2523,0.7865 L0.2523,0.7131 L0.3376,0.7131 Z M0.34,0.7089 L0.2499,0.7089 Q0.2474,0.7089,0.2474,0.711 L0.2474,0.7886 Q0.2474,0.7907,0.2499,0.7907 L0.34,0.7907 Q0.3424,0.7907,0.3424,0.7886 L0.3424,0.711 Q0.3424,0.7089,0.34,0.7089 Z M0.4593,0.2227 L0.4593,0.2836 L0.3887,0.2836 L0.3887,0.2227 L0.4593,0.2227 Z M0.4691,0.206 L0.379,0.206 Q0.3746,0.206,0.3719,0.2087 T0.3692,0.2143 L0.3692,0.2919 Q0.3692,0.2957,0.3724,0.298 T0.379,0.3003 L0.4691,0.3003 Q0.4735,0.3003,0.4761,0.2976 T0.4788,0.2919 L0.4788,0.2143 Q0.4788,0.211,0.4756,0.2085 T0.4691,0.206 Z M0.4593,0.3184 L0.4593,0.3792 L0.3887,0.3792 L0.3887,0.3184 L0.4593,0.3184 Z M0.4691,0.3016 L0.379,0.3016 Q0.3746,0.3016,0.3719,0.3043 T0.3692,0.31 L0.3692,0.3876 Q0.3692,0.3914,0.3724,0.3937 T0.379,0.396 L0.4691,0.396 Q0.4735,0.396,0.4761,0.3932 T0.4788,0.3876 L0.4788,0.31 Q0.4788,0.3062,0.4756,0.3039 T0.4691,0.3016 Z M0.4691,0.4081 L0.379,0.4081 L0.379,0.4857 L0.4691,0.4857 L0.4691,0.4081 Z M0.4691,0.5059 L0.379,0.5059 L0.379,0.5835 L0.4691,0.5835 L0.4691,0.5059 Z M0.4593,0.6149 L0.4593,0.6758 L0.3887,0.6758 L0.3887,0.6149 L0.4593,0.6149 Z M0.4691,0.5982 L0.379,0.5982 Q0.3746,0.5982,0.3719,0.6009 T0.3692,0.6065 L0.3692,0.6841 Q0.3692,0.6879,0.3724,0.6902 T0.379,0.6925 L0.4691,0.6925 Q0.4735,0.6925,0.4761,0.6898 T0.4788,0.6841 L0.4788,0.6065 Q0.4788,0.6028,0.4756,0.6005 T0.4691,0.5982 Z M0.5938,0.1137 L0.5037,0.1137 L0.5037,0.1909 L0.5938,0.1909 L0.5938,0.1137 Z M0.5938,0.2143 L0.5037,0.2143 L0.5037,0.2919 L0.5938,0.2919 L0.5938,0.2143 Z M0.5816,0.4186 L0.5816,0.4753 L0.5158,0.4753 L0.5158,0.4186 L0.5816,0.4186 Z M0.5938,0.3977 L0.5037,0.3977 Q0.4983,0.3977,0.4949,0.401 T0.4915,0.4081 L0.4915,0.4857 Q0.4915,0.4904,0.4954,0.4933 T0.5037,0.4962 L0.5938,0.4962 Q0.5991,0.4962,0.6025,0.4929 T0.6059,0.4857 L0.6059,0.4081 Q0.6059,0.4035,0.602,0.4006 T0.5938,0.3977 Z M0.5938,0.5059 L0.5037,0.5059 L0.5037,0.5835 L0.5938,0.5835 L0.5938,0.5059 Z M0.5913,0.7131 L0.5913,0.7865 L0.5061,0.7865 L0.5061,0.7131 L0.5913,0.7131 Z M0.5938,0.7089 L0.5037,0.7089 Q0.5012,0.7089,0.5012,0.711 L0.5012,0.7886 Q0.5012,0.7907,0.5037,0.7907 L0.5938,0.7907 Q0.5962,0.7907,0.5962,0.7886 L0.5962,0.711 Q0.5962,0.7089,0.5938,0.7089 Z M0.7311,0.1137 L0.641,0.1137 L0.641,0.1909 L0.7311,0.1909 L0.7311,0.1137 Z M0.7311,0.2143 L0.641,0.2143 L0.641,0.2919 L0.7311,0.2919 L0.7311,0.2143 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.31 L0.641,0.31 L0.641,0.3876 L0.7311,0.3876 L0.7311,0.31 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.7311,0.4081 L0.641,0.4081 L0.641,0.4857 L0.7311,0.4857 L0.7311,0.4081 Z M0.7311,0.5059 L0.641,0.5059 L0.641,0.5835 L0.7311,0.5835 L0.7311,0.5059 Z M0.7311,0.711 L0.641,0.711 L0.641,0.7886 L0.7311,0.7886 L0.7311,0.711 Z M0.7311,0.8154 L0.641,0.8154 L0.641,0.8926 L0.7311,0.8926 L0.7311,0.8154 Z M0.8626,0.1137 L0.7725,0.1137 L0.7725,0.1909 L0.8626,0.1909 L0.8626,0.1137 Z M0.8626,0.2143 L0.7725,0.2143 L0.7725,0.2919 L0.8626,0.2919 L0.8626,0.2143 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.31 L0.7725,0.31 L0.7725,0.3876 L0.8626,0.3876 L0.8626,0.31 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M0.8626,0.4081 L0.7725,0.4081 L0.7725,0.4857 L0.8626,0.4857 L0.8626,0.4081 Z M0.8626,0.5059 L0.7725,0.5059 L0.7725,0.5835 L0.8626,0.5835 L0.8626,0.5059 Z M0.8626,0.6065 L0.7725,0.6065 L0.7725,0.6841 L0.8626,0.6841 L0.8626,0.6065 Z M0.8626,0.711 L0.7725,0.711 L0.7725,0.7886 L0.8626,0.7886 L0.8626,0.711 Z M0.8626,0.8154 L0.7725,0.8154 L0.7725,0.8926 L0.8626,0.8926 L0.8626,0.8154 Z M1,0.1137 L0.9099,0.1137 L0.9099,0.1909 L1,0.1909 L1,0.1137 Z M1,0.2143 L0.9099,0.2143 L0.9099,0.2919 L1,0.2919 L1,0.2143 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.31 L0.9099,0.31 L0.9099,0.3876 L1,0.3876 L1,0.31 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z M1,0.4081 L0.9099,0.4081 L0.9099,0.4857 L1,0.4857 L1,0.4081 Z M1,0.5059 L0.9099,0.5059 L0.9099,0.5835 L1,0.5835 L1,0.5059 Z M1,0.6065 L0.9099,0.6065 L0.9099,0.6841 L1,0.6841 L1,0.6065 Z M1,0.711 L0.9099,0.711 L0.9099,0.7886 L1,0.7886 L1,0.711 Z M1,0.8154 L0.9099,0.8154 L0.9099,0.8926 L1,0.8926 L1,0.8154 Z",type:0}},"\uE0C6":{type:5,data:{d:"M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.6529,0.018 L0.6529,0.112 L0.7724,0.112 L0.7724,0.018 L0.6529,0.018 Z M0.6411,0 L0.7837,0 Q0.7873,0,0.7902,0.0015 T0.7943,0.005 T0.7956,0.0092 L0.7956,0.1208 Q0.7956,0.125,0.7917,0.1275 T0.7837,0.13 L0.6411,0.13 Q0.6359,0.13,0.6326,0.1271 T0.6292,0.1208 L0.6292,0.0092 Q0.6292,0.005,0.6331,0.0025 T0.6411,0 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.4325,0.0143 L0.4325,0.1158 L0.5628,0.1158 L0.5628,0.0143 L0.4325,0.0143 Z M0.4264,0.0042 L0.5695,0.0042 Q0.5721,0.0042,0.5739,0.0057 T0.5757,0.0092 L0.5757,0.1208 Q0.5757,0.1221,0.5752,0.1231 T0.5736,0.1248 T0.5716,0.1256 T0.5695,0.1258 L0.4264,0.1258 Q0.4238,0.1258,0.422,0.1244 T0.4202,0.1208 L0.4202,0.0092 Q0.4202,0.008,0.4207,0.0069 T0.4222,0.0052 T0.4243,0.0044 T0.4264,0.0042 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0.2178,0.0092 L0.3605,0.0092 L0.3605,0.1208 L0.2178,0.1208 L0.2178,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0,0.0092 L0.1432,0.0092 L0.1432,0.1208 L0,0.1208 L0,0.0092 Z M0.8574,0.3217 L0.8574,0.4098 L0.9691,0.4098 L0.9691,0.3217 L0.8574,0.3217 Z M0.8419,0.2978 L0.9846,0.2978 Q0.9892,0.2978,0.9928,0.2997 T0.9982,0.3043 T1,0.31 L1,0.4216 Q1,0.427,0.9951,0.4304 T0.9846,0.4337 L0.8419,0.4337 Q0.8352,0.4337,0.8308,0.4299 T0.8265,0.4216 L0.8265,0.31 Q0.8265,0.3062,0.829,0.3035 T0.835,0.2993 T0.8419,0.2978 Z M0.8574,0.888 L0.8574,0.9757 L0.9691,0.9757 L0.9691,0.888 L0.8574,0.888 Z M0.8419,0.8637 L0.9846,0.8637 Q0.9892,0.8637,0.9928,0.8658 T0.9982,0.8706 T1,0.8758 L1,0.9878 Q1,0.9929,0.9951,0.9964 T0.9846,1 L0.8419,1 Q0.8352,1,0.8308,0.996 T0.8265,0.9878 L0.8265,0.8758 Q0.8265,0.8708,0.8314,0.8672 T0.8419,0.8637 Z M0.6509,0.169 L0.6509,0.2706 L0.7806,0.2706 L0.7806,0.169 L0.6509,0.169 Z M0.6442,0.159 L0.7868,0.159 Q0.7899,0.159,0.7917,0.1604 T0.7935,0.164 L0.7935,0.2756 Q0.7935,0.2781,0.7915,0.2796 T0.7868,0.281 L0.6442,0.281 Q0.6416,0.281,0.6395,0.2794 T0.6375,0.2756 L0.6375,0.164 Q0.6375,0.1619,0.6398,0.1604 T0.6442,0.159 Z M0.6632,0.6044 L0.6632,0.6858 L0.7678,0.6858 L0.7678,0.6044 L0.6632,0.6044 Z M0.6442,0.5742 L0.7868,0.5742 Q0.7951,0.5742,0.8007,0.5791 T0.8064,0.5893 L0.8064,0.7013 Q0.8064,0.7076,0.8002,0.712 T0.7868,0.7164 L0.6442,0.7164 Q0.6359,0.7164,0.6305,0.7114 T0.6251,0.7013 L0.6251,0.5893 Q0.6251,0.5847,0.6282,0.5812 T0.6357,0.5759 T0.6442,0.5742 Z M0.4264,0.164 L0.5695,0.164 L0.5695,0.2756 L0.4264,0.2756 L0.4264,0.164 Z M0.4325,0.315 L0.4325,0.4165 L0.5628,0.4165 L0.5628,0.315 L0.4325,0.315 Z M0.4264,0.3049 L0.5695,0.3049 Q0.5721,0.3049,0.5739,0.3064 T0.5757,0.31 L0.5757,0.4216 Q0.5757,0.4237,0.5736,0.4251 T0.5695,0.4266 L0.4264,0.4266 Q0.4238,0.4266,0.422,0.4251 T0.4202,0.4216 L0.4202,0.31 Q0.4202,0.3087,0.4207,0.3077 T0.4222,0.306 T0.4243,0.3052 T0.4264,0.3049 Z M0.4264,0.4476 L0.5695,0.4476 L0.5695,0.5596 L0.4264,0.5596 L0.4264,0.4476 Z M0.4392,0.7408 L0.4392,0.8326 L0.5561,0.8326 L0.5561,0.7408 L0.4392,0.7408 Z M0.4264,0.7206 L0.5695,0.7206 Q0.5747,0.7206,0.5783,0.724 T0.5819,0.7307 L0.5819,0.8427 Q0.5819,0.8469,0.5778,0.8498 T0.5695,0.8528 L0.4264,0.8528 Q0.4207,0.8528,0.4171,0.8496 T0.4135,0.8427 L0.4135,0.7307 Q0.4135,0.7265,0.4176,0.7236 T0.4264,0.7206 Z M0.2178,0.164 L0.3605,0.164 L0.3605,0.2756 L0.2178,0.2756 L0.2178,0.164 Z M0.2178,0.31 L0.3605,0.31 L0.3605,0.4216 L0.2178,0.4216 L0.2178,0.31 Z M0.2178,0.5893 L0.3605,0.5893 L0.3605,0.7013 L0.2178,0.7013 L0.2178,0.5893 Z M0.2178,0.7307 L0.3605,0.7307 L0.3605,0.8427 L0.2178,0.8427 L0.2178,0.7307 Z M0.2178,0.8758 L0.3605,0.8758 L0.3605,0.9878 L0.2178,0.9878 L0.2178,0.8758 Z M0,0.164 L0.1432,0.164 L0.1432,0.2756 L0,0.2756 L0,0.164 Z M0,0.31 L0.1432,0.31 L0.1432,0.4216 L0,0.4216 L0,0.31 Z M0,0.4476 L0.1432,0.4476 L0.1432,0.5596 L0,0.5596 L0,0.4476 Z M0,0.5893 L0.1432,0.5893 L0.1432,0.7013 L0,0.7013 L0,0.5893 Z M0,0.7307 L0.1432,0.7307 L0.1432,0.8427 L0,0.8427 L0,0.7307 Z M0,0.8758 L0.1432,0.8758 L0.1432,0.9878 L0,0.9878 L0,0.8758 Z",type:0}},"\uE0C7":{type:5,data:{d:"M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.3476,0.018 L0.3476,0.112 L0.2276,0.112 L0.2276,0.018 L0.3476,0.018 Z M0.3594,0 L0.2163,0 Q0.2132,0,0.2104,0.0015 T0.2062,0.005 T0.2049,0.0092 L0.2049,0.1208 Q0.2049,0.1237,0.2067,0.1258 T0.2111,0.129 T0.2163,0.13 L0.3594,0.13 Q0.3641,0.13,0.3674,0.1271 T0.3708,0.1208 L0.3708,0.0092 Q0.3708,0.005,0.3669,0.0025 T0.3594,0 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.5675,0.0143 L0.5675,0.1158 L0.4377,0.1158 L0.4377,0.0143 L0.5675,0.0143 Z M0.5736,0.0042 L0.431,0.0042 Q0.4284,0.0042,0.4264,0.0057 T0.4243,0.0092 L0.4243,0.1208 Q0.4243,0.1221,0.4251,0.1231 T0.4269,0.1248 T0.4289,0.1256 T0.431,0.1258 L0.5736,0.1258 Q0.5767,0.1258,0.5785,0.1244 T0.5803,0.1208 L0.5803,0.0092 Q0.5803,0.008,0.5798,0.0069 T0.5783,0.0052 T0.5762,0.0044 T0.5736,0.0042 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M0.7827,0.0092 L0.6395,0.0092 L0.6395,0.1208 L0.7827,0.1208 L0.7827,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M1,0.0092 L0.8574,0.0092 L0.8574,0.1208 L1,0.1208 L1,0.0092 Z M0.1432,0.3217 L0.1432,0.4098 L0.0309,0.4098 L0.0309,0.3217 L0.1432,0.3217 Z M0.1586,0.2978 L0.0154,0.2978 Q0.0088,0.2978,0.0044,0.3016 T0,0.31 L0,0.4216 Q0,0.427,0.0049,0.4304 T0.0154,0.4337 L0.1586,0.4337 Q0.1648,0.4337,0.1694,0.4299 T0.174,0.4216 L0.174,0.31 Q0.174,0.3062,0.1715,0.3035 T0.1653,0.2993 T0.1586,0.2978 Z M0.1432,0.888 L0.1432,0.9757 L0.0309,0.9757 L0.0309,0.888 L0.1432,0.888 Z M0.1586,0.8637 L0.0154,0.8637 Q0.0108,0.8637,0.0072,0.8658 T0.0018,0.8706 T0,0.8758 L0,0.9878 Q0,0.9929,0.0049,0.9964 T0.0154,1 L0.1586,1 Q0.1648,1,0.1694,0.996 T0.174,0.9878 L0.174,0.8758 Q0.174,0.8725,0.1715,0.8695 T0.1653,0.8651 T0.1586,0.8637 Z M0.3496,0.169 L0.3496,0.2706 L0.2194,0.2706 L0.2194,0.169 L0.3496,0.169 Z M0.3563,0.159 L0.2132,0.159 Q0.2106,0.159,0.2088,0.1604 T0.207,0.164 L0.207,0.2756 Q0.207,0.2781,0.2091,0.2796 T0.2132,0.281 L0.3563,0.281 Q0.3589,0.281,0.3607,0.2794 T0.3625,0.2756 L0.3625,0.164 Q0.3625,0.1619,0.3605,0.1604 T0.3563,0.159 Z M0.3368,0.6044 L0.3368,0.6858 L0.2327,0.6858 L0.2327,0.6044 L0.3368,0.6044 Z M0.3563,0.5742 L0.2132,0.5742 Q0.2049,0.5742,0.1993,0.5791 T0.1936,0.5893 L0.1936,0.7013 Q0.1936,0.7076,0.2001,0.712 T0.2132,0.7164 L0.3563,0.7164 Q0.3641,0.7164,0.3697,0.7114 T0.3754,0.7013 L0.3754,0.5893 Q0.3754,0.5847,0.3723,0.5812 T0.3648,0.5759 T0.3563,0.5742 Z M0.5736,0.164 L0.431,0.164 L0.431,0.2756 L0.5736,0.2756 L0.5736,0.164 Z M0.5675,0.315 L0.5675,0.4165 L0.4377,0.4165 L0.4377,0.315 L0.5675,0.315 Z M0.5736,0.3049 L0.431,0.3049 Q0.4284,0.3049,0.4264,0.3064 T0.4243,0.31 L0.4243,0.4216 Q0.4243,0.4237,0.4266,0.4251 T0.431,0.4266 L0.5736,0.4266 Q0.5767,0.4266,0.5785,0.4251 T0.5803,0.4216 L0.5803,0.31 Q0.5803,0.3087,0.5798,0.3077 T0.5783,0.306 T0.5762,0.3052 T0.5736,0.3049 Z M0.5736,0.4476 L0.431,0.4476 L0.431,0.5596 L0.5736,0.5596 L0.5736,0.4476 Z M0.5613,0.7408 L0.5613,0.8326 L0.4439,0.8326 L0.4439,0.7408 L0.5613,0.7408 Z M0.5736,0.7206 L0.431,0.7206 Q0.4253,0.7206,0.4217,0.724 T0.4181,0.7307 L0.4181,0.8427 Q0.4181,0.8469,0.4222,0.8498 T0.431,0.8528 L0.5736,0.8528 Q0.5778,0.8528,0.5808,0.8511 T0.5855,0.8471 T0.587,0.8427 L0.587,0.7307 Q0.587,0.7265,0.5826,0.7236 T0.5736,0.7206 Z M0.7827,0.164 L0.6395,0.164 L0.6395,0.2756 L0.7827,0.2756 L0.7827,0.164 Z M0.7827,0.31 L0.6395,0.31 L0.6395,0.4216 L0.7827,0.4216 L0.7827,0.31 Z M0.7827,0.5893 L0.6395,0.5893 L0.6395,0.7013 L0.7827,0.7013 L0.7827,0.5893 Z M0.7827,0.7307 L0.6395,0.7307 L0.6395,0.8427 L0.7827,0.8427 L0.7827,0.7307 Z M0.7827,0.8758 L0.6395,0.8758 L0.6395,0.9878 L0.7827,0.9878 L0.7827,0.8758 Z M1,0.164 L0.8574,0.164 L0.8574,0.2756 L1,0.2756 L1,0.164 Z M1,0.31 L0.8574,0.31 L0.8574,0.4216 L1,0.4216 L1,0.31 Z M1,0.4476 L0.8574,0.4476 L0.8574,0.5596 L1,0.5596 L1,0.4476 Z M1,0.5893 L0.8574,0.5893 L0.8574,0.7013 L1,0.7013 L1,0.5893 Z M1,0.7307 L0.8574,0.7307 L0.8574,0.8427 L1,0.8427 L1,0.7307 Z M1,0.8758 L0.8574,0.8758 L0.8574,0.9878 L1,0.9878 L1,0.8758 Z",type:0}},"\uE0C8":{type:5,data:{d:"M0.0008,0.9979 Q0.0008,1,0.0032,1 Q0.0482,1,0.0602,0.9975 Q0.0667,0.9963,0.0847,0.9917 T0.1084,0.9859 Q0.1124,0.9851,0.1221,0.9851 L0.1253,0.9851 L0.1285,0.9851 Q0.1518,0.9851,0.1655,0.9809 Q0.1695,0.9801,0.1731,0.9788 T0.1791,0.9766 T0.1839,0.9747 T0.1888,0.9732 L0.1936,0.972 T0.1988,0.9712 T0.2048,0.971 L0.2096,0.971 Q0.2201,0.9714,0.2233,0.9714 T0.2345,0.9693 Q0.2386,0.9685,0.2502,0.9674 T0.2715,0.966 L0.2811,0.9656 Q0.2916,0.9647,0.2916,0.9573 Q0.2916,0.954,0.2892,0.9515 T0.2819,0.9486 Q0.2755,0.9482,0.2683,0.9482 Q0.2643,0.9482,0.2582,0.9484 T0.2498,0.9486 Q0.2426,0.9486,0.2402,0.9473 Q0.2386,0.9469,0.2317,0.943 T0.2161,0.937 Q0.2104,0.9357,0.1992,0.933 T0.1831,0.9291 Q0.1807,0.9287,0.1783,0.9285 T0.1739,0.928 T0.1703,0.9276 T0.1675,0.9272 T0.1655,0.9266 T0.1639,0.9253 Q0.1598,0.9216,0.1462,0.9216 L0.143,0.9216 L0.1398,0.9216 L0.1365,0.9216 Q0.1197,0.9195,0.1197,0.9154 L0.1197,0.9154 Q0.1205,0.9121,0.1373,0.9088 T0.1703,0.9054 Q0.1791,0.9054,0.1863,0.904 T0.1984,0.9011 T0.2064,0.8992 Q0.2402,0.8967,0.2506,0.8934 Q0.2538,0.8926,0.2602,0.8899 T0.2707,0.8872 Q0.2715,0.8872,0.2731,0.8876 Q0.2795,0.8884,0.2884,0.8884 Q0.3068,0.8884,0.3092,0.8826 L0.3092,0.8797 Q0.3092,0.8772,0.3076,0.8747 T0.3044,0.8706 T0.3028,0.8681 Q0.3076,0.8656,0.3237,0.8656 Q0.3317,0.8656,0.3622,0.8623 Q0.3655,0.8623,0.3867,0.8617 T0.4217,0.8602 Q0.4241,0.8598,0.4289,0.8598 L0.4345,0.8598 L0.441,0.8598 Q0.4578,0.8598,0.4667,0.8586 Q0.4739,0.8573,0.4851,0.8567 T0.5004,0.8552 Q0.5012,0.8552,0.5108,0.855 T0.5269,0.853 T0.5333,0.8461 Q0.5333,0.8445,0.5325,0.8432 T0.5309,0.8409 T0.5289,0.8391 T0.5261,0.8378 L0.5229,0.837 T0.5185,0.8362 T0.5133,0.8355 T0.5076,0.8349 T0.502,0.8341 Q0.4932,0.8324,0.4859,0.8324 Q0.4827,0.8324,0.4787,0.8328 T0.4731,0.8333 Q0.4707,0.8333,0.4683,0.8324 Q0.4482,0.825,0.4394,0.825 Q0.4369,0.825,0.4345,0.8254 Q0.4225,0.827,0.4153,0.827 Q0.4088,0.827,0.4064,0.8258 Q0.3976,0.8204,0.3751,0.8204 Q0.3703,0.8204,0.3667,0.8214 T0.3622,0.8225 Q0.3598,0.8225,0.3558,0.82 Q0.351,0.8175,0.3402,0.8167 T0.3177,0.8156 T0.3028,0.8146 L0.2956,0.8121 T0.2871,0.8094 T0.2771,0.8073 T0.2635,0.8063 Q0.261,0.8063,0.2586,0.8067 Q0.2378,0.8071,0.2273,0.8071 Q0.2072,0.8071,0.2024,0.8051 Q0.1976,0.8034,0.1932,0.8026 T0.1867,0.8013 T0.1847,0.8001 L0.1847,0.7993 Q0.1855,0.7984,0.1855,0.7978 T0.1859,0.7966 T0.1867,0.7959 T0.188,0.7955 T0.1896,0.7951 T0.1916,0.7949 T0.1944,0.7945 T0.1984,0.7941 T0.2032,0.7939 Q0.212,0.7926,0.2325,0.7918 T0.2562,0.7905 Q0.2691,0.7893,0.2787,0.7847 Q0.2835,0.7827,0.2968,0.7791 T0.3149,0.7756 Q0.3189,0.7756,0.3305,0.7733 T0.3446,0.771 L0.3454,0.771 Q0.3462,0.771,0.3498,0.7721 T0.3574,0.774 T0.3655,0.7748 Q0.3703,0.7748,0.3743,0.7731 T0.3823,0.7708 T0.3916,0.77 T0.3992,0.7694 Q0.4008,0.7694,0.4076,0.7688 T0.4205,0.7675 L0.4305,0.7665 Q0.4345,0.7657,0.4402,0.7617 T0.4458,0.7545 Q0.4458,0.7503,0.4353,0.7487 Q0.4297,0.7478,0.4209,0.7462 T0.4044,0.7433 T0.3904,0.7416 L0.3847,0.7416 Q0.3807,0.7416,0.3747,0.7422 T0.3663,0.7428 T0.3606,0.7424 Q0.3582,0.742,0.3562,0.7418 T0.3522,0.7412 T0.3482,0.7406 T0.3446,0.7401 T0.341,0.7397 T0.3373,0.7393 T0.3341,0.7391 L0.3293,0.7391 Q0.3277,0.7395,0.3253,0.7395 Q0.3205,0.7395,0.3052,0.7387 T0.2835,0.7379 Q0.2755,0.7379,0.253,0.7325 Q0.2506,0.7316,0.2462,0.731 T0.2382,0.7296 T0.2305,0.7271 T0.2181,0.7234 T0.2048,0.7196 T0.2,0.7155 Q0.2,0.7142,0.2016,0.713 Q0.208,0.7059,0.2285,0.6978 T0.2618,0.6898 Q0.2739,0.6898,0.2831,0.6848 T0.2956,0.6794 Q0.3028,0.6786,0.3289,0.6765 T0.3566,0.674 Q0.3582,0.674,0.3855,0.6723 T0.4406,0.6688 T0.4755,0.6653 Q0.5004,0.6607,0.5124,0.6599 L0.5165,0.6599 Q0.5213,0.6599,0.5277,0.6605 T0.5373,0.6611 Q0.543,0.6611,0.5494,0.6599 Q0.592,0.6524,0.6,0.6524 Q0.6064,0.6524,0.61,0.6499 T0.6161,0.6474 Q0.6177,0.6474,0.6261,0.6495 T0.6418,0.6516 L0.6482,0.6516 Q0.653,0.6512,0.6651,0.6506 T0.6876,0.6493 T0.7084,0.6477 T0.7229,0.645 Q0.7269,0.6437,0.7333,0.6437 Q0.7373,0.6437,0.7458,0.6443 T0.7574,0.645 Q0.7614,0.645,0.7631,0.6445 T0.7655,0.6441 Q0.7671,0.6441,0.7723,0.6448 T0.7823,0.6454 Q0.788,0.6454,0.7952,0.6445 Q0.8233,0.6408,0.8723,0.6367 Q0.9012,0.6342,0.9092,0.6342 L0.9165,0.6342 L0.9205,0.6342 Q0.9277,0.6342,0.9382,0.6323 T0.9526,0.6304 Q0.9534,0.6304,0.9594,0.6307 T0.9695,0.6309 Q0.9976,0.6309,0.9992,0.6234 Q1,0.6201,1,0.618 Q1,0.6089,0.9775,0.608 Q0.9703,0.6076,0.9582,0.6076 Q0.9518,0.6076,0.9394,0.6078 T0.9213,0.608 Q0.9036,0.608,0.8972,0.6072 Q0.894,0.6068,0.8871,0.6058 T0.8751,0.6039 T0.8627,0.6024 T0.8506,0.6018 L0.8474,0.6018 Q0.841,0.6022,0.8281,0.6041 T0.8112,0.606 Q0.8096,0.606,0.808,0.6056 Q0.7783,0.6002,0.7647,0.6002 Q0.7598,0.6002,0.7454,0.6006 T0.7261,0.601 Q0.7221,0.601,0.7145,0.6022 T0.7036,0.6035 Q0.6996,0.6035,0.6964,0.6022 Q0.6723,0.5902,0.6442,0.5902 Q0.6426,0.5902,0.6386,0.5904 T0.6337,0.5906 Q0.6273,0.5906,0.6249,0.5894 L0.6177,0.5856 T0.6116,0.5838 T0.6016,0.5825 T0.5855,0.5823 Q0.5719,0.5823,0.5574,0.5798 T0.5373,0.5774 L0.5341,0.5774 Q0.5293,0.5778,0.5213,0.5786 T0.51,0.5794 Q0.5036,0.5794,0.4988,0.5769 Q0.4932,0.574,0.4771,0.574 Q0.4723,0.574,0.4631,0.5745 T0.4498,0.5749 Q0.4418,0.5749,0.4394,0.5736 Q0.4353,0.5724,0.4305,0.5715 T0.4225,0.5707 T0.4145,0.5705 T0.4056,0.5699 Q0.4008,0.5691,0.398,0.5689 T0.394,0.5689 T0.3908,0.5686 T0.3855,0.5674 Q0.3831,0.567,0.3811,0.5662 T0.3779,0.5645 T0.3743,0.563 T0.3695,0.5624 Q0.3655,0.5624,0.3594,0.5635 T0.3494,0.5645 T0.3406,0.5635 T0.3325,0.5624 Q0.3309,0.5624,0.3301,0.5628 L0.3141,0.5628 Q0.2635,0.5628,0.2506,0.5612 Q0.2474,0.5608,0.2434,0.5608 Q0.2402,0.5608,0.2349,0.561 T0.2273,0.5612 Q0.2209,0.5612,0.2177,0.5595 Q0.2145,0.557,0.2145,0.5558 Q0.2169,0.5537,0.2345,0.5521 Q0.2876,0.5475,0.3028,0.5425 Q0.3068,0.5413,0.3149,0.5396 T0.3309,0.5367 T0.3478,0.5338 T0.3606,0.5309 Q0.3631,0.5305,0.3755,0.5259 T0.3968,0.5214 Q0.3992,0.5214,0.4024,0.5218 T0.4096,0.5222 Q0.4161,0.5222,0.4213,0.5209 T0.4313,0.5185 T0.4402,0.5172 Q0.4418,0.5168,0.447,0.5168 L0.4558,0.5168 T0.4639,0.5162 T0.4707,0.5141 T0.4731,0.5102 Q0.4731,0.5089,0.4723,0.5081 Q0.4699,0.5019,0.4627,0.4994 T0.4369,0.4965 Q0.4273,0.4961,0.4193,0.4946 T0.4048,0.4915 T0.3952,0.4894 Q0.392,0.4886,0.388,0.4886 Q0.3847,0.4886,0.3775,0.4892 T0.3647,0.4898 Q0.3598,0.4898,0.355,0.4894 Q0.3165,0.4861,0.3141,0.4853 Q0.2779,0.4774,0.2715,0.4774 Q0.2699,0.4774,0.2683,0.4776 T0.2627,0.4778 Q0.2498,0.4778,0.2281,0.4762 Q0.2241,0.4749,0.2233,0.4737 Q0.2249,0.472,0.2321,0.4708 Q0.2402,0.4695,0.2554,0.4695 L0.2675,0.4695 L0.2795,0.4695 Q0.294,0.4695,0.2996,0.4679 Q0.3141,0.4629,0.3373,0.4616 Q0.3414,0.4612,0.3466,0.4606 T0.3582,0.4589 T0.3687,0.4562 T0.3727,0.4525 Q0.3727,0.4509,0.3703,0.4492 Q0.3639,0.4455,0.3474,0.4419 T0.3213,0.4384 L0.3157,0.4384 L0.31,0.4384 Q0.294,0.4384,0.2859,0.4363 Q0.2795,0.4347,0.2691,0.4347 L0.2618,0.4347 L0.2546,0.4347 Q0.2458,0.4347,0.2394,0.4338 Q0.2257,0.4318,0.2193,0.4303 T0.2092,0.4266 T0.2052,0.4224 T0.2024,0.4154 T0.196,0.4052 Q0.1912,0.3994,0.1867,0.3949 T0.1807,0.3884 T0.1791,0.3849 Q0.1791,0.3824,0.1839,0.3745 Q0.1871,0.3687,0.1944,0.3637 T0.2072,0.3561 T0.2221,0.3501 T0.2321,0.3463 Q0.2353,0.3455,0.241,0.3445 T0.2522,0.3428 T0.2639,0.3411 T0.2731,0.3384 T0.2956,0.3351 T0.3197,0.3326 Q0.3213,0.3322,0.3237,0.3322 T0.3325,0.3331 T0.3414,0.3339 Q0.3478,0.3339,0.3518,0.3314 Q0.3606,0.3264,0.3703,0.3264 Q0.3775,0.3264,0.3847,0.3293 Q0.3888,0.331,0.396,0.331 Q0.4024,0.331,0.4116,0.3295 T0.4265,0.3266 T0.4414,0.3227 T0.4514,0.3202 Q0.4578,0.3181,0.4839,0.3152 T0.5112,0.3123 T0.5177,0.3119 T0.5285,0.3111 T0.5398,0.3096 T0.549,0.3065 T0.5526,0.3015 Q0.5526,0.2999,0.5518,0.2982 Q0.547,0.2903,0.5386,0.2883 T0.5165,0.2862 Q0.5116,0.2862,0.5056,0.2866 T0.4972,0.287 Q0.4884,0.287,0.4787,0.2833 Q0.4594,0.2758,0.4265,0.2758 Q0.4169,0.2758,0.4129,0.2766 Q0.4112,0.2771,0.4104,0.2771 Q0.4088,0.2771,0.4056,0.2748 T0.3968,0.2721 Q0.3695,0.2696,0.359,0.2659 Q0.355,0.2646,0.351,0.2646 T0.3426,0.2661 T0.3365,0.2675 T0.3333,0.2659 Q0.3277,0.2605,0.3116,0.2553 T0.2859,0.2501 L0.2843,0.2501 L0.2819,0.2501 Q0.2779,0.2501,0.2723,0.2493 T0.2586,0.2472 T0.2474,0.2455 Q0.1799,0.236,0.1719,0.236 Q0.1663,0.236,0.1606,0.235 T0.1502,0.2316 T0.1454,0.2265 Q0.1454,0.2223,0.1558,0.2173 Q0.1679,0.2115,0.1859,0.2092 T0.2185,0.207 T0.2353,0.2057 Q0.2369,0.2049,0.2502,0.2041 T0.2799,0.2022 T0.302,0.2007 Q0.3084,0.1999,0.3245,0.1954 T0.347,0.1908 Q0.3502,0.1908,0.3534,0.1916 Q0.3663,0.197,0.388,0.197 Q0.404,0.197,0.4088,0.1929 Q0.4096,0.192,0.4108,0.192 T0.4177,0.1945 T0.4277,0.197 T0.4369,0.1949 Q0.4442,0.1908,0.4843,0.1875 Q0.4892,0.1871,0.4968,0.1839 T0.5084,0.1808 L0.5108,0.1808 Q0.5213,0.1825,0.5454,0.1825 Q0.5823,0.1825,0.5992,0.1779 Q0.6096,0.1746,0.6217,0.1746 Q0.6249,0.1746,0.6309,0.1748 T0.6394,0.175 Q0.6434,0.175,0.6466,0.1746 Q0.6474,0.1746,0.6594,0.1738 T0.6787,0.1713 T0.6892,0.1659 Q0.6924,0.1634,0.6924,0.1593 Q0.6924,0.1547,0.6888,0.151 T0.6795,0.1472 Q0.6779,0.1472,0.6763,0.1477 Q0.6699,0.1493,0.6667,0.1493 Q0.661,0.1493,0.6506,0.1456 Q0.6329,0.1394,0.6129,0.1394 Q0.6048,0.1394,0.5992,0.1377 T0.5888,0.136 T0.5803,0.1377 T0.5751,0.1394 Q0.5711,0.1394,0.5639,0.1369 Q0.5365,0.1273,0.5116,0.1273 Q0.4876,0.1273,0.4667,0.1253 Q0.4627,0.1248,0.4542,0.1211 T0.4337,0.1174 L0.4305,0.1174 Q0.4217,0.1178,0.4153,0.119 T0.408,0.1203 Q0.4056,0.1203,0.4,0.117 Q0.3976,0.1153,0.396,0.1136 T0.3932,0.1112 T0.39,0.1099 T0.3847,0.1095 Q0.3799,0.1095,0.3687,0.1103 Q0.355,0.1112,0.3434,0.1141 T0.3301,0.117 Q0.3261,0.117,0.3229,0.1145 Q0.3181,0.1116,0.3052,0.1087 T0.2787,0.1043 T0.2546,0.1029 Q0.2506,0.1029,0.2474,0.1033 Q0.2418,0.1037,0.2349,0.1054 T0.2249,0.107 Q0.2225,0.107,0.2193,0.1066 Q0.2024,0.1024,0.1863,0.1024 Q0.1823,0.1024,0.1562,0.0971 T0.1269,0.0917 T0.1161,0.0896 T0.106,0.0854 Q0.1076,0.0846,0.11,0.0842 Q0.1173,0.0821,0.1261,0.0821 Q0.1301,0.0821,0.1369,0.0825 T0.1462,0.083 Q0.1494,0.083,0.151,0.0825 T0.1831,0.0813 T0.2201,0.0784 T0.243,0.074 T0.2667,0.0718 Q0.2707,0.0718,0.2755,0.0724 T0.2843,0.073 T0.2936,0.0724 T0.3024,0.0705 T0.3072,0.068 T0.3092,0.0657 T0.3108,0.0647 Q0.3116,0.0643,0.3133,0.0643 L0.3157,0.0643 L0.3181,0.0643 Q0.3446,0.0643,0.3446,0.0556 T0.3205,0.0469 L0.3189,0.0469 Q0.3157,0.0469,0.3157,0.0465 Q0.3084,0.0427,0.2835,0.0386 Q0.2739,0.0369,0.2675,0.0342 T0.2538,0.0299 Q0.249,0.029,0.245,0.029 T0.2378,0.0303 T0.2321,0.0315 Q0.2305,0.0315,0.2273,0.0307 Q0.2201,0.0286,0.2004,0.0272 T0.1775,0.0245 Q0.1735,0.0228,0.1663,0.0226 T0.1522,0.0197 T0.1345,0.0145 T0.1124,0.0079 Q0.0996,0.0033,0.0671,0.0044 T0.0297,0.0041 Q0.0169,0,0.0024,0.0017 Q0,0.0021,0,0.0037 Z M0.0064,0.9954 L0.0056,0.0058 Q0.0177,0.005,0.0281,0.0083 Q0.0345,0.01,0.0675,0.0089 T0.1108,0.012 Q0.1221,0.0162,0.1329,0.0187 T0.1498,0.0236 T0.1606,0.0268 T0.1691,0.0274 T0.1759,0.0286 Q0.1807,0.0303,0.2,0.0315 T0.2257,0.0348 Q0.2305,0.0361,0.2337,0.0361 Q0.2361,0.0361,0.2398,0.0348 T0.2466,0.0336 Q0.249,0.0336,0.2522,0.034 Q0.2586,0.0353,0.2655,0.0382 T0.2827,0.0427 Q0.3068,0.0469,0.3124,0.0502 Q0.3157,0.0523,0.3237,0.0523 L0.3277,0.0523 L0.3309,0.0523 Q0.3398,0.0523,0.3398,0.0556 Q0.3398,0.0581,0.3341,0.0587 T0.3205,0.0593 T0.3092,0.0603 T0.3036,0.0643 T0.2932,0.068 Q0.2884,0.0684,0.2843,0.0684 Q0.2811,0.0684,0.2763,0.0678 T0.2667,0.0672 Q0.2586,0.0672,0.2422,0.0697 T0.2177,0.0747 Q0.2137,0.0759,0.1831,0.0767 T0.1494,0.0784 L0.1474,0.0784 T0.1398,0.078 T0.1285,0.0776 Q0.1173,0.0776,0.1084,0.08 Q0.1004,0.0817,0.1004,0.0846 Q0.1004,0.0867,0.104,0.0888 T0.1124,0.0923 T0.1213,0.0948 T0.1269,0.0958 T0.155,0.1014 T0.1863,0.107 Q0.2016,0.107,0.2185,0.1107 Q0.2217,0.1116,0.2257,0.1116 Q0.2289,0.1116,0.2365,0.1099 T0.2482,0.1074 L0.2538,0.1074 Q0.2683,0.1074,0.2912,0.1107 T0.3197,0.1182 Q0.3245,0.1215,0.3301,0.1215 Q0.3333,0.1215,0.3454,0.1184 T0.3687,0.1145 Q0.3735,0.1141,0.3779,0.1139 T0.3843,0.1134 T0.3871,0.1132 Q0.3896,0.1132,0.39,0.1136 T0.392,0.1161 T0.3968,0.1203 Q0.404,0.1248,0.408,0.1248 Q0.4096,0.1248,0.4165,0.1234 T0.4305,0.1215 L0.4337,0.1215 Q0.4442,0.1215,0.4518,0.1251 T0.4659,0.1294 Q0.4876,0.1319,0.5116,0.1319 T0.5622,0.141 Q0.5703,0.1439,0.5751,0.1439 Q0.5791,0.1439,0.5831,0.1423 T0.5888,0.1406 Q0.592,0.1406,0.5944,0.1412 T0.6012,0.1427 T0.6129,0.1435 Q0.6313,0.1435,0.649,0.1497 Q0.6602,0.1535,0.6667,0.1535 Q0.6715,0.1535,0.6779,0.1522 Q0.6787,0.1518,0.6795,0.1518 Q0.6827,0.1518,0.6847,0.1541 T0.6867,0.1593 Q0.6867,0.1618,0.6851,0.1634 Q0.6835,0.1655,0.6775,0.1667 T0.6598,0.169 T0.6458,0.1705 T0.6402,0.1709 Q0.6378,0.1709,0.6321,0.1705 T0.6225,0.1701 Q0.6096,0.1701,0.5968,0.1738 Q0.5823,0.1779,0.5446,0.1779 Q0.5205,0.1779,0.5116,0.1767 Q0.51,0.1763,0.5084,0.1763 Q0.5028,0.1763,0.4944,0.1796 T0.4835,0.1829 L0.4771,0.1833 T0.4659,0.1844 L0.4546,0.1858 T0.443,0.1881 T0.4337,0.1912 Q0.4321,0.1916,0.4305,0.1916 Q0.4273,0.1916,0.4209,0.1895 T0.412,0.1875 Q0.408,0.1875,0.4056,0.19 Q0.4024,0.1925,0.388,0.1925 Q0.3663,0.1925,0.3558,0.1879 Q0.3518,0.1862,0.3462,0.1862 Q0.3373,0.1862,0.3213,0.191 T0.3012,0.1962 Q0.2964,0.1966,0.2799,0.1976 T0.2494,0.1997 T0.2313,0.2024 L0.2313,0.2024 L0.2293,0.2024 L0.2261,0.2024 L0.2217,0.2024 Q0.204,0.2024,0.1851,0.2047 T0.1526,0.2136 Q0.1406,0.2198,0.1406,0.226 Q0.1406,0.2319,0.1518,0.2362 T0.1719,0.2406 Q0.1791,0.2406,0.2466,0.2497 Q0.2498,0.2501,0.2574,0.2516 T0.2711,0.2538 T0.2819,0.2547 L0.2851,0.2547 Q0.2851,0.2543,0.2859,0.2543 Q0.294,0.2543,0.3096,0.2592 T0.3285,0.2684 Q0.3317,0.2721,0.3373,0.2721 Q0.3406,0.2721,0.3462,0.2708 T0.3542,0.2696 Q0.3558,0.2696,0.3574,0.27 Q0.3679,0.2737,0.3968,0.2762 Q0.3984,0.2766,0.4004,0.2779 L0.4044,0.2804 T0.4096,0.2816 Q0.412,0.2816,0.4145,0.2808 Q0.4177,0.2804,0.4249,0.2804 Q0.4586,0.2804,0.4763,0.287 Q0.4867,0.2912,0.4972,0.2912 Q0.5004,0.2912,0.5064,0.2908 T0.5165,0.2903 Q0.5293,0.2903,0.5361,0.2922 T0.547,0.3003 L0.547,0.3011 Q0.547,0.3036,0.5414,0.3049 T0.5249,0.3067 T0.51,0.3082 Q0.5092,0.3082,0.4831,0.3111 T0.4498,0.3161 Q0.408,0.3264,0.3952,0.3264 Q0.3896,0.3264,0.3863,0.3252 Q0.3783,0.3223,0.3703,0.3223 Q0.359,0.3223,0.3494,0.3277 Q0.347,0.3293,0.343,0.3293 Q0.3414,0.3293,0.3353,0.3285 T0.3253,0.3277 T0.3181,0.3285 Q0.3149,0.3289,0.2952,0.3306 T0.2699,0.3347 Q0.2675,0.3364,0.2598,0.3372 T0.2434,0.3395 T0.2297,0.3426 L0.2205,0.3461 T0.2048,0.3523 T0.1908,0.3606 T0.1791,0.3725 Q0.1743,0.3803,0.1743,0.3845 Q0.1743,0.3874,0.1763,0.3901 T0.1827,0.3976 T0.1912,0.4073 T0.198,0.4189 T0.2032,0.4276 T0.2137,0.4326 T0.2386,0.438 Q0.2458,0.4392,0.2562,0.4392 L0.2639,0.4392 L0.2699,0.4392 Q0.2795,0.4392,0.2843,0.4405 Q0.2932,0.443,0.3092,0.443 L0.3157,0.443 L0.3213,0.443 Q0.3293,0.443,0.3458,0.4463 T0.3671,0.4525 Q0.3598,0.4558,0.3373,0.4571 Q0.3124,0.4587,0.298,0.4637 Q0.294,0.465,0.2811,0.465 L0.2703,0.465 L0.2586,0.465 Q0.241,0.465,0.2305,0.4666 Q0.2185,0.4687,0.2185,0.4728 Q0.2185,0.4745,0.2205,0.4764 T0.2241,0.4791 L0.2265,0.4803 L0.2273,0.4803 Q0.2506,0.4824,0.261,0.4824 Q0.2675,0.4824,0.2699,0.482 Q0.2699,0.4815,0.2707,0.4815 Q0.2771,0.4815,0.3124,0.4898 Q0.3173,0.4907,0.3229,0.4913 T0.3386,0.4925 T0.3542,0.4936 T0.3663,0.494 Q0.3711,0.494,0.3787,0.4936 T0.3888,0.4932 Q0.392,0.4932,0.3944,0.4936 T0.4032,0.4959 T0.4181,0.499 T0.4369,0.5006 Q0.449,0.501,0.455,0.5021 T0.4639,0.5048 T0.4675,0.5093 L0.4675,0.5097 Q0.4675,0.5106,0.4663,0.511 T0.4622,0.5116 L0.4566,0.512 T0.4486,0.5124 T0.4402,0.5127 Q0.4345,0.5131,0.4257,0.5153 T0.4096,0.5176 Q0.4064,0.5176,0.4024,0.5172 L0.3968,0.5172 Q0.3863,0.5172,0.3731,0.522 T0.359,0.5268 Q0.355,0.528,0.3317,0.5321 T0.3004,0.5388 Q0.2867,0.5433,0.2337,0.5479 Q0.2096,0.55,0.2096,0.5562 Q0.2096,0.5591,0.2145,0.5628 Q0.2193,0.5662,0.2289,0.5662 Q0.2313,0.5662,0.2373,0.5657 T0.2458,0.5653 L0.2498,0.5653 Q0.2635,0.5674,0.3124,0.5674 Q0.3261,0.5674,0.3301,0.567 L0.3317,0.567 Q0.3341,0.567,0.3394,0.568 T0.3486,0.5691 Q0.3542,0.5691,0.3606,0.5678 T0.3699,0.5666 T0.3759,0.5686 T0.3839,0.5718 T0.3908,0.573 T0.3964,0.5734 T0.4048,0.5742 T0.4165,0.5751 T0.4277,0.5757 T0.4369,0.5778 Q0.4426,0.5794,0.4538,0.5794 Q0.4586,0.5794,0.4679,0.5792 T0.4811,0.579 Q0.4924,0.579,0.4956,0.5807 Q0.502,0.584,0.5108,0.584 L0.5137,0.584 T0.5173,0.5838 L0.5205,0.5834 L0.5237,0.583 L0.5269,0.5825 T0.5305,0.5821 T0.5341,0.5819 L0.5365,0.5819 Q0.5414,0.5819,0.5562,0.5842 T0.5855,0.5865 Q0.5912,0.5865,0.5948,0.5867 T0.6012,0.5869 T0.6064,0.5873 T0.61,0.5877 T0.6133,0.5886 T0.6157,0.5896 L0.6185,0.591 T0.6217,0.5931 Q0.6265,0.5952,0.6369,0.5952 L0.6418,0.5952 L0.6466,0.5952 Q0.6723,0.5952,0.6932,0.606 Q0.698,0.608,0.7044,0.608 Q0.7084,0.608,0.7161,0.6068 T0.7261,0.6056 Q0.7309,0.6056,0.7454,0.6051 T0.7647,0.6047 Q0.7775,0.6047,0.8072,0.6101 Q0.8096,0.6105,0.812,0.6105 Q0.8177,0.6105,0.8297,0.6085 T0.8474,0.606 L0.8506,0.606 Q0.8562,0.606,0.8647,0.607 T0.8831,0.6095 T0.8964,0.6118 Q0.9036,0.6122,0.9221,0.6122 L0.9406,0.6122 L0.959,0.6122 L0.9767,0.6122 Q0.9952,0.613,0.9952,0.6172 Q0.9952,0.6176,0.9944,0.6221 Q0.9936,0.6259,0.9574,0.6259 L0.955,0.6259 L0.9526,0.6259 Q0.9478,0.6259,0.9373,0.628 T0.9205,0.63 L0.9173,0.63 Q0.9133,0.6296,0.9084,0.6296 Q0.9004,0.6296,0.8715,0.6321 Q0.8233,0.6367,0.7944,0.64 Q0.7888,0.6408,0.7839,0.6408 T0.7739,0.6402 T0.7671,0.6396 Q0.7639,0.6396,0.7622,0.64 Q0.7614,0.6404,0.759,0.6404 Q0.7574,0.6404,0.749,0.6398 T0.7357,0.6392 Q0.7261,0.6392,0.7213,0.6412 Q0.7173,0.6425,0.7032,0.6437 T0.6711,0.6458 T0.6474,0.647 Q0.645,0.6474,0.6418,0.6474 Q0.6353,0.6474,0.6277,0.6454 T0.6161,0.6433 Q0.6104,0.6433,0.6072,0.6456 T0.6,0.6479 Q0.5912,0.6479,0.5486,0.6557 Q0.5422,0.657,0.5373,0.657 Q0.5349,0.657,0.5289,0.6564 T0.5173,0.6557 L0.5124,0.6557 Q0.4996,0.6562,0.4739,0.6611 Q0.4675,0.6624,0.4398,0.6645 T0.3851,0.668 T0.3558,0.6698 Q0.355,0.6698,0.3285,0.6721 T0.2948,0.6752 Q0.2892,0.6761,0.2843,0.6786 T0.2747,0.6831 T0.2618,0.6852 Q0.253,0.6852,0.2394,0.6893 T0.2141,0.6993 T0.1968,0.7105 Q0.1944,0.713,0.1944,0.7155 Q0.1944,0.7196,0.2012,0.7229 T0.2177,0.7285 T0.2281,0.7308 Q0.2321,0.7329,0.2365,0.7339 T0.245,0.7356 T0.2514,0.7366 Q0.2522,0.737,0.2554,0.7379 T0.2614,0.7393 T0.2679,0.7406 T0.2755,0.7416 T0.2835,0.742 Q0.29,0.742,0.3048,0.7428 T0.3253,0.7437 L0.3301,0.7437 L0.3333,0.7437 Q0.3341,0.7437,0.3598,0.7466 Q0.3639,0.7474,0.3671,0.7474 T0.3759,0.7466 T0.3855,0.7457 Q0.388,0.7457,0.3904,0.7462 Q0.3984,0.7466,0.4137,0.7495 T0.4349,0.7532 T0.441,0.7557 Q0.441,0.7599,0.4289,0.7619 Q0.4257,0.7628,0.4197,0.7634 T0.4072,0.7644 T0.3984,0.7652 Q0.3968,0.7652,0.3912,0.7655 T0.3811,0.7665 T0.3719,0.7694 Q0.3695,0.7702,0.3655,0.7702 T0.3546,0.7686 T0.3462,0.7665 L0.3446,0.7665 Q0.3406,0.7665,0.3293,0.769 T0.3149,0.7715 Q0.3084,0.7715,0.2952,0.7748 T0.2763,0.781 Q0.2675,0.7847,0.2554,0.7864 Q0.253,0.7864,0.2325,0.7874 T0.2024,0.7893 Q0.2008,0.7893,0.1984,0.7897 T0.1948,0.7901 T0.1916,0.7903 T0.1888,0.7908 T0.1867,0.7914 T0.1847,0.7922 L0.1831,0.793 T0.1819,0.7943 L0.1811,0.7959 T0.1799,0.7976 Q0.1791,0.7993,0.1791,0.8001 Q0.1791,0.8034,0.1831,0.8051 T0.1932,0.8078 T0.2,0.8092 Q0.2072,0.8117,0.2257,0.8117 Q0.2337,0.8117,0.2586,0.8109 L0.2635,0.8109 Q0.2707,0.8109,0.2767,0.8117 T0.2859,0.8136 T0.2936,0.8163 T0.3012,0.8187 Q0.3068,0.82,0.3277,0.8206 T0.3526,0.8237 Q0.3582,0.8266,0.3622,0.8266 Q0.3647,0.8266,0.3687,0.8258 T0.3751,0.825 Q0.396,0.825,0.404,0.8291 Q0.408,0.8316,0.4161,0.8316 Q0.4217,0.8316,0.4353,0.8295 L0.4394,0.8295 Q0.4466,0.8295,0.4659,0.8366 Q0.4699,0.8378,0.4747,0.8378 Q0.4763,0.8378,0.4807,0.8374 T0.4884,0.837 Q0.494,0.837,0.5004,0.8382 Q0.5052,0.8391,0.5124,0.8399 Q0.5221,0.8411,0.5249,0.8422 T0.5277,0.8461 Q0.5277,0.8482,0.5233,0.849 T0.5112,0.8501 T0.4996,0.8511 Q0.4964,0.8519,0.4851,0.8523 T0.4659,0.8544 Q0.4578,0.8557,0.4402,0.8557 L0.4349,0.8557 L0.4297,0.8557 L0.4209,0.8557 Q0.408,0.8565,0.3867,0.8571 T0.3614,0.8582 Q0.3317,0.8611,0.3237,0.8611 L0.3225,0.8611 L0.3213,0.8611 Q0.2972,0.8611,0.2972,0.8681 Q0.2972,0.8714,0.3008,0.8747 T0.3044,0.8805 Q0.3044,0.881,0.3036,0.8814 Q0.3012,0.8839,0.2851,0.8839 Q0.2779,0.8839,0.2739,0.883 Q0.2723,0.8826,0.2699,0.8826 T0.2643,0.8835 T0.259,0.8853 T0.2542,0.8876 T0.249,0.8893 Q0.2386,0.8922,0.2056,0.8946 Q0.2016,0.8951,0.1916,0.898 T0.1703,0.9009 Q0.1518,0.9009,0.1337,0.9044 T0.1149,0.9146 L0.1149,0.9158 Q0.1149,0.9175,0.1157,0.9187 T0.1173,0.921 T0.1201,0.9226 T0.1233,0.9237 T0.1269,0.9245 L0.1305,0.9251 T0.1337,0.9255 L0.1357,0.9258 Q0.139,0.9262,0.1446,0.9262 T0.1542,0.9266 T0.1598,0.9282 Q0.1614,0.9303,0.1647,0.9314 T0.1739,0.9328 T0.1815,0.9336 Q0.1863,0.9345,0.1976,0.9372 T0.2145,0.9415 Q0.2225,0.9432,0.2285,0.9467 T0.2378,0.9515 Q0.2426,0.9531,0.2514,0.9531 Q0.2538,0.9531,0.2602,0.9529 T0.2707,0.9527 Q0.2763,0.9527,0.2815,0.9531 T0.2867,0.9569 T0.2811,0.9614 Q0.2434,0.9627,0.2329,0.9652 Q0.2249,0.9672,0.2241,0.9672 L0.2096,0.9668 L0.2056,0.9668 Q0.2,0.9668,0.196,0.9672 T0.1884,0.9687 T0.1815,0.9708 T0.1731,0.9737 T0.1639,0.9772 Q0.1518,0.9805,0.1285,0.9805 L0.1253,0.9805 Q0.1124,0.9805,0.1076,0.9818 Q0.1012,0.983,0.0831,0.9876 T0.0594,0.9934 Q0.049,0.9954,0.0064,0.9954 Z M0.0032,0.9979 L0.0024,0.0037 Q0.0161,0.0021,0.0289,0.0062 Q0.0337,0.0075,0.0671,0.0066 T0.1116,0.01 T0.1337,0.0166 T0.151,0.022 Q0.1582,0.0249,0.1659,0.0251 T0.1767,0.0265 Q0.1807,0.0278,0.2,0.0292 T0.2265,0.0328 Q0.2305,0.034,0.2329,0.034 T0.239,0.0326 T0.2458,0.0311 T0.253,0.0319 Q0.2578,0.0332,0.2614,0.0342 T0.2667,0.0363 T0.2723,0.0384 T0.2827,0.0406 Q0.3084,0.0448,0.3141,0.0485 Q0.3149,0.0494,0.3225,0.0494 T0.3361,0.0504 T0.3422,0.0554 T0.3357,0.0606 T0.3205,0.0618 T0.31,0.0626 Q0.3092,0.0626,0.3056,0.0659 T0.2932,0.0701 Q0.2884,0.0709,0.2843,0.0709 Q0.2811,0.0709,0.2759,0.0701 T0.2667,0.0693 Q0.2586,0.0693,0.2422,0.0718 T0.2193,0.0763 Q0.2137,0.0784,0.1831,0.079 T0.1502,0.0805 Q0.1494,0.0809,0.147,0.0809 Q0.1454,0.0809,0.1386,0.0803 T0.1277,0.0796 Q0.1173,0.0796,0.1092,0.0821 Q0.1036,0.0834,0.1036,0.0854 Q0.1036,0.0879,0.1129,0.0908 T0.1269,0.0937 Q0.1293,0.0937,0.1558,0.0991 T0.1863,0.1045 Q0.2016,0.1045,0.2193,0.1087 Q0.2225,0.1091,0.2249,0.1091 Q0.2289,0.1091,0.2357,0.1076 T0.2482,0.1054 Q0.2506,0.1049,0.2546,0.1049 Q0.2699,0.1049,0.2924,0.1085 T0.3213,0.1165 Q0.3253,0.119,0.3301,0.119 Q0.3325,0.119,0.3446,0.1161 T0.3687,0.1124 Q0.3831,0.1112,0.3863,0.1112 T0.3908,0.1118 T0.3936,0.1145 T0.3984,0.1186 Q0.4048,0.1228,0.408,0.1228 Q0.4096,0.1228,0.4161,0.1213 T0.4305,0.1195 L0.4337,0.1195 Q0.4426,0.1195,0.4474,0.1211 T0.4566,0.1246 T0.4667,0.1273 Q0.4876,0.1298,0.5116,0.1298 Q0.5365,0.1298,0.5631,0.1389 Q0.5703,0.1414,0.5751,0.1414 Q0.5783,0.1414,0.5819,0.1398 T0.5888,0.1381 Q0.5928,0.1381,0.5984,0.1398 T0.6129,0.1414 Q0.6321,0.1414,0.6498,0.1477 Q0.661,0.1514,0.6667,0.1514 Q0.6707,0.1514,0.6771,0.1501 Q0.6787,0.1497,0.6795,0.1497 Q0.6835,0.1497,0.6863,0.1526 T0.6892,0.1593 Q0.6892,0.1626,0.6876,0.1647 Q0.6851,0.1672,0.6799,0.1686 T0.6695,0.1705 T0.6566,0.1715 T0.6458,0.1725 Q0.6434,0.173,0.6402,0.173 Q0.6378,0.173,0.6317,0.1727 T0.6225,0.1725 Q0.6096,0.1725,0.5984,0.1759 Q0.5823,0.1804,0.5454,0.1804 Q0.5205,0.1804,0.5116,0.1788 L0.5084,0.1788 Q0.5036,0.1788,0.4956,0.1819 T0.4843,0.185 Q0.4434,0.1887,0.4353,0.1929 Q0.4321,0.1945,0.4289,0.1945 T0.4197,0.1922 T0.4112,0.19 T0.4072,0.1912 Q0.4032,0.1949,0.388,0.1949 Q0.3663,0.1949,0.3542,0.19 Q0.351,0.1883,0.3462,0.1883 Q0.3406,0.1883,0.3321,0.1906 T0.3153,0.1954 T0.302,0.1983 Q0.2972,0.1991,0.2859,0.1997 T0.2643,0.201 T0.245,0.2024 T0.2337,0.2041 Q0.2321,0.2045,0.2181,0.2045 T0.1851,0.207 T0.1542,0.2157 Q0.143,0.2211,0.143,0.226 Q0.143,0.2314,0.153,0.2348 T0.1719,0.2381 Q0.1791,0.2381,0.2474,0.2476 Q0.2506,0.248,0.2558,0.2489 T0.2651,0.2505 T0.2739,0.252 T0.2819,0.2526 Q0.2835,0.2526,0.2851,0.2522 L0.2859,0.2522 Q0.2948,0.2522,0.3104,0.2574 T0.3309,0.2671 Q0.3333,0.2696,0.3365,0.2696 Q0.339,0.2696,0.3442,0.2684 T0.3526,0.2671 T0.3582,0.2679 Q0.3687,0.2717,0.3968,0.2742 Q0.4,0.2746,0.4036,0.2771 T0.4096,0.2796 Q0.4112,0.2796,0.4137,0.2787 Q0.4169,0.2779,0.4257,0.2779 Q0.4594,0.2779,0.4779,0.2849 Q0.4876,0.2891,0.4972,0.2891 Q0.4996,0.2891,0.506,0.2887 T0.5165,0.2883 Q0.5253,0.2883,0.5305,0.2889 T0.541,0.292 T0.5494,0.299 L0.5494,0.3015 Q0.5494,0.3036,0.5466,0.3051 T0.5386,0.3073 T0.5285,0.3086 T0.5181,0.3094 T0.5108,0.3102 Q0.5068,0.3107,0.494,0.3121 L0.4683,0.315 T0.4506,0.3181 Q0.449,0.3181,0.4426,0.32 T0.4313,0.3229 T0.4197,0.3256 T0.4064,0.3281 T0.3952,0.3289 Q0.3888,0.3289,0.3855,0.3273 Q0.3783,0.3243,0.3703,0.3243 Q0.3598,0.3243,0.351,0.3297 Q0.3478,0.3314,0.3422,0.3314 Q0.3398,0.3314,0.3337,0.3306 T0.3245,0.3297 T0.3189,0.3306 Q0.3149,0.3314,0.2956,0.3328 T0.2715,0.3368 Q0.2691,0.338,0.2635,0.3391 T0.2522,0.3407 T0.2406,0.3424 T0.2313,0.3447 Q0.2305,0.3447,0.2213,0.348 T0.206,0.354 T0.1924,0.3621 T0.1815,0.3733 Q0.1767,0.3816,0.1767,0.3849 Q0.1767,0.387,0.1783,0.3893 T0.1847,0.3961 T0.1936,0.4063 T0.2004,0.4181 T0.2052,0.4264 T0.2145,0.4309 T0.2386,0.4359 Q0.2458,0.4372,0.2554,0.4372 Q0.2578,0.4372,0.2627,0.437 T0.2699,0.4367 Q0.2795,0.4367,0.2851,0.4384 Q0.294,0.4409,0.3092,0.4409 Q0.3116,0.4409,0.3157,0.4407 T0.3213,0.4405 Q0.3301,0.4405,0.3466,0.444 T0.3687,0.4509 Q0.3703,0.4517,0.3703,0.4525 Q0.3703,0.4575,0.3373,0.4596 Q0.3133,0.4608,0.2988,0.4658 Q0.294,0.4674,0.2803,0.4674 Q0.2763,0.4674,0.2687,0.4672 T0.257,0.467 Q0.2402,0.467,0.2313,0.4687 Q0.2209,0.4708,0.2209,0.4737 Q0.2209,0.4741,0.2213,0.4749 T0.2229,0.4764 L0.2249,0.4774 T0.2265,0.4778 L0.2273,0.4782 Q0.2498,0.4803,0.2618,0.4803 Q0.2667,0.4803,0.2691,0.4799 Q0.2699,0.4795,0.2715,0.4795 Q0.2779,0.4795,0.3133,0.4873 Q0.3181,0.4886,0.3233,0.4892 T0.3386,0.4905 T0.3542,0.4915 T0.3655,0.4919 Q0.3703,0.4919,0.3779,0.4915 T0.3888,0.4911 T0.3952,0.4915 Q0.3976,0.4919,0.4008,0.4927 L0.4072,0.4944 T0.4149,0.4961 T0.4249,0.4975 T0.4369,0.4985 Q0.449,0.499,0.4554,0.5 T0.4651,0.5031 T0.4699,0.5085 Q0.4707,0.5093,0.4707,0.5097 Q0.4707,0.5114,0.4687,0.5124 T0.4631,0.5139 T0.4562,0.5145 T0.4478,0.5147 L0.4402,0.5147 Q0.4353,0.5151,0.4265,0.5174 T0.4096,0.5197 L0.4024,0.5197 Q0.4,0.5193,0.3968,0.5193 Q0.3896,0.5193,0.3831,0.5209 T0.3703,0.5253 T0.3598,0.5288 Q0.3558,0.5301,0.3321,0.5342 T0.302,0.5409 Q0.2876,0.5454,0.2337,0.55 Q0.2112,0.5521,0.2112,0.5558 Q0.2112,0.5574,0.2161,0.5612 Q0.2201,0.5637,0.2281,0.5637 Q0.2305,0.5637,0.2361,0.5633 T0.2442,0.5628 Q0.2474,0.5628,0.2498,0.5633 Q0.2635,0.5653,0.3133,0.5653 Q0.3261,0.5653,0.3301,0.5649 L0.3325,0.5649 Q0.3349,0.5649,0.3402,0.5657 T0.3494,0.5666 Q0.3542,0.5666,0.3598,0.5657 Q0.3663,0.5645,0.3695,0.5645 Q0.3735,0.5645,0.3775,0.5666 T0.3847,0.5695 Q0.3888,0.5707,0.3912,0.5709 T0.3968,0.5711 T0.4048,0.572 Q0.4096,0.5724,0.4165,0.5726 T0.4281,0.5734 T0.4378,0.5757 Q0.4418,0.5774,0.4522,0.5774 Q0.4562,0.5774,0.4655,0.5769 T0.4795,0.5765 Q0.4932,0.5765,0.4972,0.579 Q0.5028,0.5819,0.51,0.5819 Q0.5141,0.5819,0.5221,0.5809 T0.5341,0.5798 L0.5373,0.5798 Q0.5422,0.5798,0.557,0.5821 T0.5855,0.5844 L0.5936,0.5844 L0.5992,0.5844 T0.604,0.5848 T0.6076,0.5852 T0.6108,0.5859 T0.6137,0.5865 T0.6161,0.5873 T0.6181,0.5881 T0.6209,0.5896 L0.6233,0.591 Q0.6265,0.5927,0.6353,0.5927 L0.6402,0.5927 L0.645,0.5927 Q0.6723,0.5927,0.6948,0.6039 Q0.6988,0.606,0.7036,0.606 Q0.7076,0.606,0.7153,0.6045 T0.7261,0.6031 Q0.7309,0.6031,0.7454,0.6027 T0.7647,0.6022 Q0.7783,0.6022,0.808,0.608 L0.812,0.608 Q0.8169,0.608,0.8293,0.6062 T0.8474,0.6039 L0.8506,0.6039 Q0.857,0.6039,0.8655,0.6049 T0.8835,0.6074 T0.8972,0.6093 Q0.9036,0.6101,0.9213,0.6101 L0.9398,0.6101 L0.959,0.6101 L0.9767,0.6101 Q0.9976,0.6109,0.9976,0.6176 Q0.9976,0.6188,0.9968,0.6226 Q0.9952,0.6284,0.9671,0.6284 L0.959,0.6284 L0.9526,0.6284 Q0.9486,0.6284,0.9382,0.6302 T0.9205,0.6321 L0.9173,0.6321 Q0.9133,0.6317,0.9092,0.6317 Q0.9012,0.6317,0.8715,0.6346 Q0.8233,0.6387,0.7944,0.6421 Q0.7888,0.6429,0.7831,0.6429 Q0.7783,0.6429,0.7731,0.6425 T0.7663,0.6421 L0.7622,0.6421 Q0.7614,0.6425,0.7586,0.6425 T0.7474,0.6421 T0.7349,0.6416 Q0.7261,0.6416,0.7221,0.6429 Q0.7173,0.645,0.7032,0.646 T0.6711,0.6479 T0.6482,0.6491 Q0.645,0.6495,0.6418,0.6495 Q0.6353,0.6495,0.6273,0.6474 T0.6161,0.6454 Q0.612,0.6454,0.6088,0.6477 T0.6,0.6499 Q0.5912,0.6499,0.5494,0.6578 Q0.5422,0.6591,0.5373,0.6591 Q0.5341,0.6591,0.5281,0.6584 T0.5173,0.6578 L0.5124,0.6578 Q0.5004,0.6582,0.4747,0.6632 Q0.4675,0.6649,0.4398,0.6667 T0.3851,0.6703 T0.3566,0.6719 Q0.3534,0.6723,0.3406,0.6734 T0.3141,0.6757 T0.2948,0.6773 Q0.2908,0.6781,0.2819,0.6829 T0.2618,0.6877 Q0.2482,0.6877,0.2273,0.6958 T0.1992,0.7117 Q0.1976,0.7138,0.1976,0.7155 Q0.1976,0.7188,0.2032,0.7213 T0.2181,0.7258 T0.2289,0.7292 Q0.2337,0.7308,0.2378,0.7316 L0.2458,0.7333 T0.2522,0.7345 Q0.2747,0.7399,0.2835,0.7399 Q0.29,0.7399,0.3048,0.7408 T0.3253,0.7416 Q0.3277,0.7416,0.3297,0.7414 T0.3341,0.7412 L0.3598,0.7445 Q0.3639,0.7449,0.3663,0.7449 Q0.3695,0.7449,0.3751,0.7443 T0.3855,0.7437 L0.3904,0.7437 Q0.3984,0.7441,0.4141,0.7472 T0.4353,0.7507 Q0.4434,0.752,0.4434,0.7553 Q0.4434,0.7578,0.439,0.7605 T0.4297,0.764 Q0.4257,0.7648,0.4201,0.7655 T0.4076,0.7665 T0.3984,0.7673 Q0.3968,0.7673,0.3912,0.7677 T0.3815,0.7688 T0.3735,0.771 T0.3655,0.7727 Q0.3606,0.7727,0.3534,0.7708 T0.3458,0.769 L0.3446,0.769 Q0.3414,0.769,0.3297,0.7713 T0.3149,0.7735 Q0.3092,0.7735,0.296,0.7771 T0.2771,0.7831 Q0.2683,0.7872,0.2554,0.7885 Q0.253,0.7889,0.2325,0.7897 T0.2032,0.7914 Q0.2008,0.7918,0.198,0.792 T0.194,0.7924 T0.1912,0.7928 T0.1888,0.793 T0.1867,0.7934 T0.1851,0.7943 T0.1843,0.7953 T0.1835,0.7968 T0.1823,0.7984 T0.1815,0.8001 Q0.1815,0.8022,0.1847,0.8032 T0.1932,0.8053 T0.2008,0.8071 Q0.2072,0.8092,0.2265,0.8092 Q0.2361,0.8092,0.2586,0.8088 L0.2635,0.8088 Q0.2731,0.8088,0.2795,0.8098 T0.2928,0.8134 T0.302,0.8167 Q0.306,0.8179,0.3277,0.8183 T0.3542,0.8221 Q0.359,0.8246,0.3622,0.8246 Q0.3639,0.8246,0.3675,0.8237 T0.3751,0.8229 Q0.3968,0.8229,0.4048,0.8275 Q0.4088,0.8291,0.4161,0.8291 Q0.4225,0.8291,0.4353,0.8275 Q0.4369,0.827,0.4394,0.827 Q0.4474,0.827,0.4675,0.8345 Q0.4707,0.8358,0.4739,0.8358 Q0.4755,0.8358,0.4799,0.8353 T0.4876,0.8349 Q0.494,0.8349,0.5012,0.8362 L0.5076,0.837 T0.5133,0.8376 T0.5181,0.8382 T0.5221,0.8391 L0.5253,0.8399 T0.5277,0.8409 L0.5293,0.8422 T0.5301,0.8438 L0.5301,0.8461 Q0.5301,0.8499,0.5249,0.8511 T0.5112,0.8526 T0.5004,0.8532 Q0.4964,0.854,0.4851,0.8546 T0.4667,0.8565 Q0.4578,0.8577,0.441,0.8577 L0.4345,0.8577 L0.4289,0.8577 L0.4209,0.8577 Q0.4153,0.8582,0.4088,0.8586 T0.3968,0.8592 T0.3855,0.8594 T0.3755,0.8596 T0.3675,0.86 T0.3622,0.8602 Q0.3317,0.8635,0.3237,0.8635 Q0.2996,0.8635,0.2996,0.8681 Q0.2996,0.8698,0.3032,0.8733 T0.3068,0.8797 L0.3068,0.8822 Q0.3052,0.8859,0.2859,0.8859 Q0.2787,0.8859,0.2739,0.8851 L0.2699,0.8851 Q0.2659,0.8851,0.259,0.888 T0.2498,0.8913 Q0.2394,0.8946,0.2056,0.8971 Q0.2032,0.8971,0.1928,0.9002 T0.1703,0.9034 Q0.1526,0.9034,0.1353,0.9067 T0.1173,0.915 L0.1173,0.9158 Q0.1173,0.9166,0.1177,0.9175 T0.1189,0.9191 T0.1205,0.9204 T0.1229,0.9212 T0.1257,0.922 T0.1285,0.9226 T0.1309,0.9231 T0.1337,0.9235 T0.1365,0.9237 L0.1446,0.9237 T0.1554,0.9243 T0.1614,0.9268 T0.1659,0.9293 T0.1743,0.9303 T0.1823,0.9316 Q0.1863,0.932,0.1912,0.9332 T0.2028,0.9361 T0.2153,0.939 Q0.2233,0.9411,0.2297,0.9448 T0.2386,0.9494 Q0.2426,0.9506,0.2506,0.9506 Q0.253,0.9506,0.2594,0.9504 T0.2699,0.9502 Q0.2763,0.9502,0.2819,0.9511 Q0.2851,0.9511,0.2871,0.9529 T0.2892,0.9573 Q0.2892,0.9627,0.2811,0.9635 Q0.2434,0.9652,0.2337,0.9672 Q0.2257,0.9693,0.2241,0.9693 Q0.2217,0.9693,0.2096,0.9689 L0.2056,0.9689 Q0.1976,0.9689,0.1924,0.9699 T0.1787,0.9741 L0.1647,0.9793 Q0.1518,0.983,0.1285,0.983 L0.1261,0.983 L0.1237,0.983 Q0.1124,0.983,0.1076,0.9838 Q0.102,0.9851,0.0839,0.9896 T0.0602,0.9954 T0.0406,0.9971 T0.0153,0.9979 L0.0032,0.9979 Z",type:0}},"\uE0CA":{type:5,data:{d:"M0.9992,0.998 Q0.9992,1,0.9968,1 Q0.9521,1,0.9392,0.998 Q0.9335,0.997,0.9152,0.9921 T0.8913,0.9862 Q0.8873,0.9852,0.8783,0.9852 L0.8747,0.9852 L0.871,0.9852 Q0.8483,0.9852,0.8345,0.9812 Q0.8289,0.9792,0.8228,0.9773 T0.8135,0.9743 T0.8054,0.9723 T0.7948,0.9713 L0.7908,0.9713 L0.777,0.9713 T0.7656,0.9693 Q0.7616,0.9683,0.7498,0.9674 T0.7283,0.9664 L0.7186,0.9654 Q0.708,0.9644,0.708,0.9575 Q0.708,0.9545,0.7109,0.952 T0.7178,0.9486 L0.7315,0.9486 L0.7417,0.9486 L0.7502,0.9486 Q0.7575,0.9486,0.7599,0.9476 Q0.7616,0.9466,0.7685,0.9426 T0.7843,0.9377 Q0.7899,0.9357,0.8009,0.9332 T0.8175,0.9298 Q0.82,0.9288,0.8228,0.9283 T0.8277,0.9278 T0.8313,0.9273 T0.8341,0.9263 T0.8362,0.9258 Q0.8402,0.9219,0.854,0.9219 L0.8569,0.9219 L0.8597,0.9219 L0.8637,0.9219 Q0.88,0.9199,0.88,0.9159 L0.88,0.9149 Q0.88,0.913,0.8719,0.911 T0.852,0.9075 T0.8297,0.906 Q0.8224,0.906,0.8167,0.905 T0.8074,0.9031 T0.8001,0.9006 T0.794,0.8991 Q0.7599,0.8971,0.7494,0.8942 Q0.7461,0.8932,0.7397,0.8902 T0.7299,0.8872 L0.7267,0.8872 Q0.721,0.8882,0.7121,0.8882 Q0.6926,0.8882,0.691,0.8833 L0.691,0.8803 Q0.691,0.8773,0.6922,0.8749 T0.6955,0.8704 L0.6975,0.8684 Q0.6926,0.8655,0.6764,0.8655 Q0.6683,0.8655,0.6375,0.8625 Q0.6358,0.8625,0.629,0.862 T0.6148,0.8615 T0.5973,0.861 T0.5791,0.8605 L0.5718,0.8605 L0.5661,0.8605 L0.5596,0.8605 Q0.5426,0.8605,0.5337,0.8586 Q0.5264,0.8576,0.515,0.8571 T0.4996,0.8556 Q0.498,0.8556,0.4947,0.8551 T0.4882,0.8546 T0.4809,0.8541 T0.474,0.8531 T0.4692,0.8506 T0.4672,0.8467 Q0.4672,0.8437,0.468,0.8422 T0.4704,0.8398 T0.4736,0.8383 T0.4781,0.8368 T0.4838,0.8358 T0.4911,0.8353 T0.4988,0.8338 Q0.5069,0.8328,0.5142,0.8328 Q0.5174,0.8328,0.5215,0.8333 T0.5264,0.8338 Q0.5296,0.8338,0.532,0.8328 Q0.5523,0.8249,0.5604,0.8249 L0.5653,0.8249 Q0.5775,0.8269,0.5848,0.8269 Q0.5912,0.8269,0.5937,0.8259 Q0.6026,0.821,0.6253,0.821 Q0.6294,0.821,0.6334,0.822 T0.6383,0.8229 Q0.6399,0.8229,0.644,0.82 Q0.6504,0.817,0.6723,0.816 T0.6975,0.814 Q0.6999,0.814,0.7048,0.8121 T0.7129,0.8091 T0.7226,0.8071 T0.7372,0.8061 L0.7421,0.8061 Q0.7624,0.8071,0.7721,0.8071 Q0.7924,0.8071,0.7981,0.8051 Q0.8021,0.8032,0.807,0.8027 T0.8135,0.8017 T0.8151,0.8002 L0.8151,0.7992 Q0.8143,0.7962,0.8127,0.7957 T0.8045,0.7943 Q0.7997,0.7943,0.7964,0.7933 Q0.7883,0.7933,0.7676,0.7923 T0.7437,0.7903 Q0.7307,0.7893,0.7218,0.7844 Q0.7194,0.7834,0.7141,0.7819 L0.7036,0.7789 T0.693,0.7765 T0.6853,0.7755 Q0.6805,0.7755,0.6691,0.773 T0.6553,0.7705 Q0.6545,0.7705,0.6545,0.7715 Q0.6537,0.7715,0.65,0.7725 T0.6423,0.774 T0.635,0.7745 Q0.6294,0.7745,0.6257,0.773 T0.618,0.771 T0.6083,0.77 T0.601,0.7695 Q0.5985,0.7695,0.5921,0.769 T0.5795,0.7676 T0.5702,0.7666 Q0.5653,0.7656,0.5596,0.7616 T0.5539,0.7547 Q0.5539,0.7498,0.5645,0.7488 Q0.5693,0.7478,0.5852,0.7448 T0.6099,0.7418 L0.6148,0.7418 Q0.6196,0.7418,0.6253,0.7423 T0.6338,0.7428 L0.6399,0.7428 Q0.6431,0.7418,0.6488,0.7409 T0.6586,0.7394 T0.6659,0.7389 L0.6707,0.7389 Q0.6723,0.7399,0.6748,0.7399 Q0.6796,0.7399,0.6946,0.7389 T0.7161,0.7379 Q0.7251,0.7379,0.7478,0.7319 Q0.7494,0.7319,0.7539,0.7315 T0.762,0.73 T0.7697,0.727 T0.7818,0.723 T0.7948,0.7196 T0.7997,0.7151 Q0.7997,0.7141,0.7989,0.7132 Q0.7924,0.7062,0.7717,0.6978 T0.738,0.6894 Q0.7267,0.6894,0.717,0.6845 T0.7048,0.6795 Q0.6975,0.6785,0.6711,0.6766 T0.6431,0.6746 Q0.6415,0.6736,0.6144,0.6721 T0.5596,0.6686 T0.5247,0.6657 Q0.4996,0.6607,0.4874,0.6597 L0.4834,0.6597 Q0.4785,0.6597,0.4724,0.6607 T0.4631,0.6617 Q0.4574,0.6617,0.4501,0.6597 Q0.4088,0.6518,0.4006,0.6518 Q0.3933,0.6518,0.3901,0.6499 T0.3844,0.6479 T0.3739,0.6499 T0.3585,0.6518 L0.352,0.6518 Q0.3471,0.6508,0.335,0.6503 T0.3122,0.6494 T0.2912,0.6479 T0.2766,0.6449 Q0.2733,0.6439,0.2668,0.6439 Q0.2628,0.6439,0.2543,0.6444 T0.2425,0.6449 T0.2368,0.6439 L0.2344,0.6439 Q0.2336,0.6439,0.2283,0.6444 T0.2182,0.6449 Q0.2117,0.6449,0.2052,0.6439 Q0.1768,0.6409,0.1281,0.637 Q0.0989,0.634,0.0916,0.634 L0.0835,0.634 L0.0795,0.634 Q0.0722,0.634,0.0616,0.632 T0.0479,0.6301 Q0.0462,0.6301,0.0406,0.6306 T0.0308,0.6311 Q0.0032,0.6311,0.0008,0.6231 Q0,0.6202,0,0.6182 Q0,0.6083,0.0227,0.6083 Q0.03,0.6073,0.0422,0.6073 Q0.0487,0.6073,0.0608,0.6078 T0.0787,0.6083 Q0.0973,0.6083,0.103,0.6073 Q0.1062,0.6063,0.1131,0.6053 T0.1253,0.6039 T0.1375,0.6024 T0.1492,0.6014 L0.1533,0.6014 Q0.1598,0.6024,0.1723,0.6044 T0.189,0.6063 Q0.1906,0.6063,0.1922,0.6053 Q0.2214,0.6004,0.236,0.6004 Q0.2409,0.6004,0.2551,0.6009 T0.2741,0.6014 Q0.2782,0.6014,0.2859,0.6024 T0.2968,0.6034 Q0.3009,0.6034,0.3041,0.6024 Q0.3277,0.5905,0.356,0.5905 L0.3613,0.5905 L0.3666,0.5905 Q0.3731,0.5905,0.3755,0.5895 Q0.382,0.5856,0.3844,0.5846 T0.3938,0.5831 T0.4144,0.5826 T0.4428,0.5801 T0.4631,0.5776 L0.4663,0.5776 Q0.4704,0.5776,0.4785,0.5786 T0.4899,0.5796 Q0.4964,0.5796,0.5012,0.5767 Q0.5069,0.5737,0.5223,0.5737 Q0.5272,0.5737,0.5369,0.5742 T0.5499,0.5747 Q0.558,0.5747,0.5612,0.5737 Q0.5661,0.5717,0.5714,0.5712 T0.5835,0.5702 T0.5945,0.5692 T0.6018,0.5687 L0.6062,0.5687 T0.6095,0.5682 T0.6148,0.5678 Q0.6172,0.5668,0.6196,0.5653 T0.6245,0.5633 T0.631,0.5628 T0.6407,0.5638 T0.6504,0.5648 T0.6594,0.5638 T0.6675,0.5628 L0.6707,0.5628 L0.6861,0.5628 Q0.7364,0.5628,0.7494,0.5608 L0.7567,0.5608 L0.7652,0.5608 L0.7729,0.5608 Q0.7794,0.5608,0.7818,0.5589 Q0.7851,0.5569,0.7859,0.5559 Q0.7835,0.5539,0.7656,0.5519 Q0.7121,0.547,0.6975,0.543 Q0.6934,0.541,0.6853,0.5396 L0.6691,0.5366 T0.6525,0.5336 T0.6391,0.5312 Q0.6367,0.5302,0.6245,0.5257 T0.6034,0.5213 L0.5977,0.5213 Q0.5945,0.5223,0.5904,0.5223 Q0.5839,0.5223,0.5787,0.5208 T0.5685,0.5183 T0.5596,0.5173 Q0.558,0.5173,0.5552,0.5168 T0.5495,0.5163 L0.5434,0.5163 T0.5373,0.5158 T0.532,0.5148 T0.5284,0.5129 T0.5272,0.5104 L0.5272,0.5074 Q0.5304,0.5015,0.5377,0.499 T0.5629,0.4965 Q0.5734,0.4955,0.5811,0.4946 T0.5953,0.4916 T0.605,0.4896 Q0.6083,0.4886,0.6123,0.4886 Q0.6148,0.4886,0.6225,0.4891 T0.635,0.4896 L0.6456,0.4896 Q0.6837,0.4857,0.6861,0.4857 Q0.7226,0.4768,0.7283,0.4768 Q0.7307,0.4768,0.732,0.4773 T0.7372,0.4777 Q0.7502,0.4777,0.7721,0.4758 Q0.7753,0.4748,0.777,0.4738 Q0.7745,0.4718,0.768,0.4708 Q0.7599,0.4688,0.7445,0.4688 Q0.7405,0.4688,0.7324,0.4693 T0.721,0.4698 Q0.7056,0.4698,0.6999,0.4679 Q0.6861,0.4629,0.6626,0.4619 Q0.6586,0.4609,0.6533,0.4604 T0.6419,0.459 T0.6314,0.456 T0.6269,0.452 Q0.6269,0.451,0.6302,0.4491 Q0.6358,0.4451,0.6525,0.4416 T0.6788,0.4382 L0.6845,0.4382 L0.6902,0.4382 Q0.7064,0.4382,0.7145,0.4362 Q0.7202,0.4342,0.7307,0.4342 L0.7356,0.4342 L0.7409,0.4342 L0.7453,0.4342 Q0.7543,0.4342,0.7607,0.4332 Q0.7778,0.4313,0.7847,0.4288 T0.7932,0.4248 T0.7972,0.4169 T0.8045,0.4045 L0.8094,0.3986 T0.8135,0.3942 L0.8167,0.3912 T0.8191,0.3887 T0.8204,0.3867 T0.8208,0.3848 Q0.8208,0.3818,0.8167,0.3739 Q0.8127,0.3689,0.8054,0.3635 T0.7924,0.3556 T0.7778,0.3497 T0.768,0.3462 Q0.764,0.3442,0.7478,0.3427 T0.7267,0.3383 Q0.7234,0.3363,0.7044,0.3348 T0.6805,0.3323 L0.6764,0.3323 T0.6679,0.3328 T0.6586,0.3333 Q0.6521,0.3333,0.648,0.3314 Q0.6391,0.3264,0.6294,0.3264 Q0.6229,0.3264,0.6156,0.3294 Q0.6115,0.3304,0.6042,0.3304 Q0.5977,0.3304,0.5888,0.3289 T0.5738,0.3264 T0.5584,0.3225 L0.5491,0.3195 Q0.5418,0.3185,0.5162,0.3155 T0.4895,0.3121 T0.4826,0.3116 T0.4716,0.3111 T0.4607,0.3096 T0.4513,0.3066 T0.4477,0.3017 Q0.4477,0.2997,0.4485,0.2977 Q0.4526,0.2898,0.4611,0.2878 T0.4842,0.2859 Q0.4882,0.2859,0.4943,0.2864 T0.5028,0.2868 Q0.5118,0.2868,0.5215,0.2829 Q0.5401,0.276,0.5734,0.276 Q0.5831,0.276,0.5872,0.277 L0.5904,0.277 T0.5949,0.2745 T0.6034,0.272 Q0.631,0.269,0.6407,0.2661 Q0.6448,0.2641,0.6488,0.2641 T0.6573,0.2656 T0.6634,0.2671 Q0.6659,0.2671,0.6675,0.2651 Q0.6723,0.2601,0.6886,0.2552 T0.7137,0.2502 L0.7153,0.2502 L0.7178,0.2502 Q0.7218,0.2502,0.7279,0.2493 T0.7417,0.2468 T0.7526,0.2453 Q0.8208,0.2354,0.8281,0.2354 Q0.8337,0.2354,0.8394,0.2344 T0.8496,0.2315 T0.854,0.2265 Q0.854,0.2216,0.8443,0.2176 Q0.8354,0.2127,0.8216,0.2102 T0.7972,0.2072 T0.777,0.2067 T0.7648,0.2057 Q0.7632,0.2047,0.7498,0.2038 T0.7202,0.2018 T0.6983,0.1998 Q0.6918,0.1998,0.676,0.1949 T0.6537,0.1899 Q0.6496,0.1899,0.6472,0.1919 Q0.6342,0.1968,0.6123,0.1968 Q0.5961,0.1968,0.5912,0.1929 Q0.5904,0.1919,0.5892,0.1919 T0.5823,0.1944 T0.5722,0.1968 T0.5637,0.1949 Q0.5556,0.1909,0.5158,0.1869 Q0.5109,0.1869,0.5032,0.1835 T0.4915,0.18 Q0.4907,0.18,0.4891,0.181 Q0.4793,0.182,0.455,0.182 Q0.4177,0.182,0.4015,0.1771 Q0.3901,0.1741,0.3779,0.1741 Q0.3747,0.1741,0.369,0.1746 T0.3609,0.1751 Q0.3569,0.1751,0.3536,0.1741 Q0.3512,0.1741,0.3459,0.1736 T0.3358,0.1726 T0.3256,0.1716 T0.3167,0.1696 T0.3106,0.1662 Q0.3082,0.1632,0.3082,0.1592 Q0.3082,0.1543,0.3114,0.1508 T0.3204,0.1474 L0.3236,0.1474 Q0.3301,0.1494,0.3333,0.1494 Q0.339,0.1494,0.3496,0.1454 Q0.3674,0.1385,0.3869,0.1385 Q0.395,0.1385,0.4011,0.137 T0.4116,0.1355 T0.4197,0.1375 T0.425,0.1395 Q0.429,0.1395,0.4355,0.1365 Q0.4631,0.1266,0.4882,0.1266 Q0.5126,0.1266,0.5337,0.1246 Q0.5369,0.1246,0.5458,0.1207 T0.5661,0.1167 L0.5693,0.1167 Q0.5791,0.1177,0.5852,0.1187 T0.5921,0.1197 Q0.5945,0.1197,0.6002,0.1167 Q0.6026,0.1147,0.605,0.1123 T0.6091,0.1093 T0.6156,0.1088 T0.6318,0.1098 Q0.6456,0.1108,0.6569,0.1137 T0.6707,0.1167 Q0.674,0.1167,0.6772,0.1147 Q0.6821,0.1108,0.6946,0.1083 T0.721,0.1044 T0.7453,0.1029 L0.7526,0.1029 Q0.7583,0.1039,0.7652,0.1053 T0.7753,0.1068 Q0.7778,0.1068,0.7802,0.1058 Q0.7981,0.1019,0.8143,0.1019 Q0.8175,0.1019,0.8439,0.0964 T0.8735,0.091 Q0.8759,0.091,0.8836,0.089 T0.8938,0.0851 Q0.8929,0.0841,0.8905,0.0841 Q0.8832,0.0821,0.8735,0.0821 Q0.8694,0.0821,0.8629,0.0826 T0.854,0.0831 Q0.8508,0.0831,0.8491,0.0821 Q0.8475,0.0821,0.8171,0.0811 T0.7802,0.0781 T0.7571,0.0737 T0.7332,0.0712 Q0.7299,0.0712,0.7247,0.0717 T0.7161,0.0722 L0.7064,0.0722 Q0.7032,0.0712,0.7003,0.0707 T0.6959,0.0692 T0.693,0.0678 T0.6914,0.0663 T0.6902,0.0648 T0.689,0.0643 L0.6869,0.0643 L0.6845,0.0643 L0.6821,0.0643 Q0.6553,0.0643,0.6553,0.0554 T0.6796,0.0465 L0.6813,0.0465 L0.6845,0.0465 Q0.6918,0.0425,0.717,0.0376 Q0.7226,0.0366,0.7267,0.0356 T0.7324,0.0336 T0.7376,0.0317 T0.747,0.0297 Q0.7518,0.0287,0.7551,0.0287 T0.762,0.0297 T0.768,0.0307 L0.7729,0.0307 Q0.7802,0.0277,0.7997,0.0267 T0.8224,0.0237 Q0.8273,0.0227,0.8341,0.0223 T0.8475,0.0193 T0.8654,0.0143 T0.8873,0.0079 Q0.9002,0.003,0.9331,0.004 T0.97,0.004 Q0.9838,0,0.9976,0.001 Q1,0.001,1,0.003 Z M0.9935,0.996 L0.9951,0.0049 Q0.9822,0.0049,0.9716,0.0079 Q0.9659,0.0099,0.9327,0.0089 T0.8897,0.0119 Q0.8775,0.0158,0.8666,0.0183 T0.85,0.0237 Q0.8418,0.0267,0.8341,0.0272 T0.8248,0.0277 Q0.82,0.0297,0.8001,0.0312 T0.7745,0.0346 Q0.7697,0.0356,0.7664,0.0356 Q0.764,0.0356,0.7603,0.0341 T0.7534,0.0326 Q0.751,0.0326,0.7478,0.0336 Q0.7429,0.0346,0.7397,0.0356 T0.7344,0.0376 T0.7283,0.0401 T0.7178,0.0425 Q0.6926,0.0465,0.6878,0.0495 Q0.6845,0.0514,0.6764,0.0514 L0.6723,0.0514 L0.6691,0.0514 Q0.6602,0.0514,0.6602,0.0554 Q0.6602,0.0574,0.6659,0.0579 T0.6796,0.0589 T0.691,0.0603 T0.6967,0.0643 T0.7072,0.0673 Q0.7121,0.0682,0.7153,0.0682 T0.7238,0.0678 T0.7332,0.0673 Q0.7413,0.0673,0.7579,0.0692 T0.7818,0.0742 Q0.7867,0.0752,0.8171,0.0762 T0.8508,0.0781 L0.852,0.0781 T0.8601,0.0776 T0.8719,0.0772 Q0.8832,0.0772,0.8921,0.0791 Q0.8994,0.0811,0.8994,0.0841 T0.8933,0.0895 T0.8812,0.094 T0.8735,0.0959 T0.8451,0.1014 T0.8143,0.1068 Q0.7989,0.1068,0.7818,0.1098 Q0.7778,0.1108,0.7745,0.1108 T0.768,0.1103 T0.7603,0.1088 T0.7518,0.1068 L0.7461,0.1068 Q0.7315,0.1068,0.7088,0.1103 T0.6805,0.1177 Q0.6756,0.1207,0.6699,0.1207 Q0.6667,0.1207,0.6545,0.1177 T0.631,0.1147 Q0.6269,0.1137,0.6225,0.1133 T0.616,0.1128 L0.6123,0.1128 T0.6103,0.1133 L0.6083,0.1157 T0.6034,0.1197 Q0.5961,0.1246,0.5921,0.1246 Q0.5904,0.1246,0.5835,0.1231 T0.5693,0.1217 L0.5661,0.1217 Q0.558,0.1217,0.5535,0.1231 T0.5446,0.1266 T0.5345,0.1296 Q0.5126,0.1316,0.4882,0.1316 T0.438,0.1405 Q0.4298,0.1434,0.425,0.1434 Q0.4209,0.1434,0.4173,0.1419 T0.4112,0.1405 T0.4027,0.1419 T0.3869,0.1434 Q0.3682,0.1434,0.3512,0.1494 Q0.3398,0.1533,0.3333,0.1533 Q0.3285,0.1533,0.3228,0.1513 L0.3212,0.1513 Q0.3179,0.1513,0.3155,0.1538 T0.3131,0.1592 Q0.3131,0.1612,0.3147,0.1632 Q0.3171,0.1652,0.3232,0.1667 T0.3406,0.1691 T0.3544,0.1701 L0.3601,0.1701 L0.3678,0.1701 L0.3771,0.1701 Q0.3909,0.1701,0.4031,0.1731 Q0.4177,0.178,0.4558,0.178 Q0.4793,0.178,0.4882,0.1761 L0.4915,0.1761 Q0.498,0.1761,0.5061,0.179 T0.5158,0.183 Q0.5166,0.183,0.5231,0.1835 T0.5341,0.1845 T0.545,0.1855 T0.5572,0.1874 T0.5661,0.1909 Q0.5677,0.1919,0.5702,0.1919 T0.5791,0.1894 T0.588,0.1869 Q0.5921,0.1869,0.5945,0.1899 Q0.5977,0.1919,0.6123,0.1919 Q0.6334,0.1919,0.6448,0.1879 Q0.6488,0.186,0.6537,0.186 Q0.6626,0.186,0.6784,0.1909 T0.6983,0.1958 Q0.704,0.1968,0.7206,0.1973 T0.7506,0.1993 T0.7689,0.2018 L0.7705,0.2018 L0.7741,0.2018 L0.7786,0.2018 Q0.8248,0.2018,0.8475,0.2136 Q0.8597,0.2196,0.8597,0.2255 T0.8483,0.2359 T0.8281,0.2404 Q0.8208,0.2404,0.7534,0.2493 Q0.7502,0.2502,0.7425,0.2512 T0.7287,0.2532 T0.7178,0.2542 L0.7153,0.2542 L0.7137,0.2542 Q0.7064,0.2542,0.6906,0.2591 T0.6715,0.2681 T0.6626,0.272 Q0.6594,0.272,0.6541,0.2705 T0.6464,0.269 T0.6431,0.27 Q0.6318,0.273,0.6034,0.276 Q0.6018,0.276,0.5998,0.2774 T0.5957,0.2799 T0.5904,0.2809 L0.5856,0.2809 Q0.5823,0.2799,0.575,0.2799 Q0.541,0.2799,0.5239,0.2868 Q0.5134,0.2908,0.5028,0.2908 Q0.4996,0.2908,0.4935,0.2903 T0.4842,0.2898 Q0.4704,0.2898,0.4635,0.2918 T0.4534,0.2997 L0.4534,0.3007 Q0.4534,0.3037,0.459,0.3046 T0.4753,0.3066 T0.4899,0.3076 Q0.4907,0.3076,0.5166,0.3106 T0.5507,0.3155 Q0.5921,0.3264,0.605,0.3264 Q0.6107,0.3264,0.6131,0.3254 Q0.6212,0.3225,0.6294,0.3225 Q0.6407,0.3225,0.6513,0.3274 Q0.6529,0.3294,0.6569,0.3294 Q0.6594,0.3294,0.665,0.3284 T0.6748,0.3274 T0.6821,0.3284 Q0.6861,0.3294,0.6967,0.3299 T0.7165,0.3314 T0.7299,0.3343 Q0.7324,0.3363,0.7486,0.3383 T0.7697,0.3422 Q0.7713,0.3432,0.7774,0.3452 T0.7887,0.3492 T0.8005,0.3546 T0.8127,0.3625 T0.8208,0.3719 Q0.8256,0.3798,0.8256,0.3848 Q0.8256,0.3877,0.8236,0.3902 T0.8171,0.3976 T0.809,0.4075 T0.8021,0.4189 T0.7968,0.4273 T0.7867,0.4322 T0.7616,0.4382 Q0.7543,0.4392,0.7437,0.4392 L0.7364,0.4392 L0.7299,0.4392 Q0.7202,0.4392,0.7161,0.4402 Q0.7072,0.4431,0.691,0.4431 L0.6845,0.4431 L0.6788,0.4431 Q0.6707,0.4431,0.6545,0.4461 T0.6334,0.452 Q0.6399,0.456,0.6626,0.457 Q0.6878,0.458,0.7024,0.4639 Q0.7064,0.4649,0.7186,0.4649 L0.7295,0.4649 L0.7413,0.4649 Q0.7591,0.4649,0.7697,0.4669 Q0.7818,0.4688,0.7818,0.4728 Q0.7818,0.4748,0.7798,0.4763 T0.7753,0.4787 L0.7737,0.4797 L0.7729,0.4797 Q0.7494,0.4827,0.7388,0.4827 Q0.7332,0.4827,0.7307,0.4817 L0.7291,0.4817 Q0.7226,0.4817,0.6878,0.4896 Q0.6829,0.4906,0.6772,0.4911 T0.6618,0.4921 T0.646,0.4931 T0.6342,0.4936 T0.6212,0.4931 T0.6115,0.4926 Q0.6083,0.4926,0.6058,0.4931 T0.5969,0.4955 T0.5819,0.499 T0.5629,0.5005 Q0.5572,0.5005,0.5527,0.501 T0.545,0.502 T0.5397,0.503 T0.5361,0.5045 T0.5337,0.5064 T0.5328,0.5094 L0.532,0.5094 Q0.532,0.5104,0.5337,0.5109 T0.5381,0.5114 T0.5438,0.5119 T0.5515,0.5124 L0.5604,0.5124 Q0.5661,0.5134,0.5746,0.5153 T0.5912,0.5173 L0.5977,0.5173 L0.6026,0.5173 Q0.6139,0.5173,0.6273,0.5218 T0.6407,0.5272 Q0.6448,0.5282,0.6683,0.5321 T0.6991,0.5381 Q0.7137,0.543,0.7664,0.548 Q0.7908,0.55,0.7908,0.5559 Q0.7908,0.5589,0.7859,0.5628 Q0.781,0.5658,0.7713,0.5658 Q0.7689,0.5658,0.7628,0.5653 T0.7543,0.5648 T0.7502,0.5658 Q0.7364,0.5678,0.6878,0.5678 Q0.674,0.5678,0.6699,0.5668 L0.6683,0.5668 Q0.6659,0.5668,0.6606,0.5678 T0.6513,0.5687 Q0.6464,0.5687,0.6391,0.5678 Q0.6334,0.5668,0.6302,0.5668 T0.6241,0.5687 T0.6164,0.5717 Q0.6123,0.5727,0.6099,0.5727 L0.6062,0.5727 T0.6022,0.5732 T0.5953,0.5737 Q0.5904,0.5747,0.5839,0.5747 T0.5726,0.5752 T0.5629,0.5776 T0.5458,0.5796 Q0.5418,0.5796,0.5324,0.5791 T0.5191,0.5786 Q0.5077,0.5786,0.5045,0.5806 Q0.498,0.5836,0.4899,0.5836 Q0.4858,0.5836,0.4777,0.5826 T0.4655,0.5816 L0.4631,0.5816 Q0.4582,0.5816,0.4436,0.5841 T0.4144,0.5865 L0.4051,0.5865 L0.3986,0.5865 T0.3933,0.587 T0.3897,0.5875 T0.3869,0.5885 T0.3844,0.5895 T0.3812,0.591 T0.3779,0.5925 Q0.3739,0.5955,0.3633,0.5955 L0.3585,0.5955 L0.3536,0.5955 Q0.3277,0.5955,0.3066,0.6053 Q0.3017,0.6083,0.296,0.6083 Q0.2912,0.6083,0.2839,0.6068 T0.2741,0.6053 Q0.2693,0.6053,0.2547,0.6048 T0.236,0.6044 Q0.2222,0.6044,0.193,0.6103 L0.1882,0.6103 Q0.1825,0.6103,0.1703,0.6083 T0.1525,0.6063 L0.15,0.6063 Q0.1436,0.6063,0.135,0.6073 T0.1168,0.6098 T0.1038,0.6113 Q0.0973,0.6123,0.0787,0.6123 L0.06,0.6123 L0.0414,0.6123 L0.0235,0.6123 Q0.0049,0.6133,0.0049,0.6172 L0.0057,0.6222 Q0.0073,0.6261,0.043,0.6261 L0.0454,0.6261 L0.0479,0.6261 Q0.0527,0.6261,0.0633,0.6281 T0.0803,0.6301 L0.0835,0.6301 L0.0916,0.6301 Q0.0998,0.6301,0.129,0.632 Q0.1768,0.636,0.206,0.64 Q0.2117,0.6409,0.2165,0.6409 Q0.2206,0.6409,0.2263,0.6405 T0.2336,0.64 L0.2384,0.64 L0.2409,0.64 T0.251,0.6395 T0.2644,0.639 Q0.2741,0.639,0.279,0.6409 Q0.283,0.6429,0.2972,0.6439 T0.3293,0.6459 T0.3528,0.6469 L0.3577,0.6469 Q0.3642,0.6469,0.3723,0.6449 T0.3844,0.6429 Q0.3901,0.6429,0.3933,0.6454 T0.4006,0.6479 Q0.4088,0.6479,0.4517,0.6558 Q0.4582,0.6568,0.4623,0.6568 Q0.4655,0.6568,0.4716,0.6563 T0.4826,0.6558 L0.4882,0.6558 Q0.5004,0.6558,0.5255,0.6607 Q0.5328,0.6627,0.5604,0.6647 T0.6152,0.6682 T0.644,0.6696 T0.6719,0.6721 T0.7056,0.6756 Q0.7113,0.6756,0.7198,0.6805 T0.738,0.6855 Q0.7453,0.6855,0.7551,0.6879 T0.7741,0.6939 T0.7912,0.7018 T0.8029,0.7102 Q0.8054,0.7132,0.8054,0.7151 Q0.8054,0.7191,0.8009,0.7216 T0.7908,0.7255 T0.779,0.7285 T0.7721,0.731 Q0.7672,0.7329,0.7632,0.7339 T0.7551,0.7354 T0.7486,0.7369 Q0.7478,0.7369,0.7445,0.7379 T0.7388,0.7394 T0.7324,0.7404 L0.7242,0.7413 T0.7161,0.7418 Q0.7105,0.7418,0.6955,0.7428 T0.6748,0.7438 L0.6699,0.7438 L0.6667,0.7438 Q0.6659,0.7438,0.6407,0.7468 Q0.6367,0.7478,0.6334,0.7478 T0.6245,0.7468 T0.6148,0.7458 L0.6099,0.7458 Q0.6018,0.7468,0.5864,0.7498 T0.5653,0.7532 T0.5596,0.7557 Q0.5596,0.7596,0.571,0.7616 Q0.5742,0.7626,0.5803,0.7631 T0.5929,0.7641 T0.6018,0.7656 L0.6087,0.7656 T0.6192,0.7666 T0.6277,0.7695 Q0.631,0.7705,0.6342,0.7705 Q0.6383,0.7705,0.6452,0.7685 T0.6537,0.7666 L0.6553,0.7666 Q0.6602,0.7666,0.6711,0.769 T0.6853,0.7715 Q0.691,0.7715,0.7048,0.775 T0.7242,0.7814 Q0.7324,0.7854,0.7445,0.7864 Q0.7478,0.7864,0.768,0.7873 T0.7972,0.7893 Q0.7989,0.7893,0.8017,0.7898 T0.8054,0.7903 L0.8082,0.7903 T0.811,0.7908 T0.8131,0.7913 T0.8151,0.7918 L0.8167,0.7928 T0.8179,0.7943 T0.8191,0.7957 T0.8204,0.7977 T0.8208,0.8002 Q0.8208,0.8032,0.8171,0.8051 T0.8074,0.8081 T0.7997,0.8091 Q0.7932,0.8121,0.7737,0.8121 Q0.7664,0.8121,0.7413,0.8111 L0.7364,0.8111 Q0.7275,0.8111,0.7214,0.8121 T0.7084,0.8155 T0.6991,0.819 Q0.6934,0.82,0.6723,0.8205 T0.6472,0.8239 Q0.6423,0.8269,0.6375,0.8269 Q0.6358,0.8269,0.6338,0.8264 T0.6294,0.8254 T0.6253,0.8249 Q0.6042,0.8249,0.5961,0.8289 Q0.5921,0.8318,0.5839,0.8318 Q0.5783,0.8318,0.5645,0.8299 L0.5604,0.8299 Q0.5531,0.8299,0.5337,0.8368 Q0.5296,0.8378,0.5255,0.8378 Q0.5239,0.8378,0.5195,0.8373 T0.5118,0.8368 Q0.5061,0.8368,0.4996,0.8388 Q0.4947,0.8388,0.4882,0.8398 Q0.4777,0.8417,0.4753,0.8427 T0.4728,0.8467 Q0.4728,0.8487,0.4769,0.8492 T0.4886,0.8501 T0.5004,0.8516 Q0.5036,0.8516,0.515,0.8521 T0.5345,0.8546 Q0.5426,0.8556,0.5596,0.8556 L0.5649,0.8556 L0.5702,0.8556 L0.5791,0.8556 Q0.5921,0.8566,0.6135,0.8571 T0.6383,0.8586 Q0.6683,0.8615,0.6764,0.8615 L0.6776,0.8615 L0.6788,0.8615 Q0.7032,0.8615,0.7032,0.8684 Q0.7032,0.8714,0.6995,0.8749 T0.6959,0.8803 L0.6959,0.8813 Q0.6991,0.8843,0.7153,0.8843 Q0.7218,0.8843,0.7259,0.8833 L0.7299,0.8833 Q0.7324,0.8833,0.7348,0.8838 T0.7393,0.8848 T0.7433,0.8863 L0.7474,0.8882 T0.751,0.8892 Q0.7616,0.8922,0.7948,0.8952 Q0.7981,0.8952,0.8082,0.8981 T0.8297,0.9011 T0.8528,0.9026 T0.8747,0.907 T0.8856,0.9149 L0.8856,0.9159 Q0.8856,0.9179,0.8848,0.9189 T0.8828,0.9209 T0.88,0.9228 T0.8767,0.9243 T0.8731,0.9248 T0.8698,0.9253 T0.8666,0.9258 L0.8646,0.9258 Q0.8621,0.9258,0.8577,0.9263 T0.85,0.9268 T0.8439,0.9273 T0.8402,0.9278 Q0.8386,0.9298,0.8358,0.9308 T0.8305,0.9322 T0.8244,0.9332 T0.8183,0.9337 Q0.8135,0.9347,0.8025,0.9372 T0.7859,0.9416 Q0.7778,0.9436,0.7717,0.9471 T0.7624,0.9515 Q0.7575,0.9535,0.7486,0.9535 Q0.7461,0.9535,0.7397,0.953 T0.7291,0.9525 Q0.7234,0.9525,0.7186,0.953 T0.7137,0.957 T0.7194,0.9614 Q0.7567,0.9634,0.7664,0.9654 Q0.7745,0.9674,0.7762,0.9674 L0.7908,0.9674 Q0.7924,0.9664,0.7948,0.9664 Q0.8029,0.9664,0.8082,0.9679 T0.8224,0.9723 T0.8362,0.9773 Q0.8483,0.9812,0.871,0.9812 L0.8751,0.9812 Q0.8873,0.9812,0.8929,0.9822 T0.9165,0.9876 T0.9408,0.9931 Q0.9513,0.996,0.9935,0.996 Z M0.9968,0.998 L0.9976,0.003 Q0.9838,0.002,0.9708,0.0059 Q0.9659,0.0069,0.9327,0.0059 T0.8881,0.0099 Q0.8767,0.0138,0.8658,0.0163 T0.8491,0.0218 Q0.8418,0.0247,0.8341,0.0247 T0.8232,0.0257 Q0.8191,0.0277,0.7997,0.0292 T0.7737,0.0326 Q0.7697,0.0336,0.7672,0.0336 T0.7612,0.0321 T0.7543,0.0307 T0.747,0.0317 Q0.7397,0.0326,0.7336,0.0356 T0.717,0.0406 Q0.6918,0.0445,0.6861,0.0475 Q0.6845,0.0485,0.6772,0.0485 T0.6638,0.05 T0.6577,0.0549 T0.6642,0.0598 T0.6796,0.0613 T0.6902,0.0623 Q0.691,0.0623,0.6946,0.0658 T0.7064,0.0702 L0.7161,0.0702 Q0.7194,0.0702,0.7242,0.0697 T0.7332,0.0692 Q0.7413,0.0692,0.7579,0.0717 T0.781,0.0762 Q0.7867,0.0781,0.8171,0.0786 T0.85,0.0801 L0.8532,0.0801 Q0.8548,0.0801,0.8613,0.0796 T0.8727,0.0791 Q0.8832,0.0791,0.8913,0.0811 Q0.897,0.0831,0.897,0.0851 Q0.897,0.088,0.8873,0.0905 T0.8735,0.093 Q0.871,0.093,0.8447,0.0984 T0.8143,0.1039 Q0.7981,0.1039,0.781,0.1078 Q0.7778,0.1088,0.7745,0.1088 T0.7644,0.1073 T0.7518,0.1048 L0.7453,0.1048 Q0.7299,0.1048,0.7076,0.1083 T0.6788,0.1157 Q0.6748,0.1187,0.6699,0.1187 Q0.6675,0.1187,0.6557,0.1157 T0.6318,0.1118 Q0.6164,0.1108,0.6135,0.1108 T0.6095,0.1113 T0.6067,0.1142 T0.6018,0.1187 Q0.5953,0.1227,0.5921,0.1227 Q0.5904,0.1227,0.5839,0.1212 T0.5693,0.1187 L0.5661,0.1187 Q0.558,0.1187,0.5527,0.1207 T0.5434,0.1246 T0.5337,0.1266 Q0.5126,0.1296,0.4882,0.1296 T0.4371,0.1385 Q0.4298,0.1414,0.425,0.1414 Q0.4225,0.1414,0.4189,0.1395 T0.4112,0.1375 Q0.4079,0.1375,0.4019,0.1395 T0.3869,0.1414 Q0.3682,0.1414,0.3504,0.1474 Q0.3398,0.1513,0.3333,0.1513 Q0.3293,0.1513,0.3228,0.1494 L0.3204,0.1494 Q0.3179,0.1494,0.3155,0.1508 T0.3118,0.1543 T0.3106,0.1592 T0.3127,0.1642 T0.32,0.1677 T0.3305,0.1701 T0.3435,0.1716 T0.3544,0.1721 Q0.3569,0.1731,0.3601,0.1731 Q0.3625,0.1731,0.3686,0.1726 T0.3779,0.1721 Q0.3901,0.1721,0.4023,0.1751 Q0.4177,0.18,0.455,0.18 Q0.4793,0.18,0.4882,0.178 L0.4915,0.178 Q0.4964,0.178,0.5045,0.1815 T0.5158,0.185 Q0.5564,0.1889,0.5645,0.1929 Q0.5677,0.1939,0.571,0.1939 Q0.575,0.1939,0.5807,0.1919 T0.5888,0.1899 T0.5929,0.1909 Q0.5969,0.1949,0.6123,0.1949 Q0.6334,0.1949,0.6456,0.1899 Q0.6488,0.1879,0.6537,0.1879 Q0.661,0.1879,0.6772,0.1929 T0.6983,0.1978 Q0.704,0.1988,0.7206,0.1998 T0.7502,0.2018 T0.7664,0.2038 Q0.7672,0.2038,0.7818,0.2043 T0.8151,0.2067 T0.8459,0.2156 Q0.8573,0.2206,0.8573,0.2255 Q0.8573,0.2295,0.8516,0.2324 T0.8394,0.2369 T0.8281,0.2384 Q0.8208,0.2384,0.7526,0.2473 Q0.7494,0.2483,0.7421,0.2493 T0.7287,0.2512 T0.7178,0.2522 L0.7153,0.2522 L0.7137,0.2522 Q0.7056,0.2522,0.6898,0.2572 T0.6691,0.2671 Q0.6667,0.269,0.6634,0.269 Q0.661,0.269,0.6557,0.2681 T0.6472,0.2671 Q0.6448,0.2671,0.6415,0.2681 Q0.631,0.271,0.6034,0.274 Q0.5994,0.274,0.5961,0.2765 T0.5904,0.2789 L0.5864,0.2789 Q0.5831,0.2779,0.5742,0.2779 Q0.541,0.2779,0.5223,0.2849 Q0.5126,0.2888,0.5028,0.2888 Q0.5004,0.2888,0.4943,0.2883 T0.4842,0.2878 Q0.4704,0.2878,0.4627,0.2898 T0.4509,0.2987 Q0.4501,0.2997,0.4501,0.3007 Q0.4501,0.3046,0.4574,0.3066 T0.4765,0.3091 T0.4899,0.3096 Q0.4931,0.3106,0.5061,0.3121 T0.5316,0.315 T0.5499,0.3175 Q0.5507,0.3175,0.5572,0.3195 T0.5685,0.3225 T0.5803,0.3254 T0.5933,0.3279 T0.605,0.3284 T0.6148,0.3274 Q0.6221,0.3244,0.6294,0.3244 Q0.6399,0.3244,0.6496,0.3294 Q0.6529,0.3314,0.6577,0.3314 Q0.6602,0.3314,0.6663,0.3304 T0.6756,0.3294 T0.6813,0.3304 Q0.6837,0.3304,0.6873,0.3309 L0.6946,0.3318 T0.7024,0.3323 T0.7105,0.3328 T0.7178,0.3338 T0.7238,0.3348 T0.7283,0.3363 Q0.7324,0.3383,0.7482,0.3403 T0.7689,0.3442 Q0.7697,0.3442,0.779,0.3477 T0.794,0.3536 T0.8074,0.3615 T0.8183,0.3729 Q0.8232,0.3808,0.8232,0.3848 Q0.8232,0.3867,0.8216,0.3892 T0.8151,0.3961 T0.8062,0.406 T0.7997,0.4179 T0.7952,0.4263 T0.7855,0.4308 T0.7616,0.4362 Q0.7543,0.4372,0.7445,0.4372 L0.7372,0.4372 L0.7307,0.4372 Q0.7202,0.4372,0.7153,0.4382 Q0.7064,0.4402,0.691,0.4402 L0.6845,0.4402 L0.6788,0.4402 Q0.6699,0.4402,0.6533,0.4436 T0.6318,0.451 Q0.6302,0.451,0.6302,0.452 Q0.6302,0.457,0.6626,0.459 Q0.6869,0.4609,0.7015,0.4659 Q0.7064,0.4669,0.7202,0.4669 L0.7311,0.4669 L0.7429,0.4669 Q0.7599,0.4669,0.7689,0.4688 Q0.7794,0.4708,0.7794,0.4738 L0.7786,0.4748 T0.777,0.4763 T0.7749,0.4773 L0.7737,0.4777 L0.7729,0.4777 Q0.7502,0.4797,0.738,0.4797 L0.7315,0.4797 L0.7291,0.4797 Q0.7226,0.4797,0.6869,0.4876 Q0.6821,0.4886,0.6768,0.4891 T0.6614,0.4901 T0.6456,0.4916 L0.6342,0.4916 Q0.6294,0.4916,0.6217,0.4911 T0.6115,0.4906 Q0.6083,0.4906,0.6054,0.4911 T0.5961,0.4936 T0.5815,0.4965 T0.5629,0.4985 Q0.5507,0.4985,0.5442,0.4995 T0.5345,0.5025 T0.5304,0.5084 L0.5296,0.5094 Q0.5296,0.5114,0.5316,0.5124 T0.5373,0.5138 T0.5442,0.5143 L0.5523,0.5143 L0.5604,0.5143 Q0.5637,0.5153,0.5677,0.5158 T0.5742,0.5173 T0.5811,0.5188 T0.5904,0.5193 L0.5977,0.5193 L0.6026,0.5193 Q0.6107,0.5193,0.6168,0.5208 T0.6294,0.5252 T0.6399,0.5292 Q0.6448,0.5302,0.6679,0.5341 T0.6983,0.541 Q0.7129,0.545,0.7664,0.55 Q0.7883,0.5519,0.7883,0.5559 Q0.7883,0.5579,0.7843,0.5608 T0.7721,0.5638 Q0.7697,0.5638,0.764,0.5633 T0.7559,0.5628 L0.7502,0.5628 Q0.7364,0.5648,0.6869,0.5648 L0.6699,0.5648 L0.6675,0.5648 Q0.665,0.5648,0.6602,0.5658 T0.6513,0.5668 Q0.6464,0.5668,0.6399,0.5658 Q0.6342,0.5648,0.6302,0.5648 T0.6225,0.5668 T0.6156,0.5697 Q0.6107,0.5707,0.6087,0.5707 T0.6034,0.5712 T0.5953,0.5717 Q0.5904,0.5727,0.5835,0.5727 T0.5718,0.5732 T0.562,0.5757 Q0.558,0.5767,0.5483,0.5767 L0.5349,0.5767 L0.5207,0.5767 Q0.5069,0.5767,0.5028,0.5786 Q0.4972,0.5816,0.4899,0.5816 Q0.4858,0.5816,0.4781,0.5806 T0.4663,0.5796 L0.4631,0.5796 Q0.4582,0.5796,0.4432,0.5821 T0.4144,0.5846 L0.4071,0.5846 L0.4011,0.5846 T0.3958,0.5851 T0.3921,0.5856 T0.3889,0.5861 T0.3865,0.5865 T0.384,0.5875 L0.382,0.5885 L0.3796,0.5895 L0.3771,0.5905 Q0.3731,0.5925,0.365,0.5925 L0.3601,0.5925 L0.3552,0.5925 Q0.3277,0.5925,0.3049,0.6044 Q0.3017,0.6053,0.296,0.6053 Q0.292,0.6053,0.2847,0.6044 T0.2741,0.6034 Q0.2693,0.6034,0.2547,0.6029 T0.236,0.6024 Q0.2222,0.6024,0.1922,0.6073 Q0.1906,0.6083,0.1882,0.6083 Q0.1833,0.6083,0.1711,0.6063 T0.1533,0.6044 Q0.1517,0.6034,0.1492,0.6034 Q0.1436,0.6034,0.135,0.6048 T0.1168,0.6078 T0.103,0.6093 Q0.0973,0.6103,0.0787,0.6103 L0.0604,0.6103 L0.0414,0.6103 L0.0235,0.6103 Q0.0024,0.6113,0.0024,0.6172 Q0.0024,0.6192,0.0032,0.6231 Q0.0049,0.6281,0.0333,0.6281 L0.0414,0.6281 L0.0479,0.6281 Q0.0519,0.6281,0.0624,0.6301 T0.0803,0.632 L0.0835,0.632 L0.0916,0.632 Q0.0989,0.632,0.1281,0.634 L0.206,0.6419 Q0.2117,0.6429,0.2174,0.6429 Q0.2214,0.6429,0.2271,0.6424 T0.2344,0.6419 L0.2376,0.6419 Q0.2393,0.6429,0.2417,0.6429 T0.2526,0.6419 T0.2652,0.6409 Q0.2741,0.6409,0.2782,0.6429 T0.2968,0.6459 T0.3293,0.6479 T0.352,0.6489 Q0.3552,0.6499,0.3585,0.6499 Q0.365,0.6499,0.3731,0.6474 T0.3844,0.6449 Q0.3885,0.6449,0.3917,0.6474 T0.4006,0.6499 Q0.4088,0.6499,0.4509,0.6578 Q0.4574,0.6588,0.4631,0.6588 Q0.4655,0.6588,0.4716,0.6583 T0.4834,0.6578 L0.4874,0.6578 Q0.5004,0.6588,0.5255,0.6637 Q0.532,0.6647,0.56,0.6667 T0.6148,0.6701 T0.644,0.6716 Q0.6464,0.6726,0.6594,0.6736 T0.6861,0.6756 T0.7048,0.6775 Q0.7097,0.6775,0.7186,0.6825 T0.738,0.6874 Q0.7518,0.6874,0.7729,0.6958 T0.8005,0.7122 Q0.8029,0.7141,0.8029,0.7151 Q0.8029,0.7191,0.7968,0.7216 T0.7818,0.726 T0.7705,0.729 L0.764,0.731 T0.7583,0.7324 T0.753,0.7334 T0.7486,0.7349 Q0.7251,0.7399,0.7161,0.7399 Q0.7097,0.7399,0.6951,0.7409 T0.6748,0.7418 L0.6703,0.7418 L0.6667,0.7418 Q0.6659,0.7418,0.6399,0.7448 L0.6334,0.7448 Q0.631,0.7448,0.6249,0.7443 T0.6148,0.7438 L0.6099,0.7438 Q0.601,0.7448,0.5856,0.7473 T0.5645,0.7507 Q0.5572,0.7517,0.5572,0.7547 T0.5616,0.7606 T0.5702,0.7646 Q0.5734,0.7646,0.5779,0.7651 T0.5864,0.7661 T0.5949,0.7671 T0.6018,0.7676 L0.6071,0.7676 T0.6135,0.7681 T0.62,0.769 T0.6269,0.771 T0.6342,0.7725 Q0.6391,0.7725,0.6464,0.7705 T0.6541,0.7685 L0.6553,0.7685 Q0.6586,0.7685,0.6699,0.771 T0.6853,0.7735 Q0.6902,0.7735,0.704,0.777 T0.7226,0.7834 Q0.7315,0.7873,0.7445,0.7883 Q0.747,0.7883,0.7676,0.7893 T0.7972,0.7913 Q0.7989,0.7913,0.8017,0.7918 T0.8058,0.7923 T0.809,0.7928 T0.8114,0.7933 T0.8131,0.7938 T0.8147,0.7943 T0.8159,0.7953 L0.8171,0.7967 T0.8175,0.7982 Q0.8183,0.7992,0.8183,0.8002 Q0.8183,0.8022,0.8155,0.8032 T0.807,0.8051 T0.7989,0.8071 Q0.7932,0.8091,0.7737,0.8091 L0.7413,0.8091 L0.7372,0.8091 Q0.7275,0.8091,0.721,0.8101 T0.7072,0.8136 T0.6983,0.817 Q0.6942,0.818,0.6825,0.818 T0.6602,0.819 T0.6456,0.822 Q0.6415,0.8249,0.6375,0.8249 Q0.6367,0.8249,0.6326,0.8239 T0.6253,0.8229 Q0.6034,0.8229,0.5953,0.8279 Q0.5912,0.8289,0.5848,0.8289 Q0.5775,0.8289,0.5645,0.8279 Q0.5629,0.8269,0.5604,0.8269 Q0.5523,0.8269,0.5328,0.8348 Q0.5296,0.8358,0.5264,0.8358 Q0.5247,0.8358,0.5203,0.8353 T0.5126,0.8348 Q0.5061,0.8348,0.4988,0.8358 Q0.4947,0.8368,0.4882,0.8378 Q0.4826,0.8388,0.4797,0.8388 T0.474,0.8398 T0.4704,0.8422 T0.4696,0.8462 T0.472,0.8501 T0.4781,0.8521 T0.4854,0.8526 L0.4935,0.8526 T0.4996,0.8536 Q0.5036,0.8536,0.515,0.8546 T0.5337,0.8566 Q0.5426,0.8576,0.5596,0.8576 L0.5657,0.8576 L0.571,0.8576 L0.5791,0.8576 Q0.5921,0.8586,0.6135,0.8591 T0.6383,0.8605 Q0.6683,0.8635,0.6764,0.8635 Q0.6999,0.8635,0.6999,0.8684 Q0.6999,0.8694,0.6967,0.8734 T0.6934,0.8803 L0.6934,0.8823 Q0.6951,0.8863,0.7137,0.8863 Q0.7218,0.8863,0.7267,0.8853 L0.7299,0.8853 Q0.734,0.8853,0.7409,0.8882 T0.7502,0.8912 Q0.7607,0.8942,0.794,0.8971 Q0.7972,0.8971,0.8078,0.9001 T0.8297,0.9031 Q0.8475,0.9031,0.8646,0.9065 T0.8824,0.9149 L0.8824,0.9159 Q0.8824,0.9169,0.882,0.9179 T0.8808,0.9194 L0.8792,0.9204 T0.8767,0.9214 T0.8743,0.9224 T0.8715,0.9228 L0.8686,0.9228 T0.8662,0.9233 T0.8637,0.9238 L0.8556,0.9238 T0.8447,0.9243 T0.8386,0.9268 Q0.837,0.9278,0.835,0.9288 T0.8305,0.9303 T0.8244,0.9308 T0.8175,0.9318 Q0.8127,0.9327,0.8017,0.9352 T0.7851,0.9397 Q0.777,0.9416,0.7705,0.9451 T0.7616,0.9496 Q0.7575,0.9505,0.7494,0.9505 L0.7405,0.9505 L0.7307,0.9505 Q0.7234,0.9505,0.7178,0.9515 Q0.7145,0.9515,0.7125,0.9535 T0.7105,0.9575 Q0.7105,0.9624,0.7194,0.9634 Q0.7567,0.9654,0.7664,0.9674 Q0.7745,0.9693,0.7762,0.9693 L0.7908,0.9693 L0.7948,0.9693 Q0.8005,0.9693,0.8058,0.9698 T0.8143,0.9718 T0.824,0.9753 T0.8354,0.9792 Q0.8483,0.9832,0.871,0.9832 L0.8739,0.9832 L0.8767,0.9832 Q0.8873,0.9832,0.8921,0.9842 Q0.8978,0.9852,0.9157,0.9896 T0.94,0.996 Q0.9424,0.996,0.9469,0.9965 T0.9566,0.997 T0.9676,0.9975 T0.9781,0.998 L0.9874,0.998 L0.9943,0.998 L0.9968,0.998 Z",type:0}},"\uE0CC":{type:5,data:{d:"M1,0.5071 L0.8623,0.7102 L0.5865,0.7102 L0.4489,0.5071 L0.5865,0.3045 L0.8623,0.3045 Z M0.4135,0.7974 L0.2758,1 L0,1 L0,0.5944 L0.2758,0.5944 Z M0.4135,0.2026 L0.2758,0.4056 L0,0.4056 L0,0 L0.2758,0 Z",type:0}},"\uE0CD":{type:5,data:{d:"M0.9726,0.5071 L0.8451,0.3184 L0.59,0.3184 L0.4624,0.5071 L0.59,0.6955 L0.8451,0.6955 Z M1,0.5071 L0.8588,0.716 L0.5768,0.716 L0.4355,0.5071 L0.5768,0.2982 L0.8588,0.2982 Z M0.401,0.7911 L0.2735,0.6028 L0.0236,0.6028 L0.0236,0.9799 L0.2735,0.9799 Z M0.4284,0.7911 L0.2872,1 L0,1 L0,0.5826 L0.2872,0.5826 Z M0.401,0.2089 L0.2735,0.0201 L0.0236,0.0201 L0.0236,0.3972 L0.2735,0.3972 Z M0.4284,0.2089 L0.2872,0.4174 L0,0.4174 L0,0 L0.2872,0 Z",type:0}},"\uE0CE":{type:5,data:{d:"M1,0.4996 Q1,0.5365,0.9924,0.568 T0.9718,0.6177 T0.9433,0.6363 L0.9425,0.6367 Q0.9355,0.6367,0.9285,0.6326 L0.9308,0.6326 Q0.9129,0.6195,0.9013,0.587 T0.8871,0.5164 T0.8943,0.4373 T0.9254,0.3687 L0.9254,0.3691 Q0.9339,0.3628,0.9425,0.3628 Q0.9584,0.3628,0.9716,0.3811 T0.9924,0.431 T1,0.4996 Z M0.9234,0.6321 L0.8776,0.7169 Q0.8791,0.732,0.8791,0.7441 Q0.8791,0.781,0.8716,0.8123 T0.8508,0.862 T0.8224,0.8809 L0.8216,0.8809 Q0.8154,0.8809,0.8092,0.8775 L0.8088,0.8775 Q0.7905,0.8633,0.7792,0.8297 T0.766,0.7571 T0.775,0.6768 T0.8088,0.6086 L0.7431,0.6065 Q0.719,0.6313,0.7072,0.6705 T0.6965,0.7487 T0.7097,0.823 T0.7423,0.8763 L0.7913,0.8775 L0.7314,0.9895 L0.4648,0.5038 L0.7299,0.0176 L0.7882,0.1229 L0.7404,0.1212 Q0.7244,0.138,0.7136,0.1617 T0.6982,0.2108 T0.6943,0.2632 T0.7003,0.3144 T0.7159,0.3586 T0.7396,0.3909 L0.8072,0.3926 Q0.7894,0.3796,0.7777,0.3479 T0.7635,0.2789 T0.7697,0.2011 T0.7987,0.1326 Q0.8092,0.1225,0.8204,0.1225 Q0.8321,0.1225,0.8426,0.1332 T0.8609,0.1623 T0.8731,0.2062 T0.8776,0.2592 Q0.8776,0.268,0.8768,0.2815 L0.9219,0.3628 L0.8644,0.3612 Q0.8403,0.3855,0.8284,0.4247 T0.8177,0.5029 T0.8309,0.5772 T0.8632,0.6305 Z M0.6759,0.6384 Q0.6576,0.625,0.6457,0.5914 T0.6319,0.5185 T0.6407,0.4375 T0.6751,0.3691 L0.609,0.367 Q0.5849,0.3918,0.5731,0.431 T0.5626,0.509 T0.5758,0.5833 T0.6082,0.6367 Z M0.6459,0.0025 L0.391,0.4551 L0.0035,0.4551 L0.246,0 Z M0.6553,1 L0.2421,1 L0,0.5449 L0.3875,0.5449 Z",type:0}},"\uE0CF":{type:5,data:{d:"M0.4996,0 Q0.5562,0,0.5961,0.0166 T0.6364,0.0566 L0.6368,0.0575 Q0.6368,0.0646,0.6324,0.0713 L0.6324,0.0692 Q0.6196,0.0868,0.5872,0.0986 T0.5166,0.1128 T0.4373,0.1057 T0.3689,0.0747 L0.3694,0.0747 Q0.3627,0.0663,0.3627,0.0575 Q0.3627,0.0336,0.4028,0.0168 T0.4996,0 Z M0.6324,0.0768 L0.717,0.1225 Q0.7321,0.1212,0.744,0.1212 Q0.8007,0.1212,0.8406,0.1378 T0.8809,0.1779 L0.8813,0.1783 Q0.8813,0.1846,0.8778,0.1909 Q0.8636,0.2093,0.8299,0.2208 T0.7573,0.2343 T0.6769,0.2253 T0.6089,0.1913 L0.6067,0.2567 Q0.6315,0.281,0.6707,0.2928 T0.7489,0.3035 T0.8231,0.2903 T0.8764,0.258 L0.8778,0.2085 L0.9898,0.2685 L0.504,0.5352 L0.0177,0.2701 L0.1227,0.2118 L0.1213,0.2596 Q0.1457,0.2836,0.1851,0.2955 T0.2635,0.3062 T0.3377,0.293 T0.3911,0.2605 L0.3928,0.193 Q0.38,0.2106,0.3483,0.2221 T0.2792,0.2364 T0.2013,0.2303 T0.1324,0.2013 Q0.1222,0.1909,0.1222,0.1795 Q0.1222,0.156,0.1623,0.1393 T0.2591,0.1225 Q0.2679,0.1225,0.2817,0.1233 L0.3627,0.078 L0.3609,0.1359 Q0.3857,0.1598,0.4249,0.1718 T0.5031,0.1825 T0.5773,0.1693 T0.6306,0.1367 Z M0.6386,0.3242 Q0.6253,0.3427,0.5917,0.3544 T0.5186,0.3683 T0.4376,0.3595 T0.3689,0.3251 L0.3671,0.3909 Q0.3915,0.4148,0.4309,0.4268 T0.5093,0.4375 T0.5835,0.4243 T0.6368,0.3918 Z M0.0027,0.354 L0.4553,0.6091 L0.4553,0.9962 L0,0.7542 Z M1,0.3448 L1,0.7576 L0.5447,1 L0.5447,0.6128 Z",type:0}},"\uE0D0":{type:5,data:{d:"M0,0.7699 Q0,0.7172,0.0277,0.6731 T0.103,0.6032 T0.2066,0.5774 Q0.2487,0.5774,0.2865,0.5922 T0.3526,0.6339 L0.3935,0.6715 Q0.4218,0.6984,0.438,0.7336 T0.4541,0.8075 Q0.4541,0.8602,0.4264,0.9046 T0.3511,0.9745 T0.2475,1 Q0.2054,1,0.1676,0.9852 T0.1016,0.9435 L0.0606,0.9059 Q0.0317,0.879,0.0159,0.8438 T0,0.7699 Z M0.5459,0.7699 Q0.5459,0.7172,0.5736,0.6731 T0.6489,0.6032 T0.7525,0.5774 Q0.7946,0.5774,0.8324,0.5922 T0.8984,0.6339 L0.9394,0.6715 Q0.9579,0.6892,0.9714,0.7105 T0.9925,0.7567 T1,0.8075 Q1,0.8602,0.9723,0.9046 T0.897,0.9745 T0.7934,1 Q0.7513,1,0.7135,0.9852 T0.6474,0.9435 L0.6065,0.9059 Q0.5776,0.879,0.5617,0.8438 T0.5459,0.7699 Z M0,0.1925 Q0,0.1398,0.0277,0.0957 T0.103,0.0258 T0.2066,0 Q0.2487,0,0.2865,0.0148 T0.3526,0.0565 L0.3935,0.0941 Q0.4218,0.121,0.438,0.1562 T0.4541,0.2301 Q0.4541,0.2828,0.4264,0.3269 T0.3511,0.3968 T0.2475,0.4226 Q0.2054,0.4226,0.1676,0.4078 T0.1016,0.3661 L0.0606,0.3285 Q0.0317,0.3016,0.0159,0.2664 T0,0.1925 Z M0.5459,0.1925 Q0.5459,0.1398,0.5736,0.0957 T0.6489,0.0258 T0.7525,0 Q0.7946,0,0.8324,0.0148 T0.8984,0.0565 L0.9394,0.0941 Q0.9677,0.121,0.9838,0.1562 T1,0.2301 Q1,0.2828,0.9723,0.3269 T0.897,0.3968 T0.7934,0.4226 Q0.7513,0.4226,0.7135,0.4078 T0.6474,0.3661 L0.6065,0.3285 Q0.5874,0.3108,0.5741,0.2895 T0.5534,0.2433 T0.5459,0.1925 Z M0.3301,0.6403 Q0.3306,0.6403,0.3312,0.6409 L0.3272,0.6371 L0.3272,0.6371 Z M0.8759,0.6403 Q0.8765,0.6403,0.8771,0.6409 Q0.8748,0.6387,0.8725,0.6371 L0.8731,0.6371 Z M0.3301,0.0629 Q0.3306,0.0629,0.3312,0.0634 L0.3272,0.0597 L0.3272,0.0602 Z M0.8759,0.0629 Q0.8765,0.0629,0.8771,0.0634 Q0.8748,0.0613,0.8725,0.0597 Q0.8731,0.0597,0.8731,0.0602 Z M0.779,0.4113 L0.7501,0.3849 Q0.7046,0.3844,0.6636,0.3661 Q0.7132,0.407,0.779,0.4113 Z M0.7957,0.4118 Q0.8477,0.4113,0.8918,0.3874 T0.9619,0.3223 T0.9885,0.2323 L0.9585,0.2048 Q0.9538,0.2769,0.8987,0.3282 T0.7657,0.3844 Z M0.9879,0.2167 Q0.9827,0.1554,0.9388,0.1097 Q0.9585,0.1478,0.959,0.1898 Z M0.2331,0.4113 L0.2043,0.3849 Q0.1587,0.3844,0.1177,0.3661 Q0.1673,0.407,0.2331,0.4113 Z M0.2499,0.4118 Q0.2885,0.4118,0.324,0.3973 T0.3852,0.3589 T0.4264,0.3019 T0.4426,0.2323 L0.4126,0.2048 Q0.408,0.2769,0.3529,0.3282 T0.2198,0.3844 Z M0.442,0.2167 Q0.4368,0.1554,0.393,0.1097 Q0.4126,0.1478,0.4132,0.1903 Z M0.779,0.9887 L0.7501,0.9624 Q0.7046,0.9618,0.6636,0.9435 Q0.7132,0.9844,0.779,0.9887 Z M0.7957,0.9892 Q0.8477,0.9887,0.8918,0.9648 T0.9619,0.8997 T0.9885,0.8097 L0.9585,0.7823 Q0.9538,0.8543,0.8987,0.9056 T0.7657,0.9618 Z M0.9879,0.7941 Q0.9827,0.7328,0.9388,0.6871 Q0.9585,0.7253,0.959,0.7672 Z M0.2331,0.9887 L0.2043,0.9624 Q0.1587,0.9618,0.1177,0.9435 Q0.1673,0.9844,0.2331,0.9887 Z M0.2499,0.9892 Q0.3018,0.9887,0.3459,0.9648 T0.416,0.8997 T0.4426,0.8102 L0.4126,0.7823 Q0.408,0.8543,0.3529,0.9056 T0.2198,0.9618 Z M0.442,0.7941 Q0.4368,0.7328,0.393,0.6871 Q0.4126,0.7253,0.4132,0.7672 Z M0.3191,0.6452 Q0.2943,0.622,0.2643,0.6091 T0.2066,0.5962 Q0.1795,0.5962,0.1497,0.6091 T0.0949,0.6441 T0.0537,0.6995 T0.0375,0.7699 Q0.0375,0.8419,0.0941,0.8941 Q0.1189,0.9172,0.1489,0.9304 T0.2066,0.9435 Q0.2337,0.9435,0.2634,0.9304 T0.3182,0.8952 T0.3595,0.8398 T0.3756,0.7699 Q0.3756,0.6978,0.3191,0.6452 Z M0.026,0.7731 L0.026,0.7699 Q0.026,0.6935,0.0854,0.6376 Q0.0658,0.6538,0.0514,0.6739 T0.0289,0.718 T0.0202,0.7677 Z M0.0271,0.7892 L0.0208,0.7833 Q0.0254,0.8419,0.0681,0.886 Q0.0664,0.8828,0.0646,0.879 Q0.0329,0.8382,0.0271,0.7892 Z M0.3866,0.7823 Q0.382,0.8511,0.3278,0.9016 Q0.3843,0.8565,0.3918,0.7871 Z M0.3872,0.7677 L0.393,0.7726 L0.393,0.7699 Q0.393,0.7349,0.3791,0.7038 Q0.3739,0.6973,0.3681,0.6914 Q0.3866,0.7274,0.3872,0.7677 Z M0.865,0.6452 Q0.8402,0.622,0.8102,0.6091 T0.7525,0.5962 Q0.7305,0.5962,0.7072,0.6043 T0.6619,0.628 T0.6223,0.6642 T0.5941,0.7124 T0.5834,0.7699 Q0.5834,0.8419,0.6399,0.8941 Q0.6561,0.9097,0.6757,0.9207 T0.7149,0.9376 T0.7525,0.9435 Q0.7796,0.9435,0.8093,0.9304 T0.8641,0.8952 T0.9054,0.8398 T0.9215,0.7699 Q0.9215,0.6978,0.865,0.6452 Z M0.5718,0.7731 L0.5718,0.7699 Q0.5718,0.6935,0.6313,0.6376 Q0.6013,0.6618,0.584,0.6954 T0.5661,0.7677 Z M0.573,0.7892 L0.5666,0.7833 Q0.5713,0.8419,0.614,0.886 Q0.6122,0.8828,0.6105,0.879 Q0.5788,0.8382,0.573,0.7892 Z M0.9325,0.7823 Q0.9279,0.8511,0.8736,0.9016 Q0.9308,0.8565,0.9377,0.7871 Z M0.9331,0.7672 L0.9388,0.7726 L0.9388,0.7699 Q0.9388,0.7349,0.925,0.7038 Q0.9198,0.6973,0.914,0.6914 Q0.9325,0.7274,0.9331,0.7672 Z M0.3191,0.0677 Q0.2943,0.0446,0.2643,0.0317 T0.2066,0.0188 Q0.1795,0.0188,0.1497,0.0317 T0.0949,0.0667 T0.0537,0.122 T0.0375,0.1925 Q0.0375,0.2645,0.0941,0.3167 Q0.1189,0.3398,0.1489,0.353 T0.2066,0.3661 Q0.2337,0.3661,0.2634,0.353 T0.3182,0.3177 T0.3595,0.2624 T0.3756,0.1925 Q0.3756,0.1204,0.3191,0.0677 Z M0.026,0.1957 L0.026,0.1925 Q0.026,0.1161,0.0854,0.0602 Q0.0554,0.0844,0.0381,0.118 T0.0202,0.1903 Z M0.0271,0.2118 L0.0208,0.2059 Q0.0254,0.2645,0.0681,0.3086 Q0.0664,0.3054,0.0646,0.3016 Q0.0329,0.2608,0.0271,0.2118 Z M0.3866,0.2048 Q0.382,0.2737,0.3278,0.3242 Q0.3849,0.279,0.3918,0.2097 Z M0.3872,0.1903 L0.393,0.1952 L0.393,0.1925 Q0.393,0.1581,0.3791,0.1263 Q0.3739,0.1199,0.3681,0.114 Q0.3866,0.15,0.3872,0.1903 Z M0.865,0.0677 Q0.8402,0.0446,0.8102,0.0317 T0.7525,0.0188 Q0.7253,0.0188,0.6956,0.0317 T0.6408,0.0667 T0.5995,0.122 T0.5834,0.1925 Q0.5834,0.2645,0.6399,0.3167 Q0.6647,0.3398,0.6947,0.353 T0.7525,0.3661 Q0.7796,0.3661,0.8093,0.353 T0.8641,0.3177 T0.9054,0.2624 T0.9215,0.1925 Q0.9215,0.1204,0.865,0.0677 Z M0.5718,0.1957 L0.5718,0.1925 Q0.5718,0.1161,0.6313,0.0602 Q0.6013,0.0844,0.584,0.118 T0.5661,0.1903 Z M0.573,0.2118 L0.5666,0.2059 Q0.5713,0.2645,0.614,0.3086 Q0.6122,0.3054,0.6105,0.3016 Q0.5788,0.2608,0.573,0.2118 Z M0.9325,0.2048 Q0.9279,0.2737,0.8736,0.3242 Q0.9308,0.279,0.9377,0.2097 Z M0.9331,0.1898 L0.9388,0.1952 L0.9388,0.1925 Q0.9388,0.1575,0.925,0.1263 Q0.9198,0.1199,0.914,0.114 Q0.9325,0.15,0.9331,0.1898 Z",type:0}},"\uE0D1":{type:5,data:{d:"M0.7639,0.1974 L0.9593,0.1974 L0.9593,0.1443 L0.7639,0.1443 L0.7639,0.1974 Z M0.7586,0.109 L0.9727,0.109 Q0.9839,0.109,0.992,0.1153 T1,0.1291 L1,0.382 Q1,0.3906,0.9912,0.3964 T0.9727,0.4021 L0.7586,0.4021 Q0.7468,0.4021,0.739,0.3956 T0.7313,0.382 L0.7313,0.1291 Q0.7313,0.1246,0.7339,0.1207 T0.7406,0.1143 T0.7495,0.1104 T0.7586,0.109 Z M0.7639,0.6575 L0.9593,0.6575 L0.9593,0.6044 L0.7639,0.6044 L0.7639,0.6575 Z M0.7313,0.8347 L0.7313,0.5843 Q0.7313,0.5757,0.7401,0.5699 T0.7586,0.5641 L0.9706,0.5641 Q0.9818,0.5641,0.9898,0.5705 T0.9979,0.5843 L0.9979,0.8347 Q0.9979,0.8433,0.989,0.8491 T0.9706,0.8549 L0.7586,0.8549 Q0.7468,0.8549,0.739,0.8483 T0.7313,0.8347 Z M0,1 L0,0 L0.7607,0 L0.7607,1 L0,1 Z",type:0}},"\uE0D2":{type:5,data:{d:"M0.9764,0.0029 L0.3179,0.4552 L0,0.4552 L0,0 Z M1,1 L0,1 L0,0.5448 L0.3091,0.5448 Z",type:0}},"\uE0D4":{type:5,data:{d:"M0.0236,0.0029 L0.6824,0.4552 L1,0.4552 L1,0 Z M0,1 L1,1 L1,0.5448 L0.6912,0.5448 Z",type:0}},"\uEE00":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z"},"\uEE01":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z"},"\uEE02":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z"},"\uEE03":{type:3,data:"M0,0 L1,0 L1,.05 L.1,.05 L.1,.95 L1,.95 L1,1 L0,1 Z M.25,.15 L1,.15 L1,.85 L.25,.85 Z"},"\uEE04":{type:3,data:"M0,0 L1,0 L1,.05 L0,.05 Z M0,.95 L1,.95 L1,1 L0,1 Z M0,.15 L1,.15 L1,.85 L0,.85 Z"},"\uEE05":{type:3,data:"M1,0 L0,0 L0,.05 L.9,.05 L.9,.95 L0,.95 L0,1 L1,1 Z M0,.15 L.75,.15 L.75,.85 L0,.85 Z"},"\uEE06":{type:5,data:{d:"M0.6574,0.303 Q0.623,0.291,0.5852,0.285 T0.5082,0.279 T0.4311,0.285 T0.359,0.303 L0.3082,0.248 Q0.3525,0.232,0.4041,0.2235 T0.5082,0.215 T0.6123,0.2235 T0.7082,0.248 Z",type:0},scaleType:1},"\uEE07":{type:5,data:{d:"M0.8557,0.582 L0.7656,0.551 Q0.7852,0.53,0.7951,0.507 T0.8049,0.46 Q0.8049,0.424,0.782,0.3905 T0.718,0.332 T0.6221,0.293 T0.5082,0.279 L0.5082,0.215 Q0.5607,0.215,0.6123,0.2235 T0.709,0.248 T0.7918,0.287 T0.8557,0.3375 T0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.582 Z",type:0},scaleType:1},"\uEE08":{type:5,data:{d:"M0.5082,0.705 Q0.482,0.705,0.4557,0.703 T0.4049,0.697 L0.4311,0.635 Q0.4508,0.638,0.4697,0.6395 T0.5082,0.641 Q0.5672,0.641,0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 Q0.8049,0.436,0.7951,0.413 T0.7656,0.369 L0.8557,0.338 Q0.882,0.365,0.8959,0.3965 T0.9098,0.46 T0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"\uEE09":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 L0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 T0.6221,0.627 T0.718,0.588 T0.782,0.5295 T0.8049,0.46 L0.9098,0.46 Q0.9098,0.492,0.8959,0.5235 T0.8557,0.5825 T0.7918,0.633 T0.709,0.672 T0.6123,0.6965 T0.5082,0.705 Z",type:0},scaleType:1},"\uEE0A":{type:5,data:{d:"M0.5082,0.705 Q0.4557,0.705,0.4041,0.6965 T0.3074,0.672 T0.2246,0.633 T0.1607,0.5825 T0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.338 L0.2508,0.369 Q0.2311,0.39,0.2213,0.413 T0.2115,0.46 Q0.2115,0.496,0.2344,0.5295 T0.2984,0.588 T0.3943,0.627 T0.5082,0.641 Q0.5279,0.641,0.5467,0.6395 T0.5852,0.635 L0.6115,0.697 Q0.5869,0.701,0.5607,0.703 T0.5082,0.705 Z",type:0},scaleType:1},"\uEE0B":{type:5,data:{d:"M0.1607,0.582 Q0.1344,0.555,0.1205,0.5235 T0.1066,0.46 T0.1205,0.3965 T0.1607,0.3375 T0.2246,0.287 T0.3074,0.248 T0.4041,0.2235 T0.5082,0.215 L0.5082,0.279 Q0.4492,0.279,0.3943,0.293 T0.2984,0.332 T0.2344,0.3905 T0.2115,0.46 Q0.2115,0.484,0.2213,0.507 T0.2508,0.551 Z",type:0},scaleType:1},"\uF5D0":l.LINE_H,"\uF5D1":l.LINE_V,"\uF5D2":l.FADE_RIGHT,"\uF5D3":l.FADE_LEFT,"\uF5D4":l.FADE_DOWN,"\uF5D5":l.FADE_UP,"\uF5D6":l.CURVE_DOWN_RIGHT,"\uF5D7":l.CURVE_DOWN_LEFT,"\uF5D8":l.CURVE_UP_RIGHT,"\uF5D9":l.CURVE_UP_LEFT,"\uF5DA":[l.LINE_V,l.CURVE_UP_RIGHT],"\uF5DB":[l.LINE_V,l.CURVE_DOWN_RIGHT],"\uF5DC":[l.CURVE_DOWN_RIGHT,l.CURVE_UP_RIGHT],"\uF5DD":[l.LINE_V,l.CURVE_UP_LEFT],"\uF5DE":[l.LINE_V,l.CURVE_DOWN_LEFT],"\uF5DF":[l.CURVE_DOWN_LEFT,l.CURVE_UP_LEFT],"\uF5E0":[l.LINE_H,l.CURVE_DOWN_LEFT],"\uF5E1":[l.LINE_H,l.CURVE_DOWN_RIGHT],"\uF5E2":[l.CURVE_DOWN_LEFT,l.CURVE_DOWN_RIGHT],"\uF5E3":[l.LINE_H,l.CURVE_UP_LEFT],"\uF5E4":[l.LINE_H,l.CURVE_UP_RIGHT],"\uF5E5":[l.CURVE_UP_LEFT,l.CURVE_UP_RIGHT],"\uF5E6":[l.LINE_V,l.CURVE_UP_LEFT,l.CURVE_UP_RIGHT],"\uF5E7":[l.LINE_V,l.CURVE_DOWN_LEFT,l.CURVE_DOWN_RIGHT],"\uF5E8":[l.LINE_H,l.CURVE_DOWN_LEFT,l.CURVE_UP_LEFT],"\uF5E9":[l.LINE_H,l.CURVE_DOWN_RIGHT,l.CURVE_UP_RIGHT],"\uF5EA":[l.LINE_V,l.CURVE_DOWN_RIGHT,l.CURVE_UP_LEFT],"\uF5EB":[l.LINE_V,l.CURVE_DOWN_LEFT,l.CURVE_UP_RIGHT],"\uF5EC":[l.LINE_H,l.CURVE_DOWN_RIGHT,l.CURVE_UP_LEFT],"\uF5ED":[l.LINE_H,l.CURVE_DOWN_LEFT,l.CURVE_UP_RIGHT],"\uF5EE":[l.NODE_FILL,l.NODE_STROKE],"\uF5EF":l.NODE_STROKE,"\uF5F0":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_RIGHT],"\uF5F1":[l.NODE_STROKE,l.NODE_LINE_RIGHT],"\uF5F2":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_LEFT],"\uF5F3":[l.NODE_STROKE,l.NODE_LINE_LEFT],"\uF5F4":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF5F5":[l.NODE_STROKE,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF5F6":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN],"\uF5F7":[l.NODE_STROKE,l.NODE_LINE_DOWN],"\uF5F8":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP],"\uF5F9":[l.NODE_STROKE,l.NODE_LINE_UP],"\uF5FA":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_UP],"\uF5FB":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_UP],"\uF5FC":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF5FD":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF5FE":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF5FF":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF600":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_RIGHT],"\uF601":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_RIGHT],"\uF602":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT],"\uF603":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT],"\uF604":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF605":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_RIGHT],"\uF606":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF607":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT],"\uF608":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF609":[l.NODE_STROKE,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60A":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60B":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60C":[l.NODE_FILL,l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\uF60D":[l.NODE_STROKE,l.NODE_LINE_UP,l.NODE_LINE_DOWN,l.NODE_LINE_LEFT,l.NODE_LINE_RIGHT],"\u{1FB00}":f(1),"\u{1FB01}":f(2),"\u{1FB02}":f(3),"\u{1FB03}":f(4),"\u{1FB04}":f(5),"\u{1FB05}":f(6),"\u{1FB06}":f(7),"\u{1FB07}":f(8),"\u{1FB08}":f(9),"\u{1FB09}":f(10),"\u{1FB0A}":f(11),"\u{1FB0B}":f(12),"\u{1FB0C}":f(13),"\u{1FB0D}":f(14),"\u{1FB0E}":f(15),"\u{1FB0F}":f(16),"\u{1FB10}":f(17),"\u{1FB11}":f(18),"\u{1FB12}":f(19),"\u{1FB13}":f(20),"\u{1FB14}":f(22),"\u{1FB15}":f(23),"\u{1FB16}":f(24),"\u{1FB17}":f(25),"\u{1FB18}":f(26),"\u{1FB19}":f(27),"\u{1FB1A}":f(28),"\u{1FB1B}":f(29),"\u{1FB1C}":f(30),"\u{1FB1D}":f(31),"\u{1FB1E}":f(32),"\u{1FB1F}":f(33),"\u{1FB20}":f(34),"\u{1FB21}":f(35),"\u{1FB22}":f(36),"\u{1FB23}":f(37),"\u{1FB24}":f(38),"\u{1FB25}":f(39),"\u{1FB26}":f(40),"\u{1FB27}":f(41),"\u{1FB28}":f(43),"\u{1FB29}":f(44),"\u{1FB2A}":f(45),"\u{1FB2B}":f(46),"\u{1FB2C}":f(47),"\u{1FB2D}":f(48),"\u{1FB2E}":f(49),"\u{1FB2F}":f(50),"\u{1FB30}":f(51),"\u{1FB31}":f(52),"\u{1FB32}":f(53),"\u{1FB33}":f(54),"\u{1FB34}":f(55),"\u{1FB35}":f(56),"\u{1FB36}":f(57),"\u{1FB37}":f(58),"\u{1FB38}":f(59),"\u{1FB39}":f(60),"\u{1FB3A}":f(61),"\u{1FB3B}":f(62),"\u{1FB3C}":{type:3,data:"M0,0.6667 L0,1 L0.5,1 Z"},"\u{1FB3D}":{type:3,data:"M0,0.6667 L0,1 L1,1 Z"},"\u{1FB3E}":{type:3,data:"M0,0.3333 L0,1 L0.5,1 Z"},"\u{1FB3F}":{type:3,data:"M0,0.3333 L0,1 L1,1 Z"},"\u{1FB40}":{type:3,data:"M0,0 L0,1 L0.5,1 Z"},"\u{1FB41}":{type:3,data:"M0,0.3333 L0.5,0 L1,0 L1,1 L0,1 Z"},"\u{1FB42}":{type:3,data:"M0,0.3333 L1,0 L1,1 L0,1 Z"},"\u{1FB43}":{type:3,data:"M0,0.6667 L0.5,0 L1,0 L1,1 L0,1 Z"},"\u{1FB44}":{type:3,data:"M0,0.6667 L1,0 L1,1 L0,1 Z"},"\u{1FB45}":{type:3,data:"M0,1 L0.5,0 L1,0 L1,1 Z"},"\u{1FB46}":{type:3,data:"M0,0.6667 L1,0.3333 L1,1 L0,1 Z"},"\u{1FB47}":{type:3,data:"M0.5,1 L1,0.6667 L1,1 Z"},"\u{1FB48}":{type:3,data:"M0,1 L1,0.6667 L1,1 Z"},"\u{1FB49}":{type:3,data:"M0.5,1 L1,0.3333 L1,1 Z"},"\u{1FB4A}":{type:3,data:"M0,1 L1,0.3333 L1,1 Z"},"\u{1FB4B}":{type:3,data:"M0.5,1 L1,0 L1,1 Z"},"\u{1FB4C}":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.3333 Z"},"\u{1FB4D}":{type:3,data:"M0,0 L0,1 L1,1 L1,0.3333 Z"},"\u{1FB4E}":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 L1,0.6667 Z"},"\u{1FB4F}":{type:3,data:"M0,0 L0,1 L1,1 L1,0.6667 Z"},"\u{1FB50}":{type:3,data:"M0.5,0 L0,0 L0,1 L1,1 Z"},"\u{1FB51}":{type:3,data:"M0,0.3333 L0,1 L1,1 L1,0.6667 Z"},"\u{1FB52}":{type:3,data:"M0,0.6667 L0.5,1 L1,1 L1,0 L0,0 Z"},"\u{1FB53}":{type:3,data:"M0,0.6667 L1,1 L1,0 L0,0 Z"},"\u{1FB54}":{type:3,data:"M0,0.3333 L0.5,1 L1,1 L1,0 L0,0 Z"},"\u{1FB55}":{type:3,data:"M0,0.3333 L1,1 L1,0 L0,0 Z"},"\u{1FB56}":{type:3,data:"M0,0 L0.5,1 L1,1 L1,0 Z"},"\u{1FB57}":{type:3,data:"M0,0.3333 L0,0 L0.5,0 Z"},"\u{1FB58}":{type:3,data:"M0,0.3333 L0,0 L1,0 Z"},"\u{1FB59}":{type:3,data:"M0,0.6667 L0,0 L0.5,0 Z"},"\u{1FB5A}":{type:3,data:"M0,0.6667 L0,0 L1,0 Z"},"\u{1FB5B}":{type:3,data:"M0,1 L0,0 L0.5,0 Z"},"\u{1FB5C}":{type:3,data:"M0,0.6667 L0,0 L1,0 L1,0.3333 Z"},"\u{1FB5D}":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.6667 Z"},"\u{1FB5E}":{type:3,data:"M0,1 L0,0 L1,0 L1,0.6667 Z"},"\u{1FB5F}":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 L1,0.3333 Z"},"\u{1FB60}":{type:3,data:"M0,1 L0,0 L1,0 L1,0.3333 Z"},"\u{1FB61}":{type:3,data:"M0.5,1 L0,1 L0,0 L1,0 Z"},"\u{1FB62}":{type:3,data:"M0.5,0 L1,0 L1,0.3333 Z"},"\u{1FB63}":{type:3,data:"M0,0 L1,0 L1,0.3333 Z"},"\u{1FB64}":{type:3,data:"M0.5,0 L1,0 L1,0.6667 Z"},"\u{1FB65}":{type:3,data:"M0,0 L1,0 L1,0.6667 Z"},"\u{1FB66}":{type:3,data:"M0.5,0 L1,0 L1,1 Z"},"\u{1FB67}":{type:3,data:"M0,0.3333 L1,0.6667 L1,0 L0,0 Z"},"\u{1FB68}":{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0.5,0.5 Z"},"\u{1FB69}":{type:3,data:"M0,0 L0.5,0.5 L1,0 L1,1 L0,1 Z"},"\u{1FB6A}":{type:3,data:"M0,0 L1,0 L0.5,0.5 L1,1 L0,1 Z"},"\u{1FB6B}":{type:3,data:"M0,0 L1,0 L1,1 L0.5,0.5 L0,1 Z"},"\u{1FB6C}":{type:3,data:"M0,0 L0.5,0.5 L0,1 Z"},"\u{1FB6D}":{type:3,data:"M0,0 L1,0 L0.5,0.5 Z"},"\u{1FB6E}":{type:3,data:"M1,0 L1,1 L0.5,0.5 Z"},"\u{1FB6F}":{type:3,data:"M0,1 L1,1 L0.5,0.5 Z"},"\u{1FB70}":{type:0,data:[{x:1,y:0,w:1,h:8}]},"\u{1FB71}":{type:0,data:[{x:2,y:0,w:1,h:8}]},"\u{1FB72}":{type:0,data:[{x:3,y:0,w:1,h:8}]},"\u{1FB73}":{type:0,data:[{x:4,y:0,w:1,h:8}]},"\u{1FB74}":{type:0,data:[{x:5,y:0,w:1,h:8}]},"\u{1FB75}":{type:0,data:[{x:6,y:0,w:1,h:8}]},"\u{1FB76}":{type:0,data:[{x:0,y:1,w:8,h:1}]},"\u{1FB77}":{type:0,data:[{x:0,y:2,w:8,h:1}]},"\u{1FB78}":{type:0,data:[{x:0,y:3,w:8,h:1}]},"\u{1FB79}":{type:0,data:[{x:0,y:4,w:8,h:1}]},"\u{1FB7A}":{type:0,data:[{x:0,y:5,w:8,h:1}]},"\u{1FB7B}":{type:0,data:[{x:0,y:6,w:8,h:1}]},"\u{1FB7C}":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"\u{1FB7D}":{type:0,data:[{x:0,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"\u{1FB7E}":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:0,w:8,h:1}]},"\u{1FB7F}":{type:0,data:[{x:7,y:0,w:1,h:8},{x:0,y:7,w:8,h:1}]},"\u{1FB80}":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:7,w:8,h:1}]},"\u{1FB81}":{type:0,data:[{x:0,y:0,w:8,h:1},{x:0,y:2,w:8,h:1},{x:0,y:4,w:8,h:1},{x:0,y:7,w:8,h:1}]},"\u{1FB82}":{type:0,data:[{x:0,y:0,w:8,h:2}]},"\u{1FB83}":{type:0,data:[{x:0,y:0,w:8,h:3}]},"\u{1FB84}":{type:0,data:[{x:0,y:0,w:8,h:5}]},"\u{1FB85}":{type:0,data:[{x:0,y:0,w:8,h:6}]},"\u{1FB86}":{type:0,data:[{x:0,y:0,w:8,h:7}]},"\u{1FB87}":{type:0,data:[{x:6,y:0,w:2,h:8}]},"\u{1FB88}":{type:0,data:[{x:5,y:0,w:3,h:8}]},"\u{1FB89}":{type:0,data:[{x:3,y:0,w:5,h:8}]},"\u{1FB8A}":{type:0,data:[{x:2,y:0,w:6,h:8}]},"\u{1FB8B}":{type:0,data:[{x:1,y:0,w:7,h:8}]},"\u{1FB8C}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},"\u{1FB8D}":{type:1,data:[[1,0],[0,1]],clipPath:"M0.5,0 L1,0 L1,1 L0.5,1 Z"},"\u{1FB8E}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},"\u{1FB8F}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},"\u{1FB90}":{type:1,data:[[0,1],[1,0]]},"\u{1FB91}":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0.5 L1,0.5 L1,1 L0,1 Z"},{type:0,data:[{x:0,y:0,w:8,h:4}]}],"\u{1FB92}":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L1,0 L1,0.5 L0,0.5 Z"},{type:0,data:[{x:0,y:4,w:8,h:4}]}],"\u{1FB94}":[{type:1,data:[[0,1],[1,0]],clipPath:"M0,0 L0.5,0 L0.5,1 L0,1 Z"},{type:0,data:[{x:4,y:0,w:4,h:8}]}],"\u{1FB95}":{type:0,data:[{x:0,y:0,w:2,h:2},{x:4,y:0,w:2,h:2},{x:2,y:2,w:2,h:2},{x:6,y:2,w:2,h:2},{x:0,y:4,w:2,h:2},{x:4,y:4,w:2,h:2},{x:2,y:6,w:2,h:2},{x:6,y:6,w:2,h:2}]},"\u{1FB96}":{type:0,data:[{x:2,y:0,w:2,h:2},{x:6,y:0,w:2,h:2},{x:0,y:2,w:2,h:2},{x:4,y:2,w:2,h:2},{x:2,y:4,w:2,h:2},{x:6,y:4,w:2,h:2},{x:0,y:6,w:2,h:2},{x:4,y:6,w:2,h:2}]},"\u{1FB97}":{type:0,data:[{x:0,y:2,w:8,h:2},{x:0,y:6,w:8,h:2}]},"\u{1FB98}":{type:2,data:"M-0.25,-0.25 L1.25,1.25 M-0.25,0 L1,1.25 M-0.25,0.25 L0.75,1.25 M-0.25,0.5 L0.5,1.25 M0,-0.25 L1.25,1 M0.25,-0.25 L1.25,0.75 M0.5,-0.25 L1.25,0.5 M-0.25,0.75 L0.25,1.25 M0.75,-0.25 L1.25,0.25",strokeWidth:1},"\u{1FB99}":{type:2,data:"M-0.25,0.5 L0.5,-0.25 M-0.25,0.75 L0.75,-0.25 M-0.25,1 L1,-0.25 M-0.25,1.25 L1.25,-0.25 M0,1.25 L1.25,0 M0.25,1.25 L1.25,0.25 M0.5,1.25 L1.25,0.5 M-0.25,0.25 L0.25,-0.25 M0.75,1.25 L1.25,0.75",strokeWidth:1},"\u{1FB9A}":{type:5,data:{d:"M0,0 L.5,.5 L0,1 L1,1 L.5,.5 L1,0",type:0}},"\u{1FB9B}":{type:5,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1",type:0}},"\u{1FB9C}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L0,1 Z"},"\u{1FB9D}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,0 L1,1 Z"},"\u{1FB9E}":{type:1,data:[[1,0],[0,1]],clipPath:"M1,0 L1,1 L0,1 Z"},"\u{1FB9F}":{type:1,data:[[1,0],[0,1]],clipPath:"M0,0 L1,1 L0,1 Z"},"\u{1FBA0}":{type:2,data:"M.5,0 L0,.5",strokeWidth:1},"\u{1FBA1}":{type:2,data:"M.5,0 L1,.5",strokeWidth:1},"\u{1FBA2}":{type:2,data:"M0,.5 L.5,1",strokeWidth:1},"\u{1FBA3}":{type:2,data:"M1,.5 L.5,1",strokeWidth:1},"\u{1FBA4}":{type:2,data:"M.5,0 L0,.5 L.5,1",strokeWidth:1},"\u{1FBA5}":{type:2,data:"M.5,0 L1,.5 L.5,1",strokeWidth:1},"\u{1FBA6}":{type:2,data:"M0,.5 L.5,1 L1,.5",strokeWidth:1},"\u{1FBA7}":{type:2,data:"M0,.5 L.5,0 L1,.5",strokeWidth:1},"\u{1FBA8}":{type:2,data:"M.5,0 L0,.5 M1,.5 L.5,1",strokeWidth:1},"\u{1FBA9}":{type:2,data:"M.5,0 L1,.5 M0,.5 L.5,1",strokeWidth:1},"\u{1FBAA}":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5",strokeWidth:1},"\u{1FBAB}":{type:2,data:"M.5,0 L0,.5 L.5,1 L1,.5",strokeWidth:1},"\u{1FBAC}":{type:2,data:"M0,.5 L.5,0 L1,.5 L.5,1",strokeWidth:1},"\u{1FBAD}":{type:2,data:"M1,.5 L.5,0 L0,.5 L.5,1",strokeWidth:1},"\u{1FBAE}":{type:2,data:"M.5,0 L1,.5 L.5,1 L0,.5 Z",strokeWidth:1},"\u{1FBAF}":{type:2,data:"M0,.5 L1,.5 M.5,.35 L.5,.65",strokeWidth:1},"\u{1FBB0}":{type:3,data:"M0.1,0.2 L0.1,.8 L.4,.6 L.9,0.6 Z",scaleType:1},"\u{1FBB1}":{type:4,data:{d:"M.1,.525 L.35,.675 L.9,.35",type:1},scaleType:1},"\u{1FBB2}":{type:3,data:"M.29,.27 L0.13,.56 L.22,.59 L.35,0.35 L.67,.35 L.57,.57 L.71,.76 L.22,.76 L.42,1 L.53,.98 L.43,.86 L.9,.86 L.71,.6 L1,.6 L1,.52 L.83,.52 L.92,.36 L1,.36 L1,.27Z M.99,.13 A.12,.12,0,1,1,.75,.13 A.12,.12,0,1,1,.99,.13"},"\u{1FBB3}":{type:3,data:"M0,.27 L.3,.27 L.55,.12 L.63,.18 L.33,.36 L0,.36 M0,.52 L.33,.52 L.59,.89 L.73,.89 L.73,.98 L.53,.98 L.28,.6 L0,.6"},"\u{1FBB4}":{type:4,data:{d:"M.15,.55 L.5,.4 L.5,.45 L.65,.45 L.65,.35 L.85,.35 L.85,.625 L.5,.625 L.5,.7 Z",type:0},scaleType:1},"\u{1FBB5}":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.15,.5 L.5,.35 L.5,.425 L.85,.425 L.85,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"\u{1FBB6}":[{type:5,data:{d:"M0,0 L1,0 L1,.0625 L0,.0625 Z M0,.9375 L1,.9375 L1,1 L0,1 Z",type:0}},{type:5,data:{d:"M.85,.5 L.5,.35 L.5,.425 L.15,.425 L.15,.575 L.5,.575 L.5,.65 Z",type:0},scaleType:1}],"\u{1FBB7}":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.675 L.2,.5 L.35,.5 L.35,.325 L.65,.325 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"\u{1FBB8}":[{type:5,data:{d:"M.875,0 L1,0 L1,1 L.875,1 Z",type:0}},{type:5,data:{d:"M.5,.325 L.2,.5 L.35,.5 L.35,.675 L.65,.675 L.65,.5 L.8,.5 Z",type:0},scaleType:1}],"\u{1FBB9}":{type:5,data:{d:"M1,.89 L.11,.89 L.11,.37 L.36,.12 L.74,.12 L.96,.34 L1,.34 L1,.405 L.92,.405 L.69,.185 L.41,.185 L.21,.42 L.21,.825 L1,.825 Z",type:0}},"\u{1FBBA}":{type:5,data:{d:"M0,.89 L0,.825 L.78,.825 L.78,.53 L.7,.415 L0,.415 L0,.35 L.75,.35 L.88,.48 L.88,.89 Z",type:0}},"\u{1FBBB}":{type:5,data:{d:"M.31,.275 L.44,.275 L.44,.47 L.05,.47 L.05,.405 L.31,.405 Z M.56,.275 L.69,.275 L.69,.405 L.95,.405 L.95,.47 L.56,.47 Z M.05,.53 L.44,.53 L.44,.725 L.31,.725 L.31,.595 L.05,.595 Z M.56,.53 L.95,.53 L.95,.595 L.69,.595 L.69,.725 L.56,.725 Z",type:0},scaleType:1},"\u{1FBBC}":[{type:3,data:"M0,0 L1,0 L1,1 L0,1 L0,.935 L.885,.935 L.885,.065 L0,.065 Z"},{type:3,data:"M.67,.5 A.17,.085,0,1,1,.33,.5 A.17,.085,0,1,1,.67,.5",scaleType:1}],"\u{1FBBD}":{type:4,data:{d:"M0,0 L.5,.5 L1,0 L1,1 L.5,.5 L0,1 Z",type:1}},"\u{1FBBE}":{type:4,data:{d:"M1,.5 L.5,1",type:1}},"\u{1FBBF}":{type:4,data:{d:"M.5,0 L1,.5 L.5,1 L0,.5 Z",type:1}},"\u{1FBC0}":{type:3,data:"M.16,.445 A.02,.01,0,0,1,.39,.33 L.5,.375 L.61,.33 A.02,.01,0,0,1,.84,.445 L.75,.5 L.84,.555 A.02,.01,0,0,1,.61,.67 L.5,.625 L.39,.67 A.02,.01,0,0,1,.16,.555 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",scaleType:1},"\u{1FBC1}":{type:3,data:"M0.142308,0.924 Q0.130770,0.924,0.120193,0.922 T0.101924,0.916 T0.089424,0.9065 T0.084616,0.895 V0.025 Q0.084616,0.019,0.089424,0.0135 T0.101924,0.004 T0.120193,-0.002 T0.142308,-0.004 Q0.150000,-0.004,0.157693,-0.003 T0.173078,0.000 L0.430770,0.085 Q0.451924,0.059,0.494232,0.041 T0.587501,0.013 T0.692309,-0.0005 T0.800001,-0.004 H1 V0.055 H0.800001 Q0.771155,0.055,0.742309,0.056 T0.685578,0.060 T0.630770,0.0685 T0.580770,0.0825 T0.543270,0.1045 T0.528847,0.133 V0.647 H0.530770 Q0.596155,0.645,0.659616,0.638 T0.782693,0.6165 T0.893270,0.5805 T1,0.531 V0.623 Q0.934616,0.644,0.880770,0.6595 T0.769232,0.685 T0.650963,0.700 T0.528847,0.707 V0.787 Q0.528847,0.802,0.543270,0.8155 T0.580770,0.8375 T0.630770,0.8515 T0.685578,0.860 T0.742309,0.864 T0.800001,0.865 H1 V0.924 H0.800001 Q0.746155,0.924,0.692309,0.9205 T0.587501,0.907 T0.494232,0.879 T0.430770,0.835 L0.173078,0.920 Q0.165386,0.922,0.157693,0.923 T0.142308,0.924 Z M0.2,0.841 L0.415385,0.770 V0.150 L0.2,0.079 V0.841 Z M1,0.698 Q0.973077,0.694,0.969231,0.6885 T0.965385,0.677 Q0.965385,0.672,0.969231,0.6665 T1,0.657 V0.698 Z"},"\u{1FBC2}":{type:3,data:"M0,0.623 V0.531 Q0.044231,0.512,0.0625,0.4905 T0.092308,0.4465 T0.108654,0.4005 T0.113462,0.354 V0.351 Q0.113462,0.345,0.117308,0.3395 T0.129808,0.3305 T0.148846,0.3245 T0.171154,0.323 H0.501923 Q0.532692,0.323,0.563462,0.3185 T0.617308,0.303 T0.651923,0.2765 T0.663462,0.2435 V0.241 Q0.663462,0.219,0.657692,0.197 T0.639423,0.1545 T0.604808,0.115 T0.549615,0.082 T0.475577,0.0615 T0.392308,0.055 H0 V-0.004 H1 V0.055 H0.667308 Q0.694231,0.071,0.713462,0.09 T0.746154,0.129 T0.766346,0.1705 T0.775,0.213 H1 V0.316 Q0.971154,0.305,0.955769,0.2965 T0.920192,0.2825 T0.876923,0.2745 T0.830769,0.272 H0.773077 Q0.767308,0.297,0.743269,0.319 T0.680769,0.355 T0.595192,0.375 T0.501923,0.381 H0.227308 Q0.223462,0.415,0.211,0.4485 T0.172692,0.5135 T0.108269,0.573 T0,0.623 Z M0.611538,0.924 H0 V0.865 H0.611538 Q0.642308,0.865,0.673077,0.8605 T0.727885,0.845 T0.762308,0.8185 T0.773077,0.787 V0.785 Q0.773077,0.769,0.762308,0.7535 T0.727885,0.727 T0.673077,0.7115 T0.611538,0.707 H0.059615 Q0.048077,0.707,0.037115,0.7045 T0,0.694 V0.653 Q0.026923,0.648,0.037115,0.646 T0.059615,0.644 H0.722692 Q0.753462,0.644,0.784231,0.6395 T0.839038,0.624 T0.873846,0.5975 T0.884615,0.566 V0.564 Q0.884615,0.548,0.873846,0.532 T0.839038,0.5055 T0.784231,0.49 T0.722692,0.4855 H0.392308 Q0.380769,0.4855,0.370192,0.483 T0.351923,0.4765 T0.339423,0.467 T0.334615,0.4555 T0.339423,0.444 T0.351923,0.4345 T0.370192,0.428 T0.392308,0.4255 H0.832692 Q0.855769,0.4255,0.878846,0.4235 T0.922115,0.416 T0.957692,0.4015 T1,0.3815 V0.4685 Q0.975,0.4705,0.966346,0.4725 T0.95,0.4765 Q0.961538,0.4835,0.969231,0.4915 T1,0.5075 V0.6205 Q0.965385,0.6455,0.926923,0.665 T0.84,0.6935 Q0.866923,0.7115,0.877596,0.7345 T0.894231,0.7855 V0.787 Q0.894231,0.815,0.876923,0.8425 T0.820192,0.8895 T0.726923,0.916 T0.611538,0.924 Z"},"\u{1FBC3}":{type:3,data:"M0,0.473 V0.386 Q0.025490,0.378,0.028431,0.3695 T0.031373,0.352 V0.35 Q0.031373,0.342,0.028431,0.333 T0,0.316 V0.213 H0.652941 Q0.684314,0.213,0.715686,0.2085 T0.770588,0.193 T0.804902,0.1665 T0.815686,0.135 V0.133 Q0.815686,0.117,0.804902,0.101 T0.770588,0.0745 T0.715686,0.0595 T0.652941,0.055 H0 V-0.004 H0.652941 Q0.707843,-0.004,0.761765,0.004 T0.856863,0.031 T0.915686,0.0775 T0.933333,0.133 V0.135 Q0.933333,0.163,0.915686,0.1905 T0.856863,0.237 T0.761765,0.264 T0.652941,0.272 H0.109804 Q0.131373,0.29,0.140196,0.31 T0.149020,0.35 V0.352 Q0.149020,0.37,0.142157,0.388 T0.118627,0.4225 T0.076471,0.452 T0,0.473 Z M0,0.625 V0.513 Q0.029412,0.526,0.032353,0.54 T0.035294,0.568 V0.57 Q0.035294,0.584,0.032353,0.598 T0,0.625 Z"},"\u{1FBC4}":{type:3,data:"M0.019231,1.085 V-0.165 H0.980769 V1.085 H0.019231 Z M0.446154,0.527 H0.553846 Q0.553846,0.511,0.5625,0.495 T0.591346,0.466 T0.631731,0.4405 T0.666346,0.4135 T0.688462,0.3825 T0.696154,0.35 Q0.696154,0.33,0.682692,0.311 T0.641346,0.2785 T0.575,0.259 T0.498077,0.253 T0.421154,0.259 T0.356731,0.279 T0.315385,0.3125 T0.301923,0.352 V0.357 H0.409615 V0.354 Q0.409615,0.345,0.414423,0.335 T0.431731,0.318 T0.4625,0.3075 T0.498077,0.304 Q0.517308,0.304,0.534615,0.307 T0.564423,0.3165 T0.582692,0.332 T0.588462,0.35 Q0.588462,0.366,0.572115,0.3805 T0.535577,0.4075 T0.496154,0.4335 T0.465385,0.4625 T0.45,0.4945 T0.446154,0.527 Z M0.5,0.667 Q0.519231,0.667,0.5375,0.664 T0.569231,0.654 T0.588462,0.637 T0.594231,0.617 T0.588462,0.5975 T0.569231,0.581 T0.5375,0.571 T0.5,0.568 T0.4625,0.571 T0.430769,0.581 T0.411538,0.5975 T0.405769,0.617 T0.411538,0.637 T0.430769,0.654 T0.4625,0.664 T0.5,0.667 Z",scaleType:1},"\u{1FBC5}":{type:5,data:{d:"M.44,.425 L.44,.51 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.51 L.56,.425 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC6}":{type:5,data:{d:"M.44,.425 L.44,.46 L.23,.385 L.19,.43 L.44,.51 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.61,.735 L.7,.71 L.56,.56 L.56,.51 L.81,.43 L.77,.385 L.56,.46 L.56,.425 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC7}":{type:5,data:{d:"M.44,.425 L.44,.56 L.29,.71 L.38,.735 L.5,.605 L.74,.72 L.81,.685 L.56,.56 L.56,.425 Z M.18,.53 L.23,.575 L.81,.43 L.77,.385 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC8}":{type:5,data:{d:"M.44,.425 L.44,.56 L.19,.685 L.26,.72 L.5,.605 L.62,.735 L.71,.71 L.56,.56 L.56,.425 Z M.23,.385 L.18,.43 L.77,.575 L.81,.53 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBC9}":{type:5,data:{d:"M.44,.425 L.45,.495 L.15,.645 L.34,.645 L.34,.7 L.44,.7 L.44,.645 L.56,.645 L.56,.7 L.66,.7 L.66,.645 L.84,.645 L.54,.495 L.56,.425 Z M.39,.6 L.5,.55 L.60,.6 Z M.17,.46 L.17,.51 L.83,.51 L.83,.46 Z M.67,.35 C.67,.303,.594,.265,.5,.265 C.406,.265,.33,.303,.33,.35 C.33,.397,.406,.435,.5,.435 C.594,.435,.67,.397,.67,.35 Z M.56,.35 C.56,.3665,.533,.38,.5,.38 C.467,.38,.44,.3665,.44,.35 C.44,.3335,.467,.32,.5,.32 C.533,.32,.56,.3335,.56,.35 Z",type:0},scaleType:1},"\u{1FBCA}":{type:5,data:{d:"M.26,.375 L.5,.255 L.74,.375 L.74,.665 L.5,.55 L.26,.665 Z M.37,.395 L.37,.54 L.5,.475 L.63,.54 L.63,.395 L.5,.33 Z",type:0},scaleType:1},"\u{1FBCB}":{type:5,data:{d:"M.09,.41 L.32,.295 L.5,.375 L.68,.295 L.91,.41 L.75,.5 L.91,.59 L.68,.705 L.5,.625 L.32,.705 L.09,.59 L.25,.5 Z M.24,.41 L.39,.5 L.24,.59 L.32,.63 L.5,.555 L.68,.63 L.76,.59 L.61,.5 L.76,.41 L.68,.37 L.5,.445 L.32,.37 Z",type:0},scaleType:1},"\u{1FBCC}":{type:5,data:{d:"M.55,.305 L.88,.305 L.88,.355 L.65,.355 L.65,.47 L.88,.47 L.88,.52 L.55,.52 Z",type:0},scaleType:1},"\u{1FBCD}":{type:5,data:{d:"M.38,.39 L.5,.33 L.62,.39 L.62,.53 L.5,.47 L.38,.53 Z",type:0},scaleType:1},"\u{1FBCE}":{type:3,data:"M0,0 L0.6667,0 L0.6667,1 L0,1 Z"},"\u{1FBCF}":{type:3,data:"M0,0 L0.3333,0 L0.3333,1 L0,1 Z"},"\u{1FBD0}":{type:2,data:"M1,.5 L0,1",strokeWidth:1},"\u{1FBD1}":{type:2,data:"M1,0 L0,.5",strokeWidth:1},"\u{1FBD2}":{type:2,data:"M0,0 L1,.5",strokeWidth:1},"\u{1FBD3}":{type:2,data:"M0,.5 L1,1",strokeWidth:1},"\u{1FBD4}":{type:2,data:"M0,0 L.5,1",strokeWidth:1},"\u{1FBD5}":{type:2,data:"M.5,0 L1,1",strokeWidth:1},"\u{1FBD6}":{type:2,data:"M1,0 L.5,1",strokeWidth:1},"\u{1FBD7}":{type:2,data:"M.5,0 L0,1",strokeWidth:1},"\u{1FBD8}":{type:2,data:"M0,0 L.5,.5 L1,0",strokeWidth:1},"\u{1FBD9}":{type:2,data:"M1,0 L.5,.5 L1,1",strokeWidth:1},"\u{1FBDA}":{type:2,data:"M0,1 L.5,.5 L1,1",strokeWidth:1},"\u{1FBDB}":{type:2,data:"M0,0 L.5,.5 L0,1",strokeWidth:1},"\u{1FBDC}":{type:2,data:"M0,0 L.5,1 L1,0",strokeWidth:1},"\u{1FBDD}":{type:2,data:"M1,0 L0,.5 L1,1",strokeWidth:1},"\u{1FBDE}":{type:2,data:"M0,1 L.5,0 L1,1",strokeWidth:1},"\u{1FBDF}":{type:2,data:"M0,0 L1,.5 L0,1",strokeWidth:1},"\u{1FBE0}":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0",type:1}},"\u{1FBE1}":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1",type:1}},"\u{1FBE2}":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1",type:1}},"\u{1FBE3}":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1",type:1}},"\u{1FBE4}":{type:0,data:[{x:2,y:0,w:4,h:4}]},"\u{1FBE5}":{type:0,data:[{x:2,y:4,w:4,h:4}]},"\u{1FBE6}":{type:0,data:[{x:0,y:2,w:4,h:4}]},"\u{1FBE7}":{type:0,data:[{x:4,y:2,w:4,h:4}]},"\u{1FBE8}":{type:5,data:{d:"M0,0 C0,.276,.224,.5,.5,.5 C.776,.5,1,.276,1,0 Z",type:0}},"\u{1FBE9}":{type:5,data:{d:"M1,0 C.724,0,.5,.224,.5,.5 C.5,.776,.724,1,1,1 Z",type:0}},"\u{1FBEA}":{type:5,data:{d:"M0,1 C0,.724,.224,.5,.5,.5 C.776,.5,1,.724,1,1 Z",type:0}},"\u{1FBEB}":{type:5,data:{d:"M0,0 C.276,0,.5,.224,.5,.5 C.5,.776,.276,1,0,1 Z",type:0}},"\u{1FBEC}":{type:5,data:{d:"M1,0 L.5,0 C.5,.276,.724,.5,1,.5 Z",type:0}},"\u{1FBED}":{type:5,data:{d:"M0,1 L.5,1 C.5,.724,.276,.5,0,.5 Z",type:0}},"\u{1FBEE}":{type:5,data:{d:"M1,1 L1,.5 C.724,.5,.5,.724,.5,1 Z",type:0}},"\u{1FBEF}":{type:5,data:{d:"M0,0 L0,.5 C.276,.5,.5,.276,.5,0 Z",type:0}},"\u{1FBF0}":{type:5,data:{d:o0(126),type:0},scaleType:1},"\u{1FBF1}":{type:5,data:{d:o0(48),type:0},scaleType:1},"\u{1FBF2}":{type:5,data:{d:o0(109),type:0},scaleType:1},"\u{1FBF3}":{type:5,data:{d:o0(121),type:0},scaleType:1},"\u{1FBF4}":{type:5,data:{d:o0(51),type:0},scaleType:1},"\u{1FBF5}":{type:5,data:{d:o0(91),type:0},scaleType:1},"\u{1FBF6}":{type:5,data:{d:o0(95),type:0},scaleType:1},"\u{1FBF7}":{type:5,data:{d:o0(114),type:0},scaleType:1},"\u{1FBF8}":{type:5,data:{d:o0(127),type:0},scaleType:1},"\u{1FBF9}":{type:5,data:{d:o0(123),type:0},scaleType:1},"\u{1FBFA}":{type:5,data:{d:"M.5,.175 C.2,.175,.15,.305,.15,.435 L.05,.63 L.35,.63 C.35,.682,.42,.76,.5,.76 C.58,.76,.65,.682,.65,.63 L.95,.63 L.85,.435 C.85,.305,.8,.175,.5,.175 Z",type:0},scaleType:1},...Object.fromEntries(Array.from({length:256},(i,e)=>[String.fromCodePoint(10240+e),{type:6,data:e}]))},$e=new Set([9617,9618,9619,129932,129933,129934,129935,129936,129937,129938,129940,129948,129949,129950,129951]);function f(i){return{type:2,data:()=>{let e=[],r=[.375,.25,.375],s=[0,3/8,5/8];for(let a=0;a<3;a++){let o=i>>a*2&1,n=i>>a*2+1&1;o&&n?e.push(`M0,${s[a]} L1,${s[a]} L1,${s[a]+r[a]} L0,${s[a]+r[a]} Z`):o?e.push(`M0,${s[a]} L${.5},${s[a]} L${.5},${s[a]+r[a]} L0,${s[a]+r[a]} Z`):n&&e.push(`M${.5},${s[a]} L1,${s[a]} L1,${s[a]+r[a]} L${.5},${s[a]+r[a]} Z`)}return e.join(" ")}}}function o0(i){let e=[];if(i&64){let Q=.21500000000000002,m=.95-.15-.015;e.push(`M${Q},${.2125} L${Q+.075},${.175} L${m-.075},${.175} L${m},${.2125} L${m-.075},${.25} L${Q+.075},${.25} Z`)}if(i&32){let c=.7999999999999999,u=.95-.15/2,C=.95,Q=.175+.075+.015,m=.5-.015;e.push(`M${u},${Q} L${C},${Q+.0375} L${C},${m-.0375} L${u},${m} L${c},${m-.0375} L${c},${Q+.0375} Z`)}if(i&16){let c=.7999999999999999,u=.95-.15/2,C=.95,Q=.5+.015,m=.825-.075-.015;e.push(`M${u},${Q} L${C},${Q+.0375} L${C},${m-.0375} L${u},${m} L${c},${m-.0375} L${c},${Q+.0375} Z`)}if(i&8){let Q=.21500000000000002,m=.95-.15-.015;e.push(`M${Q},${.7875} L${Q+.075},${.75} L${m-.075},${.75} L${m},${.7875} L${m-.075},${.825} L${Q+.075},${.825} Z`)}if(i&4&&e.push(`M${.125},${.515} L${.2},${.515+.0375} L${.2},${.735-.0375} L${.125},${.735} L${.05},${.735-.0375} L${.05},${.515+.0375} Z`),i&2&&e.push(`M${.125},${.265} L${.2},${.265+.0375} L${.2},${.485-.0375} L${.125},${.485} L${.05},${.485-.0375} L${.05},${.265+.0375} Z`),i&1){let Q=.21500000000000002,m=.95-.15-.015;e.push(`M${Q},${.5} L${Q+.075},${.4625} L${m-.075},${.4625} L${m},${.5} L${m-.075},${.5375} L${Q+.075},${.5375} Z`)}return e.join(" ")}var k=0,H=0,T0=!1,_0=!1,$0=!1,z,x0=0,G0=class{constructor(e,t,r,s,a,o){this._terminal=e;this._optionService=t;this._selectionRenderModel=r;this._decorationService=s;this._coreBrowserService=a;this._themeService=o;this.result={fg:0,bg:0,ext:0}}resolve(e,t,r,s,a){this.result.bg=e.bg,this.result.fg=e.fg,this.result.ext=e.bg&268435456?e.extended.ext:0,H=0,k=0,_0=!1,T0=!1,$0=!1,z=this._themeService.colors,x0=0;let o=e.getCode();if(o!==0&&e.extended.underlineStyle===4){let n=Math.max(1,Math.floor(this._optionService.rawOptions.fontSize*this._coreBrowserService.dpr/15));x0=t*s%(Math.round(n)*2)}if(x0===0&&$e.has(o)&&(x0=t*s%2*2+r*a%2),this._decorationService.forEachDecorationAtCell(t,r,"bottom",n=>{n.backgroundColorRGB&&(H=n.backgroundColorRGB.rgba>>8&16777215,_0=!0),n.foregroundColorRGB&&(k=n.foregroundColorRGB.rgba>>8&16777215,T0=!0)}),$0=this._selectionRenderModel.isCellSelected(this._terminal,t,r),$0){if(this.result.fg&67108864||(this.result.bg&50331648)!==0){if(this.result.fg&67108864)switch(this.result.fg&50331648){case 16777216:case 33554432:H=this._themeService.colors.ansi[this.result.fg&255].rgba;break;case 50331648:H=(this.result.fg&16777215)<<8|255;break;case 0:default:H=this._themeService.colors.foreground.rgba}else switch(this.result.bg&50331648){case 16777216:case 33554432:H=this._themeService.colors.ansi[this.result.bg&255].rgba;break;case 50331648:H=(this.result.bg&16777215)<<8|255;break}H=d0.blend(H,(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba&4294967040|128)>>8&16777215}else H=(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba>>8&16777215;if(_0=!0,z.selectionForeground&&(k=z.selectionForeground.rgba>>8&16777215,T0=!0),V0(e.getCode())){if(this.result.fg&67108864&&(this.result.bg&50331648)===0)k=(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba>>8&16777215;else{if(this.result.fg&67108864)switch(this.result.bg&50331648){case 16777216:case 33554432:k=this._themeService.colors.ansi[this.result.bg&255].rgba;break;case 50331648:k=(this.result.bg&16777215)<<8|255;break}else switch(this.result.fg&50331648){case 16777216:case 33554432:k=this._themeService.colors.ansi[this.result.fg&255].rgba;break;case 50331648:k=(this.result.fg&16777215)<<8|255;break;case 0:default:k=this._themeService.colors.foreground.rgba}k=d0.blend(k,(this._coreBrowserService.isFocused?z.selectionBackgroundOpaque:z.selectionInactiveBackgroundOpaque).rgba&4294967040|128)>>8&16777215}T0=!0}}this._decorationService.forEachDecorationAtCell(t,r,"top",n=>{n.backgroundColorRGB&&(H=n.backgroundColorRGB.rgba>>8&16777215,_0=!0),n.foregroundColorRGB&&(k=n.foregroundColorRGB.rgba>>8&16777215,T0=!0)}),_0&&($0?H=e.bg&-16777216&-134217729|H|50331648:H=e.bg&-16777216|H|50331648),T0&&(k=e.fg&-16777216&-67108865|k|50331648),this.result.fg&67108864&&(_0&&!T0&&((this.result.bg&50331648)===0?k=this.result.fg&-134217728|z.background.rgba>>8&16777215&16777215|50331648:k=this.result.fg&-134217728|this.result.bg&67108863,T0=!0),!_0&&T0&&((this.result.fg&50331648)===0?H=this.result.bg&-67108864|z.foreground.rgba>>8&16777215&16777215|50331648:H=this.result.bg&-67108864|this.result.fg&67108863,_0=!0)),z=void 0,this.result.bg=_0?H:this.result.bg,this.result.fg=T0?k:this.result.fg,this.result.ext&=536870911,this.result.ext|=x0<<29&3758096384}};var Ke=.5,K0=Be||we?"bottom":"ideographic";function qe(i,e,t,r,s,a,o,n,L,T,h,d,_=0){let p=Ve[e];if(p){let c=Array.isArray(p)?p:[p];for(let u of c)Pt(i,u,t,r,s,a,o,n,L,T,h,d,_);return!0}return!1}function Pt(i,e,t,r,s,a,o,n,L,T,h,d,_=0){let p=s,c=a,u=t,C=r;switch(e.scaleType===1&&(p=o,c=n,u=t+(s-o)/2,C=r+(a-n)/2),e.clipPath&&(i.save(),Vt(i,e.clipPath,u,C,p,c)),e.type){case 0:Bt(i,e.data,u,C,p,c);break;case 1:Ut(i,e.data,u,C,p,c,_);break;case 2:Wt(i,e.data,u,C,p,c,T,h,e.strokeWidth);break;case 3:Ht(i,e.data,u,C,p,c,T,e.strokeWidth);break;case 4:Zt(i,e.data,u,C,p,c,T,d);break;case 5:$t(i,e.data,u,C,p,c,L,T,h);break;case 6:wt(i,e.data,u,C,p,c);break}e.clipPath&&i.restore()}function Bt(i,e,t,r,s,a){for(let o=0;o{let F=parseFloat(m);return R%2===0?t+F*s:r+F*a});if(u==="M")i.moveTo(Q[0],Q[1]),T=Q[0],h=Q[1],d=T,_=h;else if(u==="L")i.lineTo(Q[0],Q[1]),T=Q[0],h=Q[1],d=T,_=h;else if(u==="Q")i.quadraticCurveTo(Q[0],Q[1],Q[2],Q[3]),d=Q[0],_=Q[1],T=Q[2],h=Q[3];else if(u==="T"){let m,R;p==="Q"||p==="T"?(m=2*T-d,R=2*h-_):(m=T,R=h),i.quadraticCurveTo(m,R,Q[0],Q[1]),d=m,_=R,T=Q[0],h=Q[1]}else u==="C"&&(i.bezierCurveTo(Q[0],Q[1],Q[2],Q[3],Q[4],Q[5]),d=Q[2],_=Q[3],T=Q[4],h=Q[5]);p=u}n!==void 0?(i.strokeStyle=i.fillStyle,i.lineWidth=o*n,i.stroke()):i.fill()}function kt(i,e,t,r,s,a,o,n,L,T){if(r===0||s===0){i.lineTo(L,T);return}r=Math.abs(r),s=Math.abs(s);let h=Math.cos(a),d=Math.sin(a),_=(e-L)/2,p=(t-T)/2,c=h*_+d*p,u=-d*_+h*p,C=r*r,Q=s*s,m=c*c,R=u*u,F=m/C+R/Q;if(F>1){let I=Math.sqrt(F);r*=I,s*=I,C=r*r,Q=s*s}let E=(C*Q-C*R-Q*m)/(C*R+Q*m);E<0&&(E=0);let y=(o===n?-1:1)*Math.sqrt(E),Y=y*(r*u/s),X=y*-(s*c/r),A0=h*Y-d*X+(e+L)/2,t0=d*Y+h*X+(t+T)/2,L0=(c-Y)/r,A=(u-X)/s,n0=(-c-Y)/r,a0=(-u-X)/s,$=Math.atan2(A,L0),q=Math.atan2(a0,n0)-$;n===0&&q>0?q-=2*Math.PI:n===1&&q<0&&(q+=2*Math.PI);let g0=$+q;i.ellipse(A0,t0,r,s,a,$,g0,n===0)}function Zt(i,e,t,r,s,a,o,n){i.save(),i.fillRect(t,r,s,a),n&&(i.fillStyle=n,i.strokeStyle=n),i.lineWidth=o,i.lineCap="square",i.beginPath();for(let L of e.d.split(" ")){let T=L[0],h=L.substring(1).split(",");if(!h[0]||!h[1]){T==="Z"&&i.closePath();continue}let d=h.map((_,p)=>{let c=parseFloat(_);return p%2===0?t+c*s:r+c*a});T==="M"?i.moveTo(d[0],d[1]):T==="L"&&i.lineTo(d[0],d[1])}e.type===1?i.stroke():i.fill(),i.restore()}var Xe=new Map;function Ut(i,e,t,r,s,a,o=0){let n=Xe.get(e);n||(n=new Map,Xe.set(e,n));let L=i.fillStyle;if(typeof L!="string")throw new Error(`Unexpected fillStyle type "${L}"`);let T=n.get(L);if(!T){let _=e[0].length,p=e.length,c=i.canvas.ownerDocument.createElement("canvas");c.width=_,c.height=p;let u=g(c.getContext("2d")),C=new ImageData(_,p),Q,m,R,F;if(L.startsWith("#"))Q=parseInt(L.slice(1,3),16),m=parseInt(L.slice(3,5),16),R=parseInt(L.slice(5,7),16),F=L.length>7&&parseInt(L.slice(7,9),16)||1;else if(L.startsWith("rgba"))[Q,m,R,F]=L.substring(5,L.length-1).split(",").map(E=>parseFloat(E));else throw new Error(`Unexpected fillStyle color format "${L}" when drawing pattern glyph`);for(let E=0;E>1&1,d=o&1;h!==0||d!==0?T.setTransform(new DOMMatrix().translateSelf(-h,-d)):T.setTransform(new DOMMatrix),i.fillStyle=T,i.fillRect(t,r,s,a)}function Wt(i,e,t,r,s,a,o,n,L){i.save(),i.beginPath(),i.rect(t,r,s,a),i.clip(),i.beginPath();let T;if(typeof e=="function"){let _=.15/a*s;T=e(.15,_)}else T=e;let h={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(let d of T.split(" ")){let _=d[0];if(_==="Z"){i.closePath(),h.lastCommand=_;continue}let p=je[_];if(!p){n.error(`Could not find drawing instructions for "${_}"`);continue}let c=d.substring(1).split(",");!c[0]||!c[1]||(p(i,Je(c,s,a,t,r,!0,o,0,0,!1),h),h.lastCommand=_)}L!==void 0?(i.strokeStyle=i.fillStyle,i.lineWidth=o*L,i.stroke()):i.fill(),i.closePath(),i.restore()}function Vt(i,e,t,r,s,a){i.beginPath();for(let o of e.split(" ")){let n=o[0];if(n==="Z"){i.closePath();continue}let L=o.substring(1).split(",");if(!L[0]||!L[1])continue;let T=t+parseFloat(L[0])*s,h=r+parseFloat(L[1])*a;n==="M"?i.moveTo(T,h):n==="L"&&i.lineTo(T,h)}i.clip()}function $t(i,e,t,r,s,a,o,n,L){let T=new Path2D;T.rect(t,r,s,a),i.clip(T),i.beginPath();let h=o/12;i.lineWidth=n*h;let d={currentX:0,currentY:0,lastControlX:0,lastControlY:0,lastCommand:""};for(let _ of e.d.split(" ")){let p=_[0];if(p==="Z"){i.closePath(),d.lastCommand=p;continue}let c=je[p];if(!c){L.error(`Could not find drawing instructions for "${p}"`);continue}let u=_.substring(1).split(",");!u[0]||!u[1]||(c(i,Je(u,s,a,t,r,!1,n,(e.leftPadding??0)*(h/2),(e.rightPadding??0)*(h/2)),d),d.lastCommand=p)}e.type===1?(i.strokeStyle=i.fillStyle,i.stroke()):i.fill(),i.closePath()}function Ye(i,e,t=0){return Math.max(Math.min(i,e),t)}var je={C:(i,e,t)=>{i.bezierCurveTo(e[0],e[1],e[2],e[3],e[4],e[5]),t.lastControlX=e[2],t.lastControlY=e[3],t.currentX=e[4],t.currentY=e[5]},L:(i,e,t)=>{i.lineTo(e[0],e[1]),t.lastControlX=t.currentX=e[0],t.lastControlY=t.currentY=e[1]},M:(i,e,t)=>{i.moveTo(e[0],e[1]),t.lastControlX=t.currentX=e[0],t.lastControlY=t.currentY=e[1]},Q:(i,e,t)=>{i.quadraticCurveTo(e[0],e[1],e[2],e[3]),t.lastControlX=e[0],t.lastControlY=e[1],t.currentX=e[2],t.currentY=e[3]},T:(i,e,t)=>{let r,s;t.lastCommand==="Q"||t.lastCommand==="T"?(r=2*t.currentX-t.lastControlX,s=2*t.currentY-t.lastControlY):(r=t.currentX,s=t.currentY),i.quadraticCurveTo(r,s,e[0],e[1]),t.lastControlX=r,t.lastControlY=s,t.currentX=e[0],t.currentY=e[1]}};function Je(i,e,t,r,s,a,o,n=0,L=0,T=!0){let h=i.map(d=>parseFloat(d)||parseInt(d));if(h.length<2)throw new Error("Too few arguments for instruction");for(let d=0;da){s-t<-20&&this._logService.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=a}this.clear()}},Ce=class extends X0{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Qe=class extends X0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},et="requestIdleCallback"in globalThis?Qe:Ce;var s0=class i{constructor(){this.fg=0;this.bg=0;this.extended=new P0}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let e=new i;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},P0=class i{constructor(e=0,t=0){this._ext=0;this._urlId=0;this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new i(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}};var U=class{constructor(){this._listeners=[];this._disposed=!1}get event(){return this._event?this._event:(this._event=(e,t,r)=>{if(this._disposed)return M(()=>{});let s={fn:e,thisArgs:t};this._listeners.push(s);let a=M(()=>{let o=this._listeners.indexOf(s);o!==-1&&this._listeners.splice(o,1)});return r&&(Array.isArray(r)?r.push(a):r.add(a)),a},this._event)}fire(e){if(!this._disposed)switch(this._listeners.length){case 0:return;case 1:{let{fn:t,thisArgs:r}=this._listeners[0];t.call(r,e);return}default:{let t=this._listeners.slice();for(let{fn:r,thisArgs:s}of t)r.call(s,e)}}}dispose(){this._disposed||(this._disposed=!0,this._listeners.length=0)}},c0;(s=>{function i(a,o){return a(n=>o.fire(n))}s.forward=i;function e(a,o){return(n,L,T)=>a(h=>n.call(L,o(h)),void 0,T)}s.map=e;function t(...a){return(o,n,L)=>{let T=new R0;for(let h of a)T.add(h(d=>o.call(n,d)));return L&&(Array.isArray(L)?L.push(T):L.add(T)),T}}s.any=t;function r(a,o,n){return o(n),a(L=>o(L))}s.runAndSubscribe=r})(c0||={});var tt={texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},offset:{x:0,y:0},size:{x:0,y:0},sizeClipSpace:{x:0,y:0}},B0=2;var w0,J=class i{constructor(e,t,r,s){this._document=e;this._config=t;this._unicodeService=r;this._logService=s;this._didWarmUp=!1;this._cacheMap=new D0;this._cacheMapCombined=new D0;this._pages=[];this._activePages=[];this._workBoundingBox={top:0,left:0,bottom:0,right:0};this._workAttributeData=new s0;this._textureSize=512;this._onAddTextureAtlasCanvas=new U;this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event;this._onRemoveTextureAtlasCanvas=new U;this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event;this._requestClearModel=!1;this._clearModelGeneration=0;this._createNewPage(),this._tmpCanvas=it(e,this._config.deviceCellWidth*4+B0*2,this._config.deviceCellHeight+B0*2),this._tmpCtx=g(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:!0}))}get pages(){return this._pages}dispose(){this._tmpCanvas.remove();for(let e of this.pages)e.canvas.remove();this._onAddTextureAtlasCanvas.dispose(),this._onRemoveTextureAtlasCanvas.dispose()}warmUp(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)}_doWarmUp(){let e=new et(this._logService);for(let t=33;t<126;t++)e.enqueue(()=>{if(!this._cacheMap.get(t,0,0,0)){let r=this._drawToCache(t,0,0,0,!1,void 0);this._cacheMap.set(t,0,0,0,r)}})}beginFrame(){let e=this._requestClearModel;return this._requestClearModel=!1,e}clearTexture(){if(this._pages.some(e=>e._glyphs.length>0||e.currentRow.x!==0||e.currentRow.y!==0)){for(let e of this._pages)e.clear();this._activePages.length=0;for(let e of this._pages)e!==this._overflowSizePage&&this._activePages.push(e);this._cacheMap.clear(),this._cacheMapCombined.clear(),this._didWarmUp=!1,this._requestClearModel=!0,this._clearModelGeneration++}}_createNewPage(){if(i.maxAtlasPages&&this._pages.length>=Math.max(4,i.maxAtlasPages)){let t=this._pages.filter(T=>T.canvas.width*2<=(i.maxTextureSize||4096)).sort((T,h)=>h.canvas.width!==T.canvas.width?h.canvas.width-T.canvas.width:h.percentageUsed-T.percentageUsed),r=-1,s=0;for(let T=0;TT.canvas.width!==a[0].canvas.width)){let T=new u0(this._document,this._textureSize);return this._pages.push(T),this._activePages.push(T),this._onAddTextureAtlasCanvas.fire(T.canvas),T}let o=a.map(T=>T.glyphs[0].texturePage).sort((T,h)=>T-h),n=this.pages.length-a.length,L=this._mergePages(a,n);L.version=++u0.nextVersion;for(let T=o.length-1;T>=0;T--)this._deletePage(o[T]);this.pages.push(L),this._requestClearModel=!0,this._clearModelGeneration++,this._onAddTextureAtlasCanvas.fire(L.canvas)}let e=new u0(this._document,this._textureSize);return this._pages.push(e),this._activePages.push(e),this._onAddTextureAtlasCanvas.fire(e.canvas),e}_mergePages(e,t){let r=e[0].canvas.width*2,s=new u0(this._document,r,e);for(let[a,o]of e.entries()){let n=a*o.canvas.width%r,L=Math.floor(a/2)*o.canvas.height;s.ctx.drawImage(o.canvas,n,L);for(let h of o.glyphs)h.texturePage=t,h.sizeClipSpace.x=h.size.x/r,h.sizeClipSpace.y=h.size.y/r,h.texturePosition.x+=n,h.texturePosition.y+=L,h.texturePositionClipSpace.x=h.texturePosition.x/r,h.texturePositionClipSpace.y=h.texturePosition.y/r;this._onRemoveTextureAtlasCanvas.fire(o.canvas);let T=this._activePages.indexOf(o);T!==-1&&this._activePages.splice(T,1)}return s}_deletePage(e){this._pages.splice(e,1);for(let t=e;t=this._config.colors.ansi.length)throw new Error("No color found for idx "+e);return this._config.colors.ansi[e]}_getBackgroundColor(e,t,r,s){if(this._config.allowTransparency)return K;let a;switch(e){case 16777216:case 33554432:a=this._getColorFromAnsiIndex(t);break;case 50331648:let o=s0.toColorRGB(t);a=Z.toColor(o[0],o[1],o[2]);break;case 0:default:r?a=I0.opaque(this._config.colors.foreground):a=this._config.colors.background;break}return this._config.allowTransparency||(a=I0.opaque(a)),a}_getForegroundColor(e,t,r,s,a,o,n,L,T,h){let d=this._getMinimumContrastColor(e,t,r,s,a,o,n,T,L,h);if(d)return d;let _;switch(a){case 16777216:case 33554432:this._config.drawBoldTextInBrightColors&&T&&o<8&&(o+=8),_=this._getColorFromAnsiIndex(o);break;case 50331648:let p=s0.toColorRGB(o);_=Z.toColor(p[0],p[1],p[2]);break;case 0:default:n?_=this._config.colors.background:_=this._config.colors.foreground}return this._config.allowTransparency&&(_=I0.opaque(_)),L&&(_=I0.multiplyOpacity(_,Ke)),_}_resolveBackgroundRgba(e,t,r){switch(e){case 16777216:case 33554432:return this._getColorFromAnsiIndex(t).rgba;case 50331648:return t<<8;case 0:default:return r?this._config.colors.foreground.rgba:this._config.colors.background.rgba}}_resolveForegroundRgba(e,t,r,s){switch(e){case 16777216:case 33554432:return this._config.drawBoldTextInBrightColors&&s&&t<8&&(t+=8),this._getColorFromAnsiIndex(t).rgba;case 50331648:return t<<8;case 0:default:return r?this._config.colors.background.rgba:this._config.colors.foreground.rgba}}_getMinimumContrastColor(e,t,r,s,a,o,n,L,T,h){if(this._config.minimumContrastRatio===1||h)return;let d=this._getContrastCache(T),_=d.getColor(e,s);if(_!==void 0)return _??void 0;let p=this._resolveBackgroundRgba(t,r,n),c=this._resolveForegroundRgba(a,o,n,L),u=d0.ensureContrastRatio(p,c,this._config.minimumContrastRatio/(T?2:1));if(!u){d.setColor(e,s,null);return}let C=Z.toColor(u>>24&255,u>>16&255,u>>8&255);return d.setColor(e,s,C),C}_getContrastCache(e){return e?this._config.colors.halfContrastCache:this._config.colors.contrastCache}_drawToCache(e,t,r,s,a,o){let n=typeof e=="number"?String.fromCharCode(e):e;o&&this._tmpCanvas.parentElement!==o&&(this._tmpCanvas.style.display="none",o.append(this._tmpCanvas));let L=Math.min(this._config.deviceCellWidth*Math.max(n.length,2)+B0*2,this._config.deviceMaxTextureSize);this._tmpCanvas.width=b?b*2-f0:b-f0;!(f0>=b)===!1||Z0===0?(this._tmpCtx.setLineDash([Math.round(b),Math.round(b)]),this._tmpCtx.moveTo(j+Z0,G),this._tmpCtx.lineTo(Q0,G)):(this._tmpCtx.setLineDash([Math.round(b),Math.round(b)]),this._tmpCtx.moveTo(j,G),this._tmpCtx.lineTo(j+Z0,G),this._tmpCtx.moveTo(j+Z0+b,G),this._tmpCtx.lineTo(Q0,G)),f0=We(Q0-j,b,f0);break;case 5:let vt=.6,Ot=.3,de=Q0-j,Se=Math.floor(vt*de),Re=Math.floor(Ot*de),It=de-Se-Re;this._tmpCtx.setLineDash([Se,Re,It]),this._tmpCtx.moveTo(j,G),this._tmpCtx.lineTo(Q0,G);break;case 1:default:this._tmpCtx.moveTo(j,G),this._tmpCtx.lineTo(Q0,G);break}y0||this._tmpCtx.stroke(),this._tmpCtx.restore()}if(this._tmpCtx.restore(),!n0&&this._config.fontSize>=12&&!this._config.allowTransparency&&n!==" "){this._tmpCtx.save(),this._tmpCtx.textBaseline="alphabetic";let r0=this._tmpCtx.measureText(n);if(this._tmpCtx.restore(),"actualBoundingBoxDescent"in r0&&r0.actualBoundingBoxDescent>0){this._tmpCtx.save();let y0=new Path2D;y0.rect(i0,C0-Math.ceil(b/2),this._config.deviceCellWidth*$,v0-C0+Math.ceil(b/2)),this._tmpCtx.clip(y0),this._tmpCtx.lineWidth=this._config.devicePixelRatio*3,this._tmpCtx.strokeStyle=y.css,this._tmpCtx.strokeText(n,A,A+this._config.deviceCharHeight),this._tmpCtx.restore()}}}if(Q){let b=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/15)),D=b%2===1?.5:0;this._tmpCtx.lineWidth=b,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(A,A+D),this._tmpCtx.lineTo(A+this._config.deviceCharWidth*$,A+D),this._tmpCtx.stroke()}if(n0||this._tmpCtx.fillText(n,A,A+this._config.deviceCharHeight),n==="_"&&!this._config.allowTransparency){let b=fe(this._tmpCtx.getImageData(A,A,this._config.deviceCellWidth,this._config.deviceCellHeight),y,L0,a0);if(b)for(let D=1;D<=5&&(this._tmpCtx.save(),this._tmpCtx.fillStyle=y.css,this._tmpCtx.fillRect(0,0,this._tmpCanvas.width,this._tmpCanvas.height),this._tmpCtx.restore(),this._tmpCtx.fillText(n,A,A+this._config.deviceCharHeight-D),b=fe(this._tmpCtx.getImageData(A,A,this._config.deviceCellWidth,this._config.deviceCellHeight),y,L0,a0),!!b);D++);}if(C){let b=Math.max(1,Math.floor(this._config.fontSize*this._config.devicePixelRatio/10)),D=this._tmpCtx.lineWidth%2===1?.5:0;this._tmpCtx.lineWidth=b,this._tmpCtx.strokeStyle=this._tmpCtx.fillStyle,this._tmpCtx.beginPath(),this._tmpCtx.moveTo(A,A+Math.floor(this._config.deviceCharHeight/2)-D),this._tmpCtx.lineTo(A+this._config.deviceCharWidth*$,A+Math.floor(this._config.deviceCharHeight/2)-D),this._tmpCtx.stroke()}this._tmpCtx.restore();let q=this._tmpCtx.getImageData(0,0,this._tmpCanvas.width,this._tmpCanvas.height),g0;if(this._config.allowTransparency?g0=Gt(q):g0=fe(q,y,L0,a0),g0)return tt;let I=this._findGlyphBoundingBox(q,this._workBoundingBox,L,t0,n0,A),O,v;for(;;){if(this._activePages.length===0){let b=this._createNewPage();O=b,v=b.currentRow,v.height=I.size.y;break}O=this._activePages[this._activePages.length-1],v=O.currentRow;for(let b of this._activePages)I.size.y<=b.currentRow.height&&(O=b,v=b.currentRow);for(let b=this._activePages.length-1;b>=0;b--)for(let D of this._activePages[b].fixedRows)D.height<=v.height&&I.size.y<=D.height&&(O=this._activePages[b],v=D);if(I.size.x>this._textureSize){this._overflowSizePage||(this._overflowSizePage=new u0(this._document,this._config.deviceMaxTextureSize),this.pages.push(this._overflowSizePage),this._requestClearModel=!0,this._clearModelGeneration++,this._onAddTextureAtlasCanvas.fire(this._overflowSizePage.canvas)),O=this._overflowSizePage,v=this._overflowSizePage.currentRow,v.x+I.size.x>=O.canvas.width&&(v.x=0,v.y+=v.height,v.height=0);break}if(v.y+I.size.y>=O.canvas.height||v.height>I.size.y+2){let b=!1;if(O.currentRow.y+O.currentRow.height+I.size.y>=O.canvas.height){let D;for(let i0 of this._activePages)if(i0.currentRow.y+i0.currentRow.height+I.size.y=i.maxAtlasPages&&v.y+I.size.y<=O.canvas.height&&v.height>=I.size.y&&v.x+I.size.x<=O.canvas.width)b=!0;else{let i0=this._createNewPage();O=i0,v=i0.currentRow,v.height=I.size.y,b=!0}}b||(O.currentRow.height>0&&O.fixedRows.push(O.currentRow),v={x:0,y:O.currentRow.y+O.currentRow.height,height:I.size.y},O.fixedRows.push(v),O.currentRow={x:0,y:v.y+v.height,height:0})}if(v.x+I.size.x<=O.canvas.width)break;v===O.currentRow?(v.x=0,v.y+=v.height,v.height=0):O.fixedRows.splice(O.fixedRows.indexOf(v),1)}return I.texturePage=this._pages.indexOf(O),I.texturePosition.x=v.x,I.texturePosition.y=v.y,I.texturePositionClipSpace.x=v.x/O.canvas.width,I.texturePositionClipSpace.y=v.y/O.canvas.height,I.sizeClipSpace.x/=O.canvas.width,I.sizeClipSpace.y/=O.canvas.height,v.height=Math.max(v.height,I.size.y),v.x+=I.size.x,O.ctx.putImageData(q,I.texturePosition.x-this._workBoundingBox.left,I.texturePosition.y-this._workBoundingBox.top,this._workBoundingBox.left,this._workBoundingBox.top,I.size.x,I.size.y),O.addGlyph(I),O.version=++u0.nextVersion,I}_findGlyphBoundingBox(e,t,r,s,a,o){t.top=0;let n=s?this._config.deviceCellHeight:this._tmpCanvas.height,L=s?this._config.deviceCellWidth:r,T=!1;for(let h=0;h=o;h--){for(let d=0;d=0;h--){for(let d=0;d>>24,a=e.rgba>>>16&255,o=e.rgba>>>8&255,n=t.rgba>>>24,L=t.rgba>>>16&255,T=t.rgba>>>8&255,h=Math.floor((Math.abs(s-n)+Math.abs(a-L)+Math.abs(o-T))/12),d=!0;for(let _=0;_0)return!1;return!0}function it(i,e,t){let r=i.createElement("canvas");return r.width=e,r.height=t,r}function rt(i,e,t,r,s,a,o,n,L=!0){let T={foreground:a.foreground,background:a.background,cursor:K,cursorAccent:K,selectionForeground:K,selectionBackgroundTransparent:K,selectionBackgroundOpaque:K,selectionInactiveBackgroundTransparent:K,selectionInactiveBackgroundOpaque:K,overviewRulerBorder:K,scrollbarSliderBackground:K,scrollbarSliderHoverBackground:K,scrollbarSliderActiveBackground:K,ansi:a.ansi.slice(),contrastCache:a.contrastCache,halfContrastCache:a.halfContrastCache};return{customGlyphs:L,devicePixelRatio:o,deviceMaxTextureSize:n,letterSpacing:s.letterSpacing,lineHeight:s.lineHeight,deviceCellWidth:i,deviceCellHeight:e,deviceCharWidth:t,deviceCharHeight:r,fontFamily:s.fontFamily,fontSize:s.fontSize,fontWeight:s.fontWeight,fontWeightBold:s.fontWeightBold,allowTransparency:s.allowTransparency,drawBoldTextInBrightColors:s.drawBoldTextInBrightColors,minimumContrastRatio:s.minimumContrastRatio,colors:T}}function Ee(i,e){for(let t=0;t=0){if(Ee(u.config,h))return u.atlas;u.ownedBy.length===1?(u.atlas.dispose(),e0.splice(c,1)):u.ownedBy.splice(C,1);break}}for(let c=0;c{this._renderCallback(),this._animationFrame=void 0})))}_restartInterval(e=600){this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout=this._coreBrowserService.window.setTimeout(()=>{if(this._animationTimeRestarted){let t=600-(Date.now()-this._animationTimeRestarted);if(this._animationTimeRestarted=void 0,t>0){this._restartInterval(t);return}}this.isCursorVisible=!1,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0}),this._blinkInterval=this._coreBrowserService.window.setInterval(()=>{if(this._animationTimeRestarted){let t=600-(Date.now()-this._animationTimeRestarted);this._animationTimeRestarted=void 0,this._restartInterval(t);return}this.isCursorVisible=!this.isCursorVisible,this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._renderCallback(),this._animationFrame=void 0})},600)},e)}pause(){this.isCursorVisible=!0,this._isIdlePaused=!1,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._idleTimeout&&(this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0)}resume(){this.pause(),this._animationTimeRestarted=void 0,this._restartInterval(),this._resetIdleTimer(),this.restartBlinkAnimation()}_resetIdleTimer(){this._isIdlePaused=!1,this._idleTimeout&&this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=this._coreBrowserService.window.setTimeout(()=>{this._stopBlinkingDueToIdle()},3e5)}_stopBlinkingDueToIdle(){this.isCursorVisible=!0,this._isIdlePaused=!0,this._blinkInterval&&(this._coreBrowserService.window.clearInterval(this._blinkInterval),this._blinkInterval=void 0),this._blinkStartTimeout&&(this._coreBrowserService.window.clearTimeout(this._blinkStartTimeout),this._blinkStartTimeout=void 0),this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0),this._coreBrowserService.window.clearTimeout(this._idleTimeout),this._idleTimeout=void 0,this._renderCallback()}};function ve(i,e,t){let r=new e.ResizeObserver(s=>{let a=s.find(L=>L.target===i);if(!a)return;if(!("devicePixelContentBoxSize"in a)){r?.disconnect(),r=void 0;return}let o=a.devicePixelContentBoxSize[0].inlineSize,n=a.devicePixelContentBoxSize[0].blockSize;o>0&&n>0&&t(o,n)});try{r.observe(i,{box:["device-pixel-content-box"]})}catch{r.disconnect(),r=void 0}return M(()=>r?.disconnect())}function nt(i){return i>65535?(i-=65536,String.fromCharCode((i>>10)+55296)+String.fromCharCode(i%1024+56320)):String.fromCharCode(i)}var j0=class i extends s0{constructor(){super(...arguments);this.content=0;this.fg=0;this.bg=0;this.extended=new P0;this.combinedData=""}static fromCharData(t){let r=new i;return r.setFromCharData(t),r}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?nt(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let r=!1;if(t[1].length>2)r=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:r=!0}else r=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;r&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}attributesEquals(t){if(this.getFgColorMode()!==t.getFgColorMode()||this.getFgColor()!==t.getFgColor()||this.getBgColorMode()!==t.getBgColorMode()||this.getBgColor()!==t.getBgColor()||this.isInverse()!==t.isInverse()||this.isBold()!==t.isBold()||this.isUnderline()!==t.isUnderline())return!1;if(this.isUnderline()){if(this.getUnderlineStyle()!==t.getUnderlineStyle())return!1;let r=this.isUnderlineColorDefault(),s=t.isUnderlineColorDefault();if(!(r&&s)&&(r!==s||this.getUnderlineColor()!==t.getUnderlineColor()||this.getUnderlineColorMode()!==t.getUnderlineColorMode()))return!1}return!(this.isOverline()!==t.isOverline()||this.isBlink()!==t.isBlink()||this.isInvisible()!==t.isInvisible()||this.isItalic()!==t.isItalic()||this.isDim()!==t.isDim()||this.isStrikethrough()!==t.isStrikethrough())}};var J0=class extends W{constructor(t,r,s){super();this._renderCallback=t;this._coreBrowserService=r;this._optionsService=s;this._intervalDuration=0;this._blinkOn=!0;this._needsBlinkInViewport=!1;this._isViewportVisible=!0;this._register(this._optionsService.onSpecificOptionChange("blinkIntervalDuration",a=>{this.setIntervalDuration(a)})),this.setIntervalDuration(this._optionsService.rawOptions.blinkIntervalDuration),this._register(M(()=>this._clearInterval()))}get isBlinkOn(){return this._blinkOn}get isEnabled(){return this._intervalDuration>0}setNeedsBlinkInViewport(t){this._needsBlinkInViewport!==t&&(this._needsBlinkInViewport=t,this._updateIntervalState())}setViewportVisible(t){this._isViewportVisible!==t&&(this._isViewportVisible=t,this._updateIntervalState())}setIntervalDuration(t){t!==this._intervalDuration&&(this._intervalDuration=t,this._clearInterval(),this._updateIntervalState())}_updateIntervalState(){if(this._intervalDuration>0&&this._needsBlinkInViewport&&this._isViewportVisible){if(this._interval!==void 0)return;let r=this._blinkOn;this._blinkOn=!0,this._interval=this._coreBrowserService.window.setInterval(()=>{this._blinkOn=!this._blinkOn,this._renderCallback()},this._intervalDuration),r||this._renderCallback();return}this._clearInterval(),this._blinkOn||(this._blinkOn=!0,this._renderCallback())}_clearInterval(){this._interval!==void 0&&(this._coreBrowserService.window.clearInterval(this._interval),this._interval=void 0)}};var te=new Float32Array([2,0,0,0,0,-2,0,0,0,0,1,0,-1,1,0,1]);function ie(i,e,t,r){let s=g(i.createProgram());if(i.attachShader(s,g(at(i,i.VERTEX_SHADER,e,r))),i.attachShader(s,g(at(i,i.FRAGMENT_SHADER,t,r))),i.linkProgram(s),i.getProgramParameter(s,i.LINK_STATUS))return s;r.error(i.getProgramInfoLog(s)),i.deleteProgram(s)}function at(i,e,t,r){let s=g(i.createShader(e));if(i.shaderSource(s,t),i.compileShader(s),i.getShaderParameter(s,i.COMPILE_STATUS))return s;r.error(i.getShaderInfoLog(s)),i.deleteShader(s)}function ot(i,e){let t=Math.min(i.length*2,e),r=new Float32Array(t);for(let s=0;sn.deleteProgram(this._program))),this._projectionLocation=g(n.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=g(n.getUniformLocation(this._program,"u_resolution")),this._textureLocation=g(n.getUniformLocation(this._program,"u_texture"));let L=this._vertexArrayObject=n.createVertexArray();this._register(M(()=>n.deleteVertexArray(L))),n.bindVertexArray(L);let T=new Float32Array([0,0,1,0,0,1,1,1]),h=n.createBuffer();this._register(M(()=>n.deleteBuffer(h))),n.bindBuffer(n.ARRAY_BUFFER,h),n.bufferData(n.ARRAY_BUFFER,T,n.STATIC_DRAW),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,2,this._gl.FLOAT,!1,0,0);let d=new Uint8Array([0,1,2,3]),_=n.createBuffer();this._register(M(()=>n.deleteBuffer(_))),n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,_),n.bufferData(n.ELEMENT_ARRAY_BUFFER,d,n.STATIC_DRAW),this._attributesBuffer=g(n.createBuffer()),this._register(M(()=>n.deleteBuffer(this._attributesBuffer))),n.bindBuffer(n.ARRAY_BUFFER,this._attributesBuffer),n.enableVertexAttribArray(2),n.vertexAttribPointer(2,2,n.FLOAT,!1,44,0),n.vertexAttribDivisor(2,1),n.enableVertexAttribArray(3),n.vertexAttribPointer(3,2,n.FLOAT,!1,44,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(3,1),n.enableVertexAttribArray(4),n.vertexAttribPointer(4,1,n.FLOAT,!1,44,4*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(4,1),n.enableVertexAttribArray(5),n.vertexAttribPointer(5,2,n.FLOAT,!1,44,5*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(5,1),n.enableVertexAttribArray(6),n.vertexAttribPointer(6,2,n.FLOAT,!1,44,7*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(6,1),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,!1,44,9*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(1,1),n.useProgram(this._program);let p=new Int32Array(J.maxAtlasPages);for(let c=0;cn.deleteTexture(u.texture))),n.activeTexture(n.TEXTURE0+c),n.bindTexture(n.TEXTURE_2D,u.texture),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[c]=u}n.enable(n.BLEND),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){return this._atlas?this._atlas.beginFrame():!0}updateCell(t,r,s,a,o,n,L,T,h){this._updateCell(this._vertices.attributes,t,r,s,a,o,n,L,T,h)}_updateCell(t,r,s,a,o,n,L,T,h,d){if(N=(s*this._terminal.cols+r)*11,a===0||a===void 0){t.fill(0,N,N+11-1-2);return}this._atlas&&(T&&T.length>1?S=this._atlas.getRasterizedGlyphCombinedChar(T,o,n,L,!1,this._terminal.element):S=this._atlas.getRasterizedGlyph(a,o,n,L,!1,this._terminal.element),Ie=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),o!==d&&S.offset.x>Ie?(k0=S.offset.x-Ie,t[N]=-(S.offset.x-k0)+this._dimensions.device.char.left,t[N+1]=-S.offset.y+this._dimensions.device.char.top,t[N+2]=(S.size.x-k0)/this._dimensions.device.canvas.width,t[N+3]=S.size.y/this._dimensions.device.canvas.height,t[N+4]=S.texturePage,t[N+5]=S.texturePositionClipSpace.x+k0/this._atlas.pages[S.texturePage].canvas.width,t[N+6]=S.texturePositionClipSpace.y,t[N+7]=S.sizeClipSpace.x-k0/this._atlas.pages[S.texturePage].canvas.width,t[N+8]=S.sizeClipSpace.y):(t[N]=-S.offset.x+this._dimensions.device.char.left,t[N+1]=-S.offset.y+this._dimensions.device.char.top,t[N+2]=S.size.x/this._dimensions.device.canvas.width,t[N+3]=S.size.y/this._dimensions.device.canvas.height,t[N+4]=S.texturePage,t[N+5]=S.texturePositionClipSpace.x,t[N+6]=S.texturePositionClipSpace.y,t[N+7]=S.sizeClipSpace.x,t[N+8]=S.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&Ze(a,h,S.size.x,this._dimensions.device.cell.width)&&(t[N+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width))}clear(){let t=this._terminal,r=t.cols*t.rows*11;this._vertices.count!==r?this._vertices.attributes=new Float32Array(r):this._vertices.attributes.fill(0);let s=0;for(;s=e.rows||T<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=o,this.viewportEndRow=n,this.viewportCappedStartRow=L,this.viewportCappedEndRow=T,this.startCol=t[0],this.endCol=r[0]}isCellSelected(e,t,r){return this.hasSelection?(r-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&r>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&r<=this.viewportCappedEndRow:r>this.viewportStartRow&&r=this.startCol&&t=this.startCol):!1}};function Tt(){return new Fe}var lt=2147483648,se=class{constructor(){this.cells=new Uint32Array(0),this.lineLengths=new Uint32Array(0),this.selection=Tt()}resize(e,t){let r=e*t*4;r!==this.cells.length&&(this.cells=new Uint32Array(r),this.lineLengths=new Uint32Array(t))}clear(){this.cells.fill(0,0),this.lineLengths.fill(0,0)}};var jt=`#version 300 es -+}`}var N=0,S,Ie=0,k0=0,re=class extends W{constructor(t,r,s,a,o){super();this._terminal=t;this._gl=r;this._dimensions=s;this._optionsService=a;this._logService=o;this._activeBuffer=0;this._vertices={count:0,attributes:new Float32Array(0),attributesBuffers:[new Float32Array(0),new Float32Array(0)]};let n=this._gl;J.maxAtlasPages===void 0&&(J.maxAtlasPages=Math.min(32,g(n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS))),J.maxTextureSize=g(n.getParameter(n.MAX_TEXTURE_SIZE))),this._program=g(ie(n,Xt,Yt(J.maxAtlasPages),this._logService)),this._register(M(()=>n.deleteProgram(this._program))),this._projectionLocation=g(n.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=g(n.getUniformLocation(this._program,"u_resolution")),this._textureLocation=g(n.getUniformLocation(this._program,"u_texture"));let L=this._vertexArrayObject=n.createVertexArray();this._register(M(()=>n.deleteVertexArray(L))),n.bindVertexArray(L);let T=new Float32Array([0,0,1,0,0,1,1,1]),h=n.createBuffer();this._register(M(()=>n.deleteBuffer(h))),n.bindBuffer(n.ARRAY_BUFFER,h),n.bufferData(n.ARRAY_BUFFER,T,n.STATIC_DRAW),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,2,this._gl.FLOAT,!1,0,0);let d=new Uint8Array([0,1,2,3]),_=n.createBuffer();this._register(M(()=>n.deleteBuffer(_))),n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,_),n.bufferData(n.ELEMENT_ARRAY_BUFFER,d,n.STATIC_DRAW),this._attributesBuffer=g(n.createBuffer()),this._register(M(()=>n.deleteBuffer(this._attributesBuffer))),n.bindBuffer(n.ARRAY_BUFFER,this._attributesBuffer),n.enableVertexAttribArray(2),n.vertexAttribPointer(2,2,n.FLOAT,!1,44,0),n.vertexAttribDivisor(2,1),n.enableVertexAttribArray(3),n.vertexAttribPointer(3,2,n.FLOAT,!1,44,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(3,1),n.enableVertexAttribArray(4),n.vertexAttribPointer(4,1,n.FLOAT,!1,44,4*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(4,1),n.enableVertexAttribArray(5),n.vertexAttribPointer(5,2,n.FLOAT,!1,44,5*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(5,1),n.enableVertexAttribArray(6),n.vertexAttribPointer(6,2,n.FLOAT,!1,44,7*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(6,1),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,!1,44,9*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(1,1),n.useProgram(this._program);let p=new Int32Array(J.maxAtlasPages);for(let c=0;cn.deleteTexture(u.texture))),n.activeTexture(n.TEXTURE0+c),n.bindTexture(n.TEXTURE_2D,u.texture),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[c]=u}n.enable(n.BLEND),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){if(!this._atlas)return!0;let _g=this._atlas._clearModelGeneration||0;return this._lastSeenClearModelGeneration!==_g?(this._lastSeenClearModelGeneration=_g,!0):!1}updateCell(t,r,s,a,o,n,L,T,h){this._updateCell(this._vertices.attributes,t,r,s,a,o,n,L,T,h)}_updateCell(t,r,s,a,o,n,L,T,h,d){if(N=(s*this._terminal.cols+r)*11,a===0||a===void 0){t.fill(0,N,N+11-1-2);return}this._atlas&&(T&&T.length>1?S=this._atlas.getRasterizedGlyphCombinedChar(T,o,n,L,!1,this._terminal.element):S=this._atlas.getRasterizedGlyph(a,o,n,L,!1,this._terminal.element),Ie=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),o!==d&&S.offset.x>Ie?(k0=S.offset.x-Ie,t[N]=-(S.offset.x-k0)+this._dimensions.device.char.left,t[N+1]=-S.offset.y+this._dimensions.device.char.top,t[N+2]=(S.size.x-k0)/this._dimensions.device.canvas.width,t[N+3]=S.size.y/this._dimensions.device.canvas.height,t[N+4]=S.texturePage,t[N+5]=S.texturePositionClipSpace.x+k0/this._atlas.pages[S.texturePage].canvas.width,t[N+6]=S.texturePositionClipSpace.y,t[N+7]=S.sizeClipSpace.x-k0/this._atlas.pages[S.texturePage].canvas.width,t[N+8]=S.sizeClipSpace.y):(t[N]=-S.offset.x+this._dimensions.device.char.left,t[N+1]=-S.offset.y+this._dimensions.device.char.top,t[N+2]=S.size.x/this._dimensions.device.canvas.width,t[N+3]=S.size.y/this._dimensions.device.canvas.height,t[N+4]=S.texturePage,t[N+5]=S.texturePositionClipSpace.x,t[N+6]=S.texturePositionClipSpace.y,t[N+7]=S.sizeClipSpace.x,t[N+8]=S.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&Ze(a,h,S.size.x,this._dimensions.device.cell.width)&&(t[N+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width))}clear(){let t=this._terminal,r=t.cols*t.rows*11;this._vertices.count!==r?this._vertices.attributes=new Float32Array(r):this._vertices.attributes.fill(0);let s=0;for(;s=e.rows||T<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=o,this.viewportEndRow=n,this.viewportCappedStartRow=L,this.viewportCappedEndRow=T,this.startCol=t[0],this.endCol=r[0]}isCellSelected(e,t,r){return this.hasSelection?(r-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&r>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&r<=this.viewportCappedEndRow:r>this.viewportStartRow&&r=this.startCol&&t=this.startCol):!1}};function Tt(){return new Fe}var lt=2147483648,se=class{constructor(){this.cells=new Uint32Array(0),this.lineLengths=new Uint32Array(0),this.selection=Tt()}resize(e,t){let r=e*t*4;r!==this.cells.length&&(this.cells=new Uint32Array(r),this.lineLengths=new Uint32Array(t))}clear(){this.cells.fill(0,0),this.lineLengths.fill(0,0)}};var jt=`#version 300 es ++}`}var N=0,S,Ie=0,k0=0,re=class extends W{constructor(t,r,s,a,o){super();this._terminal=t;this._gl=r;this._dimensions=s;this._optionsService=a;this._logService=o;this._activeBuffer=0;this._vertices={count:0,attributes:new Float32Array(0),attributesBuffers:[new Float32Array(0),new Float32Array(0)]};let n=this._gl;J.maxAtlasPages===void 0&&(J.maxAtlasPages=Math.min(32,g(n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS))),J.maxTextureSize=g(n.getParameter(n.MAX_TEXTURE_SIZE))),this._program=g(ie(n,Xt,Yt(J.maxAtlasPages),this._logService)),this._register(M(()=>n.deleteProgram(this._program))),this._projectionLocation=g(n.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=g(n.getUniformLocation(this._program,"u_resolution")),this._textureLocation=g(n.getUniformLocation(this._program,"u_texture"));let L=this._vertexArrayObject=n.createVertexArray();this._register(M(()=>n.deleteVertexArray(L))),n.bindVertexArray(L);let T=new Float32Array([0,0,1,0,0,1,1,1]),h=n.createBuffer();this._register(M(()=>n.deleteBuffer(h))),n.bindBuffer(n.ARRAY_BUFFER,h),n.bufferData(n.ARRAY_BUFFER,T,n.STATIC_DRAW),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,2,this._gl.FLOAT,!1,0,0);let d=new Uint8Array([0,1,2,3]),_=n.createBuffer();this._register(M(()=>n.deleteBuffer(_))),n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,_),n.bufferData(n.ELEMENT_ARRAY_BUFFER,d,n.STATIC_DRAW),this._attributesBuffer=g(n.createBuffer()),this._register(M(()=>n.deleteBuffer(this._attributesBuffer))),n.bindBuffer(n.ARRAY_BUFFER,this._attributesBuffer),n.enableVertexAttribArray(2),n.vertexAttribPointer(2,2,n.FLOAT,!1,44,0),n.vertexAttribDivisor(2,1),n.enableVertexAttribArray(3),n.vertexAttribPointer(3,2,n.FLOAT,!1,44,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(3,1),n.enableVertexAttribArray(4),n.vertexAttribPointer(4,1,n.FLOAT,!1,44,4*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(4,1),n.enableVertexAttribArray(5),n.vertexAttribPointer(5,2,n.FLOAT,!1,44,5*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(5,1),n.enableVertexAttribArray(6),n.vertexAttribPointer(6,2,n.FLOAT,!1,44,7*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(6,1),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,!1,44,9*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(1,1),n.useProgram(this._program);let p=new Int32Array(J.maxAtlasPages);for(let c=0;cn.deleteTexture(u.texture))),n.activeTexture(n.TEXTURE0+c),n.bindTexture(n.TEXTURE_2D,u.texture),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[c]=u}n.enable(n.BLEND),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){if(!this._atlas)return!0;let _g=this._atlas._clearModelGeneration||0;return this._lastSeenClearModelGeneration!==_g?(this._lastSeenClearModelGeneration=_g,!0):!1}updateCell(t,r,s,a,o,n,L,T,h){this._updateCell(this._vertices.attributes,t,r,s,a,o,n,L,T,h)}_updateCell(t,r,s,a,o,n,L,T,h,d){if(N=(s*this._terminal.cols+r)*11,a===0||a===void 0){t.fill(0,N,N+11-1-2);return}this._atlas&&(T&&T.length>1?S=this._atlas.getRasterizedGlyphCombinedChar(T,o,n,L,!1,this._terminal.element):S=this._atlas.getRasterizedGlyph(a,o,n,L,!1,this._terminal.element),Ie=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),o!==d&&S.offset.x>Ie?(k0=S.offset.x-Ie,t[N]=-(S.offset.x-k0)+this._dimensions.device.char.left,t[N+1]=-S.offset.y+this._dimensions.device.char.top,t[N+2]=(S.size.x-k0)/this._dimensions.device.canvas.width,t[N+3]=S.size.y/this._dimensions.device.canvas.height,t[N+4]=S.texturePage,t[N+5]=S.texturePositionClipSpace.x+k0/this._atlas.pages[S.texturePage].canvas.width,t[N+6]=S.texturePositionClipSpace.y,t[N+7]=S.sizeClipSpace.x-k0/this._atlas.pages[S.texturePage].canvas.width,t[N+8]=S.sizeClipSpace.y):(t[N]=-S.offset.x+this._dimensions.device.char.left,t[N+1]=-S.offset.y+this._dimensions.device.char.top,t[N+2]=S.size.x/this._dimensions.device.canvas.width,t[N+3]=S.size.y/this._dimensions.device.canvas.height,t[N+4]=S.texturePage,t[N+5]=S.texturePositionClipSpace.x,t[N+6]=S.texturePositionClipSpace.y,t[N+7]=S.sizeClipSpace.x,t[N+8]=S.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&Ze(a,h,S.size.x,this._dimensions.device.cell.width)&&(t[N+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width))}clear(){let t=this._terminal,r=t.cols*t.rows*11;this._vertices.count!==r?this._vertices.attributes=new Float32Array(r):this._vertices.attributes.fill(0);let s=0;for(;s=e.rows||T<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=o,this.viewportEndRow=n,this.viewportCappedStartRow=L,this.viewportCappedEndRow=T,this.startCol=t[0],this.endCol=r[0]}isCellSelected(e,t,r){return this.hasSelection?(r-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&r>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&r<=this.viewportCappedEndRow:r>this.viewportStartRow&&r=this.startCol&&t=this.startCol):!1}};function Tt(){return new Fe}var lt=2147483648,se=class{constructor(){this.cells=new Uint32Array(0),this.lineLengths=new Uint32Array(0),this.selection=Tt()}resize(e,t){let r=e*t*4;r!==this.cells.length&&(this.cells=new Uint32Array(r),this.lineLengths=new Uint32Array(t))}clear(){this.cells.fill(0,0),this.lineLengths.fill(0,0)}};var jt=`#version 300 es layout (location = 0) in vec2 a_position; layout (location = 1) in vec2 a_size; layout (location = 2) in vec4 a_color; +@@ -71,5 +71,5 @@ out vec4 outColor; + + void main() { + outColor = v_color; +-}`,l0=8,Me=l0*Float32Array.BYTES_PER_ELEMENT,e1=20*l0,ne=class{constructor(){this.attributes=new Float32Array(e1),this.count=0}},p0=0,Lt=0,ht=0,dt=0,_t=0,ct=0,ut=0,ae=class extends W{constructor(t,r,s,a,o){super();this._terminal=t;this._gl=r;this._dimensions=s;this._themeService=a;this._logService=o;this._vertices=new ne;this._verticesCursor=new ne;let n=this._gl;this._program=g(ie(n,jt,Jt,this._logService)),this._register(M(()=>n.deleteProgram(this._program))),this._projectionLocation=g(n.getUniformLocation(this._program,"u_projection"));let L=this._vertexArrayObject=n.createVertexArray();this._register(M(()=>n.deleteVertexArray(L))),n.bindVertexArray(L);let T=new Float32Array([0,0,1,0,0,1,1,1]),h=n.createBuffer();this._register(M(()=>n.deleteBuffer(h))),n.bindBuffer(n.ARRAY_BUFFER,h),n.bufferData(n.ARRAY_BUFFER,T,n.STATIC_DRAW),n.enableVertexAttribArray(3),n.vertexAttribPointer(3,2,this._gl.FLOAT,!1,0,0);let d=new Uint8Array([0,1,2,3]),_=n.createBuffer();this._register(M(()=>n.deleteBuffer(_))),n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,_),n.bufferData(n.ELEMENT_ARRAY_BUFFER,d,n.STATIC_DRAW),this._attributesBuffer=g(n.createBuffer()),this._register(M(()=>n.deleteBuffer(this._attributesBuffer))),n.bindBuffer(n.ARRAY_BUFFER,this._attributesBuffer),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,2,n.FLOAT,!1,Me,0),n.vertexAttribDivisor(0,1),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,!1,Me,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(1,1),n.enableVertexAttribArray(2),n.vertexAttribPointer(2,4,n.FLOAT,!1,Me,4*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(2,1),this._updateCachedColors(a.colors),this._register(this._themeService.onChangeColors(p=>{this._updateCachedColors(p),this._updateViewportRectangle()}))}renderBackgrounds(){this._renderVertices(this._vertices)}renderCursor(){this._renderVertices(this._verticesCursor)}_renderVertices(t){let r=this._gl;r.useProgram(this._program),r.bindVertexArray(this._vertexArrayObject),r.uniformMatrix4fv(this._projectionLocation,!1,te),r.bindBuffer(r.ARRAY_BUFFER,this._attributesBuffer),r.bufferData(r.ARRAY_BUFFER,t.attributes,r.DYNAMIC_DRAW),r.drawElementsInstanced(this._gl.TRIANGLE_STRIP,4,r.UNSIGNED_BYTE,0,t.count)}handleResize(){this._updateViewportRectangle()}setDimensions(t){this._dimensions=t}_updateCachedColors(t){this._bgFloat=this._colorToFloat32Array(t.background),this._cursorFloat=this._colorToFloat32Array(t.cursor)}_updateViewportRectangle(){this._addRectangleFloat(this._vertices.attributes,0,0,0,this._terminal.cols*this._dimensions.device.cell.width,this._terminal.rows*this._dimensions.device.cell.height,this._bgFloat)}updateBackgrounds(t){let r=this._terminal,s=this._vertices,a=1,o,n,L,T,h,d,_,p,c,u,C;for(o=0;o>24&255)/255,_t=(p0>>16&255)/255,ct=(p0>>8&255)/255,ut=1,this._addRectangle(t.attributes,r,Lt,ht,(n-o)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,dt,_t,ct,ut)}_addRectangle(t,r,s,a,o,n,L,T,h,d){t[r]=s/this._dimensions.device.canvas.width,t[r+1]=a/this._dimensions.device.canvas.height,t[r+2]=o/this._dimensions.device.canvas.width,t[r+3]=n/this._dimensions.device.canvas.height,t[r+4]=L,t[r+5]=T,t[r+6]=h,t[r+7]=d}_addRectangleFloat(t,r,s,a,o,n,L){t[r]=s/this._dimensions.device.canvas.width,t[r+1]=a/this._dimensions.device.canvas.height,t[r+2]=o/this._dimensions.device.canvas.width,t[r+3]=n/this._dimensions.device.canvas.height,t[r+4]=L[0],t[r+5]=L[1],t[r+6]=L[2],t[r+7]=L[3]}_colorToFloat32Array(t){return new Float32Array([(t.rgba>>24&255)/255,(t.rgba>>16&255)/255,(t.rgba>>8&255)/255,(t.rgba&255)/255])}};var oe=class extends W{constructor(t,r,s,a,o,n,L,T){super();this._container=r;this._alpha=o;this._coreBrowserService=n;this._optionsService=L;this._themeService=T;this._deviceCharWidth=0;this._deviceCharHeight=0;this._deviceCellWidth=0;this._deviceCellHeight=0;this._deviceCharLeft=0;this._deviceCharTop=0;this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add(`xterm-${s}-layer`),this._canvas.style.zIndex=a.toString(),this._initCanvas(),this._container.appendChild(this._canvas),this._register(this._themeService.onChangeColors(h=>{this._refreshCharAtlas(t,h),this.reset(t)})),this._register(M(()=>{this._canvas.remove()}))}_initCanvas(){this._ctx=g(this._canvas.getContext("2d",{alpha:this._alpha})),this._alpha||this._clearAll()}handleBlur(t){}handleFocus(t){}handleCursorMove(t){}handleGridChanged(t,r,s){}handleSelectionChanged(t,r,s,a=!1){}_setTransparency(t,r){if(r===this._alpha)return;let s=this._canvas;this._alpha=r,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,s),this._refreshCharAtlas(t,this._themeService.colors),this.handleGridChanged(t,0,t.rows-1)}_refreshCharAtlas(t,r){this._deviceCharWidth<=0&&this._deviceCharHeight<=0||(this._charAtlas=Y0(t,this._optionsService.rawOptions,r,this._deviceCellWidth,this._deviceCellHeight,this._deviceCharWidth,this._deviceCharHeight,this._coreBrowserService.dpr,2048),this._charAtlas.warmUp())}resize(t,r){this._deviceCellWidth=r.device.cell.width,this._deviceCellHeight=r.device.cell.height,this._deviceCharWidth=r.device.char.width,this._deviceCharHeight=r.device.char.height,this._deviceCharLeft=r.device.char.left,this._deviceCharTop=r.device.char.top,this._canvas.width=r.device.canvas.width,this._canvas.height=r.device.canvas.height,this._canvas.style.width=`${r.css.canvas.width}px`,this._canvas.style.height=`${r.css.canvas.height}px`,this._alpha||this._clearAll(),this._refreshCharAtlas(t,this._themeService.colors)}_fillBottomLineAtCells(t,r,s=1){this._ctx.fillRect(t*this._deviceCellWidth,(r+1)*this._deviceCellHeight-this._coreBrowserService.dpr-1,s*this._deviceCellWidth,this._coreBrowserService.dpr)}_clearAll(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))}_clearCells(t,r,s,a){this._alpha?this._ctx.clearRect(t*this._deviceCellWidth,r*this._deviceCellHeight,s*this._deviceCellWidth,a*this._deviceCellHeight):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(t*this._deviceCellWidth,r*this._deviceCellHeight,s*this._deviceCellWidth,a*this._deviceCellHeight))}_fillCharTrueColor(t,r,s,a){this._ctx.font=this._getFont(t,!1,!1),this._ctx.textBaseline=K0,this._clipCell(s,a,r.getWidth()),this._ctx.fillText(r.getChars(),s*this._deviceCellWidth+this._deviceCharLeft,a*this._deviceCellHeight+this._deviceCharTop+this._deviceCharHeight)}_clipCell(t,r,s){this._ctx.beginPath(),this._ctx.rect(t*this._deviceCellWidth,r*this._deviceCellHeight,s*this._deviceCellWidth,this._deviceCellHeight),this._ctx.clip()}_getFont(t,r,s){let a=r?t.options.fontWeightBold:t.options.fontWeight;return`${s?"italic":""} ${a} ${t.options.fontSize*this._coreBrowserService.dpr}px ${t.options.fontFamily}`}};var Te=class extends oe{constructor(e,t,r,s,a,o,n){super(r,e,"link",t,!0,a,o,n),this._register(s.onShowLinkUnderline(L=>this._handleShowLinkUnderline(L))),this._register(s.onHideLinkUnderline(L=>this._handleHideLinkUnderline(L)))}resize(e,t){super.resize(e,t),this._state=void 0}reset(e){this._clearCurrentLink()}_clearCurrentLink(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);let e=this._state.y2-this._state.y1-1;e>0&&this._clearCells(0,this._state.y1+1,this._state.cols,e),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}}_handleShowLinkUnderline(e){if(e.fg===257?this._ctx.fillStyle=this._themeService.colors.background.css:e.fg!==void 0&&st(e.fg)?this._ctx.fillStyle=this._themeService.colors.ansi[e.fg].css:this._ctx.fillStyle=this._themeService.colors.foreground.css,e.y1===e.y2)this._fillBottomLineAtCells(e.x1,e.y1,e.x2-e.x1);else{this._fillBottomLineAtCells(e.x1,e.y1,e.cols-e.x1);for(let t=e.y1+1;tthis._handleColorChange())),this._cellColorResolver=new G0(this._terminal,this._optionsService,this._model.selection,this._decorationService,this._coreBrowserService,this._themeService),this._core=this._terminal._core,this._renderLayers=[new Te(this._core.screenElement,2,this._terminal,this._core.linkifier,this._coreBrowserService,T,this._themeService)],this.dimensions=Ue(),this._devicePixelRatio=this._coreBrowserService.dpr,this._updateDimensions(),this._updateCursorBlink(),this._register(T.onOptionChange(()=>this._handleOptionsChanged())),this._textBlinkStateManager=this._register(new J0(()=>this._requestRedrawViewport(),this._coreBrowserService,this._optionsService)),this._resetBlinkingRowState(),this._deviceMaxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._register(le(this._canvas,"webglcontextlost",c=>{this._logService.debug("webglcontextlost event received"),c.preventDefault(),this._contextRestorationTimeout=setTimeout(()=>{this._contextRestorationTimeout=void 0,this._logService.warn("webgl context not restored; firing onContextLoss"),this._onContextLoss.fire(c)},3e3)})),this._register(le(this._canvas,"webglcontextrestored",c=>{this._logService.warn("webglcontextrestored event received"),clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0,be(this._terminal),this._initializeWebGLState(),this._requestRedrawViewport()})),this._observerDisposable.value=ve(this._canvas,this._coreBrowserService.window,(c,u)=>this._setCanvasDevicePixelDimensions(c,u)),this._register(this._coreBrowserService.onWindowChange(c=>{this._observerDisposable.value=ve(this._canvas,c,(u,C)=>this._setCanvasDevicePixelDimensions(u,C))})),this._register(le(this._coreBrowserService.mainDocument,"mousedown",()=>this._cursorBlinkStateManager.value?.restartBlinkAnimation())),this._core.screenElement.appendChild(this._canvas),[this._rectangleRenderer.value,this._glyphRenderer.value]=this._initializeWebGLState(),this._isAttached=this._core.screenElement.isConnected,this._register(M(()=>{clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0;for(let c of this._renderLayers)c.dispose();this._canvas.parentElement?.removeChild(this._canvas),be(this._terminal)}))}get textureAtlas(){return this._charAtlas?.pages[0].canvas}_handleColorChange(){this._refreshCharAtlas(),this._clearModel(!0)}handleDevicePixelRatioChange(){this._devicePixelRatio!==this._coreBrowserService.dpr&&(this._devicePixelRatio=this._coreBrowserService.dpr,this.handleResize(this._terminal.cols,this._terminal.rows))}handleResize(t,r){this._updateDimensions(),this._model.resize(this._terminal.cols,this._terminal.rows),this._resetBlinkingRowState();for(let s of this._renderLayers)s.resize(this._terminal,this.dimensions);this._canvas.width=this.dimensions.device.canvas.width,this._canvas.height=this.dimensions.device.canvas.height,this._canvas.style.width=`${this.dimensions.css.canvas.width}px`,this._canvas.style.height=`${this.dimensions.css.canvas.height}px`,this._core.screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._core.screenElement.style.height=`${this.dimensions.css.canvas.height}px`,this._rectangleRenderer.value?.setDimensions(this.dimensions),this._rectangleRenderer.value?.handleResize(),this._glyphRenderer.value?.setDimensions(this.dimensions),this._glyphRenderer.value?.handleResize(),this._refreshCharAtlas(),this._clearModel(!1),this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1,sync:!0})}handleCharSizeChanged(){this.handleResize(this._terminal.cols,this._terminal.rows)}handleBlur(){for(let t of this._renderLayers)t.handleBlur(this._terminal);this._cursorBlinkStateManager.value?.pause(),this._requestRedrawViewport()}handleFocus(){for(let t of this._renderLayers)t.handleFocus(this._terminal);this._cursorBlinkStateManager.value?.resume(),this._requestRedrawViewport()}handleViewportVisibilityChange(t){this._textBlinkStateManager.setViewportVisible(t)}handleSelectionChanged(t,r,s){for(let a of this._renderLayers)a.handleSelectionChanged(this._terminal,t,r,s);this._model.selection.update(this._core,t,r,s),this._requestRedrawViewport()}handleCursorMove(){for(let t of this._renderLayers)t.handleCursorMove(this._terminal);this._cursorBlinkStateManager.value?.restartBlinkAnimation()}_handleOptionsChanged(){this._updateDimensions(),this._refreshCharAtlas(),this._updateCursorBlink()}_initializeWebGLState(){return this._rectangleRenderer.value=new ae(this._terminal,this._gl,this.dimensions,this._themeService,this._logService),this._glyphRenderer.value=new re(this._terminal,this._gl,this.dimensions,this._optionsService,this._logService),this.handleCharSizeChanged(),[this._rectangleRenderer.value,this._glyphRenderer.value]}_refreshCharAtlas(){if(this.dimensions.device.char.width<=0&&this.dimensions.device.char.height<=0){this._isAttached=!1;return}let t=Y0(this._terminal,this._optionsService.rawOptions,this._themeService.colors,this.dimensions.device.cell.width,this.dimensions.device.cell.height,this.dimensions.device.char.width,this.dimensions.device.char.height,this._coreBrowserService.dpr,this._deviceMaxTextureSize,this._customGlyphs);this._charAtlas!==t&&(this._onChangeTextureAtlas.fire(t.pages[0].canvas),this._charAtlasDisposable.value=De(c0.forward(t.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas),c0.forward(t.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas))),this._charAtlas=t,this._charAtlas.warmUp(),this._glyphRenderer.value?.setAtlas(this._charAtlas)}_clearModel(t){this._model.clear(),t&&this._glyphRenderer.value?.clear()}clearTextureAtlas(){this._charAtlas?.clearTexture(),this._clearModel(!0),this._requestRedrawViewport()}clear(){this._clearModel(!0);for(let t of this._renderLayers)t.reset(this._terminal);this._resetBlinkingRowState(),this._textBlinkStateManager.setNeedsBlinkInViewport(!1),this._cursorBlinkStateManager.value?.restartBlinkAnimation(),this._updateCursorBlink()}renderRows(t,r){if(!this._isAttached)if(this._core.screenElement?.isConnected&&this._charSizeService.width&&this._charSizeService.height)this._updateDimensions(),this._refreshCharAtlas(),this._isAttached=!0;else return;for(let o of this._renderLayers)o.handleGridChanged(this._terminal,t,r);if(!this._glyphRenderer.value||!this._rectangleRenderer.value)return;this._glyphRenderer.value.beginFrame()?(this._clearModel(!0),this._updateModel(0,this._terminal.rows-1)):this._updateModel(t,r);let s=!1,a=0;for(;this._charAtlas&&this._glyphRenderer.value.beginFrame()&&a++<32;)s=!0,this._clearModel(!0),this._updateModel(0,this._terminal.rows-1);s&&this._glyphRenderer.value.invalidateAtlasTextures(),this._rectangleRenderer.value.renderBackgrounds(),this._glyphRenderer.value.render(this._model),(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible)&&this._rectangleRenderer.value.renderCursor()}_updateCursorBlink(){this._coreService.decPrivateModes.cursorBlink??this._terminal.options.cursorBlink?this._cursorBlinkStateManager.value=new q0(()=>{this._requestRedrawCursor()},this._coreBrowserService):this._cursorBlinkStateManager.clear(),this._requestRedrawCursor()}_updateModel(t,r){let s=this._core,a=this._workCell,o,n,L,T,h,d,_,p,c,u,C,Q,m,R,F,E,y;t=pt(t,s.rows-1,0),r=pt(r,s.rows-1,0);let Y=this._coreService.decPrivateModes.cursorStyle??s.options.cursorStyle??"block",X=this._terminal.buffer.active.baseY+this._terminal.buffer.active.cursorY,A0=X-s.buffer.ydisp,t0=Math.min(this._terminal.buffer.active.cursorX,s.cols-1),L0=-1,A=this._coreService.isCursorInitialized&&!this._coreService.isCursorHidden&&(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible);this._model.cursor=void 0;let n0=!1;for(n=t;n<=r;n++){L=n+s.buffer.ydisp;let a0=s.buffer.lines.get(L);if(!a0){for(this._model.lineLengths[n]=0,E=0;E=_,c=E,h.length>0&&E===h[0][0]&&p){u=h.shift();let q=this._model.selection.isCellSelected(this._terminal,u[0],L);for(F=u[0]+1;F=u[1],p?(d=!0,a=new ge(a,T.translateToString(!0,u[0],u[1]),u[1]-u[0]),c=u[1]-1):_=u[1]}if(Q=a.getChars(),m=a.getCode(),F=(n*s.cols+E)*4,!$&&a.isBlink()&&($=!0),this._cellColorResolver.resolve(a,E,L,this.dimensions.device.cell.width,this.dimensions.device.cell.height),A&&L===X&&(E===t0&&(this._model.cursor={x:t0,y:A0,width:a.getWidth(),style:this._coreBrowserService.isFocused?Y:s.options.cursorInactiveStyle,cursorWidth:s.options.cursorWidth,dpr:this._devicePixelRatio},L0=t0+a.getWidth()-1),E>=t0&&E<=L0&&(this._coreBrowserService.isFocused&&Y==="block"||this._coreBrowserService.isFocused===!1&&s.options.cursorInactiveStyle==="block")&&(this._cellColorResolver.result.fg=50331648|this._themeService.colors.cursorAccent.rgba>>8&16777215,this._cellColorResolver.result.bg=50331648|this._themeService.colors.cursor.rgba>>8&16777215)),this._textBlinkStateManager.isEnabled&&!this._textBlinkStateManager.isBlinkOn&&a.isBlink()&&(this._cellColorResolver.result.fg|=1073741824),m!==0&&(this._model.lineLengths[n]=E+1),!(this._model.cells[F]===m&&this._model.cells[F+1]===this._cellColorResolver.result.bg&&this._model.cells[F+2]===this._cellColorResolver.result.fg&&this._model.cells[F+3]===this._cellColorResolver.result.ext)&&(n0=!0,Q.length>1&&(m|=lt),this._model.cells[F]=m,this._model.cells[F+1]=this._cellColorResolver.result.bg,this._model.cells[F+2]=this._cellColorResolver.result.fg,this._model.cells[F+3]=this._cellColorResolver.result.ext,R=a.getWidth(),this._glyphRenderer.value.updateCell(E,n,m,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext,Q,R,o),d)){for(a=this._workCell,E++;E<=c;E++)y=(n*s.cols+E)*4,this._nullModelCell(E,n,y,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext);E--}}this._setRowBlinkState(n,$)}n0&&this._rectangleRenderer.value.updateBackgrounds(this._model),this._rectangleRenderer.value.updateCursor(this._model),this._updateTextBlinkState()}_nullModelCell(t,r,s,a,o,n){this._glyphRenderer.value.updateCell(t,r,0,a,o,n,"",0,0),this._model.cells[s]=0,this._model.cells[s+1]=a,this._model.cells[s+2]=o,this._model.cells[s+3]=n}_resetBlinkingRowState(){this._rowHasBlinkingCells=new Array(this._terminal.rows).fill(!1),this._rowHasBlinkingCellsCount=0}_setRowBlinkState(t,r){this._rowHasBlinkingCells[t]!==r&&(this._rowHasBlinkingCells[t]=r,this._rowHasBlinkingCellsCount+=r?1:-1)}_updateTextBlinkState(){this._textBlinkStateManager.setNeedsBlinkInViewport(this._rowHasBlinkingCellsCount>0)}_updateDimensions(){!this._charSizeService.width||!this._charSizeService.height||(this.dimensions.device.char.width=Math.floor(this._charSizeService.width*this._devicePixelRatio),this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*this._devicePixelRatio),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.top=this._optionsService.rawOptions.lineHeight===1?0:Math.round((this.dimensions.device.cell.height-this.dimensions.device.char.height)/2),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.char.left=Math.floor(this._optionsService.rawOptions.letterSpacing/2),this.dimensions.device.canvas.height=this._terminal.rows*this.dimensions.device.cell.height,this.dimensions.device.canvas.width=this._terminal.cols*this.dimensions.device.cell.width,this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/this._devicePixelRatio),this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/this._devicePixelRatio),this.dimensions.css.cell.height=this.dimensions.device.cell.height/this._devicePixelRatio,this.dimensions.css.cell.width=this.dimensions.device.cell.width/this._devicePixelRatio)}_setCanvasDevicePixelDimensions(t,r){this._canvas.width===t&&this._canvas.height===r||(this._canvas.width=t,this._canvas.height=r,this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1,sync:!0}))}_requestRedrawViewport(){this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1})}_requestRedrawCursor(){let t=this._terminal.buffer.active.cursorY;this._onRequestRedraw.fire({start:t,end:t})}},ge=class extends s0{constructor(t,r,s){super();this.content=0;this.combinedData="";this.fg=t.fg,this.bg=t.bg,this.combinedData=r,this._width=s}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(t){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}};function pt(i,e,t=0){return Math.max(Math.min(i,e),t)}var Ct=class extends W{constructor(t){if(ue&&He()<16){let r={antialias:!1,depth:!1,preserveDrawingBuffer:!0};if(!document.createElement("canvas").getContext("webgl2",r))throw new Error("WebGL2 is only supported on Safari 16 and above")}super();this._onChangeTextureAtlas=this._register(new U);this.onChangeTextureAtlas=this._onChangeTextureAtlas.event;this._onAddTextureAtlasCanvas=this._register(new U);this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event;this._onRemoveTextureAtlasCanvas=this._register(new U);this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event;this._onContextLoss=this._register(new U);this.onContextLoss=this._onContextLoss.event;this._customGlyphs=t?.customGlyphs??!0,this._preserveDrawingBuffer=t?.preserveDrawingBuffer}activate(t){let r=t._core;if(!t.element){this._register(r.onWillOpen(()=>this.activate(t)));return}this._terminal=t;let s=r.coreService,a=r.optionsService,o=r,n=o._renderService,L=o._characterJoinerService,T=o._charSizeService,h=o._coreBrowserService,d=o._decorationService,_=o._logService,p=o._themeService;this._renderer=this._register(new Le(t,L,T,h,s,d,_,a,p,this._customGlyphs,this._preserveDrawingBuffer)),this._register(c0.forward(this._renderer.onContextLoss,this._onContextLoss)),this._register(c0.forward(this._renderer.onChangeTextureAtlas,this._onChangeTextureAtlas)),this._register(c0.forward(this._renderer.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas)),this._register(c0.forward(this._renderer.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas)),n.setRenderer(this._renderer),this._register(M(()=>{if(this._terminal._core._store._isDisposed)return;let c=this._terminal._core._renderService;c.setRenderer(this._terminal._core._createRenderer()),c.handleResize(t.cols,t.rows)}))}get textureAtlas(){return this._renderer?.textureAtlas}clearTextureAtlas(){this._renderer?.clearTextureAtlas()}};export{Ct as WebglAddon}; ++}`,l0=8,Me=l0*Float32Array.BYTES_PER_ELEMENT,e1=20*l0,ne=class{constructor(){this.attributes=new Float32Array(e1),this.count=0}},p0=0,Lt=0,ht=0,dt=0,_t=0,ct=0,ut=0,ae=class extends W{constructor(t,r,s,a,o){super();this._terminal=t;this._gl=r;this._dimensions=s;this._themeService=a;this._logService=o;this._vertices=new ne;this._verticesCursor=new ne;let n=this._gl;this._program=g(ie(n,jt,Jt,this._logService)),this._register(M(()=>n.deleteProgram(this._program))),this._projectionLocation=g(n.getUniformLocation(this._program,"u_projection"));let L=this._vertexArrayObject=n.createVertexArray();this._register(M(()=>n.deleteVertexArray(L))),n.bindVertexArray(L);let T=new Float32Array([0,0,1,0,0,1,1,1]),h=n.createBuffer();this._register(M(()=>n.deleteBuffer(h))),n.bindBuffer(n.ARRAY_BUFFER,h),n.bufferData(n.ARRAY_BUFFER,T,n.STATIC_DRAW),n.enableVertexAttribArray(3),n.vertexAttribPointer(3,2,this._gl.FLOAT,!1,0,0);let d=new Uint8Array([0,1,2,3]),_=n.createBuffer();this._register(M(()=>n.deleteBuffer(_))),n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,_),n.bufferData(n.ELEMENT_ARRAY_BUFFER,d,n.STATIC_DRAW),this._attributesBuffer=g(n.createBuffer()),this._register(M(()=>n.deleteBuffer(this._attributesBuffer))),n.bindBuffer(n.ARRAY_BUFFER,this._attributesBuffer),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,2,n.FLOAT,!1,Me,0),n.vertexAttribDivisor(0,1),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,!1,Me,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(1,1),n.enableVertexAttribArray(2),n.vertexAttribPointer(2,4,n.FLOAT,!1,Me,4*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(2,1),this._updateCachedColors(a.colors),this._register(this._themeService.onChangeColors(p=>{this._updateCachedColors(p),this._updateViewportRectangle()}))}renderBackgrounds(){this._renderVertices(this._vertices)}renderCursor(){this._renderVertices(this._verticesCursor)}_renderVertices(t){let r=this._gl;r.useProgram(this._program),r.bindVertexArray(this._vertexArrayObject),r.uniformMatrix4fv(this._projectionLocation,!1,te),r.bindBuffer(r.ARRAY_BUFFER,this._attributesBuffer),r.bufferData(r.ARRAY_BUFFER,t.attributes,r.DYNAMIC_DRAW),r.drawElementsInstanced(this._gl.TRIANGLE_STRIP,4,r.UNSIGNED_BYTE,0,t.count)}handleResize(){this._updateViewportRectangle()}setDimensions(t){this._dimensions=t}_updateCachedColors(t){this._bgFloat=this._colorToFloat32Array(t.background),this._cursorFloat=this._colorToFloat32Array(t.cursor)}_updateViewportRectangle(){this._addRectangleFloat(this._vertices.attributes,0,0,0,this._terminal.cols*this._dimensions.device.cell.width,this._terminal.rows*this._dimensions.device.cell.height,this._bgFloat)}updateBackgrounds(t){let r=this._terminal,s=this._vertices,a=1,o,n,L,T,h,d,_,p,c,u,C;for(o=0;o>24&255)/255,_t=(p0>>16&255)/255,ct=(p0>>8&255)/255,ut=1,this._addRectangle(t.attributes,r,Lt,ht,(n-o)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,dt,_t,ct,ut)}_addRectangle(t,r,s,a,o,n,L,T,h,d){t[r]=s/this._dimensions.device.canvas.width,t[r+1]=a/this._dimensions.device.canvas.height,t[r+2]=o/this._dimensions.device.canvas.width,t[r+3]=n/this._dimensions.device.canvas.height,t[r+4]=L,t[r+5]=T,t[r+6]=h,t[r+7]=d}_addRectangleFloat(t,r,s,a,o,n,L){t[r]=s/this._dimensions.device.canvas.width,t[r+1]=a/this._dimensions.device.canvas.height,t[r+2]=o/this._dimensions.device.canvas.width,t[r+3]=n/this._dimensions.device.canvas.height,t[r+4]=L[0],t[r+5]=L[1],t[r+6]=L[2],t[r+7]=L[3]}_colorToFloat32Array(t){return new Float32Array([(t.rgba>>24&255)/255,(t.rgba>>16&255)/255,(t.rgba>>8&255)/255,(t.rgba&255)/255])}};var oe=class extends W{constructor(t,r,s,a,o,n,L,T){super();this._container=r;this._alpha=o;this._coreBrowserService=n;this._optionsService=L;this._themeService=T;this._deviceCharWidth=0;this._deviceCharHeight=0;this._deviceCellWidth=0;this._deviceCellHeight=0;this._deviceCharLeft=0;this._deviceCharTop=0;this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add(`xterm-${s}-layer`),this._canvas.style.zIndex=a.toString(),this._initCanvas(),this._container.appendChild(this._canvas),this._register(this._themeService.onChangeColors(h=>{this._refreshCharAtlas(t,h),this.reset(t)})),this._register(M(()=>{this._canvas.remove()}))}_initCanvas(){this._ctx=g(this._canvas.getContext("2d",{alpha:this._alpha})),this._alpha||this._clearAll()}handleBlur(t){}handleFocus(t){}handleCursorMove(t){}handleGridChanged(t,r,s){}handleSelectionChanged(t,r,s,a=!1){}_setTransparency(t,r){if(r===this._alpha)return;let s=this._canvas;this._alpha=r,this._canvas=this._canvas.cloneNode(),this._initCanvas(),this._container.replaceChild(this._canvas,s),this._refreshCharAtlas(t,this._themeService.colors),this.handleGridChanged(t,0,t.rows-1)}_refreshCharAtlas(t,r){this._deviceCharWidth<=0&&this._deviceCharHeight<=0||(this._charAtlas=Y0(t,this._optionsService.rawOptions,r,this._deviceCellWidth,this._deviceCellHeight,this._deviceCharWidth,this._deviceCharHeight,this._coreBrowserService.dpr,2048),this._charAtlas.warmUp())}resize(t,r){this._deviceCellWidth=r.device.cell.width,this._deviceCellHeight=r.device.cell.height,this._deviceCharWidth=r.device.char.width,this._deviceCharHeight=r.device.char.height,this._deviceCharLeft=r.device.char.left,this._deviceCharTop=r.device.char.top,this._canvas.width=r.device.canvas.width,this._canvas.height=r.device.canvas.height,this._canvas.style.width=`${r.css.canvas.width}px`,this._canvas.style.height=`${r.css.canvas.height}px`,this._alpha||this._clearAll(),this._refreshCharAtlas(t,this._themeService.colors)}_fillBottomLineAtCells(t,r,s=1){this._ctx.fillRect(t*this._deviceCellWidth,(r+1)*this._deviceCellHeight-this._coreBrowserService.dpr-1,s*this._deviceCellWidth,this._coreBrowserService.dpr)}_clearAll(){this._alpha?this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height))}_clearCells(t,r,s,a){this._alpha?this._ctx.clearRect(t*this._deviceCellWidth,r*this._deviceCellHeight,s*this._deviceCellWidth,a*this._deviceCellHeight):(this._ctx.fillStyle=this._themeService.colors.background.css,this._ctx.fillRect(t*this._deviceCellWidth,r*this._deviceCellHeight,s*this._deviceCellWidth,a*this._deviceCellHeight))}_fillCharTrueColor(t,r,s,a){this._ctx.font=this._getFont(t,!1,!1),this._ctx.textBaseline=K0,this._clipCell(s,a,r.getWidth()),this._ctx.fillText(r.getChars(),s*this._deviceCellWidth+this._deviceCharLeft,a*this._deviceCellHeight+this._deviceCharTop+this._deviceCharHeight)}_clipCell(t,r,s){this._ctx.beginPath(),this._ctx.rect(t*this._deviceCellWidth,r*this._deviceCellHeight,s*this._deviceCellWidth,this._deviceCellHeight),this._ctx.clip()}_getFont(t,r,s){let a=r?t.options.fontWeightBold:t.options.fontWeight;return`${s?"italic":""} ${a} ${t.options.fontSize*this._coreBrowserService.dpr}px ${t.options.fontFamily}`}};var Te=class extends oe{constructor(e,t,r,s,a,o,n){super(r,e,"link",t,!0,a,o,n),this._register(s.onShowLinkUnderline(L=>this._handleShowLinkUnderline(L))),this._register(s.onHideLinkUnderline(L=>this._handleHideLinkUnderline(L)))}resize(e,t){super.resize(e,t),this._state=void 0}reset(e){this._clearCurrentLink()}_clearCurrentLink(){if(this._state){this._clearCells(this._state.x1,this._state.y1,this._state.cols-this._state.x1,1);let e=this._state.y2-this._state.y1-1;e>0&&this._clearCells(0,this._state.y1+1,this._state.cols,e),this._clearCells(0,this._state.y2,this._state.x2,1),this._state=void 0}}_handleShowLinkUnderline(e){if(e.fg===257?this._ctx.fillStyle=this._themeService.colors.background.css:e.fg!==void 0&&st(e.fg)?this._ctx.fillStyle=this._themeService.colors.ansi[e.fg].css:this._ctx.fillStyle=this._themeService.colors.foreground.css,e.y1===e.y2)this._fillBottomLineAtCells(e.x1,e.y1,e.x2-e.x1);else{this._fillBottomLineAtCells(e.x1,e.y1,e.cols-e.x1);for(let t=e.y1+1;tthis._handleColorChange())),this._cellColorResolver=new G0(this._terminal,this._optionsService,this._model.selection,this._decorationService,this._coreBrowserService,this._themeService),this._core=this._terminal._core,this._renderLayers=[new Te(this._core.screenElement,2,this._terminal,this._core.linkifier,this._coreBrowserService,T,this._themeService)],this.dimensions=Ue(),this._devicePixelRatio=this._coreBrowserService.dpr,this._updateDimensions(),this._updateCursorBlink(),this._register(T.onOptionChange(()=>this._handleOptionsChanged())),this._textBlinkStateManager=this._register(new J0(()=>this._requestRedrawViewport(),this._coreBrowserService,this._optionsService)),this._resetBlinkingRowState(),this._deviceMaxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._register(le(this._canvas,"webglcontextlost",c=>{this._logService.debug("webglcontextlost event received"),c.preventDefault(),this._contextRestorationTimeout=setTimeout(()=>{this._contextRestorationTimeout=void 0,this._logService.warn("webgl context not restored; firing onContextLoss"),this._onContextLoss.fire(c)},3e3)})),this._register(le(this._canvas,"webglcontextrestored",c=>{this._logService.warn("webglcontextrestored event received"),clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0,be(this._terminal),this._initializeWebGLState(),this._requestRedrawViewport()})),this._observerDisposable.value=ve(this._canvas,this._coreBrowserService.window,(c,u)=>this._setCanvasDevicePixelDimensions(c,u)),this._register(this._coreBrowserService.onWindowChange(c=>{this._observerDisposable.value=ve(this._canvas,c,(u,C)=>this._setCanvasDevicePixelDimensions(u,C))})),this._register(le(this._coreBrowserService.mainDocument,"mousedown",()=>this._cursorBlinkStateManager.value?.restartBlinkAnimation())),this._core.screenElement.appendChild(this._canvas),[this._rectangleRenderer.value,this._glyphRenderer.value]=this._initializeWebGLState(),this._isAttached=this._core.screenElement.isConnected,this._register(M(()=>{clearTimeout(this._contextRestorationTimeout),this._contextRestorationTimeout=void 0;for(let c of this._renderLayers)c.dispose();this._canvas.parentElement?.removeChild(this._canvas),be(this._terminal)}))}get textureAtlas(){return this._charAtlas?.pages[0].canvas}_handleColorChange(){this._refreshCharAtlas(),this._clearModel(!0)}handleDevicePixelRatioChange(){this._devicePixelRatio!==this._coreBrowserService.dpr&&(this._devicePixelRatio=this._coreBrowserService.dpr,this.handleResize(this._terminal.cols,this._terminal.rows))}handleResize(t,r){this._updateDimensions(),this._model.resize(this._terminal.cols,this._terminal.rows),this._resetBlinkingRowState();for(let s of this._renderLayers)s.resize(this._terminal,this.dimensions);this._canvas.width=this.dimensions.device.canvas.width,this._canvas.height=this.dimensions.device.canvas.height,this._canvas.style.width=`${this.dimensions.css.canvas.width}px`,this._canvas.style.height=`${this.dimensions.css.canvas.height}px`,this._core.screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._core.screenElement.style.height=`${this.dimensions.css.canvas.height}px`,this._rectangleRenderer.value?.setDimensions(this.dimensions),this._rectangleRenderer.value?.handleResize(),this._glyphRenderer.value?.setDimensions(this.dimensions),this._glyphRenderer.value?.handleResize(),this._refreshCharAtlas(),this._clearModel(!1),this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1,sync:!0})}handleCharSizeChanged(){this.handleResize(this._terminal.cols,this._terminal.rows)}handleBlur(){for(let t of this._renderLayers)t.handleBlur(this._terminal);this._cursorBlinkStateManager.value?.pause(),this._requestRedrawViewport()}handleFocus(){for(let t of this._renderLayers)t.handleFocus(this._terminal);this._cursorBlinkStateManager.value?.resume(),this._requestRedrawViewport()}handleViewportVisibilityChange(t){this._textBlinkStateManager.setViewportVisible(t)}handleSelectionChanged(t,r,s){for(let a of this._renderLayers)a.handleSelectionChanged(this._terminal,t,r,s);this._model.selection.update(this._core,t,r,s),this._requestRedrawViewport()}handleCursorMove(){for(let t of this._renderLayers)t.handleCursorMove(this._terminal);this._cursorBlinkStateManager.value?.restartBlinkAnimation()}_handleOptionsChanged(){this._updateDimensions(),this._refreshCharAtlas(),this._updateCursorBlink()}_initializeWebGLState(){return this._rectangleRenderer.value=new ae(this._terminal,this._gl,this.dimensions,this._themeService,this._logService),this._glyphRenderer.value=new re(this._terminal,this._gl,this.dimensions,this._optionsService,this._logService),this.handleCharSizeChanged(),[this._rectangleRenderer.value,this._glyphRenderer.value]}_refreshCharAtlas(){if(this.dimensions.device.char.width<=0&&this.dimensions.device.char.height<=0){this._isAttached=!1;return}let t=Y0(this._terminal,this._optionsService.rawOptions,this._themeService.colors,this.dimensions.device.cell.width,this.dimensions.device.cell.height,this.dimensions.device.char.width,this.dimensions.device.char.height,this._coreBrowserService.dpr,this._deviceMaxTextureSize,this._customGlyphs);this._charAtlas!==t&&(this._onChangeTextureAtlas.fire(t.pages[0].canvas),this._charAtlasDisposable.value=De(c0.forward(t.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas),c0.forward(t.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas))),this._charAtlas=t,this._charAtlas.warmUp(),this._glyphRenderer.value?.setAtlas(this._charAtlas)}_clearModel(t){this._model.clear(),t&&this._glyphRenderer.value?.clear()}clearTextureAtlas(){this._charAtlas?.clearTexture(),this._clearModel(!0),this._requestRedrawViewport()}clear(){this._clearModel(!0);for(let t of this._renderLayers)t.reset(this._terminal);this._resetBlinkingRowState(),this._textBlinkStateManager.setNeedsBlinkInViewport(!1),this._cursorBlinkStateManager.value?.restartBlinkAnimation(),this._updateCursorBlink()}renderRows(t,r){if(!this._isAttached)if(this._core.screenElement?.isConnected&&this._charSizeService.width&&this._charSizeService.height)this._updateDimensions(),this._refreshCharAtlas(),this._isAttached=!0;else return;for(let o of this._renderLayers)o.handleGridChanged(this._terminal,t,r);if(!this._glyphRenderer.value||!this._rectangleRenderer.value)return;this._glyphRenderer.value.beginFrame()?(this._clearModel(!0),this._updateModel(0,this._terminal.rows-1)):this._updateModel(t,r);let s=!1,a=0;for(;this._charAtlas&&a++<32&&this._glyphRenderer.value.beginFrame();)s=!0,this._clearModel(!0),this._updateModel(0,this._terminal.rows-1);s&&this._glyphRenderer.value.invalidateAtlasTextures(),this._rectangleRenderer.value.renderBackgrounds(),this._glyphRenderer.value.render(this._model),(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible)&&this._rectangleRenderer.value.renderCursor()}_updateCursorBlink(){this._coreService.decPrivateModes.cursorBlink??this._terminal.options.cursorBlink?this._cursorBlinkStateManager.value=new q0(()=>{this._requestRedrawCursor()},this._coreBrowserService):this._cursorBlinkStateManager.clear(),this._requestRedrawCursor()}_updateModel(t,r){let s=this._core,a=this._workCell,o,n,L,T,h,d,_,p,c,u,C,Q,m,R,F,E,y;t=pt(t,s.rows-1,0),r=pt(r,s.rows-1,0);let Y=this._coreService.decPrivateModes.cursorStyle??s.options.cursorStyle??"block",X=this._terminal.buffer.active.baseY+this._terminal.buffer.active.cursorY,A0=X-s.buffer.ydisp,t0=Math.min(this._terminal.buffer.active.cursorX,s.cols-1),L0=-1,A=this._coreService.isCursorInitialized&&!this._coreService.isCursorHidden&&(!this._cursorBlinkStateManager.value||this._cursorBlinkStateManager.value.isCursorVisible);this._model.cursor=void 0;let n0=!1;for(n=t;n<=r;n++){L=n+s.buffer.ydisp;let a0=s.buffer.lines.get(L);if(!a0){for(this._model.lineLengths[n]=0,E=0;E=_,c=E,h.length>0&&E===h[0][0]&&p){u=h.shift();let q=this._model.selection.isCellSelected(this._terminal,u[0],L);for(F=u[0]+1;F=u[1],p?(d=!0,a=new ge(a,T.translateToString(!0,u[0],u[1]),u[1]-u[0]),c=u[1]-1):_=u[1]}if(Q=a.getChars(),m=a.getCode(),F=(n*s.cols+E)*4,!$&&a.isBlink()&&($=!0),this._cellColorResolver.resolve(a,E,L,this.dimensions.device.cell.width,this.dimensions.device.cell.height),A&&L===X&&(E===t0&&(this._model.cursor={x:t0,y:A0,width:a.getWidth(),style:this._coreBrowserService.isFocused?Y:s.options.cursorInactiveStyle,cursorWidth:s.options.cursorWidth,dpr:this._devicePixelRatio},L0=t0+a.getWidth()-1),E>=t0&&E<=L0&&(this._coreBrowserService.isFocused&&Y==="block"||this._coreBrowserService.isFocused===!1&&s.options.cursorInactiveStyle==="block")&&(this._cellColorResolver.result.fg=50331648|this._themeService.colors.cursorAccent.rgba>>8&16777215,this._cellColorResolver.result.bg=50331648|this._themeService.colors.cursor.rgba>>8&16777215)),this._textBlinkStateManager.isEnabled&&!this._textBlinkStateManager.isBlinkOn&&a.isBlink()&&(this._cellColorResolver.result.fg|=1073741824),m!==0&&(this._model.lineLengths[n]=E+1),!(this._model.cells[F]===m&&this._model.cells[F+1]===this._cellColorResolver.result.bg&&this._model.cells[F+2]===this._cellColorResolver.result.fg&&this._model.cells[F+3]===this._cellColorResolver.result.ext)&&(n0=!0,Q.length>1&&(m|=lt),this._model.cells[F]=m,this._model.cells[F+1]=this._cellColorResolver.result.bg,this._model.cells[F+2]=this._cellColorResolver.result.fg,this._model.cells[F+3]=this._cellColorResolver.result.ext,R=a.getWidth(),this._glyphRenderer.value.updateCell(E,n,m,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext,Q,R,o),d)){for(a=this._workCell,E++;E<=c;E++)y=(n*s.cols+E)*4,this._nullModelCell(E,n,y,this._cellColorResolver.result.bg,this._cellColorResolver.result.fg,this._cellColorResolver.result.ext);E--}}this._setRowBlinkState(n,$)}n0&&this._rectangleRenderer.value.updateBackgrounds(this._model),this._rectangleRenderer.value.updateCursor(this._model),this._updateTextBlinkState()}_nullModelCell(t,r,s,a,o,n){this._glyphRenderer.value.updateCell(t,r,0,a,o,n,"",0,0),this._model.cells[s]=0,this._model.cells[s+1]=a,this._model.cells[s+2]=o,this._model.cells[s+3]=n}_resetBlinkingRowState(){this._rowHasBlinkingCells=new Array(this._terminal.rows).fill(!1),this._rowHasBlinkingCellsCount=0}_setRowBlinkState(t,r){this._rowHasBlinkingCells[t]!==r&&(this._rowHasBlinkingCells[t]=r,this._rowHasBlinkingCellsCount+=r?1:-1)}_updateTextBlinkState(){this._textBlinkStateManager.setNeedsBlinkInViewport(this._rowHasBlinkingCellsCount>0)}_updateDimensions(){!this._charSizeService.width||!this._charSizeService.height||(this.dimensions.device.char.width=Math.floor(this._charSizeService.width*this._devicePixelRatio),this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*this._devicePixelRatio),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.top=this._optionsService.rawOptions.lineHeight===1?0:Math.round((this.dimensions.device.cell.height-this.dimensions.device.char.height)/2),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.char.left=Math.floor(this._optionsService.rawOptions.letterSpacing/2),this.dimensions.device.canvas.height=this._terminal.rows*this.dimensions.device.cell.height,this.dimensions.device.canvas.width=this._terminal.cols*this.dimensions.device.cell.width,this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/this._devicePixelRatio),this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/this._devicePixelRatio),this.dimensions.css.cell.height=this.dimensions.device.cell.height/this._devicePixelRatio,this.dimensions.css.cell.width=this.dimensions.device.cell.width/this._devicePixelRatio)}_setCanvasDevicePixelDimensions(t,r){this._canvas.width===t&&this._canvas.height===r||(this._canvas.width=t,this._canvas.height=r,this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1,sync:!0}))}_requestRedrawViewport(){this._onRequestRedraw.fire({start:0,end:this._terminal.rows-1})}_requestRedrawCursor(){let t=this._terminal.buffer.active.cursorY;this._onRequestRedraw.fire({start:t,end:t})}},ge=class extends s0{constructor(t,r,s){super();this.content=0;this.combinedData="";this.fg=t.fg,this.bg=t.bg,this.combinedData=r,this._width=s}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(t){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}};function pt(i,e,t=0){return Math.max(Math.min(i,e),t)}var Ct=class extends W{constructor(t){if(ue&&He()<16){let r={antialias:!1,depth:!1,preserveDrawingBuffer:!0};if(!document.createElement("canvas").getContext("webgl2",r))throw new Error("WebGL2 is only supported on Safari 16 and above")}super();this._onChangeTextureAtlas=this._register(new U);this.onChangeTextureAtlas=this._onChangeTextureAtlas.event;this._onAddTextureAtlasCanvas=this._register(new U);this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event;this._onRemoveTextureAtlasCanvas=this._register(new U);this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event;this._onContextLoss=this._register(new U);this.onContextLoss=this._onContextLoss.event;this._customGlyphs=t?.customGlyphs??!0,this._preserveDrawingBuffer=t?.preserveDrawingBuffer}activate(t){let r=t._core;if(!t.element){this._register(r.onWillOpen(()=>this.activate(t)));return}this._terminal=t;let s=r.coreService,a=r.optionsService,o=r,n=o._renderService,L=o._characterJoinerService,T=o._charSizeService,h=o._coreBrowserService,d=o._decorationService,_=o._logService,p=o._themeService;this._renderer=this._register(new Le(t,L,T,h,s,d,_,a,p,this._customGlyphs,this._preserveDrawingBuffer)),this._register(c0.forward(this._renderer.onContextLoss,this._onContextLoss)),this._register(c0.forward(this._renderer.onChangeTextureAtlas,this._onChangeTextureAtlas)),this._register(c0.forward(this._renderer.onAddTextureAtlasCanvas,this._onAddTextureAtlasCanvas)),this._register(c0.forward(this._renderer.onRemoveTextureAtlasCanvas,this._onRemoveTextureAtlasCanvas)),n.setRenderer(this._renderer),this._register(M(()=>{if(this._terminal._core._store._isDisposed)return;let c=this._terminal._core._renderService;c.setRenderer(this._terminal._core._createRenderer()),c.handleResize(t.cols,t.rows)}))}get textureAtlas(){return this._renderer?.textureAtlas}clearTextureAtlas(){this._renderer?.clearTextureAtlas()}};export{Ct as WebglAddon}; + //# sourceMappingURL=addon-webgl.mjs.map +diff --git a/src/GlyphRenderer.ts b/src/GlyphRenderer.ts +index be1990c2a61a0ff5a37622ef7b6d8772e7a1056c..97a02452c3ff9e43b9dfb37e8b1c9b20e7831804 100644 +--- a/src/GlyphRenderer.ts ++++ b/src/GlyphRenderer.ts +@@ -363,7 +363,10 @@ export class GlyphRenderer extends Disposable { + // Bind the atlas page texture if they have changed. AtlasPage.version is globally + // monotonic, so a page object swap at the same index (which happens after a page merge) + // is detected by the same comparison. +- for (let i = 0; i < this._atlas.pages.length; i++) { ++ // pages can temporarily exceed the texture-unit budget (merge fallback ++ // pushes past maxAtlasPages); clamp so render() cannot throw on the ++ // missing texture slot and kill rendering entirely. ++ for (let i = 0; i < Math.min(this._atlas.pages.length, this._atlasTextures.length); i++) { + if (this._atlas.pages[i].version !== this._atlasTextures[i].version) { + this._bindAtlasPageTexture(gl, this._atlas, i); + } +diff --git a/src/TextureAtlas.ts b/src/TextureAtlas.ts +index 1c3e08a1cb14208e3d8b6dd726c79285200b9df4..4785172e35b65fdc9b2c3b4dad24669a9b11b860 100644 +--- a/src/TextureAtlas.ts ++++ b/src/TextureAtlas.ts +@@ -140,12 +140,23 @@ export class TextureAtlas implements ITextureAtlas { + } + + public clearTexture(): void { +- if (this._pages[0].currentRow.x === 0 && this._pages[0].currentRow.y === 0) { ++ // Guard on real content, not pages[0].currentRow: after a page merge a ++ // merged page (never written directly, currentRow at origin) can occupy ++ // index 0, which made every subsequent clearTexture a silent no-op. ++ if (this._pages.every(page => page.glyphs.length === 0 && page.currentRow.x === 0 && page.currentRow.y === 0)) { + return; + } + for (const page of this._pages) { + page.clear(); + } ++ // Merges remove pages from the active set permanently; after a wipe every ++ // page is empty again, so restore them all for allocation. ++ this._activePages.length = 0; ++ for (const page of this._pages) { ++ if (page !== this._overflowSizePage) { ++ this._activePages.push(page); ++ } ++ } + this._cacheMap.clear(); + this._cacheMapCombined.clear(); + this._didWarmUp = false; +@@ -1111,6 +1122,10 @@ class AtlasPage { + + public clear(): void { + this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); ++ // Wiped glyphs must not linger in the page stats: stale _glyphs/_usedPixels ++ // distort merge-candidate selection after a clearTexture. ++ this._glyphs.length = 0; ++ this._usedPixels = 0; + this.currentRow.x = 0; + this.currentRow.y = 0; + this.currentRow.height = 0; +diff --git a/src/WebglRenderer.ts b/src/WebglRenderer.ts +index a951efba5c75e82735cd39b6b22c4b5d5fad5928..7cc90292d352b134e7daf2bb7857da8f3f34cb9d 100644 +--- a/src/WebglRenderer.ts ++++ b/src/WebglRenderer.ts +@@ -386,7 +386,10 @@ export class WebglRenderer extends Disposable implements IRenderer { + // page's version, so re-run the update and force a full texture rebind. + let merged = false; + let mergeRetries = 0; +- while (this._charAtlas && this._glyphRenderer.value.beginFrame() && mergeRetries++ < Constants.MERGE_RETRY_LIMIT) { ++ // Check the retry budget BEFORE beginFrame: beginFrame consumes the ++ // clear-model notification, so consuming it on the iteration that trips ++ // the limit would leave a stale model with no later rebuild. ++ while (this._charAtlas && mergeRetries++ < Constants.MERGE_RETRY_LIMIT && this._glyphRenderer.value.beginFrame()) { + merged = true; + this._clearModel(true); + this._updateModel(0, this._terminal.rows - 1); diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index bdabd2a7b791..6dc255162069 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "updatedAt": "2026-07-03", + "updatedAt": "2026-07-10", "policy": { "maturityLevels": [ "experimental", @@ -105,6 +105,291 @@ ], "demotionRule": "Demote or quarantine if the gate flakes once without a product bug or harness bug filed to the owner." }, + { + "id": "terminal-session.kill-all-surface-cleanup", + "title": "Kill all sessions removes only the confirmed terminal surfaces and current bindings", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-runtime", + "layer": "renderer-main-contract", + "surfaces": [ + "terminal lifecycle", + "terminal tab cleanup", + "PTY shutdown", + "Manage Sessions", + "Resource Manager" + ], + "platforms": [ + "macos", + "linux", + "windows" + ], + "providers": [ + "local", + "daemon", + "ssh", + "wsl", + "remote-runtime", + "mobile-relay" + ], + "coveredPlatforms": [ + "macos" + ], + "coveredProviders": [ + "local", + "daemon", + "ssh" + ], + "coverageNotes": "Local macOS deterministic evidence covers the renderer snapshot/coordinator, exact local and SSH-shaped PTY request settlement, active-last and pinned terminal-tab routing, component-unmount continuation, and the existing current/legacy daemon management contract. Windows Electron process absence, live SSH/WSL behavior, and remote-runtime/mobile host completion remain explicit gaps.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/issues/8001" + ], + "invariant": "Every terminal surface confirmed in the invoking renderer is force-closed exactly once after daemon management settles, later-created surfaces and non-terminal tabs survive, and exact shutdown requests are limited to deduplicated current non-runtime PTY bindings of the confirmed surfaces.", + "oracle": "Snapshot terminal entity IDs before the first await; mutate ownership, active selection, bindings, and tab presence while daemon management is pending; then assert only the immutable targets disappear from both terminal stores, active targets close last with valid editor/browser/deactivated post-state, every captured exact PTY promise settles before callbacks, and no provider inventory sweep or late-tab kill occurs.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts src/renderer/src/components/shared/useDaemonActions.test.tsx src/renderer/src/components/terminal/terminal-tab-actions-kill-all.test.ts src/main/ipc/pty-management.test.ts" + ], + "testFiles": [ + "src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", + "src/renderer/src/components/shared/useDaemonActions.test.tsx", + "src/renderer/src/components/terminal/terminal-tab-actions-kill-all.test.ts", + "src/main/ipc/pty-management.test.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", + "assertions": [ + "snapshot deduplicates legacy, unified-only, split, multi-worktree, and floating terminal surfaces while excluding editor tabs", + "cleanup-time moves, active-worktree switches, rebinding, missing targets, and later-created tabs preserve the confirmation boundary and active-last order", + "current exact PTY bindings are deduplicated, remote runtime IDs and stale/late bindings are excluded, and all per-PTY settlements finish before completion", + "the production dependency path calls daemon management exactly once and never invokes listSessions for a post-kill sweep", + "management rejection and per-close/provider failures do not stop remaining cleanup and produce bounded count/latency diagnostics", + "a real 100-tab Zustand fixture records 100 close attempts and exact kills, at least 100 writes, 49 event-loop yields, and no close batch over 50 ms" + ] + }, + { + "file": "src/renderer/src/components/shared/useDaemonActions.test.tsx", + "assertions": [ + "the hook snapshots before onKillAllStart and before coordinator work", + "unmounting the invoking component does not revoke cleanup while React callbacks remain mount-gated", + "error and settled callbacks run only after coordinator settlement", + "closed terminal tabs report success instead of the no-sessions informational state when daemon management reports zero" + ] + }, + { + "file": "src/renderer/src/components/terminal/terminal-tab-actions-kill-all.test.ts", + "assertions": [ + "force closes pinned terminals without a second confirmation", + "closing the last active terminal preserves and activates editor or browser content, otherwise deactivates without auto-spawn" + ] + }, + { + "file": "src/main/ipc/pty-management.test.ts", + "assertions": [ + "killAll fires one shutdown for each initial daemon session and polls those initial IDs until empty", + "freshly respawned session IDs are excluded from remainingCount", + "per-session shutdown rejection does not stop the daemon batch and refused initial sessions remain reported" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-07-09", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts src/renderer/src/components/shared/useDaemonActions.test.tsx src/renderer/src/components/terminal/terminal-tab-actions-kill-all.test.ts src/main/ipc/pty-management.test.ts", + "result": "passed", + "durationSeconds": 1.31, + "summary": "4 test files and 27 tests passed locally, including the existing daemon handler contract and a real 100-terminal Zustand cleanup fixture." + } + ], + "runtimeBudget": { + "p95Seconds": 10, + "scope": "focused renderer/main unit and performance-count tests" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "The focused 27-test slice passed locally once; it needs CI and soak history before promotion." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "The initial 100-tab implementation exposed a 145.82 ms close batch and failed the 50 ms budget; two-close event-loop batching reduced the focused run below the budget. Saved CI artifacts and intentional-break evidence for the confirmation-boundary assertions are still needed." + }, + "performanceBudget": { + "required": true, + "evidence": "The coordinator performs one existing management call, zero provider inventory sweeps, one close per present unique target, and at most one exact kill per unique current non-runtime PTY binding. A real 100-tab Zustand fixture asserts 100 close attempts, 100 exact kill calls, at least 100 store writes, 49 event-loop yields, and a maximum two-close batch at or below 50 ms." + }, + "promotionCriteria": [ + "Run the focused gate for at least 100 consecutive passes or 14 days across required CI platforms.", + "Attach Windows Electron evidence for both entry points, empty and established terminals, later-tab survival, xterm removal, and initial PTY absence after settlement.", + "Exercise the SSH fixture and WSL when available, or keep their live process-absence gaps explicit.", + "Propagate and align runtime-host tab-close completion before claiming verified remote-runtime shutdown." + ], + "knownGaps": [ + "Windows Electron screenshots and live process/xterm absence evidence were not produced by this local macOS run.", + "Live SSH and WSL process absence, Linux local/daemon behavior, and mobile/relay shutdown remain unproved.", + "Runtime-host terminal close is best-effort because closeTerminalTab still discards the existing async host result and its close-intent lifetime is shorter than the possible RPC flow.", + "Daemon adapter listing failures remain suppressed by the existing management API, so reported daemon counts are not authoritative verification of every process." + ], + "demotionRule": "Keep experimental or demote to protection none if the gate flakes, permits a late-created tab or unrelated PTY to close, or exceeds the 50 ms maximum close-batch budget without a tracked product or harness bug." + }, + { + "id": "terminal-session.startup-cwd-missing-dir-recovery", + "title": "Fresh local terminal creation cannot be bricked by a deleted startup cwd", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-runtime", + "layer": "shared-main-renderer-contract", + "surfaces": [ + "terminal lifecycle", + "tab creation", + "PTY spawn", + "startup cwd persistence" + ], + "platforms": [ + "macos", + "linux", + "windows", + "mobile" + ], + "providers": [ + "local", + "daemon", + "ssh", + "wsl", + "remote-runtime" + ], + "coveredPlatforms": [ + "macos" + ], + "coveredProviders": [ + "local", + "ssh", + "remote-runtime" + ], + "coverageNotes": "Local macOS evidence covers the shared missing-dir fallback policy, main pty:spawn recovery and metadata, no-flag and reattach strictness, renderer IPC flag routing, SSH-tagged and remote-runtime omission, and the visibility-gated terminal notice. Daemon shares the same pre-provider main cwd decision but lacks a live daemon-provider run; WSL UNC paths are exempt from the probe by design and lack a live run; Linux/Windows and mobile/API strictness are gaps.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/issues/7239", + "https://github.com/stablyai/orca/pull/7750", + "https://github.com/stablyai/orca/pull/7678" + ], + "invariant": "A fresh local renderer terminal spawn may recover from a saved startup cwd whose directory no longer exists only by spawning at the selected workspace root and printing a generic in-terminal notice; existing directories — including ones outside the worktree (#7685) — spawn as requested, and reattach, SSH, remote-runtime, runtime/API, and mobile callers keep exact cwd semantics.", + "oracle": "The shared resolver falls back to the workspace root only when the injected existence probe reports the resolved cwd missing and the workspace root present, and never probes floating terminals or a cwd equal to the root. The renderer sends cwdFallback only for fresh local IPC spawns, main honors it only when connectionId and sessionId are absent, WSL UNC paths never engage the probe-based fallback, main returns fallback metadata only after an actual fallback, the IPC transport preserves that metadata, and the connection layer writes a generic notice that omits the missing path.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal-startup-cwd.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts" + ], + "testFiles": [ + "src/shared/terminal-startup-cwd.test.ts", + "src/main/ipc/pty.test.ts", + "src/renderer/src/components/terminal-pane/pty-transport.test.ts", + "src/renderer/src/components/terminal-pane/pty-connection.test.ts" + ], + "assertionRefs": [ + { + "file": "src/shared/terminal-startup-cwd.test.ts", + "assertions": [ + "a missing requested cwd falls back to the workspace root and reports the missing path to the callback", + "existing cwds — nested or outside the worktree (#7685) — are never remapped", + "no fallback happens when the workspace root is missing too", + "floating terminal cwds and root-equal requests are never probed", + "non-ASCII worktree roots and folder workspace roots are recovered verbatim" + ] + }, + { + "file": "src/main/ipc/pty.test.ts", + "assertions": [ + "local pty:spawn with cwdFallback worktree spawns at the worktree root when the saved cwd is missing and returns fallback metadata", + "a missing cwd without the flag still surfaces the provider's missing-directory error", + "an existing outside-worktree cwd spawns as requested without fallback metadata", + "session reattach spawns ignore the fallback flag and keep exact cwd semantics" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/pty-transport.test.ts", + "assertions": [ + "IPC transport sends cwdFallback only for local fresh spawns", + "SSH-tagged and session reattach spawns omit cwdFallback", + "IPC transport returns startup cwd fallback metadata to the connection layer" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/pty-connection.test.ts", + "assertions": [ + "fresh local IPC worktree spawns are marked with cwdFallback worktree", + "startup cwd fallback metadata prints a generic in-terminal notice", + "remote-runtime worktree spawns are not marked with cwdFallback" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-07-08", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal-startup-cwd.test.ts", + "result": "passed", + "durationSeconds": 0.2, + "summary": "1 test file passed, 21 tests passed; covers the missing-dir fallback policy, #7685 outside-worktree preservation, and root-missing/floating exemptions." + }, + { + "date": "2026-07-08", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts", + "result": "passed", + "durationSeconds": 0.9, + "summary": "1 test file passed, 225 tests passed; covers main pty:spawn recovery, fallback metadata, and no-flag/reattach provider-error strictness." + }, + { + "date": "2026-07-08", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts", + "result": "passed", + "durationSeconds": 0.4, + "summary": "1 test file passed, 58 tests passed; covers cwdFallback forwarding only for local fresh spawns and metadata handoff." + }, + { + "date": "2026-07-08", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts", + "result": "passed", + "durationSeconds": 6.5, + "summary": "1 test file passed, 341 tests passed; covers local IPC marking, the generic terminal fallback notice, and remote-runtime omission." + } + ], + "runtimeBudget": { + "p95Seconds": 30, + "scope": "focused unit and IPC contract tests" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "New experimental gate added with local deterministic evidence only; needs CI soak before promotion." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "The main IPC missing-cwd tests fail with the provider's 'Working directory ... does not exist.' error when the fallback is removed and pass with it. Full live Electron reproduction from a production persisted session is not captured." + }, + "performanceBudget": { + "required": true, + "evidence": "The runtime change adds at most two statSync probes on the fresh-local spawn path (the provider already stats the same paths during validation) and one bounded terminal write only when fallback actually occurs; no polling, provider listing, hidden-pane work, startup awaits, subprocesses, or render-loop work was added." + }, + "promotionCriteria": [ + "Attach CI evidence for all declared test files.", + "Add a live Electron regression that opens a local terminal whose persisted startupCwd was deleted and proves visible shell input/output at the workspace root.", + "Add WSL/mobile/API provider-contract coverage or explicitly narrow their risk scope." + ], + "knownGaps": [ + "No live Electron fixture seeds a persisted tab whose startupCwd directory was deleted.", + "Daemon coverage is via the shared pre-provider main cwd decision, not a live daemon provider spawn.", + "WSL UNC paths bypass the probe by design and have no live existence-recovery run; Linux, Windows, and mobile/API strictness are not directly exercised." + ], + "demotionRule": "Demote or quarantine if the gate flakes without a product bug, if an existing directory is ever remapped away from the requested cwd, or if a reattach/remote/API caller can engage the fallback." + }, { "id": "agent-session.provider-ownership", "title": "Provider sessions are resumed once per workspace ownership claim", @@ -684,7 +969,7 @@ "id": "terminal-platform.windows-conpty-liveness", "title": "Windows ConPTY terminals stay input-live, render-live, and geometry-live", "maturity": "experimental", - "protection": "none", + "protection": "partial", "owner": "terminal-platform", "layer": "windows-electron-conpty", "surfaces": [ @@ -702,34 +987,77 @@ "daemon", "wsl" ], - "coveredPlatforms": [], - "coveredProviders": [], - "coverageNotes": "Registered gap only; no executable coverage is wired yet.", + "coveredPlatforms": [ + "windows" + ], + "coveredProviders": [ + "daemon" + ], + "coverageNotes": "Issue #8048 now has deterministic wrapper and cold-restore re-anchor tests plus a Windows PR-CI harness that drives the built daemon through 25 real ConPTY workspace-close races while an unrelated witness PTY stays alive. Keyboard reset, CJK repaint, WSL, and full visible Electron coverage remain gaps.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6541", "https://github.com/stablyai/orca/pull/6858", "https://github.com/stablyai/orca/pull/6876", "https://github.com/stablyai/orca/pull/6968", "https://github.com/stablyai/orca/pull/6970", - "https://github.com/stablyai/orca/pull/6999" + "https://github.com/stablyai/orca/pull/6999", + "https://github.com/stablyai/orca/issues/8048" + ], + "invariant": "Windows local and daemon terminals must spawn with the intended shell, survive overlapping graceful/forced workspace teardown without affecting unrelated PTYs, retain recovered scrollback across the fresh daemon's first checkpoint, accept normal Enter/Backspace/Arrow input after agent or TUI exit, render cursor/CJK/wide-glyph redraws without stale cells, and converge to nonzero applied size.", + "oracle": "The issue #8048 slice asserts one node-pty ConPTY close for a graceful-then-force sequence, atomically seeds recovered history before fresh shell output and re-anchoring, preserves recovery after seed failure plus adapter restart, and runs 25 built-daemon close races while checking victim session/PID reaping, a stable daemon PID, and a live witness PTY. A broader Windows live gate still needs shell input, resize, cursor, and CJK/wide-glyph pixel evidence.", + "commands": [ + "pnpm vitest run src/main/daemon/pty-subprocess.test.ts src/main/daemon/daemon-pty-adapter.test.ts", + "pnpm build:electron-vite && node config/scripts/windows-daemon-workspace-close-repro.mjs", + "node config/scripts/windows-daemon-workspace-close-repro.mjs" + ], + "testFiles": [ + "src/main/daemon/pty-subprocess.test.ts", + "src/main/daemon/daemon-pty-adapter.test.ts", + "config/scripts/windows-daemon-workspace-close-repro.mjs" + ], + "assertionRefs": [ + { + "file": "src/main/daemon/pty-subprocess.test.ts", + "assertions": [ + "graceful kill followed by force and dispose invokes Windows node-pty kill exactly once and never retries the dead child PID" + ] + }, + { + "file": "src/main/daemon/daemon-pty-adapter.test.ts", + "assertions": [ + "the first checkpoint orders recovered scrollback before synchronously emitted fresh-shell startup output", + "a failed atomic history seed remains non-authoritative across adapter restart and cannot overwrite the recovery files" + ] + }, + { + "file": "config/scripts/windows-daemon-workspace-close-repro.mjs", + "assertions": [ + "all 25 victim sessions and OS PIDs are reaped while the built daemon PID and an unrelated witness PowerShell remain alive" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-07-10", + "runner": "local", + "platform": "windows", + "command": "node config/scripts/windows-daemon-workspace-close-repro.mjs", + "result": "passed", + "durationSeconds": 7.6, + "summary": "All 25 victim sessions and OS PIDs were reaped while the built daemon and witness PTY survived the real ConPTY workspace-close races. The double-close, history ordering, and seed-failure restart regressions produced intentional red failures before their fixes and passed afterward." + } ], - "invariant": "Windows local and daemon terminals must spawn with the intended shell, accept normal Enter/Backspace/Arrow input after agent or TUI exit, render cursor/CJK/wide-glyph redraws without stale cells, and converge to nonzero applied size.", - "oracle": "A Windows live gate proves shell echo, command submission, keyboard reset, resize readback, cursor visibility, and CJK/wide-glyph redraw using PTY input logs plus visible buffer/pixel evidence.", - "commands": [], - "testFiles": [], - "assertionRefs": [], - "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 90, "scope": "Windows focused Electron ConPTY gate" }, "flakeHistory": { - "status": "not-started", - "evidence": "Windows live E2E remains a known weak area; gate must soak before blocking." + "status": "unknown", + "evidence": "The built-daemon issue #8048 harness passed locally once and is wired into Windows PR CI; it needs repeated CI history before promotion." }, "redGreenEvidence": { - "status": "missing", - "evidence": "Needs proof against stale keyboard-protocol mode, shell resolution failure, dropped resize, and CJK repaint regression." + "status": "partial", + "evidence": "The ConPTY double-close and cold-restore re-anchor assertions were each observed failing before the fix and passing afterward. Keyboard protocol, shell resolution, resize, and CJK repaint still need red/green proof." }, "performanceBudget": { "required": true, @@ -741,8 +1069,8 @@ "Split shell parity, keyboard reset, and CJK repaint into smaller gates if a combined gate is flaky." ], "knownGaps": [ - "No manifest command yet.", - "Real IME composition may require a separate lower-layer/native-text-forwarding gate." + "Real IME composition may require a separate lower-layer/native-text-forwarding gate.", + "The built-daemon harness proves process/session liveness but not renderer pixels; visible shell input, resize, cursor, and CJK repaint remain uncovered." ], "demotionRule": "Cannot promote while Windows E2E is flaky, silently skipped, or screenshot-only." }, @@ -1273,7 +1601,7 @@ "macos" ], "coveredProviders": [], - "coverageNotes": "Local macOS evidence on main@1282f5c2d; identical files to the pending stack. Real OS IME automation, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps.", + "coverageNotes": "Local macOS evidence on main@1282f5c2d, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy, and a local Electron/CDP live-PTY Sogou-style repro. Real Linux/Sogou OS IME automation, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6699", "https://github.com/stablyai/orca/pull/6682", @@ -1281,14 +1609,20 @@ "https://github.com/stablyai/orca/pull/6999" ], "invariant": "Composition, native text forwarding, synthetic input, paste, and platform keyboard bypass paths must not send preedit/control bytes before commit and must commit text exactly once to the intended PTY.", - "oracle": "The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, input-source classification handles synthetic/native paths, and paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures. Real IME paths and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.", + "oracle": "The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, input-source classification handles synthetic/native paths, paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures, and Linux/Sogou candidate Space/digit selectors do not leak keydown/keypress/keyup while ordinary post-IME typing remains available. The Electron/CDP live-PTY repro verifies Sogou-style Space and digit candidate selectors submit only the committed Chinese text. Real IME paths and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts" + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts", + "pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts" ], "testFiles": [ "src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts", "src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts", - "src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts" + "src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts", + "src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts", + "src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts", + "src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts", + "src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts", + "tests/e2e/chinese-ime-chat-input-repro.spec.ts" ], "assertionRefs": [ { @@ -1309,34 +1643,80 @@ "assertions": [ "paste/runtime forwarding avoids duplicate terminal payloads" ] + }, + { + "file": "src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts", + "assertions": [ + "empty Sogou-style compositionupdate keeps composition active", + "stale composition state expires so editing keys cannot stay suppressed indefinitely", + "post-composition candidate guard is armed only by Sogou-style empty updates and clears after real typing" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts", + "assertions": [ + "suppressed candidate keydown arms only the matching keypress/keyup release guard", + "held-key repeat keydowns stay guarded until their keyup, even past expiry", + "fresh keydowns, other keys, modified keys, and expired keypresses are not guarded, and a fresh press drops a stale pending release" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts", + "assertions": [ + "standalone Linux 229 keydowns reach xterm while Windows 229 keydowns stay suppressed", + "candidate Space/digit selectors are suppressed only while candidate guards are active" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts", + "assertions": [ + "macOS standalone Process key behavior and composition-owned key suppression stay intact" + ] + }, + { + "file": "tests/e2e/chinese-ime-chat-input-repro.spec.ts", + "assertions": [ + "Sogou-style Space candidate selection submits only the committed Chinese character", + "Sogou-style digit candidate selection submits only the committed Chinese phrase", + "Post-composition Sogou-style digit selection stays out of the PTY after compositionend" + ] } ], "evidenceRuns": [ { - "date": "2026-07-03", + "date": "2026-07-07", "runner": "local", "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts", "result": "passed", - "durationSeconds": 0.9, - "summary": "3 test file(s) passed, 63 tests passed on main@1282f5c2d in a clean checkout." + "durationSeconds": 0.7, + "summary": "7 test file(s) passed, 144 tests passed on the Linux/Sogou candidate-key branch (includes held-key repeat guard coverage)." + }, + { + "date": "2026-07-07", + "runner": "local", + "platform": "macos", + "command": "pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts", + "result": "passed", + "durationSeconds": 72.0, + "summary": "Electron/CDP IME repro passed: Sogou candidate selection, post-composition candidate selection, and existing Chinese IME harness passed; real Codex IME test was skipped behind ORCA_E2E_REAL_CODEX_IME." } ], "runtimeBudget": { - "p95Seconds": 30, - "scope": "renderer unit plus platform soak" + "p95Seconds": 90, + "scope": "renderer unit plus focused Electron/CDP IME repro" }, "flakeHistory": { "status": "unknown", - "evidence": "Focused renderer input tests are now registered; needs soak history and platform IME evidence before promotion." + "evidence": "Focused renderer input tests and the Electron/CDP Sogou-style repro are now registered; needs soak history and true platform IME evidence before promotion." }, "redGreenEvidence": { "status": "partial", - "evidence": "Focused tests cover existing native-text, input-source, and paste/runtime forwarding contracts. Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix." + "evidence": "Focused tests cover existing native-text, input-source, paste/runtime forwarding, Linux/Sogou candidate selector, post-composition guard contracts, and live-PTY Sogou-style candidate commits. Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix." }, "performanceBudget": { - "required": false, - "evidence": "Required if input forwarding adds polling, repeated event listeners, or renderer hot-path work." + "required": true, + "evidence": "Terminal IME hot-path audit clean on 2026-07-07: candidate guard adds O(1) boolean checks plus a bounded Space/digit release map; composition listeners are disposed with pane lifecycle; no polling, IPC fan-out, subprocess work, or SSH/remote transport cost added." }, "promotionCriteria": [ "Cover deterministic byte/cell oracles first.", @@ -1344,7 +1724,7 @@ "Pair with Windows ConPTY keyboard reset for Windows standard-key behavior." ], "knownGaps": [ - "Current command is a renderer-unit slice; real OS IME automation may need manual or soak evidence.", + "Current commands include renderer-unit coverage and a CDP-driven Electron repro; real OS IME automation may need manual or soak evidence.", "Backspace/Enter during composition, JIS yen, Arabic/RTL, paste edge cases, and Windows ConPTY post-agent key reset still need representative gate coverage." ], "demotionRule": "Cannot promote if success is based only on DOM text without PTY byte/cell evidence." @@ -1411,6 +1791,396 @@ ], "demotionRule": "Cannot promote if standard-key behavior is inferred without PTY byte evidence." }, + { + "id": "terminal-input.windows-modified-enter-routing", + "title": "Windows modified Enter routes agent-compatible bytes to the active pane", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-input", + "layer": "main-provider-renderer-unit-and-windows-electron", + "surfaces": [ + "terminal input", + "Windows modified Enter", + "agent identity", + "split panes", + "SSH", + "WSL", + "remote runtime" + ], + "platforms": [ + "macos", + "linux", + "windows" + ], + "providers": [ + "local", + "daemon", + "ssh", + "wsl", + "remote-runtime" + ], + "coveredPlatforms": [ + "macos" + ], + "coveredProviders": [], + "coverageNotes": "Deterministic main/renderer tests run on macOS and exercise simulated Windows plus POSIX/Linux process-confirmation behavior. They cover exact local-ConPTY membership, detached-child rejection, unchanged SSH/WSL/remote fallback, process-confirmed Droid routing and launch-triggered confirmation, typed-alias and forged-OSC isolation, shells without OSC 133, split/detach ownership with preserved shell classification, stale PTY exit/rebind rejection, command-generation revocation, daemon v21 warm-reattach identity, unavailable inspection, and lazy subprocess/RPC callback counts. The Electron byte test runs only on Windows; live Windows and Linux PTY evidence remains uncollected. Test failures report exact expected bytes; no product telemetry or raw terminal logging is added.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/issues/7620", + "https://github.com/stablyai/orca/pull/7668" + ], + "invariant": "Shift+Enter sends CSI-u only when the active pane is a genuine local Windows ConPTY with allowlisted Droid ownership or fresh routing-trusted Droid process evidence. Every new command and PTY replacement revokes stale routing until current evidence settles. All other Windows panes preserve Esc+CR; non-Windows panes remain CSI-u; SSH/WSL/remote behavior is unchanged; split or reused panes cannot inherit sibling or prior-PTY authority; unrelated keys perform no agent or ConPTY lookup.", + "oracle": "Main/renderer tests assert exact bytes for local and non-local Windows plus non-Windows policy cells. Fresh Windows process evidence authorizes bytes only after a recognized global candidate is intersected with the exact ConPTY console process list; detached descendants, helper failure/timeout/root-only fallback, stale PTY exit/rebind results, typed text, and hook/OSC output fail closed. A new OSC 133;C immediately publishes a routing-neutral generation, including during D-to-C races. In cmd.exe/Git Bash/custom shells without OSC 133, accepted inferred commands start the same fresh generation; accepted submit/interrupt, title exit, focus, and visibility revoke trusted Droid bytes while one bounded confirmation runs. Detach preserves the live PTY's source shell override so WSL/native classification cannot change with the current default. Ordinary fast shell commands use cached/no-scan paths; routing-relevant confirmation bypasses cached process snapshots and keeps the bounded three-read ladder. Daemon protocol v21 persists only an allowlisted launchAgent; warm reattach uses it as a display/confirmation hint and restores routing only after current process proof. The Windows Electron test focuses the real xterm textarea and records exact renderer-to-main PTY writes.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/daemon-server.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts src/main/daemon/pty-subprocess.test.ts src/main/ipc/pty.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider.test.ts src/main/providers/windows-conpty-process-membership.test.ts src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts src/renderer/src/store/slices/store-cascades.test.ts src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts src/shared/agent-process-recognition.test.ts src/shared/process-table-snapshot.test.ts tests/e2e/terminal-foreground-confirmation.unit.test.ts", + "pnpm run test:e2e -- tests/e2e/terminal-shortcuts.spec.ts" + ], + "testFiles": [ + "src/main/daemon/daemon-foreground-confirmation-protocol.test.ts", + "src/main/daemon/daemon-pty-adapter.test.ts", + "src/main/daemon/daemon-pty-router.test.ts", + "src/main/daemon/daemon-server.test.ts", + "src/main/daemon/degraded-daemon-pty-provider.test.ts", + "src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts", + "src/main/daemon/pty-subprocess.test.ts", + "src/main/ipc/pty.test.ts", + "src/main/providers/agent-foreground-process.test.ts", + "src/main/providers/local-pty-provider.test.ts", + "src/main/providers/windows-conpty-process-membership.test.ts", + "src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts", + "src/renderer/src/components/terminal-pane/pty-connection.test.ts", + "src/renderer/src/components/terminal-pane/pty-transport.test.ts", + "src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts", + "src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts", + "src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts", + "src/renderer/src/store/slices/store-cascades.test.ts", + "src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts", + "src/shared/agent-process-recognition.test.ts", + "src/shared/process-table-snapshot.test.ts", + "tests/e2e/terminal-foreground-confirmation.unit.test.ts", + "tests/e2e/terminal-shortcuts.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/shared/process-table-snapshot.test.ts", + "assertions": [ + "a fresh request bypasses a same-tick TTL cache and any scan already in flight before the request", + "same-turn fresh requests and ordinary cache misses share one later scan while requests arriving after it starts queue behind it" + ] + }, + { + "file": "src/main/providers/agent-foreground-process.test.ts", + "assertions": [ + "successful root-present Windows enumeration and failed, blank, malformed, or root-missing enumeration remain distinct evidence states", + "an observed shell root with no children is authoritative while a snapshot omitting that root is unavailable", + "an attached Droid candidate is authorized only when exact ConPTY membership contains it, while a detached Start-Process descendant is rejected", + "a Windows process-table scan with no recognized agent performs zero ConPTY membership helper forks", + "fresh POSIX scan failure or a snapshot missing the PTY root is unavailable rather than shell proof", + "the compatibility process-name API still preserves its existing fallback contract for other consumers" + ] + }, + { + "file": "src/main/providers/windows-conpty-process-membership.test.ts", + "assertions": [ + "the fixed node-pty helper returns validated integer console membership containing the PTY root", + "root-only fallback, malformed/missing-root messages, spawn errors, and a silent helper timeout all fail closed", + "the bounded timeout kills the child helper exactly once" + ] + }, + { + "file": "src/main/providers/local-pty-provider.test.ts", + "assertions": [ + "a delayed foreground confirmation is discarded after the owning PTY exits" + ] + }, + { + "file": "src/main/daemon/daemon-pty-adapter.test.ts", + "assertions": [ + "new daemon sessions and warm reattach results carry the same minimal allowlisted launchAgent" + ] + }, + { + "file": "src/main/daemon/daemon-server.test.ts", + "assertions": [ + "daemon protocol v21 persists allowlisted launchAgent across reattach and drops unknown identity strings" + ] + }, + { + "file": "src/main/daemon/pty-subprocess.test.ts", + "assertions": [ + "Windows daemon foreground lookup can return PowerShell synchronously before async process-tree enrichment resolves the agent", + "the enriched agent result is served by a later foreground read", + "fresh confirmation awaits a post-request scan instead of serving cached PowerShell and returns null when inspection is unavailable" + ] + }, + { + "file": "tests/e2e/terminal-foreground-confirmation.unit.test.ts", + "assertions": [ + "the real daemon handle and pane tracker keep restored Droid identity when confirmation resolves after the old cache window", + "one fresh command-finish scan confirms real shell exit, while unavailable inspection performs exactly three bounded reads and never claims shell" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts", + "assertions": [ + "Windows defaults and non-Droid agents preserve Esc+CR while explicit Droid capability selects CSI-u", + "SSH, WSL, and remote Windows-client panes preserve Esc+CR without consulting the Droid capability", + "non-Windows Shift+Enter remains CSI-u and unrelated keys invoke neither agent nor ConPTY callbacks" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts", + "assertions": [ + "only routing-trusted current process identity overrides launch evidence and confirmed shell foreground clears stale identity", + "a newer untrusted or neutral command generation blocks stale launch ownership until confirmation", + "only allowlisted fresh process or pane-scoped launch ownership selects Droid's CSI-u capability", + "forged hook or OSC-derived Droid status cannot change the Windows byte encoding", + "after split and original-pane close, a sole surviving sibling cannot inherit the original pane's Droid launch identity" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts", + "assertions": [ + "manual and restored local agent identity is published from bounded foreground-process reads", + "a delayed read cannot publish after the pane rebinds to a replacement PTY id", + "every new command publishes a routing-neutral generation before confirmation", + "typed agent text only widens the confirmation window and never becomes published or routable identity", + "unavailable typed-command confirmation stays on legacy routing through the three-read ladder and then fails closed", + "ordinary fast OSC 133;C-to-D command pairs publish shell without a fresh confirmation scan", + "command-start and visible launch recovery use at most three reads across the bounded 350 ms, 1.2 s, and 6 s ladder", + "null and rejected reads participate in the same bounded known-identity ladder", + "command-finished accepts one fresh recognized shell scan when agent evidence exists, while unavailable final evidence retires routing without claiming shell" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/pty-connection.test.ts", + "assertions": [ + "after detach remount, pane-key launch/process identity forces a leaked nested OSC 133;D through foreground confirmation", + "a still-running Droid process republishes Droid instead of being overwritten with shell-foreground evidence", + "typing droid does not route CSI-u until fresh process evidence confirms Droid", + "null and rejected command-start reads never promote typed Droid text to process evidence", + "typed Droid input cannot replace live Antigravity process or pane-scoped launch identity inside another TUI", + "typed Droid input on SSH or remote-runtime panes never writes local process evidence", + "Droid routing survives a fresh command-finish scan that still sees Droid and retires after one fresh shell result", + "a D-to-C transition immediately routes legacy bytes while the new command generation is pending", + "an identityless visible-read versus OSC 133;D race cancels stale sampling and fails closed to shell", + "a manually typed Droid in a shell without OSC 133 gains routing only after accepted-input fresh confirmation", + "accepted no-OSC exit or interrupt input immediately revokes trusted Droid bytes and confirms the returned shell", + "unavailable command-finish evidence resolves deferred cleanup, returns legacy routing, and does not assert shell foreground", + "daemon-returned allowlisted launchAgent requests warm-reattach confirmation without restoring stale byte authority or the original args/env payload, while missing identity fails closed", + "an unknown persisted wrapper cannot spoof launch identity and confirmed shell state prevents repeat focus scans" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/pty-transport.test.ts", + "assertions": [ + "allowlisted daemon launchAgent reaches PtyConnectResult on reattach", + "unknown launch identity is dropped at the renderer transport boundary" + ] + }, + { + "file": "src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts", + "assertions": [ + "pane-to-tab detach moves only the detached leaf's launch and process identity to its new pane key", + "pane-to-tab detach preserves the source PTY shell override across native PowerShell and WSL classifications", + "the source hook snapshot is retired rather than copied to a key the running PTY cannot emit", + "the detached Droid keeps CSI-u while the source sibling keeps its own legacy encoding" + ] + }, + { + "file": "src/shared/agent-process-recognition.test.ts", + "assertions": [ + "Droid's process name resolves to the allowlisted Droid agent identity without substring matching" + ] + }, + { + "file": "tests/e2e/terminal-shortcuts.spec.ts", + "assertions": [ + "on Windows the focused terminal sends CSI-u bytes for a Droid pane and Esc+CR bytes after switching that same pane to Antigravity identity", + "the byte oracle observes the real renderer-to-main PTY write path rather than terminal DOM state" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-07-10", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/daemon-server.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts src/main/daemon/pty-subprocess.test.ts src/main/ipc/pty.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider.test.ts src/main/providers/windows-conpty-process-membership.test.ts src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts src/renderer/src/store/slices/store-cascades.test.ts src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts src/shared/agent-process-recognition.test.ts src/shared/process-table-snapshot.test.ts tests/e2e/terminal-foreground-confirmation.unit.test.ts", + "result": "passed", + "durationSeconds": 8.71, + "summary": "Twenty-two focused test files passed (1206 tests) on current main, covering fresh-scan ordering/deduplication, exact ConPTY membership and detached-child rejection, stale PTY guards, daemon v21 launch ownership with current-process confirmation, no-OSC command/exit recovery, preserved detach shell classification, unavailable evidence, routing-neutral command generations, exact shortcut bytes, and the composed daemon-plus-tracker contract; the Windows Electron byte test remains platform-gated and is not counted as local macOS evidence." + } + ], + "runtimeBudget": { + "p95Seconds": 90, + "scope": "focused renderer units plus the Windows Electron terminal-shortcut spec" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "The deterministic units are stable locally; the Windows-only Electron byte path needs CI or nightly soak history before promotion." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "Reverting to the previous unconditional Windows Esc+CR branch fails the Droid byte assertion, while resolving launch metadata from any key other than the active pane fails the split-survivor isolation assertion. Saved intentional-break artifacts and live Windows history are still missing." + }, + "performanceBudget": { + "required": true, + "evidence": "Callback-count tests prove unrelated ordinary keys invoke neither ConPTY nor agent resolution. Windows Shift+Enter performs two store reads: one local-ConPTY classification with an O(tabs-in-worktree) tab lookup, then two pane-keyed O(1) ownership lookups. Typed text performs no routing write. Ordinary fast OSC 133;C-to-D shell commands perform no fresh confirmation RPC or process scan. An accepted submit/interrupt while trusted Droid is current, a typed allowlisted agent command, title exit, focus, visibility transition, or an idle burst after trusted Droid Shift+Enter can schedule the bounded confirmation ladder; each event cancels/deduplicates prior work and no timer recurs after settling. Windows confirmation performs one fresh process-table scan and forks exact ConPTY membership only after a recognized agent candidate appears; no recognized candidate makes zero helper calls. Same-turn fresh requests share one scan and later arrivals queue at most one successor. Recovery remains three bounded one-shot reads (350 ms, 1.2 s, 6 s). No polling loop, provider fanout, persistent listener, hidden-pane wake loop, or per-printable-key work is added." + }, + "promotionCriteria": [ + "Run the exact PTY-byte Electron oracle on Windows without silent platform skips.", + "Collect stable runtime and flake history for local and daemon Windows ConPTY while retaining deterministic unchanged-provider assertions for SSH, WSL, and remote runtime.", + "Attach saved intentional-break evidence for Droid capability removal and split-sibling identity leakage." + ], + "knownGaps": [ + "No Windows runner or live Linux PTY evidence is attached; the Electron byte test skips on macOS and Linux, while Linux behavior is covered only by deterministic POSIX unit paths.", + "Droid inside SSH, WSL, or remote-runtime intentionally keeps the pre-existing Windows-client Esc+CR behavior because local foreground confirmation is unavailable; this PR narrows the exception to issue #7620's local ConPTY surface.", + "The Electron test injects allowlisted pane identity rather than launching the real Droid and Antigravity binaries.", + "If both Windows process-enumeration backends remain unavailable through the bounded ladder, routing fails closed to the legacy Esc+CR path; no live Droid artifact covers that degraded host configuration.", + "Protocol v21 restarts older daemons because the minimal persisted launchAgent is a new contract; sessions preserved by pre-v21 daemons cannot supply warm-reattach launch ownership and fail closed until current process confirmation or restart.", + "No live daemon, SSH, WSL, remote-runtime, paired-web, or restore/replay byte artifact has been collected.", + "A running PTY keeps its spawn-time ORCA_PANE_KEY after pane-to-tab detach. This change transfers launch/process routing evidence and retires the stale hook snapshot, but does not redesign future hook reattribution across tab IDs." + ], + "demotionRule": "Keep non-blocking or demote to protection none if the Windows byte test silently skips, flakes without an actionable artifact, routes bytes using tab/title/terminal-output heuristics, or adds any ordinary-key lookup, IPC, polling, scan, or lifecycle leak." + }, + { + "id": "terminal-input.agent-prompt-injection", + "title": "Orchestration agent prompts arrive as bracketed paste before submit", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-input", + "layer": "runtime-contract-and-cli-repro", + "surfaces": [ + "terminal input", + "agent prompt injection", + "orchestration dispatch", + "PTY writes", + "bracketed paste" + ], + "platforms": [ + "macos", + "linux", + "windows" + ], + "providers": [ + "local", + "daemon", + "ssh", + "remote-runtime" + ], + "coveredPlatforms": [ + "macos" + ], + "coveredProviders": [ + "local" + ], + "coverageNotes": "Local macOS evidence covers the runtime PTY write contract and a live dev-runtime CLI repro. SSH, daemon, remote-runtime, Linux, and Windows remain provider/platform gaps; the product path stays provider-owned and does not add local filesystem or process assumptions.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/issues/7226" + ], + "invariant": "Injected orchestration task prompts for recognized agent CLIs must send the prompt body inside one bracketed-paste frame, sanitize embedded ESC bytes, preserve chunk boundaries without losing the frame, and send Enter only after the paste frame completes.", + "oracle": "Runtime tests assert the exact PTY write sequence and failure cleanup; orchestration tests assert dispatch/coordinator use the agent prompt path; the live CLI harness dispatches a 32KB task to a fake Codex-like TUI and requires marker present, bracketed paste present, zero unframed line breaks, and submit observed.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-prompt-injection.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/orchestration.test.ts src/main/runtime/orchestration/coordinator.test.ts", + "node tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000" + ], + "testFiles": [ + "src/shared/agent-prompt-injection.test.ts", + "src/main/runtime/orca-runtime.test.ts", + "src/main/runtime/rpc/methods/orchestration.test.ts", + "src/main/runtime/orchestration/coordinator.test.ts", + "tools/repro-orchestration-long-prompt.mjs" + ], + "assertionRefs": [ + { + "file": "src/shared/agent-prompt-injection.test.ts", + "assertions": [ + "agent prompts are always framed as bracketed paste", + "submit stays separate from the paste frame", + "embedded ESC bytes are made inert before framing", + "chunk reconstruction preserves the paste frame" + ] + }, + { + "file": "src/main/runtime/orca-runtime.test.ts", + "assertions": [ + "runtime writes bracketed paste before a delayed submit", + "large prompt frames are chunked and reconstructed before submit", + "partial prompt write failure closes the paste frame and does not submit" + ] + }, + { + "file": "src/main/runtime/rpc/methods/orchestration.test.ts", + "assertions": [ + "orchestration.dispatch uses the agent prompt path for injected preambles", + "raw terminal.send is not called for injected task prompts", + "failed prompt injection rolls back the active dispatch" + ] + }, + { + "file": "src/main/runtime/orchestration/coordinator.test.ts", + "assertions": [ + "coordinator dispatch failures from prompt injection circuit-break through the DB", + "silent-skip paths do not attempt prompt injection" + ] + }, + { + "file": "tools/repro-orchestration-long-prompt.mjs", + "assertions": [ + "fake Codex-like worker observes submit after long orchestration dispatch", + "32KB task marker survives before submit", + "prompt bytes include a bracketed-paste frame with zero unframed line breaks" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-07-07", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-prompt-injection.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/orchestration.test.ts src/main/runtime/orchestration/coordinator.test.ts", + "result": "passed", + "durationSeconds": 7.4, + "summary": "4 test files passed, 697 tests passed; covers framing, runtime PTY writes, orchestration RPC dispatch, and coordinator dispatch behavior." + }, + { + "date": "2026-07-07", + "runner": "local", + "platform": "macos", + "command": "node tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000", + "result": "passed", + "durationSeconds": 2.2, + "summary": "Live dev-runtime repro passed: expectedSpecBytes=32830, hasSubmit=true, rawContainsMarker=true, hasBracketedPasteFrame=true, unframedLineBreaks=0, contractOk=true." + } + ], + "runtimeBudget": { + "p95Seconds": 30, + "scope": "runtime contract tests plus optional local dev-runtime CLI repro" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "First local macOS evidence only; needs repeated dev-runtime harness runs and provider matrix evidence before promotion." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "The live harness reproduced the unsafe raw multiline contract before the fix and passes after the fix; intentional-break evidence is local only and not yet in CI." + }, + "performanceBudget": { + "required": true, + "evidence": "Agent prompt dispatch remains O(prompt bytes), uses the existing 16KB terminal input chunking and one existing 500ms submit delay, and adds no polling, provider listing, subprocess churn, hidden-pane wakeups, or renderer work." + }, + "promotionCriteria": [ + "Run the live harness in soak with a self-starting dev runtime or provider-contract fixture.", + "Add daemon, SSH, remote-runtime, Linux, and Windows evidence or mark narrower provider scope.", + "Capture stable red/green intentional-break evidence in CI before blocking promotion." + ], + "knownGaps": [ + "Live harness command currently expects an already-running dev runtime and generated out/bin/orca-dev wrapper.", + "No Windows ConPTY, Linux PTY, SSH, daemon, or remote-runtime live evidence yet.", + "Push-on-idle orchestration message banners remain outside this dispatch-prompt gate." + ], + "demotionRule": "Demote or quarantine if the live harness flakes without a product bug or harness bug filed to the terminal-input owner." + }, { "id": "terminal-render.windows-cjk-repaint", "title": "Windows ConPTY wide glyphs and cursor rewrites repaint without stale cells", @@ -2225,6 +2995,109 @@ "Buffer-clean, pixels-stale variants are otherwise invisible to every buffer oracle in the manifest." ], "demotionRule": "Drop from the golden suite back to nightly diagnostic if diff thresholds cannot be kept stable across CI runners." + }, + { + "id": "pty-delivery.renderer-lifecycle-accounting-reset", + "title": "Renderer lifecycle reset clears leaked PTY delivery accounting so surviving PTYs cannot freeze", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-runtime", + "layer": "main-unit", + "surfaces": [ + "terminal output delivery", + "renderer reload / crash recovery", + "surviving daemon and local PTYs" + ], + "platforms": [ + "macos", + "linux", + "windows" + ], + "providers": [ + "local", + "daemon" + ], + "coveredPlatforms": [ + "macos" + ], + "coveredProviders": [], + "coverageNotes": "Local macOS unit evidence over the shared main-process delivery pipeline in registerPtyHandlers. The oracle drives a local mock PTY, but the in-flight/pending accounting is provider-agnostic and daemon PTYs ride the identical pipeline (the manual dev repro that proved the freeze was daemon-backed). SSH is a separate relay/credit path and never enters these counters; mobile/relay ride unaffected paths; WSL terminals ride this same local/daemon pipeline and are covered by the same accounting (no dedicated provider-contract test yet). Motivated by a production incident on v1.4.131 (three frozen/broken terminal panes in one desktop session) diagnosed to leaked in-flight/pending accounting across a renderer reload (rendererGraphEpoch 3). Live validation of the fix on a rebuilt dev instance surfaced a second leak mode (the boot window): after the reset ran, main resumed flushing a flooding PTY into the still-booting page before its pty:data listener re-registered, so those sends were dropped yet counted and re-pinned rendererInFlightChars at 524288. The gate now also covers holding sends until the renderer's pty:rendererDispatcherReady handshake. A watchdog self-heals a lost handshake: on each reset a one-shot ~10s timer arms and, if the handshake never arrives, force-opens the gate (rendererDispatcherReadyForcedCount increments) so a dropped handshake degrades to pre-handshake behavior instead of a permanent hold; the real handshake or a re-registration cancels it. Two new diagnostics — rendererPtyDispatcherReady and rendererDispatcherReadyForcedCount — expose the otherwise-invisible boot-window hold, which early-returns before ackGatedFlushSkipCount increments.", + "motivatingLinks": [ + // #5787 introduced the renderer-reload delivery-accounting path this gate hardens; + // kept for lineage, not the primary motivation. THIS fix is motivated by the + // v1.4.131 three-frozen-panes incident (see coverageNotes). + "https://github.com/stablyai/orca/pull/5787", + "https://github.com/stablyai/orca/pull/8034" + ], + "invariant": "After a renderer lifecycle reset (did-start-loading / render-process-gone / destroyed), no surviving PTY remains delivery-gated by pre-reset unacked bytes: main's in-flight counters and pending backlog equal the true state of the new page (zero in-flight, zero pending). Delivery then resumes only once the reloaded page's pty:data dispatcher re-registers and signals pty:rendererDispatcherReady; during the boot window before that handshake main holds all sends (data accrues losslessly in the capped pending backlog) so bytes cannot be dropped into a listener-less page and re-pin the gate. The hold itself cannot become a permanent freeze: a one-shot ~10s watchdog armed on each reset force-opens the gate (incrementing rendererDispatcherReadyForcedCount) if the handshake is lost, and the real handshake or a re-registration cancels it. The reset fires only for a main-frame load: did-start-loading also fires for in-page subframe loads (sandboxed srcDoc iframes in notebook HTML output), which are filtered out via isLoadingMainFrame() so a subframe load never clears accounting or holds the gate on the still-alive page. If a lifecycle-reset edge is missed entirely — a main-frame reload overlapped by an in-page subframe load emits no did-start-loading at all — a backstop still recovers: because the handshake is one-shot per page load, receiving pty:rendererDispatcherReady while the gate is already open proves a reset was missed (or the watchdog force-opened the gate), so the handler reconciles by clearing the stale accounting before re-opening. The renderer sends that handshake exactly once per page load, after its pty:data listener registers.", + "oracle": "Ingest more than 512 KB of PTY output with no renderer ACKs and assert the per-PTY gate closes (sends stop at the 512 KB high-water, remainder accrues as pending). Fire the registered did-start-loading listener and assert rendererInFlightChars and pendingChars are zero and the new diagnostics record the reset (rendererLifecycleResetCount 1, lastLifecycleResetClearedChars 512 KB). Then, before any dispatcher-ready handshake, ingest another chunk and assert it is NOT sent and NOT counted in-flight (held for the boot window, accruing in pending). Finally fire the pty:rendererDispatcherReady handshake and assert the held chunk is delivered to the renderer. Counters-zero without proving both the boot-window hold and that delivery resumes is insufficient. Additional cases prove the boot-window hold also covers the interactive direct-send fast path (input-primed keystroke echo is held, not sent, until the handshake) and that the self-heal watchdog force-opens the gate (rendererDispatcherReadyForcedCount 1) when no handshake arrives, while a timely handshake cancels the watchdog and leaves no orphaned timer. A further case fires did-start-loading with isLoadingMainFrame() false (a subframe/iframe load) and asserts accounting is untouched (rendererLifecycleResetCount stays 0, pending preserved, ready stays true) and delivery still drains on ACK — proving an in-page iframe load cannot trigger a spurious freeze. A backstop case saturates the gate, then fires pty:rendererDispatcherReady while the gate is still open (ready true) with no preceding reset — modeling a missed lifecycle edge — and asserts the handler reconciles: in-flight and pending clear, rendererLifecycleResetCount increments, and fresh output flows immediately (a straggler ACK is clamped and cannot underflow). A renderer-side case (pty-dispatcher-pi-routing.test.ts) asserts ensurePtyDispatcher() sends pty:rendererDispatcherReady exactly once across two attach calls — proving the send fires (it is optional-chained) and the one-shot guard holds.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts src/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.ts" + ], + "testFiles": [ + "src/main/ipc/pty.test.ts", + "src/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.ts" + ], + "assertionRefs": [ + { + "file": "src/main/ipc/pty.test.ts", + "assertions": [ + "a PTY saturated past the 512 KB per-PTY high-water with no ACKs stops sending and accrues pending output (gate closed)", + "firing the registered did-start-loading listener zeroes rendererInFlightChars and pendingData and records rendererLifecycleResetCount and lastLifecycleResetClearedChars", + "after the reset, output ingested during the boot window is NOT sent and NOT counted in-flight until the pty:rendererDispatcherReady handshake fires (held in pending)", + "firing the pty:rendererDispatcherReady handshake releases the held backlog and delivery resumes (delivery gated on the handshake, not just counters cleared)", + "interactive input-primed keystroke echo is also held during the boot window (interactive fast path gated on the handshake) and delivered once it fires", + "when no handshake arrives, the ~10s watchdog force-opens the gate (rendererDispatcherReadyForcedCount 1) and the held backlog drains; a timely handshake cancels the watchdog and leaves no orphaned timer", + "a did-start-loading with isLoadingMainFrame() false (in-page subframe/iframe load) does NOT reset accounting (rendererLifecycleResetCount stays 0, pending and in-flight preserved, rendererPtyDispatcherReady stays true) and delivery still drains on ACK", + "a pty:rendererDispatcherReady handshake arriving while the gate is still open (ready true, no preceding reset — a missed lifecycle edge) reconciles the stale accounting: in-flight and pending clear, rendererLifecycleResetCount increments, fresh output flows, and a straggler ACK is clamped", + "re-registering handlers (macOS re-activate / new window) cancels the prior registration's armed dispatcher-ready watchdog via the cross-registration bridge, leaving no orphaned ~10s timer to force-open a dead window's gate" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.ts", + "assertions": [ + "ensurePtyDispatcher() sends pty:rendererDispatcherReady exactly once across two attach calls (the optional-chained send fires, and the ptyDispatcherAttached one-shot guard prevents a re-signal)" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-07-09", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts src/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.ts", + "result": "passed", + "durationSeconds": 1, + "summary": "243 tests passed (232 main-process + 11 renderer dispatcher) including the lifecycle-reset, boot-window (dispatcher-ready handshake), interactive-gate hold, watchdog self-heal, main-frame-filter (subframe did-start-loading is ignored), missed-reset reconcile backstop (handshake-while-open), cross-registration watchdog-cancel, and renderer-side one-shot handshake-send regressions. Removing the reset call reproduces the reload freeze (rendererInFlightChars stays 524288); removing the send-hold reproduces the boot-window leak; removing the interactive-path flag check sends keystroke echo into the not-yet-ready page; removing the watchdog arm leaves the gate held forever; removing the watchdog cancel leaves an orphaned timer after the handshake; removing the isLoadingMainFrame filter lets a subframe iframe load run a spurious reset; removing the handshake-while-open reconcile leaves the survivors pinned at 524288 after a missed lifecycle edge." + } + ], + "runtimeBudget": { + "p95Seconds": 10, + "scope": "local main-process unit test" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "Newly registered with this fix; needs soak history before any promotion. The oracle is deterministic (fake timers, mock webContents)." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "Locally verified red/green on every load-bearing branch: (1) reset call removed -> rendererInFlightChars stays 524288 after did-start-loading; (2) boot-window send-hold removed -> post-reload output is sent into the not-yet-ready page ('NOT sent until handshake' fails); (3) interactive-path flag check removed -> input-primed keystroke echo is sent during the hold; (4) watchdog arm removed -> the gate is never force-opened and the held backlog never drains; (5) watchdog cancel removed -> an orphaned ~10s timer survives the handshake (getTimerCount 1); (6) isLoadingMainFrame filter removed -> a subframe did-start-loading runs a spurious reset (rendererLifecycleResetCount 1, pending cleared, ready dropped) — locally verified red; (7) handshake-while-open reconcile removed -> a pty:rendererDispatcherReady arriving after a missed lifecycle edge leaves the gate pinned (rendererInFlightChars stays 524288, pending 90112, rendererLifecycleResetCount 0) — locally verified red; (8) cross-registration bridge cancel removed (top-of-registerPtyHandlers clearRendererDispatcherReadyWatchdog) -> a prior registration's armed watchdog survives re-registration as an orphaned timer (getTimerCount 1 instead of 0) — locally verified red. With the full fix all eight are green. The performance budget below still holds: the watchdog is a single unref'd one-shot per reset, not per-chunk. Needs a saved CI or intentional-break artifact before blocking promotion." + }, + "performanceBudget": { + "required": true, + "evidence": "The reset is an O(#ptys) map clear on rare lifecycle events (reload/crash) plus one unref'd one-shot ~10s watchdog timer per reset (cancelled by the handshake or a re-registration); no polling and no per-chunk work. Any PR changing the delivery gate, in-flight accounting, or flush loop must re-measure terminal throughput before promotion." + }, + "promotionCriteria": [ + "Run in soak for at least 100 consecutive passes or 14 days across required CI platforms.", + "Attach saved red/green evidence from removing the lifecycle-reset accounting clear.", + "Add an Electron-level reload survival test that proves a saturated pane resumes rendering and input after Cmd+R / crash recovery." + ], + "knownGaps": [ + "The unit oracle drives a local mock PTY; daemon and WSL coverage rides the same pipeline but has no dedicated provider-contract test yet.", + "The dev repro covers the output-delivery freeze only; the arrow-key input symptom and mouse-mode flood observed in the same incident are out of scope and need their own repros.", + "No live Electron reload-survival assertion yet — the gate proves the main-side accounting reset, not the full renderer reattach paint." + ], + "demotionRule": "Demote or quarantine if the gate flakes once without a product bug or harness bug filed to the owner." } ] } diff --git a/config/scripts/audit-localization-coverage.mjs b/config/scripts/audit-localization-coverage.mjs index 5a9a0ac2ef33..8b978e38ed4f 100644 --- a/config/scripts/audit-localization-coverage.mjs +++ b/config/scripts/audit-localization-coverage.mjs @@ -3,7 +3,8 @@ import path from 'node:path' import { pathToFileURL } from 'node:url' import process from 'node:process' -import ts from 'typescript' +// TypeScript 7 is a native CLI; AST consumers still need the legacy JavaScript API. +import ts from 'typescript-api' const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts']) const SKIP_PATH_PARTS = new Set(['.git', 'dist', 'node_modules', 'out', '__snapshots__', 'assets']) diff --git a/config/scripts/build-native-for-platform.mjs b/config/scripts/build-native-for-platform.mjs index a16cb34322a4..11ad15bc5f48 100755 --- a/config/scripts/build-native-for-platform.mjs +++ b/config/scripts/build-native-for-platform.mjs @@ -8,6 +8,8 @@ if (process.platform !== 'darwin') { } runPnpmScript('build:computer-macos') +runPnpmScript('build:notification-status-macos') +process.exit(0) function runPnpmScript(scriptName) { const npmExecPath = process.env.npm_execpath @@ -22,5 +24,7 @@ function runPnpmScript(scriptName) { if (result.signal) { process.kill(process.pid, result.signal) } - process.exit(result.status ?? (result.error ? 1 : 0)) + if (result.status !== 0 || result.error) { + process.exit(result.status ?? 1) + } } diff --git a/config/scripts/build-notification-status-macos.mjs b/config/scripts/build-notification-status-macos.mjs new file mode 100644 index 000000000000..e8150e32b6f1 --- /dev/null +++ b/config/scripts/build-notification-status-macos.mjs @@ -0,0 +1,97 @@ +#!/usr/bin/env node +// Builds the orca-notification-status helper binary. +// +// The helper reads UNUserNotificationCenter settings for the app it ships +// inside (see native/notification-status-macos/main.swift). The target +// CFBundleIdentifier is embedded as a __TEXT,__info_plist section so every +// later `codesign --force` pass (electron-builder's signing, the dev runner's +// ad-hoc deep sign) derives the correct code identifier automatically — +// macOS keys notification records to that identifier. +import { execFileSync } from 'node:child_process' +import { mkdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' + +const repoRoot = path.resolve(import.meta.dirname, '../..') +const sourcePath = path.join(repoRoot, 'native', 'notification-status-macos', 'main.swift') +const defaultOutputPath = path.join( + repoRoot, + 'native', + 'notification-status-macos', + '.build', + 'release', + 'orca-notification-status' +) + +if (process.platform !== 'darwin') { + process.exit(0) +} + +const args = process.argv.slice(2) +const bundleId = readArg('--bundle-id') ?? 'com.stablyai.orca' +const outputPath = readArg('--output') ?? defaultOutputPath +// Why: dev launches only need the host architecture; release builds ship a +// universal binary matching the app's x64 + arm64 targets. +const singleArch = args.includes('--single-arch') + +const workDir = path.join(tmpdir(), `orca-notification-status-${process.pid}`) +mkdirSync(workDir, { recursive: true }) +try { + const plistPath = path.join(workDir, 'Info.plist') + writeFileSync(plistPath, embeddedInfoPlist(bundleId), 'utf8') + const triples = singleArch + ? [process.arch === 'arm64' ? 'arm64-apple-macosx' : 'x86_64-apple-macosx'] + : ['arm64-apple-macosx', 'x86_64-apple-macosx'] + const builtBinaries = triples.map((triple) => { + const output = path.join(workDir, `orca-notification-status-${triple}`) + execFileSync( + 'swiftc', + [ + '-O', + sourcePath, + '-target', + triple.replace('-apple-macosx', '-apple-macosx11.0'), + '-o', + output, + '-Xlinker', + '-sectcreate', + '-Xlinker', + '__TEXT', + '-Xlinker', + '__info_plist', + '-Xlinker', + plistPath + ], + { stdio: 'inherit' } + ) + return output + }) + mkdirSync(path.dirname(outputPath), { recursive: true }) + if (builtBinaries.length === 1) { + execFileSync('cp', [builtBinaries[0], outputPath]) + } else { + execFileSync('lipo', ['-create', ...builtBinaries, '-output', outputPath]) + } + execFileSync('chmod', ['755', outputPath]) +} finally { + rmSync(workDir, { recursive: true, force: true }) +} + +function readArg(name) { + const index = args.indexOf(name) + return index >= 0 ? args[index + 1] : undefined +} + +function embeddedInfoPlist(identifier) { + return ` + + + + CFBundleIdentifier + ${identifier} + CFBundleName + orca-notification-status + + +` +} diff --git a/config/scripts/build-relay.mjs b/config/scripts/build-relay.mjs index da33ccb078d9..c9cabcea838b 100644 --- a/config/scripts/build-relay.mjs +++ b/config/scripts/build-relay.mjs @@ -59,4 +59,31 @@ for (const platform of PLATFORMS) { console.log(`Built relay for ${platform} → ${outDir}/relay.js`) } +// WSL agent-hook relay: a hooks-only guest receiver launched inside WSL +// distros via wsl.exe. Pure Node built-ins (no node-pty/@parcel/watcher), +// so a single platform-independent bundle suffices; it ships inside the +// Windows app via the same out/relay extraResources mapping. +{ + const wslEntry = join(ROOT, 'src', 'relay', 'wsl-agent-hook-relay.ts') + const outDir = join(ROOT, 'out', 'relay', 'wsl') + mkdirSync(outDir, { recursive: true }) + await build({ + entryPoints: [wslEntry], + bundle: true, + platform: 'node', + target: 'node18', + format: 'cjs', + outfile: join(outDir, 'wsl-agent-hook-relay.js'), + sourcemap: false, + minify: true, + define: { + 'process.env.NODE_ENV': '"production"' + } + }) + const content = readFileSync(join(outDir, 'wsl-agent-hook-relay.js')) + const hash = createHash('sha256').update(content).digest('hex').slice(0, 12) + writeFileSync(join(outDir, '.version'), `${RELAY_VERSION}+${hash}`) + console.log(`Built WSL hook relay → ${outDir}/wsl-agent-hook-relay.js`) +} + console.log('Relay build complete.') diff --git a/config/scripts/check-terminal-perf-report-budgets.mjs b/config/scripts/check-terminal-perf-report-budgets.mjs index 693822373f01..dd7185189d84 100644 --- a/config/scripts/check-terminal-perf-report-budgets.mjs +++ b/config/scripts/check-terminal-perf-report-budgets.mjs @@ -18,6 +18,7 @@ if (reportPaths.length === 0) { const BUDGETS = { maxMedianKeyLatencyMs: 75, maxWorstKeyLatencyMs: 300, + maxRevisitLatencyMs: 300, maxTimerDriftMs: 150, maxScrollLatencyMs: 150, maxRestoreLatencyMs: 1000, @@ -80,6 +81,12 @@ function validateRow(row) { BUDGETS.maxWorstKeyLatencyMs, 'ms' ) + addBudgetCheck( + 'revisit latency', + parseMs(row.revisit, 'revisit', row, failures), + BUDGETS.maxRevisitLatencyMs, + 'ms' + ) addBudgetCheck( 'timer drift', parseMs(row.maxTimerDrift, 'maxTimerDrift', row, failures), @@ -113,6 +120,14 @@ function validateRow(row) { parseCount(row.rendererDroppedBacklogs, 'rendererDroppedBacklogs', row, failures), BUDGETS.maxRendererDroppedBacklogs ) + // Why: parked-memory rows carry heap/view-count metrics with no latency + // budget; recognize them so memory-only scenarios pass the gate instead of + // tripping the "no recognized budget metrics" guard. + for (const fieldName of ['heapUsedMB', 'liveTerminals', 'livePaneManagers']) { + if (parseCount(row[fieldName], fieldName, row, failures) != null) { + checkedMetricCount += 1 + } + } if (checkedMetricCount === 0) { failures.push(`${row.source} ${row.scenario}: no recognized budget metrics found`) } diff --git a/config/scripts/check-terminal-perf-report-budgets.test.mjs b/config/scripts/check-terminal-perf-report-budgets.test.mjs index d1fd378b498d..e61299751516 100644 --- a/config/scripts/check-terminal-perf-report-budgets.test.mjs +++ b/config/scripts/check-terminal-perf-report-budgets.test.mjs @@ -58,6 +58,7 @@ describe('check-terminal-perf-report-budgets', () => { 'frames=180', 'median=2.9ms', 'worst=5.9ms', + 'revisit=42.0ms', 'maxTimerDrift=12.1ms', 'scroll=149.9ms', 'restore=642.0ms', @@ -82,6 +83,7 @@ describe('check-terminal-perf-report-budgets', () => { 'frames=60', 'median=76.0ms', 'worst=301.0ms', + 'revisit=301.0ms', 'maxTimerDrift=151.0ms', 'scroll=151.0ms', 'restore=1001.0ms', @@ -96,6 +98,7 @@ describe('check-terminal-perf-report-budgets', () => { expect(result.status).toBe(1) expect(result.stderr).toContain('median typing latency 76ms exceeded budget 75ms') expect(result.stderr).toContain('worst typing latency 301ms exceeded budget 300ms') + expect(result.stderr).toContain('revisit latency 301ms exceeded budget 300ms') expect(result.stderr).toContain('timer drift 151ms exceeded budget 150ms') expect(result.stderr).toContain('scroll latency 151ms exceeded budget 150ms') expect(result.stderr).toContain('restore latency 1001ms exceeded budget 1000ms') @@ -116,6 +119,31 @@ describe('check-terminal-perf-report-budgets', () => { expect(result.stderr).toContain('no recognized budget metrics found') }) + it('accepts revisit-only marker rows as budgeted perf evidence', () => { + const reportPath = writeReport('panes=19 revisit=25.7ms heldAckChars=2097184') + + const output = execFileSync(process.execPath, [scriptPath, reportPath], { + cwd: process.cwd(), + encoding: 'utf8' + }) + + expect(output).toContain('Terminal perf budget check passed for 1 annotation row(s).') + }) + + it('accepts parked-memory rows that carry only heap and view-count metrics', () => { + const reportPath = writeReport( + 'panes=8 parkedTabs=8 heapUsedMB=87.8 liveTerminals=1 livePaneManagers=1', + 'opencode-parked-memory' + ) + + const output = execFileSync(process.execPath, [scriptPath, reportPath], { + cwd: process.cwd(), + encoding: 'utf8' + }) + + expect(output).toContain('Terminal perf budget check passed for 1 annotation row(s).') + }) + it('fails OpenCode annotation rows that contain no budget metrics', () => { const reportPath = writeReport('panes=1 frames=60') diff --git a/config/scripts/computer-e2e-workflow.test.mjs b/config/scripts/computer-e2e-workflow.test.mjs index 92480315b185..3ef41583217a 100644 --- a/config/scripts/computer-e2e-workflow.test.mjs +++ b/config/scripts/computer-e2e-workflow.test.mjs @@ -110,6 +110,57 @@ describe('computer-use e2e workflow', () => { } }) + it('boots the built daemon under plain Node in the PR native-smoke job after the main build', () => { + const workflow = parse( + readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') + ) + const steps = workflow.jobs['native-smoke'].steps + const runs = steps.map((step) => step.run).filter((run) => typeof run === 'string') + const buildIndex = runs.indexOf('pnpm build:electron-vite') + const daemonSmokeIndex = runs.indexOf('node config/scripts/daemon-boot-smoke.mjs') + + expect(daemonSmokeIndex, 'native-smoke must boot the built daemon').toBeGreaterThanOrEqual(0) + expect( + buildIndex, + 'daemon boot smoke must run after the main bundle is built' + ).toBeGreaterThanOrEqual(0) + expect(daemonSmokeIndex).toBeGreaterThan(buildIndex) + }) + + it('runs the Windows workspace-close daemon repro after the main build', () => { + const workflow = parse( + readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') + ) + const steps = workflow.jobs['native-smoke'].steps + const buildIndex = steps.findIndex((step) => step.run === 'pnpm build:electron-vite') + const reproIndex = steps.findIndex( + (step) => step.run === 'node config/scripts/windows-daemon-workspace-close-repro.mjs' + ) + + expect(reproIndex).toBeGreaterThan(buildIndex) + expect(steps[reproIndex].if).toBe("runner.os == 'Windows'") + expect(workflow.on.pull_request.paths).toContain( + 'config/scripts/windows-daemon-workspace-close-repro.mjs' + ) + }) + + it('re-runs the native-smoke job when the daemon bundle graph changes', () => { + const workflow = parse( + readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') + ) + const triggerPaths = workflow.on.pull_request.paths + + expect(triggerPaths).toEqual( + expect.arrayContaining([ + 'config/scripts/daemon-boot-smoke.mjs', + 'config/scripts/windows-daemon-workspace-close-repro.mjs', + 'electron.vite.config.ts', + 'build-plugins/**', + 'src/main/daemon/**' + ]) + ) + }) + it('runs Linux computer-use e2e in the PR native-smoke job under Xvfb', () => { const workflow = parse( readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') diff --git a/config/scripts/daemon-boot-smoke.mjs b/config/scripts/daemon-boot-smoke.mjs new file mode 100644 index 000000000000..dc593b650b2e --- /dev/null +++ b/config/scripts/daemon-boot-smoke.mjs @@ -0,0 +1,217 @@ +/** + * Boots the BUILT terminal daemon (out/main/daemon-entry.js) under plain Node — + * the exact way production forks it (ELECTRON_RUN_AS_NODE = a plain-Node + * process) — and asserts it starts, serves a real PTY, and stops. + * + * Why this exists: native-smoke CI (and packaging) went green while + * v1.4.129-rc.1 shipped a daemon that exited code 1 at module load because an + * electron `require` leaked into its bundle graph. Nothing executed the built + * entry under plain Node, so the outage was invisible until an adopted old + * daemon died in the field. This runs on every PR that touches the daemon. + * + * Hard assertions (fail the job): + * - the daemon signals `{ type: 'ready' }` over IPC within the timeout, and + * - it terminates when asked (no hang / zombie). + * Best-effort (logged skip, never fails): an end-to-end `ptySpawnHealth` RPC, + * because node-pty spawn can be flaky on constrained CI runners. + */ +import { fork } from 'node:child_process' +import { connect } from 'node:net' +import { randomUUID } from 'node:crypto' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' + +const projectDir = resolve(import.meta.dirname, '../..') +const entryPath = join(projectDir, 'out', 'main', 'daemon-entry.js') + +const READY_TIMEOUT_MS = 30_000 +const PTY_HEALTH_TIMEOUT_MS = 10_000 +const SHUTDOWN_TIMEOUT_MS = 10_000 + +function log(message) { + process.stdout.write(`[daemon-boot-smoke] ${message}\n`) +} + +// Why: the daemon rejects a hello whose protocol version differs, so read the +// current version from source rather than hardcoding a number that can drift. +function readProtocolVersion() { + const source = readFileSync(join(projectDir, 'src/main/daemon/types.ts'), 'utf8') + const match = source.match(/PROTOCOL_VERSION\s*=\s*(\d+)/) + if (!match) { + throw new Error('could not read PROTOCOL_VERSION from src/main/daemon/types.ts') + } + return Number(match[1]) +} + +function makeSocketPath(userDataDir) { + // Why: Windows AF_UNIX-style IPC uses named pipes; POSIX uses a filesystem + // socket kept under the scratch userData dir so cleanup removes it. + if (process.platform === 'win32') { + return `\\\\.\\pipe\\orca-daemon-smoke-${process.pid}-${randomUUID()}` + } + return join(userDataDir, 'daemon.sock') +} + +// Best-effort end-to-end PTY check over the daemon's own control-socket RPC. +// Connects a single control socket, completes the hello handshake, and calls +// `ptySpawnHealth` (the daemon spawns a throwaway PTY internally). Resolves +// true on success, false on any failure — never throws. +function runPtySpawnHealthCheck(socketPath, tokenPath, protocolVersion) { + return new Promise((resolveCheck) => { + let settled = false + let buffer = '' + const socket = connect(socketPath) + const finish = (ok, reason) => { + if (settled) { + return + } + settled = true + clearTimeout(timer) + socket.destroy() + if (!ok && reason) { + log(`PTY spawn health check skipped (best-effort): ${reason}`) + } + resolveCheck(ok) + } + const timer = setTimeout(() => finish(false, 'timed out'), PTY_HEALTH_TIMEOUT_MS) + + socket.on('error', (err) => finish(false, err.message)) + socket.on('connect', () => { + const token = readFileSync(tokenPath, 'utf8').trim() + socket.write( + `${JSON.stringify({ + type: 'hello', + version: protocolVersion, + token, + clientId: randomUUID(), + role: 'control' + })}\n` + ) + }) + socket.on('data', (chunk) => { + buffer += chunk.toString('utf8') + let newlineIdx = buffer.indexOf('\n') + while (newlineIdx !== -1) { + const line = buffer.slice(0, newlineIdx) + buffer = buffer.slice(newlineIdx + 1) + let msg + try { + msg = JSON.parse(line) + } catch { + finish(false, 'invalid response line') + return + } + if (msg.type === 'hello') { + if (!msg.ok) { + finish(false, `hello rejected: ${msg.error ?? 'unknown'}`) + return + } + socket.write(`${JSON.stringify({ id: 'health-1', type: 'ptySpawnHealth' })}\n`) + } else if (msg.id === 'health-1') { + finish( + msg.ok === true, + msg.ok === true ? undefined : (msg.error ?? 'ptySpawnHealth failed') + ) + return + } + newlineIdx = buffer.indexOf('\n') + } + }) + }) +} + +async function main() { + const userDataDir = mkdtempSync(join(tmpdir(), 'orca-daemon-boot-smoke-')) + const socketPath = makeSocketPath(userDataDir) + const tokenPath = join(userDataDir, 'daemon.token') + const protocolVersion = readProtocolVersion() + + log(`forking ${entryPath} under plain Node (${process.execPath})`) + const child = fork(entryPath, ['--socket', socketPath, '--token', tokenPath], { + // Plain Node: no ELECTRON_RUN_AS_NODE. process.execPath is already node in + // CI, and this is exactly the runtime where a leaked `require("electron")` + // throws MODULE_NOT_FOUND — the failure this smoke exists to catch. + stdio: ['ignore', 'pipe', 'pipe', 'ipc'], + env: { ...process.env, ORCA_USER_DATA_PATH: userDataDir } + }) + + let stderr = '' + child.stderr?.on('data', (chunk) => { + stderr += chunk.toString('utf8') + }) + child.stdout?.on('data', (chunk) => { + process.stdout.write(chunk) + }) + + const cleanup = () => { + if (child.exitCode === null && child.signalCode === null && child.pid) { + try { + child.kill('SIGKILL') + } catch { + // already gone + } + } + rmSync(userDataDir, { recursive: true, force: true }) + } + + try { + await new Promise((resolveReady, rejectReady) => { + const timer = setTimeout(() => { + rejectReady( + new Error( + `daemon did not signal 'ready' within ${READY_TIMEOUT_MS}ms.\nstderr:\n${stderr}` + ) + ) + }, READY_TIMEOUT_MS) + child.on('message', (msg) => { + if (msg && typeof msg === 'object' && msg.type === 'ready') { + clearTimeout(timer) + resolveReady() + } + }) + child.on('error', (err) => { + clearTimeout(timer) + rejectReady(new Error(`daemon fork errored: ${err.message}\nstderr:\n${stderr}`)) + }) + child.on('exit', (code, signal) => { + clearTimeout(timer) + rejectReady( + new Error( + `daemon exited before 'ready' (code=${code}, signal=${signal}).\nstderr:\n${stderr}` + ) + ) + }) + }) + log('daemon signaled ready') + + const ptyHealthy = await runPtySpawnHealthCheck(socketPath, tokenPath, protocolVersion) + if (ptyHealthy) { + log('ptySpawnHealth OK — daemon spawned a real PTY end-to-end') + } + + await new Promise((resolveExit, rejectExit) => { + const timer = setTimeout(() => { + rejectExit(new Error(`daemon did not exit within ${SHUTDOWN_TIMEOUT_MS}ms of SIGTERM`)) + }, SHUTDOWN_TIMEOUT_MS) + child.on('exit', (code, signal) => { + clearTimeout(timer) + log(`daemon exited after signal (code=${code}, signal=${signal})`) + resolveExit() + }) + // Why: SIGTERM is the graceful stop on POSIX (the daemon handles it); + // Windows has no POSIX signal delivery, so Node maps this to process + // termination. Either way the hard assertion is "it stops, no hang". + child.kill('SIGTERM') + }) + + log('PASS: daemon booted, served, and shut down under plain Node') + } finally { + cleanup() + } +} + +main().catch((error) => { + process.stderr.write(`[daemon-boot-smoke] FAIL: ${error.message}\n`) + process.exitCode = 1 +}) diff --git a/config/scripts/electron-builder-config.test.mjs b/config/scripts/electron-builder-config.test.mjs index 3f318219eeb1..cd46c8003fac 100644 --- a/config/scripts/electron-builder-config.test.mjs +++ b/config/scripts/electron-builder-config.test.mjs @@ -63,12 +63,36 @@ describe('electron-builder config', () => { ) }) + // Why: on macOS 26 UNUserNotificationCenter aborts for executables launched + // from Contents/Resources, so the helper must ship in Contents/MacOS (#7929). + it('ships the mac notification-status helper in Contents/MacOS, not Resources', () => { + expect(electronBuilderConfig.mac.extraFiles).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + from: 'native/notification-status-macos/.build/release/orca-notification-status', + to: 'MacOS/orca-notification-status' + }) + ]) + ) + expect(electronBuilderConfig.mac.extraResources).not.toEqual( + expect.arrayContaining([expect.objectContaining({ to: 'orca-notification-status' })]) + ) + }) + it('unpacks the compiled CommonJS boundary with CLI runtime files', () => { expect(electronBuilderConfig.asarUnpack).toEqual( expect.arrayContaining(['out/package.json', 'out/cli/**', 'out/shared/**']) ) }) + // Why: without the unpacked entry the watcher client silently falls back to + // in-process @parcel/watcher, reintroducing the #7547 main-process crash. + it('unpacks the forked parcel-watcher process entry', () => { + expect(electronBuilderConfig.asarUnpack).toEqual( + expect.arrayContaining(['out/main/parcel-watcher-process-entry.js']) + ) + }) + it('uses the multi-size icon source for Linux packages', () => { expect(electronBuilderConfig.linux.icon).toBe('resources/build/icon.icns') }) @@ -329,6 +353,15 @@ describe('electron-builder config', () => { const launcherPath = join(resourcesDir, 'bin', 'orca-ide') await mkdir(join(resourcesDir, 'bin'), { recursive: true }) await mkdir(join(resourcesDir, 'node_modules', 'zod', 'src'), { recursive: true }) + // Why: afterPack now fails hard when the unpacked daemon entry is + // missing, so the fixture must carry one like a real package layout. + const unpackedMainDir = join(resourcesDir, 'app.asar.unpacked', 'out', 'main') + await mkdir(unpackedMainDir, { recursive: true }) + await writeFile( + join(unpackedMainDir, 'daemon-entry.js'), + 'console.error("Usage: daemon-entry "); process.exit(1)\n', + 'utf8' + ) await writeFile(launcherPath, '#!/usr/bin/env bash\n', { encoding: 'utf8', mode: 0o644 }) await electronBuilderConfig.afterPack({ diff --git a/config/scripts/ensure-native-runtime.mjs b/config/scripts/ensure-native-runtime.mjs index 848f37276537..eac27a909655 100644 --- a/config/scripts/ensure-native-runtime.mjs +++ b/config/scripts/ensure-native-runtime.mjs @@ -279,10 +279,12 @@ function getPatchedNodePtyRebuildReason() { // Why: a loadable upstream node-pty prebuild is not enough; Orca's Unix // patch only lands in the source-built build/Release artifacts. const nodePtyDir = resolve(projectDir, 'node_modules', 'node-pty') - const missingArtifact = [ - resolve(nodePtyDir, 'build', 'Release', 'pty.node'), - resolve(nodePtyDir, 'build', 'Release', 'spawn-helper') - ].find((artifactPath) => !existsSync(artifactPath)) + const artifactPaths = [resolve(nodePtyDir, 'build', 'Release', 'pty.node')] + // Why: node-pty only builds spawn-helper on macOS; Linux builds only pty.node. + if (process.platform === 'darwin') { + artifactPaths.push(resolve(nodePtyDir, 'build', 'Release', 'spawn-helper')) + } + const missingArtifact = artifactPaths.find((artifactPath) => !existsSync(artifactPath)) if (!missingArtifact) { return null diff --git a/config/scripts/ensure-native-runtime.test.mjs b/config/scripts/ensure-native-runtime.test.mjs index d5d8396aeea1..1041ca924f29 100644 --- a/config/scripts/ensure-native-runtime.test.mjs +++ b/config/scripts/ensure-native-runtime.test.mjs @@ -117,6 +117,40 @@ describe('ensure-native-runtime', () => { } } ) + + it.skipIf(process.platform === 'win32')( + 'keeps the fast path when the platform-specific patched artifacts exist', + () => { + const projectDir = mkTempProject() + + try { + const scriptPath = join(projectDir, 'config', 'scripts', 'ensure-native-runtime.mjs') + const logPath = join(projectDir, 'native-runtime.log') + const markerPath = join(projectDir, 'rebuilt.marker') + const binDir = join(projectDir, 'bin') + copyFileSync(sourceScriptPath, scriptPath) + writeLoadableNativeModules(projectDir, { nativeDir: '../build/Release/' }) + writeNodePtyPatchFile(projectDir) + writePatchedNodePtyBuildArtifacts(projectDir) + writeFakePnpm(binDir) + + const result = spawnSync(process.execPath, [scriptPath, '--runtime=node'], { + cwd: projectDir, + encoding: 'utf8', + env: envWithPrependedPath(binDir, { + ORCA_NATIVE_TEST_LOG: logPath, + ORCA_NATIVE_TEST_MARKER: markerPath + }) + }) + + expect(result.status, result.stderr).toBe(0) + expect(result.stderr).not.toContain('Patched node-pty build artifacts are missing') + expect(readFileSync(logPath, 'utf8')).not.toContain('pnpm rebuild node-pty') + } finally { + rmSync(projectDir, { recursive: true, force: true }) + } + } + ) }) function mkTempProject() { @@ -161,7 +195,7 @@ exports.loadNativeModule = function loadNativeModule(nativeName) { ) } -function writeLoadableNativeModules(projectDir) { +function writeLoadableNativeModules(projectDir, { nativeDir = null } = {}) { const nodePtyDir = join(projectDir, 'node_modules', 'node-pty') mkdirSync(join(nodePtyDir, 'lib'), { recursive: true }) @@ -173,7 +207,8 @@ const { appendFileSync, existsSync } = require('node:fs') exports.loadNativeModule = function loadNativeModule(nativeName) { const rebuilt = existsSync(process.env.ORCA_NATIVE_TEST_MARKER) - const dir = rebuilt ? '../build/Release/' : '../prebuilds/' + process.platform + '-' + process.arch + '/' + const dir = ${JSON.stringify(nativeDir)} ?? + (rebuilt ? '../build/Release/' : '../prebuilds/' + process.platform + '-' + process.arch + '/') appendFileSync(process.env.ORCA_NATIVE_TEST_LOG, \`node-pty load \${nativeName} dir=\${dir}\\n\`) return { dir, module: {} } } @@ -190,7 +225,9 @@ function writePatchedNodePtyBuildArtifacts(projectDir) { const buildDir = join(projectDir, 'node_modules', 'node-pty', 'build', 'Release') mkdirSync(buildDir, { recursive: true }) writeFileSync(join(buildDir, 'pty.node'), '') - writeFileSync(join(buildDir, 'spawn-helper'), '') + if (process.platform === 'darwin') { + writeFileSync(join(buildDir, 'spawn-helper'), '') + } } function writeFakePnpm(binDir) { diff --git a/config/scripts/generate-terminal-perf-html-report.mjs b/config/scripts/generate-terminal-perf-html-report.mjs new file mode 100644 index 000000000000..577592169bc1 --- /dev/null +++ b/config/scripts/generate-terminal-perf-html-report.mjs @@ -0,0 +1,483 @@ +import { mkdirSync, writeFileSync } from 'node:fs' +import { + budgetFailures, + collectTerminalPerfRows, + compareScenarios, + escapeHtml, + formatLargeValue, + formatMs, + readJsonReport, + scenarioTitle +} from './terminal-perf-report-rows.mjs' +import { basename, dirname } from 'node:path' + +const DEFAULT_OUTPUT_PATH = 'test-results/terminal-perf-impact-report.html' + +// Why: every tracked metric is lower-is-better, so delta coloring and the +// regression table share one direction rule. +const MS_METRICS = [ + { key: 'medianMs', label: 'Typing median', chart: true }, + { key: 'worstMs', label: 'Typing worst', chart: true }, + { key: 'scrollMs', label: 'Active scroll', chart: true }, + { key: 'restoreMs', label: 'Restore', chart: true }, + { key: 'revisitMs', label: 'Revisit marker', chart: true }, + { key: 'maxTimerDriftMs', label: 'Timer drift', chart: false } +] + +const COUNT_METRICS = [ + { key: 'rendererPeakQueuedChars', label: 'Renderer peak queued chars' }, + { key: 'mainPeakInFlightChars', label: 'Main in-flight chars' }, + { key: 'mainPeakPendingChars', label: 'Main pending chars' }, + { key: 'hiddenSkippedChars', label: 'Hidden skipped chars' }, + { key: 'rendererDroppedBacklogs', label: 'Renderer dropped backlogs' }, + // Why: parked-memory scenarios are table-only — heap/view counts have no + // ms trend story, so they stay out of the charts. + { key: 'heapUsedMB', label: 'Renderer JS heap (MB)' }, + { key: 'liveTerminals', label: 'Live xterm instances' }, + { key: 'livePaneManagers', label: 'Live pane managers' } +] + +const SERIES_COLORS = { + medianMs: '#2563eb', + worstMs: '#dc2626', + scrollMs: '#d97706', + restoreMs: '#7c3aed', + revisitMs: '#0d9488' +} + +const LABELED_INPUT_RE = /^([\w .#@()+-]+)=(.+)$/ + +export function parseHtmlReportArgs(argv, env = process.env) { + const args = [...argv] + if (args[0] === '--') { + args.shift() + } + + const inputs = [] + let outputPath = env.ORCA_E2E_TERMINAL_PERF_HTML_REPORT_PATH || DEFAULT_OUTPUT_PATH + for (let index = 0; index < args.length; index += 1) { + const arg = args[index] + if (arg === '--output' || arg === '-o') { + const next = args[index + 1] + if (!next || next.startsWith('-')) { + throw new Error(`${arg} requires a path`) + } + outputPath = next + index += 1 + continue + } + if (arg.startsWith('--output=')) { + outputPath = arg.slice('--output='.length) + continue + } + const labeled = arg.match(LABELED_INPUT_RE) + if (labeled) { + inputs.push({ label: labeled[1], path: labeled[2] }) + } else { + inputs.push({ label: basename(arg).replace(/\.json$/i, ''), path: arg }) + } + } + + if (inputs.length === 0) { + throw new Error( + 'Usage: node config/scripts/generate-terminal-perf-html-report.mjs [label=]... --output ' + ) + } + return { inputs, outputPath } +} + +// ── Trend data ──────────────────────────────────────────────────────────── + +function buildMatrix(revisions) { + const scenarios = new Map() + for (const revision of revisions) { + for (const row of revision.rows) { + if (!scenarios.has(row.scenario)) { + scenarios.set(row.scenario, new Map()) + } + scenarios.get(row.scenario).set(revision.label, row) + } + } + const orderedScenarios = [...scenarios.keys()].sort(compareScenarios) + return { scenarios, orderedScenarios } +} + +function niceCeil(value) { + if (value <= 0) { + return 1 + } + const magnitude = 10 ** Math.floor(Math.log10(value)) + for (const step of [1, 2, 2.5, 5, 10]) { + if (value <= step * magnitude) { + return step * magnitude + } + } + return 10 * magnitude +} + +// ── Rendering ───────────────────────────────────────────────────────────── + +function renderTrendChart({ scenario, byRevision, revisions, title }) { + const metrics = MS_METRICS.filter( + (metric) => + metric.chart && + revisions.some((revision) => byRevision.get(revision.label)?.[metric.key] != null) + ) + if (metrics.length === 0) { + return '' + } + const width = 560 + const height = 230 + const pad = { left: 52, right: 14, top: 30, bottom: 38 } + const plotW = width - pad.left - pad.right + const plotH = height - pad.top - pad.bottom + const maxValue = Math.max( + 1, + ...metrics.flatMap((metric) => + revisions.map((revision) => byRevision.get(revision.label)?.[metric.key] ?? 0) + ) + ) + const yMax = niceCeil(maxValue * 1.15) + const xFor = (index) => + pad.left + (revisions.length === 1 ? plotW / 2 : (plotW * index) / (revisions.length - 1)) + const yFor = (value) => pad.top + plotH - (plotH * value) / yMax + + const parts = [] + parts.push( + `` + ) + parts.push(`${escapeHtml(title)}`) + // Horizontal gridlines + y labels + const ticks = 4 + for (let tick = 0; tick <= ticks; tick += 1) { + const value = (yMax * tick) / ticks + const y = yFor(value) + parts.push( + `` + ) + parts.push( + `${value % 1 === 0 ? value : value.toFixed(1)}` + ) + } + // X labels + revisions.forEach((revision, index) => { + parts.push( + `${escapeHtml(revision.label)}` + ) + }) + // Series + for (const metric of metrics) { + const color = SERIES_COLORS[metric.key] ?? '#475569' + const points = revisions + .map((revision, index) => ({ index, value: byRevision.get(revision.label)?.[metric.key] })) + .filter((point) => point.value != null) + if (points.length === 0) { + continue + } + const path = points + .map( + (point, order) => + `${order === 0 ? 'M' : 'L'}${xFor(point.index).toFixed(1)},${yFor(point.value).toFixed(1)}` + ) + .join(' ') + parts.push(``) + for (const point of points) { + const x = xFor(point.index) + const y = yFor(point.value) + parts.push(``) + parts.push( + `${point.value % 1 === 0 ? point.value : point.value.toFixed(1)}` + ) + } + } + parts.push('') + + const legend = metrics + .map((metric) => { + const color = SERIES_COLORS[metric.key] ?? '#475569' + return `${escapeHtml(metric.label)}` + }) + .join('') + return `
${parts.join('')}
${legend} ms — lower is better
` +} + +function deltaCell(baseline, latest, { lowerIsBetter = true, zeroBudget = false } = {}) { + if (baseline == null || latest == null) { + return '—' + } + const diff = latest - baseline + const pct = baseline === 0 ? null : (diff / baseline) * 100 + let cls = 'neutral' + if (zeroBudget) { + cls = latest > 0 ? 'worse' : 'better' + } else if (pct != null && Math.abs(pct) >= 5) { + cls = diff < 0 === lowerIsBetter ? 'better' : 'worse' + } else if (baseline === 0 && diff !== 0) { + cls = diff < 0 === lowerIsBetter ? 'better' : 'worse' + } + const pctLabel = + pct == null ? (diff === 0 ? '±0%' : 'new') : `${pct >= 0 ? '+' : ''}${pct.toFixed(0)}%` + const diffLabel = `${diff >= 0 ? '+' : ''}${Math.abs(diff) >= 100 ? Math.round(diff) : diff.toFixed(1)}` + return `${escapeHtml(pctLabel)} (${escapeHtml(diffLabel)})` +} + +function renderScenarioTable({ scenario, byRevision, revisions, title }) { + const metricRows = [] + const allMetrics = [...MS_METRICS, ...COUNT_METRICS] + for (const metric of allMetrics) { + const values = revisions.map((revision) => byRevision.get(revision.label)?.[metric.key]) + if (values.every((value) => value == null)) { + continue + } + const isMs = MS_METRICS.includes(metric) + const format = isMs ? formatMs : formatLargeValue + const cells = values + .map((value) => `${value == null ? '—' : escapeHtml(format(value))}`) + .join('') + const baseline = values.find((value) => value != null) + const latest = values.toReversed().find((value) => value != null) + metricRows.push( + `${escapeHtml(metric.label)}${cells}${deltaCell(baseline, latest, { + zeroBudget: metric.key === 'rendererDroppedBacklogs' + })}` + ) + } + if (metricRows.length === 0) { + return '' + } + const headers = revisions.map((revision) => `${escapeHtml(revision.label)}`).join('') + return `
+

${escapeHtml(title)} ${escapeHtml(scenario)}

+ +${headers} +${metricRows.join('')} +
MetricΔ first → last
+
` +} + +function renderHeadline(revisions, matrix) { + if (revisions.length < 2) { + return '' + } + const first = revisions[0] + const last = revisions.at(-1) + const cards = [] + for (const scenario of matrix.orderedScenarios) { + const byRevision = matrix.scenarios.get(scenario) + const baseRow = byRevision.get(first.label) + const lastRow = byRevision.get(last.label) + if (!baseRow || !lastRow || baseRow.medianMs == null || lastRow.medianMs == null) { + continue + } + const diff = lastRow.medianMs - baseRow.medianMs + const pct = baseRow.medianMs === 0 ? 0 : (diff / baseRow.medianMs) * 100 + const cls = Math.abs(pct) < 5 ? 'neutral' : diff < 0 ? 'better' : 'worse' + cards.push(`
+
${escapeHtml(scenarioTitle(scenario, lastRow))}
+
${escapeHtml(formatMs(baseRow.medianMs))} → ${escapeHtml(formatMs(lastRow.medianMs))}
+
typing median, ${escapeHtml(first.label)} → ${escapeHtml(last.label)} (${pct >= 0 ? '+' : ''}${pct.toFixed(0)}%)
+
`) + } + if (cards.length === 0) { + return '' + } + return `

Baseline vs latest

${cards.join('')}
` +} + +function renderBudgets(latestRevision) { + const failures = [] + for (const row of latestRevision.rows) { + for (const failure of budgetFailures(row)) { + failures.push(`${row.scenario}: ${failure}`) + } + } + const status = + failures.length === 0 ? 'Pass' : 'Fail' + const failureList = + failures.length === 0 + ? '' + : `
    ${failures.map((failure) => `
  • ${escapeHtml(failure)}
  • `).join('')}
` + return `

Budget status — ${escapeHtml(latestRevision.label)}

+

${latestRevision.rows.length} scenario rows checked: ${status}

${failureList}
` +} + +function renderInputsMeta(revisions) { + const items = revisions + .map((revision) => { + const stats = revision.stats + const statsLabel = stats + ? ` — ${stats.expected ?? 0} passed, ${stats.unexpected ?? 0} failed, ${stats.flaky ?? 0} flaky` + : '' + const failNote = + stats && stats.unexpected > 0 + ? ' (failed assertions at this revision; metrics still recorded)' + : '' + return `
  • ${escapeHtml(revision.label)} — ${revision.rows.length} scenario rows (${escapeHtml(revision.path)})${escapeHtml(statsLabel)}${failNote}
  • ` + }) + .join('') + return `
      ${items}
    ` +} + +function renderRawDetails(revisions) { + return revisions + .map((revision) => { + const rows = revision.rows + .map( + (row) => + `${escapeHtml(row.scenario)}${row.panes ?? '—'}${escapeHtml(formatMs(row.medianMs))}${escapeHtml(formatMs(row.worstMs))}${escapeHtml(formatMs(row.scrollMs))}${escapeHtml(formatMs(row.restoreMs))}${escapeHtml(formatMs(row.revisitMs))}${escapeHtml(formatLargeValue(row.rendererPeakQueuedChars))}${escapeHtml(formatLargeValue(row.hiddenSkippedChars))}${row.rendererDroppedBacklogs ?? '—'}` + ) + .join('') + return `
    Raw rows — ${escapeHtml(revision.label)} + + +${rows}
    ScenarioPanesMedianWorstScrollRestoreRevisitRenderer peakHidden skippedDrops
    ` + }) + .join('') +} + +const PAGE_CSS = ` +:root { color-scheme: light; } +body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 24px auto; max-width: 1240px; padding: 0 16px; color: #0f172a; background: #f8fafc; } +h1 { font-size: 24px; margin-bottom: 4px; } +h2 { font-size: 18px; margin: 28px 0 10px; } +h3 { font-size: 15px; margin: 18px 0 6px; } +.meta { color: #64748b; font-size: 13px; } +.inputs { font-size: 13px; color: #334155; padding-left: 20px; } +.meta-warn { color: #b45309; } +.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 10px; } +.card { background: #fff; border: 1px solid #e2e8f0; border-left-width: 4px; border-radius: 8px; padding: 10px 12px; } +.card.better { border-left-color: #16a34a; } +.card.worse { border-left-color: #dc2626; } +.card.neutral { border-left-color: #94a3b8; } +.card-title { font-size: 12px; color: #64748b; } +.card-value { font-size: 18px; font-weight: 600; margin: 2px 0; } +.card-sub { font-size: 11px; color: #94a3b8; } +.charts { display: grid; grid-template-columns: repeat(auto-fill, minmax(560px, 1fr)); gap: 14px; } +.chart-card { margin: 0; background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 8px; } +.trend-chart { width: 100%; height: auto; } +.chart-title { font-size: 13px; font-weight: 600; fill: #0f172a; } +.gridline { stroke: #e2e8f0; stroke-width: 1; } +.axis-label { font-size: 10px; fill: #64748b; } +.point-label { font-size: 10px; font-weight: 600; } +.legend { font-size: 11px; color: #475569; margin-top: 2px; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; } +.legend-item { display: inline-flex; align-items: center; gap: 4px; } +.legend-swatch { width: 10px; height: 10px; border-radius: 2px; display: inline-block; } +.legend-unit { color: #94a3b8; margin-left: auto; } +.scenario-block { background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px 14px; margin: 10px 0; } +.scenario-id { font-size: 11px; color: #94a3b8; font-weight: 400; margin-left: 6px; } +table.trend-table { border-collapse: collapse; width: 100%; font-size: 12px; } +table.trend-table th, table.trend-table td { border-bottom: 1px solid #e2e8f0; padding: 5px 8px; text-align: right; white-space: nowrap; } +table.trend-table th:first-child, table.trend-table td:first-child { text-align: left; } +table.trend-table thead th { color: #475569; font-weight: 600; background: #f1f5f9; } +td.delta.better { color: #15803d; font-weight: 600; } +td.delta.worse { color: #b91c1c; font-weight: 600; } +td.delta.neutral { color: #64748b; } +.delta-abs { font-weight: 400; color: #94a3b8; } +.pass { color: #15803d; font-weight: 700; } +.fail { color: #b91c1c; font-weight: 700; } +details { margin: 8px 0; } +summary { cursor: pointer; font-size: 13px; color: #334155; } +` + +function renderHtml({ generatedAt, revisions }) { + const matrix = buildMatrix(revisions) + const charts = + revisions.length >= 2 + ? matrix.orderedScenarios + .map((scenario) => { + const byRevision = matrix.scenarios.get(scenario) + const anyRow = [...byRevision.values()][0] + return renderTrendChart({ + scenario, + byRevision, + revisions, + title: scenarioTitle(scenario, anyRow) + }) + }) + .filter(Boolean) + .join('') + : '' + const tables = matrix.orderedScenarios + .map((scenario) => { + const byRevision = matrix.scenarios.get(scenario) + const anyRow = [...byRevision.values()][0] + return renderScenarioTable({ + scenario, + byRevision, + revisions, + title: scenarioTitle(scenario, anyRow) + }) + }) + .filter(Boolean) + .join('') + + return ` + + + + +Terminal Performance Over Time + + + +

    Terminal Performance Over Time

    +

    Generated ${escapeHtml(generatedAt)} from ${revisions.length} benchmark run(s), ordered oldest (baseline) to newest. All metrics: lower is better.

    +${renderInputsMeta(revisions)} +${renderHeadline(revisions, matrix)} +${charts ? `

    Trends across revisions

    ${charts}
    ` : ''} +

    Metric detail by scenario

    ${tables}
    +${renderBudgets(revisions.at(-1))} +

    Raw data

    ${renderRawDetails(revisions)}
    + + +` +} + +export function generateTerminalPerfHtmlReport({ + inputs, + inputPaths, + outputPath, + now = new Date() +}) { + // Why: older callers (the scale report gate) pass bare inputPaths. + const resolvedInputs = + inputs ?? + (inputPaths ?? []).map((path) => ({ + label: basename(path).replace(/\.json$/i, ''), + path + })) + const revisions = resolvedInputs.map(({ label, path }) => { + const report = readJsonReport(path) + return { + label, + path, + stats: report.stats ?? null, + rows: collectTerminalPerfRows(report, label) + } + }) + const totalRows = revisions.reduce((sum, revision) => sum + revision.rows.length, 0) + if (totalRows === 0) { + throw new Error('No opencode terminal perf annotations found in the provided reports') + } + const html = renderHtml({ generatedAt: now.toISOString(), revisions }) + mkdirSync(dirname(outputPath), { recursive: true }) + writeFileSync(outputPath, html) + const latestFailures = revisions + .at(-1) + .rows.reduce((sum, row) => sum + budgetFailures(row).length, 0) + return { outputPath, rowCount: totalRows, budgetFailureCount: latestFailures } +} + +const isMain = process.argv[1] && import.meta.filename === process.argv[1] +if (isMain) { + try { + const { inputs, outputPath } = parseHtmlReportArgs(process.argv.slice(2)) + const result = generateTerminalPerfHtmlReport({ inputs, outputPath }) + console.log( + `Terminal perf HTML report saved to ${result.outputPath} (${result.rowCount} rows, ${result.budgetFailureCount} budget failures).` + ) + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)) + process.exit(1) + } +} diff --git a/config/scripts/generate-terminal-perf-html-report.test.mjs b/config/scripts/generate-terminal-perf-html-report.test.mjs new file mode 100644 index 000000000000..a804bb6639d6 --- /dev/null +++ b/config/scripts/generate-terminal-perf-html-report.test.mjs @@ -0,0 +1,272 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { + generateTerminalPerfHtmlReport, + parseHtmlReportArgs +} from './generate-terminal-perf-html-report.mjs' + +const tempDirs = [] + +function makeTempDir() { + const dir = mkdtempSync(join(tmpdir(), 'orca-terminal-perf-html-')) + tempDirs.push(dir) + return dir +} + +function writeReport( + annotationDescription, + annotationType = 'opencode-scale-same-workspace-25', + reportName = 'report.json' +) { + const dir = makeTempDir() + const reportPath = join(dir, reportName) + writeFileSync( + reportPath, + JSON.stringify({ + suites: [ + { + specs: [ + { + tests: [ + { + annotations: [ + { + type: annotationType, + description: annotationDescription + }, + { + type: 'browser-unrelated', + description: 'median=999.0ms' + } + ] + } + ] + } + ] + } + ] + }) + ) + return reportPath +} + +afterEach(() => { + while (tempDirs.length > 0) { + rmSync(tempDirs.pop(), { force: true, recursive: true }) + } +}) + +describe('generate-terminal-perf-html-report', () => { + it('parses labeled and bare input paths plus output flags', () => { + expect(parseHtmlReportArgs(['--', 'a.json', 'b.json', '--output', 'out.html'])).toEqual({ + inputs: [ + { label: 'a', path: 'a.json' }, + { label: 'b', path: 'b.json' } + ], + outputPath: 'out.html' + }) + expect(parseHtmlReportArgs(['main=runs/0-main.json', '#5038 final=runs/4-final.json'])).toEqual( + { + inputs: [ + { label: 'main', path: 'runs/0-main.json' }, + { label: '#5038 final', path: 'runs/4-final.json' } + ], + outputPath: 'test-results/terminal-perf-impact-report.html' + } + ) + expect( + parseHtmlReportArgs(['a.json'], { ORCA_E2E_TERMINAL_PERF_HTML_REPORT_PATH: 'env.html' }) + ).toEqual({ + inputs: [{ label: 'a', path: 'a.json' }], + outputPath: 'env.html' + }) + expect(() => parseHtmlReportArgs(['--output'])).toThrow('--output requires a path') + expect(() => parseHtmlReportArgs([])).toThrow('Usage:') + }) + + it('writes a single-run report with scenario tables and budget status', () => { + const reportPath = writeReport( + [ + 'panes=25', + 'frames=60', + 'median=12.4ms', + 'worst=44.8ms', + 'revisit=28.6ms', + 'scroll=61.0ms', + 'restore=320.0ms', + 'maxTimerDrift=8.0ms', + 'rendererPeakQueuedChars=2048', + 'mainPeakInFlightChars=4096', + 'heldAckChars=1024', + 'hiddenSkippedChars=512', + 'rendererDroppedBacklogs=0' + ].join(' ') + ) + const outputPath = join(makeTempDir(), 'report.html') + + const result = generateTerminalPerfHtmlReport({ + inputPaths: [reportPath], + outputPath, + now: new Date('2026-06-09T10:00:00.000Z') + }) + + const html = readFileSync(outputPath, 'utf8') + expect(result).toEqual({ budgetFailureCount: 0, outputPath, rowCount: 1 }) + expect(html).toContain('') + expect(html).toContain('Terminal Performance Over Time') + expect(html).toContain('2026-06-09T10:00:00.000Z') + expect(html).toContain('Same workspace panes — 25 panes') + expect(html).toContain('opencode-scale-same-workspace-25') + expect(html).toContain('28.6ms') + expect(html).toContain('Pass') + // Why: one run has no over-time story; the trend section must not render. + expect(html).not.toContain('Trends across revisions') + expect(html).not.toContain('browser-unrelated') + }) + + it('renders parked-memory heap and live view counts as table metrics', () => { + const reportPath = writeReport( + 'panes=8 parkedTabs=8 heapUsedMB=142.5 liveTerminals=1 livePaneManagers=1', + 'opencode-parked-memory' + ) + const outputPath = join(makeTempDir(), 'report.html') + + const result = generateTerminalPerfHtmlReport({ inputPaths: [reportPath], outputPath }) + + const html = readFileSync(outputPath, 'utf8') + // Why: heapUsedMB has no budget — a memory row alone must not fail gates. + expect(result.budgetFailureCount).toBe(0) + expect(html).toContain('Parked hidden terminal memory — 8 panes') + expect(html).toContain('Renderer JS heap (MB)') + expect(html).toContain('142.5') + expect(html).toContain('Live xterm instances') + expect(html).toContain('Live pane managers') + }) + + it('marks over-budget rows as failures for the latest run', () => { + const reportPath = writeReport( + [ + 'panes=100', + 'median=80.0ms', + 'worst=301.0ms', + 'revisit=301.0ms', + 'rendererPeakQueuedChars=2097153', + 'rendererDroppedBacklogs=1' + ].join(' '), + 'opencode-scale-cross-workspace-100' + ) + const outputPath = join(makeTempDir(), 'report.html') + + const result = generateTerminalPerfHtmlReport({ inputPaths: [reportPath], outputPath }) + + const html = readFileSync(outputPath, 'utf8') + expect(result.budgetFailureCount).toBe(5) + expect(html).toContain('Fail') + expect(html).toContain('medianMs 80 > 75') + expect(html).toContain('Cross-workspace hidden panes') + }) + + it('renders ordered revisions with trend charts and baseline deltas', () => { + const mainReport = writeReport( + 'panes=25 median=50.0ms worst=120.0ms rendererDroppedBacklogs=0', + 'opencode-scale-same-workspace-25', + 'main.json' + ) + const middleReport = writeReport( + 'panes=25 median=30.0ms worst=140.0ms rendererDroppedBacklogs=0', + 'opencode-scale-same-workspace-25', + 'backpressure.json' + ) + const finalReport = writeReport( + 'panes=25 median=20.0ms worst=100.0ms rendererDroppedBacklogs=0', + 'opencode-scale-same-workspace-25', + 'final.json' + ) + const outputPath = join(makeTempDir(), 'report.html') + + const result = generateTerminalPerfHtmlReport({ + inputs: [ + { label: 'main', path: mainReport }, + { label: 'backpressure', path: middleReport }, + { label: 'final', path: finalReport } + ], + outputPath + }) + + const html = readFileSync(outputPath, 'utf8') + expect(result.rowCount).toBe(3) + expect(html).toContain('Baseline vs latest') + expect(html).toContain('Trends across revisions') + expect(html).toContain('trend-chart') + expect(html).toContain('>main<') + expect(html).toContain('>backpressure<') + expect(html).toContain('>final<') + // Why: median 50 -> 20 is a 60% improvement and must read as better. + expect(html).toContain('delta better') + expect(html).toContain('-60%') + expect(html).toContain('50.0ms → 20.0ms') + }) + + it('renders missing scenarios at older revisions as gaps, not zeros', () => { + const mainReport = writeReport( + 'panes=25 median=50.0ms rendererDroppedBacklogs=0', + 'opencode-scale-same-workspace-25', + 'main.json' + ) + const finalReport = makeTempDir() + const finalPath = join(finalReport, 'final.json') + writeFileSync( + finalPath, + JSON.stringify({ + suites: [ + { + specs: [ + { + tests: [ + { + annotations: [ + { + type: 'opencode-scale-same-workspace-25', + description: 'panes=25 median=40.0ms rendererDroppedBacklogs=0' + }, + { + type: 'opencode-revisit-pressure', + description: 'panes=19 median=3.0ms revisit=4.4ms rendererDroppedBacklogs=0' + } + ] + } + ] + } + ] + } + ] + }) + ) + const outputPath = join(makeTempDir(), 'report.html') + + generateTerminalPerfHtmlReport({ + inputs: [ + { label: 'main', path: mainReport }, + { label: 'final', path: finalPath } + ], + outputPath + }) + + const html = readFileSync(outputPath, 'utf8') + expect(html).toContain('Revisit under pressure') + expect(html).toContain('—') + }) + + it('fails when reports contain no terminal perf annotations', () => { + const reportPath = writeReport('median=12.0ms', 'browser-unrelated') + + expect(() => + generateTerminalPerfHtmlReport({ + inputPaths: [reportPath], + outputPath: join(makeTempDir(), 'report.html') + }) + ).toThrow('No opencode terminal perf annotations found') + }) +}) diff --git a/config/scripts/git-binary-compatibility-workflow.test.mjs b/config/scripts/git-binary-compatibility-workflow.test.mjs new file mode 100644 index 000000000000..67509f7f6ccd --- /dev/null +++ b/config/scripts/git-binary-compatibility-workflow.test.mjs @@ -0,0 +1,20 @@ +import { readFileSync } from 'node:fs' +import { parse } from 'yaml' +import { describe, expect, it } from 'vitest' + +describe('Git binary compatibility PR gate', () => { + it('runs the real-binary contract at each compatibility boundary', () => { + const workflow = parse(readFileSync('.github/workflows/pr.yml', 'utf8')) + const step = workflow.jobs.verify.steps.find( + (candidate) => candidate.name === 'Verify Git binary compatibility matrix' + ) + + expect(step?.run).toContain('git-2.25.5.tar.gz') + expect(step?.run).toContain('41662c52fc16fec4963bfc41075e71f8ead6b5e386797eb6f9a1111ff95a8ddf') + expect(step?.run).toContain('ORCA_GIT_COMPAT_BINARY="$source/git"') + expect(step?.run).toContain('alpine/git:edge-2.38.1|2.38.1') + expect(step?.run).toContain('alpine/git:v2.49.1|2.49.1') + expect(step?.run).toContain('ORCA_GIT_COMPAT_IMAGE="$image"') + expect(step?.run).toContain('src/shared/git-binary-compatibility.test.ts') + }) +}) diff --git a/config/scripts/localize-renderer-strings.mjs b/config/scripts/localize-renderer-strings.mjs index 459a16ee3878..8ca12e9a13b3 100644 --- a/config/scripts/localize-renderer-strings.mjs +++ b/config/scripts/localize-renderer-strings.mjs @@ -4,7 +4,8 @@ import { createHash } from 'node:crypto' import { pathToFileURL } from 'node:url' import process from 'node:process' -import ts from 'typescript' +// TypeScript 7 is a native CLI; AST consumers still need the legacy JavaScript API. +import ts from 'typescript-api' import { collectLocalizationCandidates } from './audit-localization-coverage.mjs' diff --git a/config/scripts/package-electron-runtime-contract.test.mjs b/config/scripts/package-electron-runtime-contract.test.mjs index c106b166feb2..5e70cf68f42c 100644 --- a/config/scripts/package-electron-runtime-contract.test.mjs +++ b/config/scripts/package-electron-runtime-contract.test.mjs @@ -221,7 +221,7 @@ describe('Electron runtime package contract', () => { expect(installRun).not.toMatch(/throw\s+\$_/) }) - it('temporarily allows publishing Windows after verifying the signed installer only', () => { + it('verifies Windows inner binary signatures fail-open before publishing', () => { const releaseWorkflow = readFileSync( join(projectDir, '.github/workflows/release-cut.yml'), 'utf8' @@ -230,12 +230,38 @@ describe('Electron runtime package contract', () => { const steps = parsedWorkflow.jobs.build.steps const stepNames = steps.map((step) => step.name) const outerVerifyIndex = stepNames.indexOf('Verify signed Windows installer') - const innerVerifyIndex = stepNames.indexOf('Verify signed Windows inner executable') + const innerVerifyIndex = stepNames.indexOf('Verify Windows inner binary signatures') + const evidenceIndex = stepNames.indexOf('Upload Windows inner signing evidence') const publishIndex = stepNames.indexOf('Publish signed Windows release artifacts') expect(outerVerifyIndex).toBeGreaterThan(-1) - expect(innerVerifyIndex).toBe(-1) - expect(publishIndex).toBe(outerVerifyIndex + 1) + expect(innerVerifyIndex).toBe(outerVerifyIndex + 1) + expect(evidenceIndex).toBe(innerVerifyIndex + 1) + expect(publishIndex).toBe(evidenceIndex + 1) + + // Why fail-open: unsigned inner binaries must warn, not block, until the + // flow is proven on a real release (issue #7785). Flip this to 'true' + // together with the workflow env to make the gate required. + expect(steps[innerVerifyIndex].env.ORCA_WINDOWS_INNER_SIGNATURE_REQUIRED).toBe('false') + + // Why: every step in the inner-signing chain must be unable to fail the + // release — a SignPath outage or timeout falls through to today's + // unsigned-inner flow instead of blocking the cut. + const innerChainStepNames = [ + 'Stage unsigned inner PE files for signing', + 'Upload unsigned inner binaries for SignPath', + 'Submit inner binaries signing request', + 'Notify Slack that inner-binary signing is waiting for approval', + 'Download signed inner binaries from SignPath', + 'Restore signed inner binaries into unpacked app', + 'Replace cached elevate.exe with the signed copy', + 'Rebuild NSIS installer from signed unpacked app' + ] + for (const stepName of innerChainStepNames) { + const step = steps[stepNames.indexOf(stepName)] + expect(step, stepName).toBeDefined() + expect(step['continue-on-error'], stepName).toBe(true) + } }) it('publishes both Linux release matrix entries', () => { diff --git a/config/scripts/rebuild-native-deps.mjs b/config/scripts/rebuild-native-deps.mjs index a56c45bc05fc..199149edaa19 100644 --- a/config/scripts/rebuild-native-deps.mjs +++ b/config/scripts/rebuild-native-deps.mjs @@ -349,10 +349,12 @@ function getPatchedNodePtyRebuildReason() { // Why: Orca patches node-pty's native Unix spawn path; upstream prebuilds can // load successfully in Electron while missing the patched fd/error handling. const nodePtyDir = resolve(projectDir, 'node_modules', 'node-pty') - const missingArtifact = [ - resolve(nodePtyDir, 'build', 'Release', 'pty.node'), - resolve(nodePtyDir, 'build', 'Release', 'spawn-helper') - ].find((artifactPath) => !existsSync(artifactPath)) + const artifactPaths = [resolve(nodePtyDir, 'build', 'Release', 'pty.node')] + // Why: node-pty only builds spawn-helper on macOS; Linux builds only pty.node. + if (process.platform === 'darwin') { + artifactPaths.push(resolve(nodePtyDir, 'build', 'Release', 'spawn-helper')) + } + const missingArtifact = artifactPaths.find((artifactPath) => !existsSync(artifactPath)) if (!missingArtifact) { return null diff --git a/config/scripts/rebuild-native-deps.test.mjs b/config/scripts/rebuild-native-deps.test.mjs index 4a68a25df280..15e1e616aa92 100644 --- a/config/scripts/rebuild-native-deps.test.mjs +++ b/config/scripts/rebuild-native-deps.test.mjs @@ -412,5 +412,7 @@ function writePatchedNodePtyBuildArtifacts(projectDir) { const buildDir = join(projectDir, 'node_modules', 'node-pty', 'build', 'Release') mkdirSync(buildDir, { recursive: true }) writeFileSync(join(buildDir, 'pty.node'), '') - writeFileSync(join(buildDir, 'spawn-helper'), '') + if (process.platform === 'darwin') { + writeFileSync(join(buildDir, 'spawn-helper'), '') + } } diff --git a/config/scripts/release-rc-history.mjs b/config/scripts/release-rc-history.mjs index e3cdea2d870f..c6a0e7b47829 100644 --- a/config/scripts/release-rc-history.mjs +++ b/config/scripts/release-rc-history.mjs @@ -25,7 +25,11 @@ export function rcNumberFromTag(base, tag) { } const suffix = tag.slice(prefix.length) - return /^\d+$/.test(suffix) ? Number(suffix) : null + // Why the optional .identifier: suffixed side-branch RCs (v1.2.3-rc.4.perf) + // must advance the shared rc counter, or the next suffixed cut recomputes + // an existing tag and the workflow refuses to re-cut over it. + const match = /^(\d+)(?:\.[0-9A-Za-z]+)?$/.exec(suffix) + return match ? Number(match[1]) : null } export function rcNumberFromReleaseSubject(base, subject) { diff --git a/config/scripts/run-electron-vite-dev.mjs b/config/scripts/run-electron-vite-dev.mjs index 97df46c513b6..9b8aad895579 100644 --- a/config/scripts/run-electron-vite-dev.mjs +++ b/config/scripts/run-electron-vite-dev.mjs @@ -97,16 +97,6 @@ function setPlistValue(plistPath, key, value) { execFileSync('/usr/bin/plutil', ['-replace', key, '-string', value, plistPath]) } -function sanitizeBundleIdPart(value) { - return ( - value - .toLowerCase() - .replace(/[^a-z0-9.-]+/g, '-') - .replace(/^-+|-+$/g, '') - .slice(0, 80) || 'dev' - ) -} - function sanitizeMacAppBundleName(value) { return ( Array.from(value, (char) => { @@ -138,7 +128,10 @@ function prepareMacDevElectronApp() { const title = process.env.ORCA_DEV_DOCK_TITLE || 'Orca: dev' const identityKey = process.env.ORCA_DEV_INSTANCE_KEY || repoRoot - const bundleLayoutVersion = 'dock-title-app-preserve-framework-symlinks-v4' + // v6: bundle the notification-status helper (real permission readout) and + // ad-hoc re-sign after plist edits so Notification Center accepts the + // bundle; bumping forces stale cached copies to be recreated. + const bundleLayoutVersion = 'dock-title-app-preserve-framework-symlinks-v6' const hash = createHash('sha1') .update( `${sourceAppPath}\0${electronVersion ?? ''}\0${title}\0${identityKey}\0${bundleLayoutVersion}` @@ -151,7 +144,17 @@ function prepareMacDevElectronApp() { const appBundleName = `${sanitizeMacAppBundleName(title)}.app` const appPath = path.join(distDir, appBundleName) const markerPath = path.join(distDir, 'orca-dev-electron-app.json') - const bundleId = `com.stablyai.orca.dev.${sanitizeBundleIdPart(hash)}` + // Why: one stable id for every dev instance. Per-instance ids registered a + // new macOS Notification Settings entry for each branch × Electron version, + // piling up "Orca: " rows forever and breaking the notification + // settings deep-link (System Settings can't resolve an id it has no entry + // for and falls back to the root list). macOS keys notification permission + // by bundle id, so a single id also means granting notifications to one dev + // instance covers all of them. Trade-off: when two dev instances run at + // once, macOS may route a notification click to the other instance — + // Electron drops clicks for notification ids it didn't create, so the + // click is lost, not misdirected. + const bundleId = 'com.stablyai.orca.dev' process.env.ORCA_DEV_MACOS_BUNDLE_ID = bundleId const expectedMarker = JSON.stringify( { title, appBundleName, bundleId, sourceAppPath, electronVersion, bundleLayoutVersion }, @@ -206,9 +209,45 @@ function prepareMacDevElectronApp() { setPlistValue(plistPath, 'CFBundleDisplayName', title) setPlistValue(plistPath, 'CFBundleIdentifier', bundleId) - // Why no re-sign: dev launches execute the copied Electron binary directly, - // and Electron's framework bundle is ambiguous to codesign when deep-signing - // an already-built distribution. Avoid blocking `pn dev` on local signing. + // Why: the notification-status helper reads the app's real macOS + // notification authorization (UNUserNotificationCenter has no Electron + // API). It must live inside the bundle and carry the dev bundle id as its + // embedded/code-sign identifier — macOS keys notification records to the + // signing identifier. Non-fatal: without swiftc the permission card falls + // back to delivery-probe heuristics. + try { + execFileSync( + process.execPath, + [ + path.join(repoRoot, 'config', 'scripts', 'build-notification-status-macos.mjs'), + '--bundle-id', + bundleId, + '--single-arch', + '--output', + path.join(appPath, 'Contents', 'MacOS', 'orca-notification-status') + ], + { stdio: 'inherit' } + ) + } catch (error) { + console.warn( + `[orca-dev] notification-status helper build failed (permission card falls back to probes): ${error?.message ?? error}` + ) + } + + // Why: the plist edits above (and the copy itself) break the bundle's + // ad-hoc seal, and macOS refuses Notification Center registration for + // invalidly-signed apps — every dev notification fails with UNErrorDomain + // error 1 and the app never appears in System Settings > Notifications. + // An ad-hoc re-sign restores delivery, the permission prompt, and the + // notification-settings deep link for dev builds. Non-fatal: a signing + // failure should not block `pnpm dev`. + try { + execFileSync('/usr/bin/codesign', ['--force', '--deep', '--sign', '-', appPath]) + } catch (error) { + console.warn( + `[orca-dev] ad-hoc codesign failed (dev notifications will not deliver): ${error?.message ?? error}` + ) + } writeFileSync(markerPath, expectedMarker, 'utf8') process.env.ELECTRON_EXEC_PATH = executablePath } diff --git a/config/scripts/run-multi-workspace-typing-bench.mjs b/config/scripts/run-multi-workspace-typing-bench.mjs new file mode 100644 index 000000000000..7208afb470a3 --- /dev/null +++ b/config/scripts/run-multi-workspace-typing-bench.mjs @@ -0,0 +1,63 @@ +/** + * Entry point for the multi-workspace typing-latency bench + * (tests/e2e/terminal-multi-workspace-typing-latency.spec.ts). + * + * Usage: + * pnpm bench:multi-workspace-typing [-- --panes 8 --rate-kbps 512 \ + * --keys 48 --cadence-ms 250 --cpu-workers 4 --label before-fix] + * + * Results land in tools/benchmarks/results/multi-workspace-typing-*.json. + * Run once per build/config with distinct --label values, then diff the + * totalMs/inputHalfMs/echoHalfMs percentiles. + */ +import { spawn } from 'node:child_process' + +const npxCommand = process.platform === 'win32' ? 'npx.cmd' : 'npx' + +const knobByFlag = { + '--panes': 'ORCA_TYPING_BENCH_LOAD_PANES', + '--rate-kbps': 'ORCA_TYPING_BENCH_RATE_KBPS', + '--keys': 'ORCA_TYPING_BENCH_KEYS', + '--cadence-ms': 'ORCA_TYPING_BENCH_KEY_CADENCE_MS', + '--cpu-workers': 'ORCA_TYPING_BENCH_CPU_WORKERS', + '--label': 'ORCA_TYPING_BENCH_LABEL' +} + +const env = { ...process.env, ORCA_TYPING_BENCH: '1' } +const passthroughArgs = [] +const argv = process.argv.slice(2) +for (let i = 0; i < argv.length; i++) { + if (argv[i] === '--') { + continue + } + const knob = knobByFlag[argv[i]] + if (knob) { + env[knob] = argv[++i] + } else { + passthroughArgs.push(argv[i]) + } +} + +const child = spawn( + npxCommand, + [ + 'playwright', + 'test', + 'tests/e2e/terminal-multi-workspace-typing-latency.spec.ts', + '--config', + 'tests/playwright.config.ts', + '--project', + 'electron-headless', + '--workers=1', + ...passthroughArgs + ], + { stdio: 'inherit', env } +) + +child.on('exit', (code, signal) => { + if (signal) { + process.kill(process.pid, signal) + return + } + process.exit(code ?? 1) +}) diff --git a/config/scripts/run-terminal-scale-perf-report-gate.mjs b/config/scripts/run-terminal-scale-perf-report-gate.mjs index eef60041da17..59b1b443fa94 100644 --- a/config/scripts/run-terminal-scale-perf-report-gate.mjs +++ b/config/scripts/run-terminal-scale-perf-report-gate.mjs @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' const DEFAULT_REPORT_PATH = 'test-results/terminal-scale-perf-report.json' +const DEFAULT_HTML_REPORT_PATH = 'test-results/terminal-perf-impact-report.html' export function parseReportGateArgs(argv, env = process.env) { const forwardedArgs = [...argv] @@ -114,7 +115,20 @@ export function runTerminalScalePerfReportGate({ spawnSyncImpl, env ) - return exitCode(budgetResult) + const budgetExitCode = exitCode(budgetResult) + if (budgetExitCode !== 0) { + return budgetExitCode + } + + const htmlReportPath = env.ORCA_E2E_TERMINAL_PERF_HTML_REPORT_PATH || DEFAULT_HTML_REPORT_PATH + const htmlResult = runNodeScript( + 'config/scripts/generate-terminal-perf-html-report.mjs', + [reportPath, '--output', htmlReportPath], + 'inherit', + spawnSyncImpl, + env + ) + return exitCode(htmlResult) } if (process.argv[1] === import.meta.filename) { diff --git a/config/scripts/run-terminal-scale-perf-report-gate.test.mjs b/config/scripts/run-terminal-scale-perf-report-gate.test.mjs index 929e2d5b9ba4..e4d7be8861e6 100644 --- a/config/scripts/run-terminal-scale-perf-report-gate.test.mjs +++ b/config/scripts/run-terminal-scale-perf-report-gate.test.mjs @@ -77,7 +77,8 @@ describe('run-terminal-scale-perf-report-gate', () => { expect(calls.map((call) => call.args[0])).toEqual([ 'config/scripts/run-terminal-scale-perf-e2e.mjs', 'config/scripts/summarize-terminal-perf-report.mjs', - 'config/scripts/check-terminal-perf-report-budgets.mjs' + 'config/scripts/check-terminal-perf-report-budgets.mjs', + 'config/scripts/generate-terminal-perf-html-report.mjs' ]) expect(calls[0].args).toEqual([ 'config/scripts/run-terminal-scale-perf-e2e.mjs', @@ -92,6 +93,12 @@ describe('run-terminal-scale-perf-report-gate', () => { 'config/scripts/check-terminal-perf-report-budgets.mjs', reportPath ]) + expect(calls[3].args).toEqual([ + 'config/scripts/generate-terminal-perf-html-report.mjs', + reportPath, + '--output', + 'test-results/terminal-perf-impact-report.html' + ]) }) it('uses the report path from env when no flag is provided', () => { @@ -107,6 +114,28 @@ describe('run-terminal-scale-perf-report-gate', () => { expect(calls[1].args).toEqual(['config/scripts/summarize-terminal-perf-report.mjs', reportPath]) }) + it('uses the HTML report path from env when provided', () => { + const reportPath = tempReportPath() + const { calls, spawnSyncImpl } = makeSpawnSync() + + const status = runTerminalScalePerfReportGate({ + env: { + ...process.env, + ORCA_E2E_TERMINAL_PERF_HTML_REPORT_PATH: 'tmp/terminal-report.html', + ORCA_E2E_TERMINAL_PERF_REPORT_PATH: reportPath + }, + spawnSyncImpl + }) + + expect(status).toBe(0) + expect(calls[3].args).toEqual([ + 'config/scripts/generate-terminal-perf-html-report.mjs', + reportPath, + '--output', + 'tmp/terminal-report.html' + ]) + }) + it('preserves the report when Playwright clears the target report directory', () => { const reportPath = tempReportPath() const { spawnSyncImpl } = makeSpawnSync({ diff --git a/config/scripts/serve-headless-fresh-profile-pairing.mjs b/config/scripts/serve-headless-fresh-profile-pairing.mjs new file mode 100755 index 000000000000..6d4f7ac8656e --- /dev/null +++ b/config/scripts/serve-headless-fresh-profile-pairing.mjs @@ -0,0 +1,326 @@ +#!/usr/bin/env node + +import { spawn, spawnSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs' +import { hostname, tmpdir } from 'node:os' +import path from 'node:path' +import { createInterface } from 'node:readline' + +const scriptDir = import.meta.dirname +const repoRoot = path.resolve(scriptDir, '..', '..') +const orcaDevScript = path.join(scriptDir, 'orca-dev.mjs') +const ensureNativeRuntimeScript = path.join(scriptDir, 'ensure-native-runtime.mjs') +const fixedProfileDir = process.env.ORCA_HEADLESS_PAIRING_PROFILE_DIR +const parsed = parseArgs(process.argv.slice(2)) + +if (parsed.help) { + printHelp() + process.exit(0) +} + +if (hasForwardedServeFlag(parsed.serveArgs, 'no-pairing')) { + console.error('serve-headless-fresh-profile-pairing: --no-pairing cannot print a pairing code.') + process.exit(2) +} +if (hasForwardedServeFlag(parsed.serveArgs, 'recipe-json')) { + console.error( + 'serve-headless-fresh-profile-pairing: --recipe-json detaches the server and cannot use an ephemeral profile safely.' + ) + process.exit(2) +} + +const serveArgs = withDefaultPairingAddress(parsed.serveArgs) + +ensureElectronRuntime() + +const profileDir = + fixedProfileDir ?? mkdtempSync(path.join(tmpdir(), 'orca-headless-pairing-profile-')) +const ownsProfileDir = !fixedProfileDir +mkdirSync(profileDir, { recursive: true }) + +let cleanedUp = false +let child = null +let sawPairingUrl = false +let stopAttempts = 0 +// Why: temp dev worktrees do not have a root-owned chrome-sandbox; this script +// is only for local headless testing, not packaged production. +const childEnv = { + ...process.env, + ORCA_DEV_USER_DATA_PATH: profileDir, + ...(process.platform === 'linux' + ? { ELECTRON_DISABLE_SANDBOX: process.env.ELECTRON_DISABLE_SANDBOX ?? '1' } + : {}) +} + +console.error(`[headless-pairing] userData=${profileDir}`) +console.error(`[headless-pairing] starting: orca-dev serve --json${formatForwardedArgs(serveArgs)}`) + +child = spawn(process.execPath, [orcaDevScript, 'serve', '--json', ...serveArgs], { + cwd: repoRoot, + detached: process.platform !== 'win32', + env: childEnv, + stdio: ['inherit', 'pipe', 'inherit'] +}) + +const stdoutLines = createInterface({ input: child.stdout }) +stdoutLines.on('line', (line) => { + if (!printReadyLine(line)) { + console.log(line) + } +}) + +child.once('error', (error) => { + console.error(`[headless-pairing] failed to start server: ${error.message}`) + cleanupProfile() + process.exitCode = 1 +}) + +child.once('exit', (code, signal) => { + stdoutLines.close() + if (!sawPairingUrl && code !== 0) { + console.error('[headless-pairing] server exited before printing a pairing URL.') + } + cleanupProfile() + if (typeof code === 'number') { + process.exitCode = code + return + } + process.exitCode = signal ? 1 : 0 +}) + +process.on('SIGINT', () => stopChild('SIGINT')) +process.on('SIGTERM', () => stopChild('SIGTERM')) + +/** + * Parses wrapper flags and forwards everything else to `orca serve`. + */ +function parseArgs(args) { + const serveArgs = [] + let keepProfile = false + let help = false + for (const arg of args) { + if (arg === '--keep') { + keepProfile = true + continue + } + if (arg === '-h' || arg === '--help') { + help = true + continue + } + serveArgs.push(arg) + } + return { help, keepProfile, serveArgs } +} + +/** + * Prints script usage without touching the dev profile or starting the server. + */ +function printHelp() { + console.log(`Usage: node config/scripts/serve-headless-fresh-profile-pairing.mjs [--keep] [orca serve flags] + +Starts orca-dev serve --json with a fresh isolated userData profile, ensures Electron's dev runtime is usable, and prints the pairing URL. + +Wrapper flags: + --keep Keep the fresh profile after the server exits. + -h, --help Show this help. + +Forwarded examples: + node config/scripts/serve-headless-fresh-profile-pairing.mjs --port 6768 + node config/scripts/serve-headless-fresh-profile-pairing.mjs --pairing-address 100.64.1.20 + node config/scripts/serve-headless-fresh-profile-pairing.mjs --mobile-pairing + +Environment: + ORCA_HEADLESS_PAIRING_ADDRESS= Override the auto pairing address. + ORCA_HEADLESS_PAIRING_PROFILE_DIR=/path/to/profile Use a fixed profile directory. +`) +} + +/** + * Adds a reachable pairing address unless the caller provided one explicitly. + */ +function withDefaultPairingAddress(args) { + if (hasPairingAddress(args)) { + return args + } + const address = resolveDefaultPairingAddress() + if (!address) { + return args + } + console.error(`[headless-pairing] pairingAddress=${address} (auto)`) + return [...args, '--pairing-address', address] +} + +/** + * Checks both supported CLI forms for an explicit pairing address. + */ +function hasPairingAddress(args) { + return hasForwardedServeFlag(args, 'pairing-address') +} + +/** + * Checks both exact and `--flag=value` forms for a forwarded serve flag. + */ +function hasForwardedServeFlag(args, name) { + const flag = `--${name}` + return args.some((arg) => arg === flag || arg.startsWith(`${flag}=`)) +} + +/** + * Prefers an override, then Tailscale, then the OS hostname over loopback. + */ +function resolveDefaultPairingAddress() { + const configured = process.env.ORCA_HEADLESS_PAIRING_ADDRESS?.trim() + if (configured) { + return configured + } + const tailscaleAddress = readTailscaleAddress() + if (tailscaleAddress) { + return tailscaleAddress + } + const host = hostname().trim() + return host && host !== 'localhost' ? host : null +} + +/** + * Reads the first Tailscale IPv4 address when Tailscale is installed. + */ +function readTailscaleAddress() { + const result = spawnSync('tailscale', ['ip', '-4'], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'] + }) + if (result.error || result.status !== 0) { + return null + } + return ( + result.stdout + .split(/\r?\n/) + .map((line) => line.trim()) + .find(Boolean) ?? null + ) +} + +/** + * Formats forwarded arguments for the startup log. + */ +function formatForwardedArgs(args) { + if (args.length === 0) { + return '' + } + return ` ${args.map(formatShellArg).join(' ')}` +} + +/** + * Quotes a shell-ish argument for display only. + */ +function formatShellArg(value) { + if (/^[\w./:=@+-]+$/.test(value)) { + return value + } + return JSON.stringify(value) +} + +/** + * Runs the same Electron runtime preflight used by dev/start package scripts. + */ +function ensureElectronRuntime() { + console.error('[headless-pairing] ensuring Electron runtime...') + const result = spawnSync(process.execPath, [ensureNativeRuntimeScript, '--runtime=electron'], { + cwd: repoRoot, + stdio: 'inherit' + }) + if (result.error) { + console.error(`[headless-pairing] Electron runtime preflight failed: ${result.error.message}`) + process.exit(1) + } + if (result.status !== 0) { + process.exit(result.status ?? 1) + } +} + +/** + * Rewrites the CLI JSON readiness line into the pairing URL testers need. + */ +function printReadyLine(line) { + let payload + try { + payload = JSON.parse(line) + } catch { + return false + } + if (!payload || payload.type !== 'orca_server_ready') { + return false + } + console.log(`Orca server ready: ${payload.endpoint ?? 'websocket unavailable'}`) + if (payload.pairing?.endpoint) { + console.log(`Pairing endpoint: ${payload.pairing.endpoint}`) + } + if (payload.pairing?.webClientUrl) { + console.log(`Web client URL: ${payload.pairing.webClientUrl}`) + } + if (payload.pairing?.url) { + sawPairingUrl = true + console.log(`Pairing URL: ${payload.pairing.url}`) + console.error('[headless-pairing] server is running; press Ctrl+C to stop.') + return true + } + console.log('Pairing URL: unavailable') + return true +} + +/** + * Stops the foreground server; repeated signals force its process tree down. + */ +function stopChild(signal) { + if (!child || child.killed) { + return + } + stopAttempts += 1 + const targetSignal = stopAttempts > 1 ? 'SIGKILL' : signal + if (process.platform === 'win32' && child.pid) { + // Why: child.kill() only targets orca-dev on Windows; taskkill walks the + // CLI/Electron descendants so the fresh profile is not left locked. + const killer = spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], { + stdio: 'ignore', + windowsHide: true + }) + killer.on('error', () => child?.kill(targetSignal)) + return + } + if (process.platform !== 'win32' && child.pid) { + // Why: orca-dev synchronously owns the CLI child, which owns Electron; kill + // the spawned process group so programmatic shutdown does not orphan serve. + try { + process.kill(-child.pid, targetSignal) + return + } catch { + // Fall back to the direct child below if the process group already exited. + } + } + child.kill(targetSignal) +} + +/** + * Removes only the ephemeral profile directory this script created. + */ +function cleanupProfile() { + if (cleanedUp) { + return + } + cleanedUp = true + if (parsed.keepProfile || !ownsProfileDir) { + console.error(`[headless-pairing] kept ${profileDir}`) + return + } + if (!existsSync(profileDir) || !profileDir.includes('orca-headless-pairing-profile-')) { + console.error(`[headless-pairing] skipped cleanup for unexpected profile path: ${profileDir}`) + return + } + try { + rmSync(profileDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }) + console.error(`[headless-pairing] removed ${profileDir}`) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + console.error(`[headless-pairing] skipped cleanup for ${profileDir}: ${message}`) + } +} diff --git a/config/scripts/styled-scrollbars/styled-scrollbar-jsx-check.mjs b/config/scripts/styled-scrollbars/styled-scrollbar-jsx-check.mjs index 4dab6f3b6875..2a9d13b6fee6 100644 --- a/config/scripts/styled-scrollbars/styled-scrollbar-jsx-check.mjs +++ b/config/scripts/styled-scrollbars/styled-scrollbar-jsx-check.mjs @@ -1,4 +1,5 @@ -import ts from 'typescript' +// TypeScript 7 is a native CLI; AST consumers still need the legacy JavaScript API. +import ts from 'typescript-api' const STYLED_SCROLLBAR_CLASSES = new Set( 'scrollbar-sleek scrollbar-editor worktree-sidebar-scrollbar'.split(' ') diff --git a/config/scripts/summarize-terminal-perf-report.mjs b/config/scripts/summarize-terminal-perf-report.mjs index 6d2adea54f9c..2e4f77732b3b 100644 --- a/config/scripts/summarize-terminal-perf-report.mjs +++ b/config/scripts/summarize-terminal-perf-report.mjs @@ -25,6 +25,7 @@ function printMarkdownTable(rows) { ['Frames', 'frames'], ['Median', 'median'], ['Worst', 'worst'], + ['Revisit', 'revisit'], ['Scroll', 'scroll'], ['Restore', 'restore'], ['Max Drift', 'maxTimerDrift'], diff --git a/config/scripts/terminal-perf-report-rows.mjs b/config/scripts/terminal-perf-report-rows.mjs new file mode 100644 index 000000000000..c1f562f3b9e7 --- /dev/null +++ b/config/scripts/terminal-perf-report-rows.mjs @@ -0,0 +1,199 @@ +import { readFileSync } from 'node:fs' + +const BUDGETS = { + medianMs: 75, + worstMs: 300, + revisitMs: 300, + maxTimerDriftMs: 150, + scrollMs: 150, + restoreMs: 1000, + rendererQueuedChars: 2 * 1024 * 1024, + rendererPeakQueuedChars: 2 * 1024 * 1024, + rendererDroppedBacklogs: 0 +} + +const SCENARIO_LABELS = [ + ['opencode-scale-same-workspace', 'Same workspace panes'], + ['opencode-scale-cross-workspace', 'Cross-workspace hidden panes'], + ['opencode-scale-pressure', 'ACK-backpressured PTYs'], + ['opencode-scale-hidden-pressure', 'Hidden real PTYs'], + ['opencode-cross-workspace-typing', 'Cross-workspace typing'], + ['opencode-main-pressure', 'Main renderer pressure'], + ['opencode-hidden-pressure', 'Hidden pressure'], + ['opencode-revisit-pressure', 'Revisit under pressure'], + // Why: the prefix also matches opencode-parked-memory-disabled, so both + // parked-memory scenarios group under one label. + ['opencode-parked-memory', 'Parked hidden terminal memory'] +] + +export function readJsonReport(path) { + const raw = readFileSync(path, 'utf8') + const start = raw.indexOf('{') + const end = raw.lastIndexOf('}') + if (start === -1 || end <= start) { + throw new Error(`${path}: no JSON object found`) + } + return JSON.parse(raw.slice(start, end + 1)) +} + +function parseAnnotationDescription(description) { + const values = {} + for (const part of description.split(/\s+/)) { + const index = part.indexOf('=') + if (index === -1) { + continue + } + values[part.slice(0, index)] = part.slice(index + 1) + } + return values +} + +export function collectTerminalPerfRows(report, source) { + const rows = [] + const visitSuite = (suite) => { + for (const spec of suite.specs ?? []) { + for (const test of spec.tests ?? []) { + for (const annotation of test.annotations ?? []) { + if (!annotation.type.startsWith('opencode-')) { + continue + } + rows.push( + normalizeRow({ + source, + scenario: annotation.type, + ...parseAnnotationDescription(annotation.description ?? '') + }) + ) + } + } + } + for (const child of suite.suites ?? []) { + visitSuite(child) + } + } + for (const suite of report.suites ?? []) { + visitSuite(suite) + } + return rows +} + +function parseMs(value) { + const match = String(value ?? '').match(/^(-?\d+(?:\.\d+)?)ms$/) + return match ? Number(match[1]) : null +} + +function parseCount(value) { + if (value == null || value === '') { + return null + } + const count = Number(value) + return Number.isFinite(count) ? count : null +} + +function normalizeRow(row) { + return { + ...row, + group: scenarioGroup(row.scenario), + panes: parseCount(row.panes), + frames: parseCount(row.frames), + medianMs: parseMs(row.median), + worstMs: parseMs(row.worst), + revisitMs: parseMs(row.revisit), + maxTimerDriftMs: parseMs(row.maxTimerDrift), + scrollMs: parseMs(row.scroll), + restoreMs: parseMs(row.restore), + rendererQueuedChars: parseCount(row.rendererQueuedChars), + rendererPeakQueuedChars: parseCount(row.rendererPeakQueuedChars), + rendererDroppedBacklogs: parseCount(row.rendererDroppedBacklogs), + mainPeakPendingChars: parseCount(row.mainPeakPendingChars), + mainPeakInFlightChars: parseCount(row.mainPeakInFlightChars), + heldAckChars: parseCount(row.heldAckChars), + hiddenSkippedChars: parseCount(row.hiddenSkippedChars), + // Why: parked-memory annotations report a fractional MB heap figure plus + // live renderer view counts; Number() keeps the MB float intact. + heapUsedMB: parseCount(row.heapUsedMB), + liveTerminals: parseCount(row.liveTerminals), + livePaneManagers: parseCount(row.livePaneManagers) + } +} + +export function scenarioGroup(scenario) { + for (const [prefix, label] of SCENARIO_LABELS) { + if (scenario.startsWith(prefix)) { + return label + } + } + return 'Other terminal scenarios' +} + +function scenarioSortKey(scenario) { + const prefixIndex = SCENARIO_LABELS.findIndex(([prefix]) => scenario.startsWith(prefix)) + const paneMatch = scenario.match(/-(\d+)$/) + return [ + prefixIndex === -1 ? SCENARIO_LABELS.length : prefixIndex, + paneMatch ? Number(paneMatch[1]) : 0, + scenario + ] +} + +export function compareScenarios(a, b) { + const ka = scenarioSortKey(a) + const kb = scenarioSortKey(b) + if (ka[0] !== kb[0]) { + return ka[0] - kb[0] + } + if (ka[1] !== kb[1]) { + return ka[1] - kb[1] + } + return ka[2] < kb[2] ? -1 : ka[2] > kb[2] ? 1 : 0 +} + +export function scenarioTitle(scenario, row) { + const group = scenarioGroup(scenario) + if (row?.panes != null) { + return `${group} — ${row.panes} panes` + } + return group +} + +export function budgetFailures(row) { + const failures = [] + for (const [key, budget] of Object.entries(BUDGETS)) { + const value = row[key] + if (value == null) { + continue + } + if (value > budget) { + failures.push(`${key} ${value} > ${budget}`) + } + } + return failures +} + +export function formatMs(value) { + if (value == null) { + return '—' + } + return `${value.toFixed(1)}ms` +} + +export function formatLargeValue(value) { + if (value == null) { + return '—' + } + if (value >= 1024 * 1024) { + return `${(value / (1024 * 1024)).toFixed(2)}M` + } + if (value >= 1024) { + return `${Math.round(value / 1024)}k` + } + return String(value) +} + +export function escapeHtml(value) { + return String(value) + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') +} diff --git a/config/scripts/verify-localization-catalog.mjs b/config/scripts/verify-localization-catalog.mjs index e49c9413da3a..23126da730f1 100644 --- a/config/scripts/verify-localization-catalog.mjs +++ b/config/scripts/verify-localization-catalog.mjs @@ -3,7 +3,8 @@ import path from 'node:path' import { pathToFileURL } from 'node:url' import process from 'node:process' -import ts from 'typescript' +// TypeScript 7 is a native CLI; AST consumers still need the legacy JavaScript API. +import ts from 'typescript-api' const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts']) const SKIP_PATH_PARTS = new Set(['.git', 'dist', 'node_modules', 'out', '__snapshots__', 'assets']) diff --git a/config/scripts/verify-packaged-daemon-entry.cjs b/config/scripts/verify-packaged-daemon-entry.cjs new file mode 100644 index 000000000000..8f5e802825c3 --- /dev/null +++ b/config/scripts/verify-packaged-daemon-entry.cjs @@ -0,0 +1,58 @@ +const { existsSync } = require('node:fs') +const { spawnSync } = require('node:child_process') +const { join } = require('node:path') + +// Why: `asarUnpack` in config/electron-builder.config.cjs lists +// out/main/daemon-entry.js on every platform, and the packaged daemon fork +// (src/main/daemon/daemon-init.ts) resolves exactly this unpacked path. A +// missing entry means the package layout regressed, so the check throws +// instead of skipping — a silent skip false-passed exactly the layout bug +// this gate exists to catch. +function assertPackagedDaemonEntryExists(resourcesDir) { + const entryPath = join(resourcesDir, 'app.asar.unpacked', 'out', 'main', 'daemon-entry.js') + if (!existsSync(entryPath)) { + throw new Error( + `[verify-packaged-daemon-entry] missing unpacked daemon entry at ${entryPath} — ` + + `asarUnpack expects out/main/daemon-entry.js on every platform, so the packaged ` + + `daemon cannot be forked from this layout` + ) + } + return entryPath +} + +// Why: v1.4.129-rc.1 shipped a terminal daemon that could not load (an electron +// `require` leaked into its bundle) while every build check passed. This boots +// the PACKAGED daemon-entry under plain Node against the asar-unpacked layout, +// so a bundling / asar-unpack regression fails packaging instead of reaching +// users. Module-load proof only: with no args the entry must reach argv parsing +// and print its "Usage: daemon-entry" error — a MODULE_NOT_FOUND or a missing +// usage line means the packaged graph does not load and the build must fail. +// +// resourcesDir is the packaged Resources dir (Contents/Resources on macOS, +// /resources elsewhere). execPath defaults to the packaging Node. +function verifyPackagedDaemonEntryBoots(resourcesDir, options = {}) { + const execPath = options.execPath || process.execPath + const entryPath = assertPackagedDaemonEntryExists(resourcesDir) + + const result = spawnSync(execPath, [entryPath], { encoding: 'utf8', timeout: 10_000 }) + if (result.error) { + throw new Error( + `[verify-packaged-daemon-entry] could not launch daemon-entry.js: ${result.error.message}` + ) + } + const stderr = result.stderr || '' + if (/Cannot find module|MODULE_NOT_FOUND/.test(stderr)) { + throw new Error( + `[verify-packaged-daemon-entry] packaged daemon-entry.js failed to load under plain Node:\n${stderr}` + ) + } + if (!stderr.includes('Usage: daemon-entry')) { + throw new Error( + `[verify-packaged-daemon-entry] packaged daemon-entry.js did not reach argv parsing ` + + `(expected the "Usage: daemon-entry" error). stderr:\n${stderr}` + ) + } + console.log('[verify-packaged-daemon-entry] OK — packaged daemon-entry loads under plain Node') +} + +module.exports = { assertPackagedDaemonEntryExists, verifyPackagedDaemonEntryBoots } diff --git a/config/scripts/verify-packaged-daemon-entry.test.mjs b/config/scripts/verify-packaged-daemon-entry.test.mjs new file mode 100644 index 000000000000..8705953ba619 --- /dev/null +++ b/config/scripts/verify-packaged-daemon-entry.test.mjs @@ -0,0 +1,57 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +const require = createRequire(import.meta.url) +const { + assertPackagedDaemonEntryExists, + verifyPackagedDaemonEntryBoots +} = require('./verify-packaged-daemon-entry.cjs') + +describe('verify-packaged-daemon-entry', () => { + let resourcesDir + + beforeEach(() => { + resourcesDir = mkdtempSync(join(tmpdir(), 'orca-daemon-entry-verify-')) + }) + + afterEach(() => { + rmSync(resourcesDir, { recursive: true, force: true }) + }) + + function writePackagedEntry(source) { + const entryDir = join(resourcesDir, 'app.asar.unpacked', 'out', 'main') + mkdirSync(entryDir, { recursive: true }) + writeFileSync(join(entryDir, 'daemon-entry.js'), source) + } + + // Why: a silent skip on a missing entry false-passed exactly the packaged + // layout regression this gate exists to catch (rc.1 daemon-load incident). + it('throws when the unpacked daemon entry is missing', () => { + expect(() => assertPackagedDaemonEntryExists(resourcesDir)).toThrow( + /missing unpacked daemon entry/ + ) + expect(() => verifyPackagedDaemonEntryBoots(resourcesDir)).toThrow( + /missing unpacked daemon entry/ + ) + }) + + it('passes when the packaged entry loads and reaches argv parsing', () => { + writePackagedEntry('console.error("Usage: daemon-entry "); process.exit(1)\n') + expect(() => verifyPackagedDaemonEntryBoots(resourcesDir)).not.toThrow() + }) + + it('fails when the packaged entry cannot resolve its module graph', () => { + writePackagedEntry('require("orca-module-that-does-not-exist")\n') + expect(() => verifyPackagedDaemonEntryBoots(resourcesDir)).toThrow( + /failed to load under plain Node/ + ) + }) + + it('fails when the packaged entry never reaches argv parsing', () => { + writePackagedEntry('process.exit(0)\n') + expect(() => verifyPackagedDaemonEntryBoots(resourcesDir)).toThrow(/did not reach argv parsing/) + }) +}) diff --git a/config/scripts/windows-daemon-workspace-close-repro.mjs b/config/scripts/windows-daemon-workspace-close-repro.mjs new file mode 100644 index 000000000000..be920ca71927 --- /dev/null +++ b/config/scripts/windows-daemon-workspace-close-repro.mjs @@ -0,0 +1,271 @@ +/** + * Reproduces issue #8048 against the built daemon on Windows. + * + * A witness PowerShell stays alive while victim sessions receive the same + * graceful-then-immediate kill pair emitted when Orca closes a workspace. + * The daemon PID and witness session must survive every iteration. + */ +import { fork } from 'node:child_process' +import { randomUUID } from 'node:crypto' +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { connect } from 'node:net' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' + +const projectDir = resolve(import.meta.dirname, '../..') +const entryPath = join(projectDir, 'out', 'main', 'daemon-entry.js') +const iterations = Number(process.env.ORCA_WINDOWS_DAEMON_CLOSE_ITERATIONS ?? 25) +const requestTimeoutMs = 15_000 + +function log(message) { + process.stdout.write(`[windows-daemon-workspace-close] ${message}\n`) +} + +function readProtocolVersion() { + const source = readFileSync(join(projectDir, 'src/main/daemon/types.ts'), 'utf8') + const match = source.match(/PROTOCOL_VERSION\s*=\s*(\d+)/) + if (!match) { + throw new Error('Could not read the daemon protocol version') + } + return Number(match[1]) +} + +function createRpcClient(socketPath, tokenPath) { + const socket = connect(socketPath) + const pending = new Map() + let buffer = '' + let requestId = 0 + let helloResolve + let helloReject + const hello = new Promise((resolveHello, rejectHello) => { + helloResolve = resolveHello + helloReject = rejectHello + }) + + const rejectPending = (error) => { + helloReject(error) + for (const { reject, timer } of pending.values()) { + clearTimeout(timer) + reject(error) + } + pending.clear() + } + + socket.on('error', rejectPending) + socket.on('close', () => rejectPending(new Error('Daemon control socket closed'))) + socket.on('data', (chunk) => { + buffer += chunk.toString('utf8') + let newline = buffer.indexOf('\n') + while (newline !== -1) { + const line = buffer.slice(0, newline) + buffer = buffer.slice(newline + 1) + const message = JSON.parse(line) + if (message.type === 'hello') { + if (message.ok) { + helloResolve() + } else { + helloReject(new Error(message.error ?? 'Daemon rejected hello')) + } + } else if (message.id) { + const request = pending.get(message.id) + if (request) { + pending.delete(message.id) + clearTimeout(request.timer) + if (message.ok) { + request.resolve(message.payload) + } else { + request.reject(new Error(message.error ?? 'Daemon request failed')) + } + } + } + newline = buffer.indexOf('\n') + } + }) + + const connected = new Promise((resolveConnected, rejectConnected) => { + socket.once('connect', resolveConnected) + socket.once('error', rejectConnected) + }).then(() => { + socket.write( + `${JSON.stringify({ + type: 'hello', + version: readProtocolVersion(), + token: readFileSync(tokenPath, 'utf8').trim(), + clientId: randomUUID(), + role: 'control' + })}\n` + ) + return hello + }) + + return { + async request(type, payload) { + await connected + const id = `repro-${++requestId}` + return new Promise((resolveRequest, rejectRequest) => { + const timer = setTimeout(() => { + pending.delete(id) + rejectRequest(new Error(`Daemon request ${type} timed out`)) + }, requestTimeoutMs) + pending.set(id, { resolve: resolveRequest, reject: rejectRequest, timer }) + socket.write(`${JSON.stringify({ id, type, ...(payload ? { payload } : {}) })}\n`) + }) + }, + close() { + socket.destroy() + } + } +} + +function waitForReady(child, stderr) { + return new Promise((resolveReady, rejectReady) => { + const timer = setTimeout( + () => rejectReady(new Error(`Daemon readiness timed out.\n${stderr()}`)), + requestTimeoutMs + ) + child.on('message', (message) => { + if (message?.type === 'ready') { + clearTimeout(timer) + resolveReady() + } + }) + child.once('exit', (code, signal) => { + clearTimeout(timer) + rejectReady( + new Error(`Daemon exited before readiness (code=${code}, signal=${signal}).\n${stderr()}`) + ) + }) + }) +} + +async function stopChild(child) { + if (child.exitCode !== null || child.signalCode !== null) { + return + } + const exited = new Promise((resolveExit) => child.once('exit', resolveExit)) + child.kill('SIGTERM') + await Promise.race([ + exited, + new Promise((resolveTimeout) => + setTimeout(() => { + if (child.exitCode === null && child.signalCode === null) { + child.kill('SIGKILL') + } + resolveTimeout() + }, 5_000) + ) + ]) +} + +function isProcessAlive(pid) { + try { + process.kill(pid, 0) + return true + } catch (error) { + if (error?.code === 'ESRCH') { + return false + } + throw error + } +} + +async function waitForVictimExit(rpc, sessionId, pid) { + const deadline = Date.now() + requestTimeoutMs + while (Date.now() < deadline) { + const { sessions } = await rpc.request('listSessions') + const sessionAlive = sessions.some((session) => session.sessionId === sessionId) + if (!sessionAlive && !isProcessAlive(pid)) { + return sessions + } + await new Promise((resolveDelay) => setTimeout(resolveDelay, 25)) + } + throw new Error(`Victim ${sessionId} or OS pid ${pid} was not reaped`) +} + +async function main() { + if (process.platform !== 'win32') { + log('SKIP: Windows ConPTY is required') + return + } + if (!existsSync(entryPath)) { + throw new Error(`Missing ${entryPath}; run pnpm build:electron-vite first`) + } + + const scratch = mkdtempSync(join(tmpdir(), 'orca-windows-daemon-close-')) + const socketPath = `\\\\.\\pipe\\orca-daemon-close-${process.pid}-${randomUUID()}` + const tokenPath = join(scratch, 'daemon.token') + const daemonLogPath = join(scratch, 'daemon.log') + const child = fork( + entryPath, + ['--socket', socketPath, '--token', tokenPath, '--log-file', daemonLogPath], + { + stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + windowsHide: true, + env: { ...process.env, ORCA_USER_DATA_PATH: scratch } + } + ) + const daemonPid = child.pid + let stderr = '' + child.stderr?.on('data', (chunk) => { + stderr += chunk.toString('utf8') + }) + let rpc + + try { + await waitForReady(child, () => stderr) + rpc = createRpcClient(socketPath, tokenPath) + const witnessId = `repro-witness@@${randomUUID().slice(0, 8)}` + await rpc.request('createOrAttach', { + sessionId: witnessId, + cols: 80, + rows: 24, + cwd: projectDir, + shellOverride: 'powershell.exe' + }) + + for (let index = 0; index < iterations; index += 1) { + const victimId = `repro-victim-${index}@@${randomUUID().slice(0, 8)}` + const victim = await rpc.request('createOrAttach', { + sessionId: victimId, + cols: 80, + rows: 24, + cwd: projectDir, + shellOverride: 'powershell.exe' + }) + if (!Number.isInteger(victim.pid) || victim.pid <= 0) { + throw new Error(`Victim ${victimId} did not return a valid OS pid`) + } + + // Why: sending both RPCs before awaiting either preserves the renderer + // unmount/worktree-sweep overlap that produced issue #8048. + const graceful = rpc.request('kill', { sessionId: victimId, immediate: false }) + const forced = rpc.request('kill', { sessionId: victimId, immediate: true }) + await Promise.all([graceful, forced]) + + const sessions = await waitForVictimExit(rpc, victimId, victim.pid) + if (child.pid !== daemonPid || child.exitCode !== null) { + throw new Error(`Daemon PID ${daemonPid} exited while closing victim ${index}`) + } + if (!sessions.some((session) => session.sessionId === witnessId && session.isAlive)) { + throw new Error(`Witness PTY disappeared while closing victim ${index}`) + } + } + + await rpc.request('kill', { sessionId: witnessId, immediate: true }) + log( + `PASS: ${iterations} victim sessions/PIDs were reaped while daemon ${daemonPid} and the witness PTY survived` + ) + } catch (error) { + const daemonLog = existsSync(daemonLogPath) ? readFileSync(daemonLogPath, 'utf8') : '' + throw new Error(`${error.message}\nstderr:\n${stderr}\ndaemon.log:\n${daemonLog}`) + } finally { + rpc?.close() + await stopChild(child) + rmSync(scratch, { recursive: true, force: true }) + } +} + +main().catch((error) => { + process.stderr.write(`[windows-daemon-workspace-close] FAIL: ${error.message}\n`) + process.exitCode = 1 +}) diff --git a/config/tsconfig.cli.json b/config/tsconfig.cli.json index a7c4761a0ec4..5c1ec10b7b29 100644 --- a/config/tsconfig.cli.json +++ b/config/tsconfig.cli.json @@ -13,9 +13,13 @@ "../src/main/codex/codex-config-mirror.ts", "../src/main/codex/codex-config-path-reference-rewrite.ts", "../src/main/codex/codex-home-paths.ts", + "../src/main/codex/codex-hook-identity.ts", + "../src/main/codex/codex-wsl-hook-install-plan.ts", + "../src/main/codex/config-settings-promotion.ts", "../src/main/codex/config-toml-line-scan.ts", "../src/main/codex/config-toml-trust.ts", "../src/main/codex/hook-service.ts", + "../src/main/codex/hook-trust-promotion.ts", "../src/main/codex-accounts/fs-utils.ts", "../src/main/command-code/command-code-managed-script.ts", "../src/main/command-code/hook-service.ts", @@ -36,8 +40,9 @@ ], "compilerOptions": { "composite": true, - "module": "CommonJS", - "moduleResolution": "Node", + // TypeScript 7 removed node10 resolution; Node16 preserves CommonJS emit for this package. + "module": "Node16", + "moduleResolution": "Node16", "rootDir": "../src", "outDir": "../out" } diff --git a/config/tsconfig.node.json b/config/tsconfig.node.json index a8145eb76c31..817b00c9cbea 100644 --- a/config/tsconfig.node.json +++ b/config/tsconfig.node.json @@ -2,6 +2,7 @@ "extends": "@electron-toolkit/tsconfig/tsconfig.node.json", "include": [ "../electron.vite.config.*", + "../build-plugins/**/*", "../src/main/**/*", "../src/preload/**/*", "../src/shared/**/*", diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index f3f66700bc19..9f71e6e79008 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -13,7 +13,6 @@ "../src/main/wsl.ts" ], "compilerOptions": { - "baseUrl": null, "paths": { "@renderer/*": ["../src/renderer/src/*"], "@/*": ["../src/renderer/src/*"] diff --git a/docs/STYLEGUIDE.md b/docs/STYLEGUIDE.md index 538b7805d912..d795f74039a5 100644 --- a/docs/STYLEGUIDE.md +++ b/docs/STYLEGUIDE.md @@ -225,7 +225,7 @@ Three scrollbar classes are defined globally in `main.css`: - **`.scrollbar-sleek`** — the default thin, neutral scrollbar for sidebars, lists, popovers. Pair with `.scrollbar-sleek-parent` on a hover-target ancestor if you want the thumb to fade in only on parent hover. - **`.scrollbar-editor`** — slightly heavier, used inside Monaco-adjacent surfaces. -- **`.worktree-sidebar-scrollbar`** — reserves the gutter but keeps the thumb invisible until the parent (`.scrollbar-sleek-parent`) is hovered. Used only in the worktree sidebar so the chrome stays still. +- **`.worktree-sidebar-scrollbar`** — no reserved gutter: paired with `overflow-y-auto`, the scrollbar (and its width) exists only while content actually overflows, so a short list stays flush with the fixed header controls and classic-scrollbar Windows shows no arrow buttons on empty lists. The thumb stays invisible until the parent (`.scrollbar-sleek-parent`) is hovered. Used only in the worktree sidebar. Apply one of these to overflow containers; don't write a fourth style. diff --git a/docs/agent-status-over-wsl.md b/docs/agent-status-over-wsl.md new file mode 100644 index 000000000000..e5a6ac9aa3bb --- /dev/null +++ b/docs/agent-status-over-wsl.md @@ -0,0 +1,374 @@ +# Agent Status over WSL (STA-1515) + +Status: implemented and rig-validated (2026-07-09 round 3 + 2026-07-10 round-4 re-run +pinned to the hardened build, Windows 11 + WSL2 NAT): Claude end-to-end live — +provisioning, working→done in the store, completion toast, loopback-only posture, and +restart resume over a daemon-surviving PTY with the instance-keyed endpoint dir reused +across restarts. The round-4 re-run also proved the `--exec` spawn form live (host +process table) and the stale-exit reinstall upgrading the guest to the new bundle +version in place. Residual: Codex's done/Stop leg unproven live — env-blocked on the +rig (no dev-profile Codex credentials AND the model backend is unreachable from the +guest under NAT); everything that fired behaved correctly. Confirm on a credentialed +rig with a guest-reachable backend, ideally on a fresh distro to also observe the +deferred Codex trust entries landing after config.toml is seeded. +Owner: brennanb2025. Linear: STA-1515. +Precedent this mirrors: the SSH agent-hook relay (`src/relay/agent-hook-server.ts`, +`src/shared/agent-hook-relay.ts`, ingest at `agentHookServer.ingestRemote` in +`src/main/agent-hooks/server.ts`). + +## Background — how we got here + +GitHub issue `7565` reported OMP agents in WSL worktrees disappearing from the worktree +sidebar after v1.4.124. Diagnosis split it into a regression and a pre-existing class gap: + +- The **regression** was a title-normalization change (PR `7447`) that stopped idle OMP + titles from producing the sidebar's title-derived fallback row. Decision: the sidebar is + moving to **hook-driven rows only** (fallback removal in flight, separate PR), so the + fallback was not restored. +- The **class gap** is that agent hooks have never worked from inside WSL for any agent. + Two scoped PRs fixed it for OMP alone (merged, live-validated on a Windows+WSL2-NAT rig): + - PR `7642` — Orca-managed WSL shells wrap interactive `omp` invocations with + `--extension "$ORCA_OMP_STATUS_EXTENSION"` (the env var is WSLENV `/p`-translated so + the WSL process reads the extension out of the Windows filesystem via `/mnt/c`). + - PR `7641` — when the extension's loopback POST cannot connect, it delivers via + Windows-side `/mnt/c/Windows/System32/curl.exe` (a Windows process, so *its* + `127.0.0.1` is the loopback Orca actually binds). Fire-and-forget spawn, + `--noproxy 127.0.0.1`, memoized WSL/curl probes, load-tolerant timeouts + (`--connect-timeout 3 --max-time 10`; 0.5s dropped events under load). + +This document is the full context for the general fix: every other hook client is still +dead from WSL, and the hooks-only sidebar change makes this work the gate for the +Windows+WSL story. + +## Why hooks don't work on Windows+WSL — two independent gaps + +### Gap A — transport + +The hook listener binds `127.0.0.1` only, deliberately (`src/main/agent-hooks/server.ts`, +`listen(0, '127.0.0.1')`; auth via `X-Orca-Agent-Hook-Token`, 403 otherwise). Every hook +client POSTs to a hardcoded `http://127.0.0.1:$ORCA_AGENT_HOOK_PORT/hook/`. + +WSL2 under default **NAT** networking is a VM with its own network namespace. Microsoft's +localhost forwarding is **one-way (Windows→WSL only)**: `127.0.0.1` inside WSL is WSL's +own loopback, so every POST dies `ECONNREFUSED` — silently, because hook clients are +deliberately fail-open. Reaching Windows from WSL would require the host vNIC IP (changes +per boot) + a non-loopback listener bind + a firewall rule — all three conflict with the +loopback-only security posture. + +The env coordinates DO cross correctly (`src/main/pty/wsl-orca-env.ts` +`addOrcaWslInteropEnv`: WSLENV `PORT/u TOKEN/u ENV/u VERSION/u` plus +`ORCA_AGENT_HOOK_ENDPOINT/p` path-translated; called from `src/main/ipc/pty.ts` and +`src/main/daemon/pty-subprocess.ts`). The address is simply unreachable. + +Opt-in **mirrored** networking (Win11, `.wslconfig`) shares loopback and makes plain fetch +work — the fix must not fight it. No `wslinfo` probing is needed: under mirrored mode the +relay's preferred-port bind collides with the Windows listener and the `EADDRINUSE` +fallback (below) handles it, while clients that go straight to the shared loopback reach +the Windows listener directly. Both delivery paths stay valid. + +### Gap B — installation + +Hook configs and scripts are written to the **Windows** home by every hook service: +Claude `settings.json` + managed scripts, Codex config, Gemini/Cursor/Droid/Devin/Grok/ +Copilot scripts, Amp/OpenCode plugin files, the Pi/OMP extension file. An agent inside WSL +reads the **WSL-side** `$HOME` and sees none of it. There is zero WSL-targeted install +code in `src/main/agent-hooks/` or any hook service. SSH remotes have the exact precedent +needed: dedicated remote installers (`src/main/ssh/ssh-relay-session.ts` remote +settings.json handling; PR `7744` installed Droid/Copilot hooks over SSH). + +Consequence: even mirrored-networking users get no hooks — transport fine, configs absent. +OMP escapes Gap B by *pointing across* the boundary (`/mnt/c` path via `/p` translation) +rather than installing WSL-side; that trick can carry file *content* for some clients, but +shell hooks still execute inside WSL and then hit Gap A regardless. + +## Transport map — every client, how it posts + +Endpoint file contract: `writeEndpointFile` (`src/shared/agent-hook-listener.ts`) emits +exactly four keys (`ORCA_AGENT_HOOK_PORT/TOKEN/ENV/VERSION`) to `endpoint.env` (POSIX) / +`endpoint.cmd` (Windows) — **no host field**. Shell clients source it to refresh stale +coords after an Orca restart; node clients parse it. It is never executed as a delivery +script. Clients prefer endpoint-FILE coords over env (restart re-coordination) — any +transport change must preserve that property. + +| Client | Mechanism | Runtime that POSTs | +| --- | --- | --- | +| Claude, Codex, Gemini, Cursor, Droid, Devin, Grok | managed shell script | `curl` (POSIX) / `curl.exe` (Windows), built in `src/main/agent-hooks/installer-utils.ts` | +| Copilot | managed script | `curl` (POSIX) / PowerShell `Invoke-WebRequest` (Windows) | +| command-code | managed script (parse-not-source hardened) | `curl` | +| Amp, OpenCode | in-process node plugin | `fetch` | +| Pi / OMP | bundled in-process extension (`src/main/pi/agent-status-extension-source.ts`) | `fetch`, now with the WSL curl.exe fallback | + +All of them target `127.0.0.1`. + +## Status quo + why this gates the hooks-only sidebar + +Today the worktree-card rows still have a title-derived fallback producer +(`src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts`), so WSL users +DO currently see rows for title-rich agents (Claude `✳`/spinner titles, Gemini glyphs) — +degraded (generic text, no prompt/last-message preview, no notifications) but present. +Title-poor agents are dark (Codex — hence GH `6907`). When the hooks-only change removes +that producer, **every non-OMP agent in a WSL worktree loses its card row entirely until +this work ships**. Hook fidelity adds: prompt + last-assistant-message previews, +waiting/blocked precision, completion notifications, AI Vault / native chat session +integration. + +## Solution design — WSL relay + WSL-side installation + +### Transport (Gap A): guest-resident relay, host-owned stdio + +Run a small receiver **inside WSL on WSL's own loopback, listening on the very port the +clients were already given** (`$ORCA_AGENT_HOOK_PORT` — free inside WSL, since that port +only exists on the Windows side). Unmodified clients then deliver successfully with +**zero client changes**; the reporter's diagnostic relay in GH `7565` proved this shape +live. Forward each parsed envelope to the Windows host over the relay's **own stdio** +(Orca spawns it via `wsl.exe`, so it owns that pipe). Ingest through the existing trust +boundary: `agentHookServer.ingestRemote` (`src/main/agent-hooks/server.ts`), envelope +shape `src/shared/agent-hook-relay.ts` — identical to the SSH relay, which runs a +loopback-only receiver on the remote box and forwards over the SSH control channel. + +**Port binding.** Bind the inherited `$ORCA_AGENT_HOOK_PORT` first — it keeps every +already-crossed coordinate (env and the `/p`-translated endpoint file) truthful with zero +divergence. On `EADDRINUSE` inside the guest, fall back to the SSH relay's own pattern: +bind `127.0.0.1:0`, write a **WSL-side endpoint file**, and point WSL PTYs' +`ORCA_AGENT_HOOK_ENDPOINT` at it (clients already prefer endpoint-file coords over env). +The relay writes that WSL-side endpoint file in **both** modes so restart re-coordination +never depends on `/mnt/c` translation being readable. + +Lifecycle: one relay per distro **per Orca instance** (concurrent instances have distinct +ports, so guest listeners never collide); **ensure** — not just start — whenever a WSL PTY +exists: first spawn *and* daemon-PTY reattach after an Orca restart (WSL PTYs survive in +the daemon; the new instance has a new port + token and must respawn the relay before +surviving agents re-coordinate). The relay **exits when its stdin closes**: a lingering +guest listener would let WSL's own Windows→WSL forwarder grab the freed Windows-side port +and blackhole stale Windows-side hook posts. Restart if WSL restarts; token still +validated at the relay's HTTP receiver; harmless under mirrored networking (bind +fallback) and inert on non-WSL platforms (ensure only fires from WSL PTY spawns). + +Reliability contract (invariant class `agent-session.hook-transport`): hook clients are +fail-open silent, so the relay must not be — spawn failures, `EADDRINUSE` fallback, and +forward errors each leave a diagnosable breadcrumb; the `wsl.exe` "Catastrophic failure +(E_UNEXPECTED)" retry is **bounded** with backoff, never a spawn loop. Oracle: provider- +contract tests with fault injection (stdin close → exit, occupied port → fallback + file +rewrite, envelope round-trip to `ingestRemote`) rather than end-to-end flows only. + +Design notes from a survey of comparable WSL-capable tools (kept nameless per policy): +- Guest-resident component + host-owned channel + guest-side installation, explicitly + reusing the tool's SSH-remote machinery, **is the established pattern**. No surveyed + tool makes guest processes dial back to a Windows-localhost listener — the merged OMP + curl.exe stopgap is the outlier as a primary path (but see the round-4 revised + stance below: it survives as the no-node fallback). +- Prefer host-owned **stdio** over Windows→WSL localhost port forwarding (wslhost + forwarding is known-flaky under load; one surveyed tool dials the distro vNIC IP just to + avoid it — stdio sidesteps the question entirely). +- WSL offers no persistent control channel between separate `wsl.exe` invocations — + collapse the relay's ensure-installed + launch into **one idempotent script per spawn**. +- Install into the guest from inside the guest (download/extract in WSL) or stream the + binary through `wsl.exe` stdin — not by copying through `/mnt/c`. + +### Installation (Gap B): WSL-side hook installers + +Write agent hook configs/scripts into the WSL-side home, per agent, analogous to the SSH +remote installers — via `wsl.exe`-executed scripts (preferred, mirrors SSH most closely) +or `\\wsl.localhost\\...` writes. Without this half, the relay receives nothing: +the hook clients themselves are absent from the WSL filesystem. + +## Alternatives considered (and why not) + +1. **Endpoint-file host/URL field** — the file already crosses into WSL (`/p`-translated), + but clients read only PORT/TOKEN and hardcode the host, so all ~13 still need edits; + and a WSL-reachable listener bind breaks the loopback-only posture (LAN exposure, + firewall prompts). +2. **Replicate the curl.exe bridge per client** — the shell clients share ~2 generated + builders so it is cheaper than it sounds, but it is N point fixes, requires WSL interop + enabled (`/etc/wsl.conf` can disable it), pays a per-event process spawn (load-sensitive, + see validation facts), and keeps the ecosystem-outlier direction. +3. **Listener-side bind changes / rely on mirrored networking** — posture conflict / + opt-in only. +4. **OSC 9999 in-band status** (`src/shared/agent-status-osc.ts`, parsed per-pane in + `pty-transport.ts` and `orca-runtime.ts`) — zero-network and pane-attributed, but only + viable for in-process clients and carries status payloads, not the full hook event + vocabulary (prompts, tools, completion) — cannot replace the pipeline. + +## Facts + gotchas from the 2026-07-08 Windows-rig validation + +- curl.exe interop delivery works under NAT (shipped for OMP), but per-event process spawn + is load-sensitive: `--connect-timeout 0.5` dropped 3/3 events to a *healthy* listener + under load; fine at 3s. A resident relay avoids per-event spawns entirely. +- `wslinfo --networking-mode` distinguishes NAT vs mirrored. +- Clients prefer endpoint-FILE coords over env. Testing gotcha: unset + `ORCA_AGENT_HOOK_ENDPOINT` in synthetic tests or events go to the real running app. +- Server ingest silently drops paneKeys that are not `uuid:uuid`-shaped — use real-shaped + keys in synthetic validation. +- OMP is a Bun single-file binary; Bun's `node:child_process`/`fetch` compat held. Other + in-process clients run inside their agents' runtimes — verify per runtime. +- Environmental: fresh WSL 2.7.10 intermittently threw "Catastrophic failure + (E_UNEXPECTED)" from `wsl.exe -d -- bash -lc` under concurrent spawn load + (cleared by `wsl --terminate`). The relay spawn path should tolerate/retry this. +- Fork-PR CI runs sit in `action_required` until approved: + `gh api repos/stablyai/orca/actions/runs//approve -X POST`. + +## Acceptance + +On a default-config Windows 11 + WSL2 **NAT** machine: launch **Codex or Claude** +(explicitly not OMP) in a WSL worktree → live hook-driven worktree-card row with status +transitions and a completion notification; hook listener still bound to Windows loopback +only; zero per-client transport changes; hooks installed WSL-side automatically (no manual +config); harmless under mirrored networking and inert on non-WSL platforms. After an Orca +restart with the WSL agent still running (daemon-surviving PTY), status events resume +without relaunching the agent. + +## 2026-07-09 Windows-rig validation follow-ups + +The first live GUI run proved every mechanism in isolation but failed end-to-end, yielding +two fixes: + +1. **Link death must be handled, not just child death.** A mux protocol error or timeout + can kill the host↔guest link while the guest process (and its 204-returning receiver) + stays alive — the exact observed signature: hooks POST 204, store never populates. + `wsl-hook-relay-link.ts` now guarantees exactly-once death handling from either signal; + the manager breadcrumbs it, kills the child, and self-restarts after a short cooldown + (a live agent session produces no new PTY spawns to re-trigger ensure). + `ORCA_WSL_HOOK_RELAY_DEBUG=1` traces every received envelope pre-ingest so a live rig + can pinpoint any residual drop. The full host chain is pinned by a live integration + test (real bundle over real child stdio through the real manager into a real + `ingestRemote`). +2. **(Round 2) The renderer's SSH-era ownership gate dropped `wsl:*` events.** With the + link fixed, envelopes reached `ingestRemote` and the durable cache, but + `useIpcEvents.applyAgentStatus` compares the stamped connectionId against the owning + repo's — `"wsl:" !== null` for a local repo, so every WSL-relayed status died + before `setAgentStatus`/notifications. Fix: `wsl:*` ids are transport provenance, not + ownership — the gate normalizes them to local (null) via + `isWslHookRelayConnectionId`, while still rejecting WSL-stamped events against + SSH-owned repos. Provenance stays stamped (it made the drop diagnosable in the first + place). +3. **Codex reads a redirected home.** Orca launches WSL Codex with `CODEX_HOME` pointed at + the managed runtime home (`~/.local/share/orca/codex-runtime-home/home`), so installing + hooks to `~/.codex` left Codex dark. The installers now accept an explicit codex home; + the trust write into `config.toml` is deferred while that file doesn't exist (the + launch path seeds it only-if-absent — creating it first would cancel the seed), and the + manager re-runs the idempotent installers on later ensures (throttled) to upsert trust + once the seed lands. Consequence: the very first WSL Codex session after a cold relay + may miss hooks; the next one has them. + +## 2026-07-09 adversarial-review hardening (pre-rig round 3) + +Four independent review lenses over the full diff; confirmed findings fixed: + +- **Endpoint identity (all 4 reviewers)**: the guest endpoint dir was keyed by the + ephemeral Windows hook port, so a daemon-surviving agent kept sourcing the DEAD + `port-P1` file after an Orca restart — breaking the restart-resume acceptance criterion + and regressing shipped OMP recovery. Now keyed by a restart-stable instance key + (hash of the Windows endpoint file path = userData + namespace, crossed via + `ORCA_WSL_HOOK_INSTANCE`): the restarted instance's relay REWRITES the same file, which + is exactly what re-coordinates survivors. +- **Restart policy**: every failure now arms the restart timer (one failed relaunch no + longer ends self-recovery), and the timer probes `wsl --list --running` first — `wsl -d` + BOOTS a stopped distro, so recovery must never resurrect a VM the user shut down; a + stopped distro's state is dropped instead (next WSL terminal re-ensures). Failure + counters only reset after 2 min of stable uptime, so connect-then-die loops escalate to + the 10-min cap instead of cycling every 10s. +- **Install-dir versioning**: the guest install dir is namespaced by bundle version, so + concurrent Orca instances with different bundles (dev + prod) never reinstall over each + other; tmp files carry the guest PID. The install spawn also gained the 30s timeout it + was missing (a wedged wsl.exe could previously pin the state machine at 'starting' + forever). +- **Guest node resolution**: candidates (PATH, nvm glob, fixed paths) are each + version-probed, first pass wins — an apt node 12 on PATH no longer masks an nvm node 20 + into a false "no node >= 18" 10-minute cooldown. +- **wsl.exe text handling**: `WSL_UTF8=1` on all spawns + NUL-stripping on stderr, so the + "Catastrophic failure" transient-retry matcher and breadcrumbs survive UTF-16LE output. +- Smaller: ordered post-sentinel chunk handoff (frame-decoder desync race), port-fallback + breadcrumb now reaches host logs via the home handshake, bad home reply fails the + connect (was: silently 'running' without installs), missing-bundle warn-once, distro + map keys case-normalized, `disposeAll` wired to app `will-quit`, single-spawn Codex + trust catch-up via a one-shot 60s reinstall timer. + +Accepted gaps (reviewed, deliberately not addressed here): old version-namespaced +install dirs accrete across upgrades (~200KB each); an outdated running daemon +/p-translates the guest endpoint path until it restarts (hook scripts fall back to env +coords, which same-port binding keeps correct); `wslDistroCache` caches a transient +empty list for the app run (pre-existing semantics, now load-bearing for default-distro +resolution); default-distro resolution caches the first answer for the app run. + +## 2026-07-09 round-4 external adversarial review + +A second adversarial sweep (five independent lenses: guest relay + fs bridge, host +lifecycle state machine, app integration + renderer gate, design-vs-alternatives, and a +platform fact-check of every WSL claim). Design verdict: the guest-resident relay over +host-owned stdio is the right architecture — the zero-per-client-change chokepoint is +what the curl.exe alternative cannot match, and the lifecycle weight is inherent to any +guest-resident helper. Confirmed findings, all fixed on this branch: + +- **`dropState` identity race (major)**: the recovery timer re-checked state identity + only BEFORE the async `wsl --list --running` probe; an ensure() landing during the + probe could get its fresh state deleted by key — orphaning a live relay child outside + the map (unkillable by `disposeAll`, duplicate relay on next ensure). Fixed: identity + re-check after the probe await + identity-guarded delete in the manager. +- **Distro-running probe failed OPEN**: any probe error (including its 10s timeout) + reported "running", so recovery could `wsl -d` — and thereby BOOT — a distro the user + shut down, in exactly the wedged-wsl.exe failure mode where the probe errors. Now + fails closed: drop the state; the next WSL PTY spawn re-ensures. +- **Spawn form hardened to `--exec`**: `wsl.exe -- ` routes through the distro's + default login shell (Microsoft docs: only `--exec` runs "without using the default + Linux shell"), so a fish/nushell chsh could mangle the launch; `--exec sh -c`/-`s` + bypasses it and passes argv verbatim (no `$`-preprocessing, escaping shim dropped) — + same form as the Codex WSL login spawn. +- **Post-sentinel handoff microtask**: pending chunks flushed synchronously inside the + mux constructor, before the manager could register notification handlers — an + envelope arriving in the trailing bytes dispatched to zero handlers (recovered only + by the later replay request). Flush now rides a microtask: after the caller's + synchronous wiring, still ahead of any subsequent stdout IO event. +- **Relay process posture**: the guest relay now mirrors the SSH relay's + `uncaughtException` (log + exit → manager respawns) / `unhandledRejection` (log + + survive) handlers. +- **Replay cache recency cap**: the WSL relay has no per-pane teardown signal, so the + per-pane replay cache grew for the relay's lifetime; now capped at 256 panes, + evicting longest-idle first (meta map kept in lockstep). Backstop for SSH too. +- Smaller: guest launch script derives the stale-exit code from the shared contract + constant (was a hardcoded 42 twin); one-shot reinstall timer refuses to arm after + dispose; fs-bridge scope comment states the lexical (symlink-following) bound + honestly. New oracles: sentinel unit suite (chunk splits, overflow kill, timeout, + microtask handoff), fs-bridge scoping suite, 403 + fallback endpoint-file rewrite, + cache-cap eviction, and the recovery/manager race regressions. + +**Revised stance on the OMP curl.exe bridge — keep it, do not retire.** The relay +requires node ≥ 18 in the distro; a fresh WSL Ubuntu ships none, Codex CLI is a native +binary that brings none, and Claude Code's native installer no longer implies a system +node. A distro running only Codex would hit the no-node cooldown and stay dark — the +exact GH `6907` shape. The interop bridge is the one delivery path with no guest +runtime requirement, so it stays as the documented no-node fallback (currently wired +for OMP; extending it to the shared shell-script builders is the tracked follow-up if +no-node distros show up in telemetry). The relay remains the primary path: resident +(no per-event spawn cost) and interop-independent. + +## Implementation map + +- Guest: `src/relay/wsl-agent-hook-relay.ts` (entry; exits on stdin close), + `src/relay/wsl-hook-fs-bridge.ts` (home-scoped fs RPCs for installs), + `src/relay/agent-hook-server.ts` (`token`/`preferredPort` options + `EADDRINUSE` + fallback). Bundled by `config/scripts/build-relay.mjs` → `out/relay/wsl/`. +- Host: `src/main/agent-hooks/wsl-hook-relay-manager.ts` (per-distro state machine), + `wsl-hook-relay-launch.ts` (bundle resolve, guest launch/install scripts, spawn env, + sentinel wait), `wsl-hook-relay-link.ts` (envelope forward + exactly-once link-death + handling), `wsl-hook-relay-deps.ts` (DI seam), `wsl-hook-fs-adapter.ts` (SFTP-shaped + adapter + `installWslGuestHooks`, which targets Codex's managed runtime home). +- Wiring: `buildPtyHostEnv` (`src/main/ipc/pty.ts`) ensures the relay on every WSL spawn + and repoints `ORCA_AGENT_HOOK_ENDPOINT` at the guest endpoint file once known; + `src/main/pty/wsl-orca-env.ts` picks `/u` vs `/p` by value shape. +- Contract shared by both sides: `src/shared/wsl-hook-relay-contract.ts`. +- Oracles: `src/relay/wsl-agent-hook-relay.test.ts`, + `src/main/agent-hooks/wsl-hook-relay-manager.test.ts` (fault injection: stale-42 + reinstall, no-node-43 cooldown, bounded E_UNEXPECTED retry, exit re-ensure gating, and a + full installer run against an in-memory guest). + +## References + +- GitHub: issues `6907` (Codex/WSL), `7091` + `7565` (OMP, fixed), `7563` (WSL CLI + detection, adjacent); PRs `7642` + `7641` (OMP fixes), `7744` (SSH hook installers + precedent), `7447` (title-collapse regression). +- Linear: STA-1515 (this work; ticket comments carry the same context). +- Key files: `src/main/agent-hooks/server.ts`, `src/shared/agent-hook-listener.ts`, + `src/shared/agent-hook-relay.ts`, `src/relay/agent-hook-server.ts`, `src/relay/relay.ts`, + `src/main/pty/wsl-orca-env.ts`, `src/main/agent-hooks/installer-utils.ts`, + `src/main/pi/agent-status-extension-source.ts`, `src/main/ssh/ssh-relay-session.ts`, + `src/main/providers/windows-shell-args.ts`, `src/shared/wsl-login-shell-command.ts`. diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index 3f124029e89f..c6cde5794e12 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 3.7m + + downloads: 4.4m @@ -15,7 +15,7 @@ downloads downloads - 3.7m - 3.7m + 4.4m + 4.4m diff --git a/docs/assets/wechat-qr-backup.jpg b/docs/assets/wechat-qr-backup.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a6392babbceff75e298d0dff49ec84af33b8e083 GIT binary patch literal 211009 zcmcG#2V4`+w+Fh^&_kCV6ciK?>7Ae`MWk9lDN*UtL8J%?f`A}JK=3CjRiqo~RRU5) zI!N!JAT>b}<`Undva|7dRSN@&~t-w8BU(Y``;pP3%-^%ckxXtZ5;*g*J zn8Tl5_Z$O!FIre!`$PZR_aFK{3V!_WI|fGO{*3h>_5UM^#mPCq5o}2Uj|+~z{tvHng=^55VeibpYUE1%RFg-+TV|{vPfR2hzHLe7RQ$0PME` zfM*EoV;kV2r1`S}qzoE*feF00UQwf#&b>_dwtW$cpp~j1VSf7FMu94JSZLLq|tTPshMO5AqaE z_#alK=VIVKsc?~z$MPQJlpn9+layR0iAxo2d{)C)Nu~S#k<2XoCjK)~xWIYQ($mw?L;lQ*hBoNW#JT7hPAV{RU$lhW z^W!fTL@}qXczz_2tH2m*%`O9v-bO}b{{6z&w_mc@O(5X^N zoZ3?qR=slP|eS(`bDr@;pT0)M)s$kDB&Qu^yG1$a1n`mgza^3F(!b@h&HZ1}@Y4lEj zLxbK?9X9ci0jYs%yI=iTqlKR!d`ETNCvV(g?o9VUg|UxBCEfaM-fUlKx}$?~D!>}- zaUGW&r##5A-gbv*U7s`!yRdD#r#hS(3U#P?;!uYb`Z+zgVi@@mU0@`he5+bs^69xE zZjOQ^1wB~tI0|ck;pum$e?|41HF!)4u|ahD&3D5Bt;S^V54)odTvK;G(79TbN0wa3{LW;~M4L zp=|wpH9Hk&5t?B~eg^UOvl0GA7Dkp|wf)AM3(BK~IgWSyYY6 zlT^{FxkzX>+oO#WP8B)Q15W4vvMUxmis(eyNWHj%ycEWSV~p~n0t|3Mqt}7V?JGYs z?#4Rx%zF-pzv@e5f-9XFpUqF74j3AO#D4{Mj0=vXt4ltlQcYE60Q3#Z#h z$F)Ex?I^Amg)n!Vd0SKY)lt1SZRV1pH7n5SGAkKnw+e%@m`gi_?^>k=rPQyJ5n?fz zlkoeyoNm^bI_NeZUd~{8g=m0#Upu9!kfpx!VRrZ~X`?B|s7Fw&nr3MNgEdIzz2fY5 zCL4EYVELCs0I!w1l|iZz&2-uFkKST+hR9lox{eI4yJKGDd)Uck)9YVCH<)VVgf<>) zy}ZT2?-8WXqjvV>r``||v6gglvr+G}fz@+Gl4-3#=mahrw~QaWPME>bS&SAY?Tl<9 z#tLHG{?hh0I6U9G-X6&$9tpi>0ZALa!V6gbrz1QBJ!U?&LSc?ufhA#Bl`-*}v58*V zYF;0GQb!iH5<|CXYuh9~Wr`QPw*9gC{alfSPj`7*?Kr0v`}f-p6{w@$K?4V z$uvRO>ABx|%Zj0dppX zIxDTnK`*u6UF_|I37z`Dpt_y7Kg5ccZB1}7yN8{9M90HC^%hHssQEb zAo#gzOk1sBVbWamdrfDVyhz2ThYy|T6+bOTO(s>-kSdT9hzj^~loJ)$vNyDt@FE%J zZF&xM2Z|U>8|`rND^y?GF*>IxAQDK=p@dUG9)TkKehn*>a7mk?;LS723^`wU!F9gH z=jBOfMbCjpk$O@BU(v0-fOKAR0T2rLf{7J6>|A)J32V=03vslX@aCWAPp{3}S*>~u zFdw2P=s^*o92`;fTlegY%w2BA7ptz5J3WY@Ww6w4Ys`12O2ZbNh9dmQHWfVJFIEI z-|vO)1EL$MO-N;c3h;R~P=O*XDgdvsuGtXUiOI&^tZ(kWG^dnXUc`74_Dk$Cs&SP} zfqomu*lVJ)f0K&n2;GDwEUF`$hH_>T&PuYDRXcI4kKWDk8aCmL7t?_FH85$JOQ>s4 zq*>3wu$DxkoFTp$_pA_Y)RLIH$$!l8E~j0juC6Ng^~(X9OK~iXO0On6QhRyn2InBVqUIE)iRGDa z)r}Qn!W-9+a1pbii)a4AzORh9Dq(b9B*&#yuBKvw@jbY%DhreC%jmdF&pNK|paAy| z#=NH^QZFa&Xm{Pze$h1gNYlx+2tEHiF0U@qct`Yp{At;pRfd}m#*$b-BomTGZLV>-ZLq^aTbi)eOq>MK_D%m*3%K>q=uLKJ`-%WGU%SV%B*BZS6IRTI ze9$B{9RHy8ce!QPx~eoY59h2af?P*k%X-m`wAO-MMk2|1n8nvZT`7-O(8+#Nh>Kcw z!B6cjSM($}J$YZ>Q9|>BS^L7`@x-P<{$uAt8@mTWFLBe;wgw~p${!_?)Q6m3&wb+4 z6O`N+8G>MO+VVciFN{IUQy3y4zJk{1Vk$}&`A)WM->^1|^>w$4)a0~zdyGVk7d=iI zqd8_Jo>-3^x@{_c2>As4sCKdFX}2l zzCqvtH9{p0-35ygQtK#p?W)ZZvJX`V@Nld33SMybW%JjLbo+k0TkC?aLdL)iUrY_0 z#8cRXs4{QwB)mEiza3^-U^^(Hmg|-H@{{0Sl4d0%y^>aI?rrqGz6Mt*yU4D_#Fzr2 z97*w&Sws9UiD9|>kK(?6`O58?!l4v%i~hm}6q1ScA)Gr?P&keJn)&_R_c7mDhlO9o zwA%5>66Jl~UoM2)FDgiyZ_NUfX^xh#*%W5A6~wb_j(wP@2U4pVOYUm&5Z!v@aeu-^ zUCIK-b8b*zwnv|nrpwnX7|ls8hu?+qQ@-i)j5hm8#cem6=g-ZOlUz(5RcA2U@h7h; z8h^HtaoQ13UtE(omLtClWMwy8gtfnUr@1Us1YZ&x84WZ0*pyeBDC%D*2;T5kYf=ri zj>K1s?}ANzGx?MnywXrVA(tur9N6L32;#f`l}zQDa`bH1Oy6IJ1O_2waGF z&>YqkBe;H}j81&C8mE(?*BhMsYagIRrTeMuW43%y&L5CtaQ59A;b-M?%ir_nWCyrT zoQ(LU064v10FVit;Inea@m&6ZioaESX1KxHIOV0P22Em5&tdDa_0P3!4WcTc5Py#l z6UMr%wXR}Q_{{E(gPtmLuC{Z&0&^>O}O>lpP~xG8F)}IQ-`SIvqf}AY&a^geG#{^EESJ#wk``^ zu#U8C5GhlgsIqORcmAu)Ek#lK=3Elw!3t*SA?ZF9$lY}SS>)XW6%auyOTc?mBXpD~ zC(OI#kHrplNrH1ITrd1zTdH&Rers^NU-&{#oeCU0Jm~(YskLKmVBuL}{TZ8V&*Y$H_-O7Y;$&nZ+?bmu2I|F<0{M zi6Kya?k5xM;R2ZT$DncR8b}4YWe&bkm=Q$%FiV_ka!qoygVMzL=8K>{b*mj=19N7$HT_YUPVB=j?-YjapXPxf&D!KUXQ76@EH(hLrEqAcKUb@w_-qjogV-S4EjTUcLFSUwlepJ{OM z`Z;XyMkLaC^01Wc++Fs!Ay3j{<{JbyJAuFj>^4l43JiA=3isYnfi#)lCQE8trYqY) z_{s?+gZy*rD;R9#=O5!0E>21zlIOdh(kA|dXErdr67>1&kdoWqApmbi^q~@w8et5$ z!^rcX{P}?4Mau=wXp|o$YLv^a-hNro-+^$I7cm`v9ags}7H>45q$lb%NaE4zPM!G% zBPpB5tt)jnU_avlK}vlY5hnoWT%5B)*+whO$vJ~>OJC& zW1so~|lts!5>pu{Cq@`F!~3D|&5J>lbS5)Z6 zm#9B;$AiDh80~TYxb2qZo6;K%O>(k&d%g5U#;|!veGZ3`HONM)?r{b7EwMPo+ckV~ z{f&0+B`=zDM4!yL-Y+qu<9z?52T~B`P86rKy;`X5%R1LQ-h3@fbW~fxfBLcV1#(Hq z`8GC#FT+I%=lwe?%>aQ_lv(D7n)hzgf#c;R^X=}guEPDwBaQF~kgpjdP4 zcwzVw{Mq2+(wWvh+qRIqpW0-fDOIfAe)~~xv*vSWSRqk>(pm?vF@GAEEVj{d7QwMT z9lq&4RCWv8YFV~_tt8!6I~)AnLb8Nr)`UA4aH0an^9ne%*f519Q-lMKKi{X&eOz_q ztM>1nVi7mqAAhB7c25)_!Rxn)lMHjzT2VZ~_X1f1N@oZ$j~nFF&~Ix;@7(DYDbU<< zO>EUsd~X4XAYBJn)UbVVAr^TO7Zig$sasIAo^jowyykmE{CVtoT zaC7DG*+WstA}Tph&c`CMYs@V(!NvIf4b#0=TvvlsM$pL{fszr79?RwgNeU)+4%s&$ zBys|4T=eVs`-<$=?X4yY)>YTN|M8k}r3yj>6=(dinZ z(y09OZiCI#MNdE}VM5{x5U6_!*PR$<_o91wkn@4i$V{r^iMs1{Po*Mn81*L{cKVN5 z>ap-P(TmzFV;&&+!G|NU-Rz1b>fwUokSANRQRR281drouW&C*EHRB{KC3>H}C{qi| zhe%`<;_fTbKePQ{;6Xf3fGo4KIuN85z4Q&o#9L~-_`kpv&+-j5Tb$Bd6=V4%o|F>> zx@kdFz;ky}6*Xnso~f2ljp2oIxof`rT9r0XM^wg{-Dq6WH!6D%n#c4az5xinUno9Z zsr5&kzwXEY7oa;NY!RDd4g7wikxPRn^`#uM~*W zUA=ZQD0-CZ)gz7RYl|saulbH-h!;FGtz$86a2gNIx!Fgms+na_+20q8R_szT99so- zJc!Vkz#0Rl)F4LiEWs4g#mQuPH&~U zA4iqy4d-}jq$*%M&U0Mo*3H9Q%LVs_TQKfqB77+?%;L=rHtB4))@{mP>Y}A-8wzJ$7C)Nt~h-zb7TOaL^+B>vrS zLEJ^PnXAkR+mTBGgND)fKHJ)AnS@+BFJh={3E)yS6|U-1KL zzdO@+{ze#zMf`GR2e!;;i|A8BSpbSF+);kAy=&nF$!q2DV;_|@bMe-Mh+ou_Fe*$wi zP8oBd-xt48sqxBbC?da4Si|v~uV!`*6>x(Rq@+4P(GJEinoUo1y>kTjma6{)EB9mc zTe%PM{ntjE-ozPT1F_>_UDUs6#8WZfo^v!n+`ACYZaMcUb>N zlaxi7W$oL$FFdy4)3F^{upziBB2F!HKA$0hoACI0o$;9z3&9<^_wl?|<_jUBH}zIi zfu9j@FpTAtOpv0_t`7P#NjVoB+Xcra-+sXJjXi-Mk9m-uF>erm>t$6J&zhaIV9!^b zD~~{YP@cp+Na2Hiu@72CM3Wv)_sxq&qtDBEmqmYi?Dj-aU{3PY8eKYlKvF|18iQJV zg_IbQ$2iUL7*vgkXM%R|=P~}hIs0q1+bUzJ2BM*f>-zHdH6K4#+y1-^hpwY4F&&Pj z8>)De&&YY%ZPHiT*WPC?74tflDv3p)WQQPoa1s?5^dzev53h%70@?vH9$n$c z+1!}1a?g{ls^4YWjL~oVm)&RS4QK&?+zev`_laNFrEy(uf=7oH>A`oB9J$V&KVK}n zAf#(tVCSWY7*l=h+PT&i&HzyQP7EOG%A|ry*m)|awk-Yp6 z$Ny^Cq@pn26f)%+|Lci!FJsD8K2d)ri2{@n=rc7N<^(4%t;MQ*hFC^fjP5)nI*MR> z(8AFPXWQu}Bbl}WW`#(t;Cg)wE^N10N3iXm4b%!8yEn1YoVpNt^xQM0vbx}+q_ia4 zTMI}Q0Yzb2aMXS73V%kC{N`1n{a}L2)_qf!`Q&Pe*0qGz&~(AgctRb%gdD8`pIYd0 zfMW5<%SH#AaKWo`UO%(stBm=&7MUKht+)tqwqa-%j)RA_FXjcu8di^2>s(^pWStzh zk&6DloFd?)_(@%yXuYaN;vMYF5~?L+V;y=|Zqyp@ZyU|obvfA&wb}zI-4^eoB12c= zfweODVq&I}jcrRYPBD0w&CSK;VQ28T9ebO=!22Q%;03eD;zM*SQkC)rDM7eSycn#t z_%U`_T16RGC4~>%@44%SopJhYX|jFp;!I7Ffu{8VyK{+q9sb3_q$7NPNj1n*24mLzBu8 zpQYyPYooV>-^aCAD`pIQRd}naWdZq71V)iuN!*7NQ%HOE0kIhM>qa`MA*qIJfNGOR ztqz50Pys~aD@wYt9xPXWbOiHemms~neHIr?LVj-%aTAkh8LEbHlrf8bj{Y_iC+Rdl z(scReU++2qb6U*%Q#6Ycd$Ay=bAw)F18$HU7zH9!1wh!+e+4gK{{`K!el3=M%24v@ zQ-+Flr6Zi4Sla(%k9Xl&E0mDBRn(W{s#(;aDk+&@0m%c+@&5vM82%SPBz+CxT2BSC zypCYl{H;ULYhKBR=KnWc^|J|P{|4jy4vIHA3Y3|VI+X`o10~q;I^8yGDhQuXm{|nf zUmm*7#*EU!2h;Bg(to6HufF0mb?g&_zkjfQa7|ujW9Uz9A1ZLl1w?xsP9XjOT7;yJRA9+4x-85O2mhkW`du>E^I-cn& z@VM6Nkuztr6lv5+iN1VW3srx0cQ3@u0`Mh?k@{}3PPZOxVj;RkguvRS$yXQ?CbhIF zDq~V<`l5}Y@tpL*uWw=n$&#z7#wx?8dv2(GXdM;6oTc!UUICo{a|Q2z{_!to`Hn!V zoxzl#hCL?YQB8z={uGAnIBlIEmlOxvb|Dj4rM^$qil2aL$G+K|{d?W?YX>eEUDRSB zXvW3p;ta{*zp{^Q`2dt$&G9?X9(w_DU*dQ87ONi>$mhn$dK_p`m`_pxDd7^-BtMA6 z7@P)B#y5}Xz^j5#aH`58ng~U0mwi7bBVNFB+E(I2BxDPI~qQz&83Nln~xQo^%mDiXJ&#p*vc=USwLQl?giovk1+gey+ z$Nae#Q#F%n%qfq!dLz=LQ=*BQy6|7L=5)oapzd}_qcF>33mmVYV1&2nfQSiTM`m*s z!J`KTg^*voa*>mv@>{>XmZQ$US!OsfjOcwoce;pe>tp^8rLgymu(RswqB6(k$(w7LkZrETsP&+SKQUr0XTlH!XDR?y$2y>?0Q2cLHtwp1rj7O7F47<8BrSQ2 z4+9z^v;4B4+7^%x$pp#nFK>Y`)N)t?^xzW;hZ(`}!5{cU@*oFL!YbJ@!w(8?n(**- zexB;>8#aryAq^S>>YjdCv3z9zWPZYpBA@N&I)yL72slCj;@cpJH>i^$h%4N_xom3w zW%{Y+yMk)fM`&d!|B#_e#iwGrIL7InoI))iov@k41v0%991r5zT~+y+HqJbkew@Dk zVsYuoLC??pya*MJy7CL>rk}2g<@Ay$HJ1c`*1k0N{(1I8ho-6{YdcB#NYTeDyz-Upvu z5f#;+D&p3%Tz9SXzvgL%dMWb?E>0tjA+nOk=rtxg67-lCf?F`RS zSY{KJi9KR+)yY*jMo+mJlnC@0Smi9P@0cY)9KLqC(zZFHw5ZyDTDgdo;k6~5m*?He z)#T4HU86Y6)=46Z+d_3=WX<5S`E$6NKNIh{B9HAjf4!I8R`%;uPL?q$%T+iP4LBzS z)X@d)Gpr=XVW8Tl7s-wt$Wu7>#EduhJd~@h{>}$-xLWBm?gz8bNG<}#d`HRPZ6p(( zEWR<1bU1^(iLdeS`Dp7gy20+D{6vx{iyt4B%twNl&z!L+)XrNF_(@SjwaGN|f$AfA zUJ3_`)($B*Endeffw7hMxNlzKHP>Y%o(}dCATgY1CSR^AD3QFe4_t7tjnKZ5~1wrAXYR;M#UTpCScu3rWrP#fHU%_yJ)mAY*Qm z%9Pu1B~@AXfzk;U|FtJsK&Ctf@)5D4AN`{N%^o6Y4hvB;RuAZCpXADbu+8+}puL&0qUnnLxW`lRQvrc?IAF z555nL%eCn0h)&V;y1K zUUZ#q9X*9wbXus6?edaeYMw5{+nw+@-T(b7!|L9>Hs6Q@L1A@=IV)<~Ss3{pd10J%x~RQm5|w{(t#u~PU2f56m1R!YqgYTx zEI*#`CE|39yVvUNy8%3C1N|5g$H;TPH#IxrtxSGRUT9-95KkWXvo?3LJZ{t14%`bI z5abw9>h^xHl{rvxPT7B9V7;AQP#_Yza=Y4s9)D=9ni^7@TFqggCc&q^-&1O}aa@i2 ztFR^WvUkad0t73?_wEWHvLae^xStmfkZ+TtF?Z2W$}oZ>P(Ch87H3aM^pwy1GQDu^ zT+*Gno9{y$^jeGObM?gDXGOL|5y0>leH}LFDUvI=u#>`x8>sRt4i5biZhUVnORY9t zcIewFm>eBMx{RyQyDRvsST5N9Ep9hToSdzKV6pR1{p2BptPAkdDXT2G`eOD9XZ$4? zeW}1CtyUyd1s}AnkCSTEg^{y#Pt87tPFojOl-4*SeFRGUIH!bmhk$z8pXA5ts3JCppA6gszIJB-7eX3iQ@#jzD+|#xYkKEpr7e;qEZampS)$W3+ zIO~|owGJi~(MKa^YrGU6vtH&dZJxNEYqNaiT7^{FC_vj0!JGr_TbP1_F34hXB8EX3 z6`!SrGbO*Jh%1?R`4q}NNV&*c&LOFo&;4UKSpaZ+`?C}|j=`FmGlX#v6iP_fK|v(H zduGVtL_^)!WzWisvd^JAebV*5JB4o(8+PN#>>&RKkuGC(^NCUfCBwQ2Irg1rb+_t1 zHJ7AbRA|VsC=-b4)qLTX@KEJCg+&Q>qO}%L8T)+y_Cb?*-6qDVwkrDcZON>g^+{GG zylH!RN+9YV3W5c{X4JbMNK>Bv-n;@JqHc_BJ95t0f8##eb0Z~!RAn(cKkrcareXCh z+H}iSaKHanUWD?=?=`l;9jb>_SA_OiC8S{yDtDGQHnuxnSv7;{`Az)lqMG<3=^S=} zn(#YJ;{x(7i99_HhCK$W>sLQwRAq@*Miv(-6#mrY+vwifX zJ+U(8zDNJ)3q)@yQJBFP@tLTl!DI3mX1@f? z>S0CyV5P8}22J>YmE_}JpgEIgg(;n;SYQ_O5PLzo>Qvxk2I!8RmZn=aAH%8hOT^Qjts44I(<3opS?IsE_h>w8{=;=i1~IBH%8GkSr#3ZB(AUomg< ziJ=1gx*{G9oVZ7^9y-nVv?Il55=wXaf7E_m^mKN*%=0vDF>iDK8%Khx2;gAJr^^AfZq8FSWvt>Df*Ea|OxF%`ILn@ko+ zKXODAFJO(KN9uFe!GIy`SV8)KlTz^K7D!-PDaSkYeC_*S^3uT}x&-5hh`6J+4a0$e zbl|eiC3~%_{J-aCt6A7a3>jy;68!nz1kH=D&@WE()*PZpJkOWaA}NBD(NOQ2m3LNh zF!Rr!nksBx5A-}8^^_JJWa1c6G*fyqYXR8=c_-3@@-3JOBxATxiw|L>L_}nEb?g@- zT?Udn=zwo({VuU}ODnnJyIGN`!R2Jp4rWk%@|*QTjB}B5DRg(KK{a^UDG^$~{?_(A^f4Z#les-qFUJm$NcNLGsEgac7gW?Li`kInY-!yFQaA@Hes9 z+xjbWkJ`I66Z^9gmo{yFrV3vw*538KZNV&}SY*`zmvMcvi=dy_z>v7Jmoe>wF$>%z zL?L0)=UIeahS-O|-nwQp~KCs_Yp41F84#z*!b1(M%W=xo9SaLuvZ zp*kIDZik-?*=x3x`X%c)t1a`oh57H>x2_ak?^YqDC80#Je;--U7@ECn1T9y&)4Ucm zBbYES?FLOaz1zAg6efbLOALElvT>M+c~*9J%xNd2x52s`giW>*VVfsUac+ zkjBXkn8j=mfzt&@C(Yxi0DGXR@tv+6na6LuF0Q=2R>xLUAjqv4ZEkUKuvUWof)XSLx4-}ZQ`cW%rllUQrc3pb{d7L}SzO+`@b#>)-VeP2 zK-Rn*rKM@waVxX@-PjseyRvsTy0?rOy}8+zUA?eH{zxz}`d+Rp?pDzr=)uE~g%@x} zyre}7e{#NSz$9@h0uDkui#f20pa_(U36!0Xz4Wv2v2J$xHGJyyf}+W(-e*p~`7hrP z5O;KU&|IDPX^NagwOLb?Nb<&{>1&=*0lDV{(pm>X zGfCz-wDHoLdScx~I7vQg1>Pmk8m8FTtQn@cz1$|*+w__zwF7F$#zNjVCrH+9HFMqE z)xOjRk=p*W_xNr2o8$tdFr}wO1-sk6Fs;?vaslTxSus+*ebFIgl3T)xWp$<2T!n05 zNW4s9d}xh$c8BJcAPlDn!fwm!bXbF3JU2ETITJ_JXh+YYW2UD9m6T4s$*$VI%?6O? zsDSDm(eR^|_4*)5(*timfSg!9nE)kFK$JG6^yi#D{ux0v8+%=V6bPb4DpkS0?xh7N zH^%;=#=R83pX9lwmx)v$NN4jPn<6Bb45U~ha3o|zC~W8^!a!xKYB$Gk9lOke6s1u7Yz{wL{-A# z?}UWoi8U|;*1e31Xb~non21d}C=KV3bG^DJ_o2y;O-|OIS@2q7^z~|P#gOiD*dUZ8M)T$Ma%iJJF!x<^iG7-*ydN5=#X$w>2tR z+3Hf2M=vLdwm-F8O*I&O3(DQx%t8{k3En;1v@zCXtcGav^;BS_`}v%7iI>GpTagU2 zyo>3xN~03xVK^c?awr?JKR6w`Qd?CXoV0ND6K){S=i!^@<3#Q2?V|mCvGQkVYo~5R zd-4p5h#)_0z^eDwKNoN4DztL@0>rGCGdm7jVqJB9jUth1(6OMd-^qg;V(eG7R$> zG`aBZ#2%|t=1kw4bay7C15k7GF>@~D7_4d{_MyynfCb@6-sjH=rZQzGKK08m zh;pk>HYu#rCZvr-z>~feU8xxxpPKujb!MlVK0fl}10K1~gO1_a)eym#$B`XtIP$r7 zfc*7Q<<}AmAYKbG)A?g}NFR%Y1|+%VMZiIQ?1Cbkfw##&gEMH$gKpe2q1y7GlHjCq z9esYQZZ9?kv)oiUG;ehLp=Ux?dz6Dc(FfJ0L*Wf$BB)7q%EwH9$g6S>QpMTLAbMWW zIyI)>vrkCrvP^lSy{4m%9zsq2#wQVkP%aBJzg}gjj_eb+VWyE^Hs<$swA}Nv<}Q6Y zD|5E{5>tcO!W#3$=^4g6I(^#I&mMy=DZ|< zA=1euA3ht8J7vdxCoTyKj;xk(O2oP7^wb~x4oI+?w6xYeIS@ackc)M!nW)ja-C zkvV>pYJFR~_T|;eQw9prZC0NjPi)t9@B1rzrFnr;H&ZR zL28KVqZ9biYXqqWk`WcHYfpaZ!G>Bu{Yn3l{CeqAU99C;An|$8iluB^5SzPX1khK! zsybw5BpfI90V9R+K}-dF!Bm1coEOXxdn?~BWhBShyOsd1G(Ls&eq??kcP zA+XxkO)$oOXjb#TQ=h>X;xu0(X;&)x+1E^K2=W6x@pkxl_zEEXzX=Qml5$aPmock5 zVIVSRFGmITuUa2GM)aN_@tRP~*1BN_BMbis{29+oxf4;~@la5C9KrKM0Fa)(vhv*QUAccLS5K&5qnV+Aj zfVhr6KBs}Q^P@enNU&VOI4RGgdzIFag5}Zr9T){iduWsx-_sGvP zJITBSHk{##Pz$5BkFO}gP`oYZ0T(Xqk_6g7eP{t0xnbRp!A_zo7s!0z8<&e+P|CSv zf+u{+hZ3I+Zb3%~_@WoM#MW!wB;G^HHDV|1;P3-PfMHvNyZZ`9YWjchza zJ@`c95E&}}O*Ae7{=Vd2GQY{le@PI}fv#mV`NYigMRkk8u^=*fzR)8$@cE=1`0AAN zZGp4mVuX)pKC>>VJ=-5-3cH5wj#o+jcCTQA|B&aUeV;^Pn`07zmxe4k38JD3aHrD8 z>Rvk!S(}O-uUMy}Kd@~vvT~LIQXhd%#*o*}})dkQ2>Nj)WTDG%l^Om~N~DT(%bOG*mVrM;pP z;TilGn!R2D_cWjKTj9X)Hp3%n+Qv@OyJlVVSwjpika&GopbXT^s z*7%8j{3KFD#*Y{?Mn>kIBc3B`5EH?g`@~b22wFsA_pCF7D5Ub|GdsOMJLcfWMFrXJ z1}XK^ukHBP6+v(tfP0&hc%<-`yLAN{yU9<_!wDs%Zo)+(l%zHRz74P-6vl?*BY!`P zZa(RKxE^)rKP#DK{feijP{Q@yH)-M8eL)rCRn#ALhV9*G2BRra0)K|cB1jQ$h4F!y zRpb*eXY5U}2YhOtA7`IGIrZR#%n$t*c?qb5+N|N;8xOUTHTvZUT^yKV_MCXim?w|m zz0FEX$9lA5AH;nB=W0k(rTgvZgl_F)z+8y)?W5xdh3&j;UGef(Zn_ zx?|6C1$WSw_N(qyeT>Kz<;rDi&k*PIC-$>ET^C!$VF3%MwhI`irZ+OrJ;G`C#&0`5 zG)_HsahrNVGp2FwYL=dOvSmDJh73Al_fau$KBR1zHTJOM^^S^{($XAmR6J7Ai!!vU zjf-1#zW?nB<0Fpk3A*elnS~i8yiH|Q7T!Ewh%L@X*yxtbdO=DgtW&5gR!L4gPvP~Cym!2*%r`R z6%^t0;Z`oHz<$boT5cyhP}wZSu3+mUsK=vyKR&7*jf!gPVn+sntPRK99|T{V5bjQ@ z*^OuSE14mLl78J9uh6J7{T8cKl{;$;lXd`B-@bJ`IJ6=Y@c5Qu!=+c1>(`k(~gUS5ptAMgrIK9sXFZJ@j%&hd0AtWEax{? z8nIysPVLsv+%7{2bx$DNX9Yn3fy1o^)RO6)iS}u)pU;bRnq%eOj-m8P z>7Polt?h#vXFX9$%4G?|{+c&x1_h5L*n*KQciVeum(fKm5Z+MIAth2DQQ;X~f_9m# zi;Jo@C^LQE={@g&J{}$vgbqzKk})m0G?7ux3f~Up34(rtHsa^OE3h&}N}d{lD-<~{ zjW=bzn?gD`a=dq&kgsyRU7Ertiu4-lCy@M*y`$Gd0)e0Cpk)6&v`)Q;`Q9HaMt*IL zIHI2Iw6Sf{P#r$fxu8=L<60Nu7rwFZdHt@{f@sEr&$goq|;8$r49#;{;>oH zOFj5Nhe0-8dfO)DzBb5ST9rA^^5i17fm9^su+5(gsxN&6 zSvk^3RY!kmbrK@iWY2OrBV%<;QJ#8_>QV!ek$z7V?lRv@YWJND7@=>wIl*+cvFmsh_ zP|cTgS@n3e-cQ^=#Yrp%lUu00+`$d!%HefY`5)cK6DA~lO4&NFb{LKWaGUNmI=9*z z767B#pCCqG6fY{M=QH7ROnB&5Ij=EmCf=lWA3uGml$l!GnjNW#Q1gahW<*TA<&mCq z9Pg+$J7T2CUhunN-e0Hk7w%%$HNSn?d{7<`_c)YK4)$3NcARJ}?Y zH0Ba2zVg%eP49>uSxW3WB_=L3@Ae)yBnX}?7fknuP${mdGceAqy)APb*UU1Kjo$wk zR*h^4xj~tO?#!+8J2>8GYvMknw7P1!pl@%eaOUIr$G2$T&r9y?SNs#@)vT23oj`|N z7-24!{3GZw&L1#5k3mNh zlPgK{ox`zT8CpKtSp=sHsy$E@g`XSh?z7DCbvmLo8;URn{J~7cXd8aqv{O$hW7Z@m zM6*qZQd;Aq_0(LR_(BODx2$#D7xwx0Cj(kU&f~rV#x%DJ8#!~Bc5lw??5t}oPxMgxlNzi`UHvf~&k@fvj{-~> z*!aThV3LM@p;-4F^9du0?ckq@vMV5hMWWUI($-5tW30z(=}GJJ{pnB6H(RhN0Btdx z-a7NiycHietqx_O$ZDnu_I)k((ZE>1d#1(?865g!E#BdL5`#hW*ROD!CASzb??P5| z7Uj*@y4O1{Bw^LBesq$btW@X2a_l{nD2w=cO-(1F8=9fB{id1+i;%n%n^bU#@QXZA z`DCy62PJn@@>V%jg*&%*0&*YPYyXEY*J>)e>Ve zK2naB)mo3;+Jugqub&|q5l2D8Ox$gk60$?1tgC)5G;$PQsUi1pefRw!lHF}1-DzO) zu)#N6Y1Mq(h|+lg6zIf@(6;#?Jg9IrW4}Bhq{zYEWAx1Aq>1ht*CEeK3csy=Z2z#c z^$9SLZPrAoEHo~tg>-CmHluwtDBIa$RAuA3Vv1XB;)s$-4y@$&>n~c@JCd%!#Q8#$ zDCMAPJi+woaX=iieGzI*Pxix8AJJUQ8gmNvjb*{?fY6jc(DyQSZ`6@s&Am zsOQl$ZA}v7&Me$YJv~-PJsZZfWwKqDvftBJ6{r8?RG48!;5tn3LH}bt= z$PLWJ*ee%@M*p!48Ec^XWm-ANra6*iTb(q>J82_dN}Le?di)$vJGr4Wgpyu z{f_yn1?Oa#{|l=vT9YSTBrG=XH7Nw2312jB8rWEWn<@NiL$)q)!77^NyIhIP?dHUW za4n_~59%?@=uBl{#@ad|fzb&ZXx>V_P%d}&V^r~^d})tHMWnn{-}i(T>+1&MJ~zYW zkR(gocq+jt0pS+Z7foj&KTe9#$o8TPyp6k-rgF)|Q|;=el8g)kM`YhAENJmxZg2t;lrj*Z)yTt6=zft0|unEi!$c!z`7ATAHdLlAbh zM3rx)awXX@_v4jX-VOoQm8*%b*iC$^B+cbO?i48}R>yK;lmuvh9m_w9BcYt^x5%+q z{wpSd;s3uO_q83s?{(#Fp|Bi?HOC?Rp9`bpopt1(!kQ7)E0{@&q2UYxDS^)EX${uV}d;b}A-%K>{>r2EmBWu;JX+naVyYOVG!?6P^=40I;qFDy3y z|Bz$I#6D2{Z;k=`e{&3yfVcU7pl^N}bz&zbD4ryvwnk^`ewy1mD9bv?BfsL~(4xbu zOKfq*)r}4=ct0g+)K1k0Soa0v;3#mciL##@TCoG(}tu zC}LCi>b?WkLF^2Kg+3tu*FRxUN-WizE-^v91?a8>g#++Q|8;Nv^OHQDnE#_+!{5LX zQlz$g>x&M;ybyox+5mAv+ZQYe&cXW^CWmT4QoxO$uq)Zw$4g@gpAcJy4WReB zvw2XR8H&iU-^2((ce^@)W=4akY%->-fr69^U8pT`KHNHPf-N=yBz!x?i5*HH_6e;R z4~~0il5Smj-}54&<@^tpD=_-oH879Ntxzs3I9EZ_t*LWQw&;=X__2HPwB08~QQd1W zTn7$1p}DqAnjt8(<9LeNl+F#Ef?vER-=2Qw)okQ!NUqGo-YD_cnFmSLpt{Flz6t{- z9}zzylqMMO?S1;5oJ$mgc48Vd0LW9RgM2-4dOwmkSQpV|`bzZ=kWi1AFixonB-*5d z@*w?yKk*e9Bx?E22!ij{d`Y-AgecZMi5+6;Jh|l|oMLi{{AS$6R#uHkq1alMMSQL> zxCMC)(}fodK0`uMB1yIFQlbHI1$HK<{JtLDa36919`tPo0Bmv41m#;&4`I5moXd?C zauZqA1q_KKt_LhjI*{HB$x>-1ymG=!HKKHl`(w@J38pH`Zsndu|8&l5zt5qE19~wp zv2E>mmm8y9Y>9aCCISmFW1Kx^YP?$&@q{-vx#I8AiEs)3I|t8eF?QWb0=_Zdc(Qtw zrQYdl$(F$|?{k0gPz=^d(|z>6Fwl&WSLmKtlvL!j6r=%+GHt}s$fHJsk4hq`=U@E( zDW7nU-FUSY(;r0OM-IFKS2hOI-IWAgll=>84!}dP^oRKSGqLt8ok>a4Do_&9{kNHt zb=?h?*Iyh{6w^=t4)U7#!jha5kjImwxU*Zh7c|g^;qldH1>Nt5T+&tSSP9XlE5x~T zf2Ko1lj=3o_TEiEC~@O?rIVr?E;xgs|SaGxwF1Zm>g85L`EKf|PC7FjJ`EJ~*tm+53 zwfN1g@4@e^RivKp<5Y^6Hu+5i z26~x}2rx6qyl6{doj=_b3=6@N@f7BR^dTZoylSuxVW~>l)O>IQr@X0LlwFYMV4G<* zYbRkW|Ky`=(HmSUXarv8R`4_@#m+Ep(2vosksz{AVaWTw2XVe~F%k{dZ}hj?uNEnP zIc1yktLw&}#m-zv(PpjjF)6k4sDCu=>f;b|i@}Z3_4Pa9`dg-c{FfT)BVj^4{1X~m zc#ud)>4t;hch(qt+@B-S77x*3%f^L^i_ znMWL*)j}6A=U$bR7~H5f4Jz?)byaoazbbn#-ROE!EmxU)&zShD@1DK-1%V!T)_-Z~Tv8b)_-cGLrGIN+gTqWj^!=#ap&Z|SD3!WnLsmqx(L3Nnr6`&K^f3J9G zBkMtJeL`7Qb_x7br|}BoX~6??G!XY~QWch)_y!+T^Dtd3bu{u6&hq!u?aJ0kW6o~9 z@_|hul!bAJZu@BBMa8hEx44k4ya}s>u_4R8%?=L`m_Uk)Yam#{@#N-pvJK_laQZ+% zO{Kw!6wyP(|rzzQWlA|z=u`cWJk+H2)N>tVre?Gfg_C~T_IhYd) z_;}8|itvs2!TJZ+jnQSs)M8t%{Ds}eKgCL_=dzs|?=04Y znfm1%W(lOF$M(8DAlVjTXZ0(l>!d%x1fX%1d)4Wi;c)Sq#ae3EyM#pSe|K z+GhAh_jSsh)H=z!D5`M)OM(=m*OF#B$)G)R+QyQB!+8fYmdn;~hGa^4Mn<%49^Q+~ zAA5Pc*5ukkg4Z#-Cte!@uMY)u1lRSg=5{va9(kL?-N= zBktJ5rBB{n7GhrdaKh+!0hn*t`egxs;7;Nx6F921K3WaL^H+Qmx%H|Ts3$;o@a^D5 z6K61rq#4@~LN+zhlgSyfr1#d=yqZrGNtTIqmfjk({UUm16vl%==+hOjEqaK1rhU;l zGI53^mq3ZFF|$*`HI>(f4CG7~loV48FMcBcsIkQ(yWK`-drx%$t_M*9RsiCkje5H; zH(H-OyuRo@ZtP+crFhl(ww(4}fR>0fd9aBFrGdrz=s~(?1H&xKK*QDXj_olsaiQl1 z(kUKt*JD4}T}ZrUq5uP`?XKK^uvCoT)`5$#FKS1|jI%@0mKj#*o$8q;e2TI)iRZqt zzG8D#6HhUR-DcmVFlcI@!HJ7RMa?bK&9{hbgU|*aYLky?} zU^OwoyPDYm8TKDl4s=2_NHQ2yRbO?ml}@%RXpGFW?kTnq#>}Pmivy~#*Q7sG8& zNFNeMG&VoKNe?(s1T;}U%O6!LH>Q225}$x~li~srhpuT6b6%95EcJ3vkDpxkF*cpn zPkAx@p6$0^&(9A_)tax}pu!kle%ZIoZiS+r?17jmaebakuU#D=^0a z9bhU214UD{p*Z4V+q&=0lyke`H0z+EqqU6q*R#fJ1WpD?n0U%%SfIk%D=G)3*M4)2 zN|+IVhFW80mEGEf&fFIk*1U1G^eEvlZ(i(WiOM%nAl#eC`8R?)I}oW?v7AfI&{Np=?3?2sFU=h}%L)i86~`uR0c!I)rb zmu~Im##la;$C=|dq|WfCZ;eW2r1$J1m>WbtK>4k_sQq_kg<~ti!v6f%%C{U_Qw7@} zo{V&yFp^*n&IZq?#6dFVFiiondW+s9ray)21Zo&Ra7|=$LBC5R+NR%8(&8*cOD7UW zhh`YCgf~)^LfIr#OC};F*m(Th`vMQ^bYY=N16j4N9(=71itNuP7*%*Kt|Cu@0X%3d zyu(0Pbd$hR6BFcCqE{DmP$KvTCw?`#L!$npOnm6Qm!CTUk-L!uQa#Oc$FBD@Ycpwg zh0l&`CcIEH3-W`no*FcMGxpNxSn+BojKJ`96$!((7=lhG9O!mRgV|=yqXI2SyOfa+ z^;SO{RJJa4FZC@XX}pR^_}uAZfU9o;fElzG_u`Tcxht2VUoUHZ8fz0DNo|oy5so>e zmh!=1-p63x56Scovg04{L?A@~Mb3!!Cl=B&$NG1yeyX?`XP*CQ$?|bFfv5t+`457@h&T$V^j-(6d^;KEK~pzFt`{L(S0k zggW@$P=wObKXp-_Us9kwjOG88l%4&5D`oE#6@(n90YHQ<(j*&vy9p{IefX*|Vdi_6 zdKsS?qki_7=XtKso9ine|A(gYwh7E%{}WaI&rcXbbjgseiJ7 z|Ml-sJ-Po+eh&WMKOd^+0|9NtnKDFETWWoK&L{n*|(^?UB~Jh z*y*lVXD}@Bs;0u-S4pc~BYaSF%fMNUqUSdqZ8zj!IsXtG=y79;7oU?RU_ShN#x5Ns z=LiJA4TAX9!Y!6-FTIDacVFPvb`b~e)ur_Q6R7PWx@06(2HW2SdY|wK99`3hrprMA z&)l2DUGM|7NSaqD;=&TH&m0OAUW){Ad=i^<4lg_e@^SyDj&abVbY^HmAStjOm>u5Y zbrHlRWQFhnr#~K2t_LZ8kFah1co)@ukxeYg0bIJyCB{E0u{3}_qu*e~~>y^IZeIpO6B1Vh&i1+*O|m)`NS=h!t!;_G})2r~>l6)4qe z&b*lcX`U3ltPl-khp}L7meM&Wu=WKB>&m1@dsC7Z;bF@)o`10I! zM(uXObDpbnAi%G5Rdr05a=)S~yjM?RS>@xgJhxiTcEwKHoPu2q$QPWE0VGda1RZ4i zCf8)J&ft(?bh{9rnV&b$k(gttw_R=p*GYirY#ju2Qgtm&xAg23Dr00@TM2G-tt`_Un>-!Ej)}Gp0#-z{p7a5%0VD z;2l1zZ(@$S+uxGQBOXD{JmogM{IykWL6BJRTQg-L<^26y4PleN8HD8He{C+FA-Xu=OTB=NVH`k6kh69jRBVKmXl4)!Kx6h1ln$w;(cUWJ*FzEUkA;pm|* z^o!SFozuY2wt>M>CFs3JJJSLR%}G?#FjX0J{PPR4X^ij1lDlN09`ZONyGNguN)I*| zy!Uugcf|fyFP~eAl}K3XYN*owoe>1#J)$BlJuSfh-OA{A9+Fd;a_}T}j5XSN$c?FiyYRwnMBevWfKE#X<}o+oFT_#6CrW z$wON7ec-iKJIK^9 z2ik{0xC}O^^#1<4tjG5}Jt-&hICqT)4tvO3ys>#Q*C&0OlZ^Z!q_x>40F!(TfEJ$4 zwoFx_agbHl`iOu+Lszz@XKqx_YI*&x%iM#n<6Z00$M{a8tvE!^uK+;ZiOA;G8Qt(- zLr}57Y>*L&#TarVtITei3^(X1f6Fhdsy#DlxN&^2Eb)~D8n!P?Sv*L` zFaq;`B_fVyMVw(7TdJ>#5b#eQJ!dTAvnp*?YUnS+ZNP$;6{L;$E+ZRrYZPb#3KT4q zO5$k8b2mv$O|2fqKTB4&avF4SiPVhtuq(7;5%Yn4mD_h2C1k?{4-Dx&$O`kdEri=9 zVQiJoQ)buGsJt5LVPmG*y<%-8&= z8cR+`2G!F@LRldcl>2C3{Zmu*QXBc~KI^;J(EB!9=0#H+VpP=NmyU+_$7dYlxe-_B z=`-+(I@e8sKUj9ceZ+&ennfBKyDE!oDyg8ar>RQyQb;|*X51gybH|1}_4 z%OzrxK-m%v*6V-M@3pz%@+n8jvVtYSvcUSp0m)EJJF&5Z{1$%`OL+SiR>RY}Ij(w* zR2zvA5sRB}JQkp;(2yfs>$nkh=4e5vR_DWOXNJl!HWn-&gJC4E1TxEv@d zCaeZsSK~oX2-L>mnY5!&5Gi_2C{a(+Bd)*!RdaYD$o+Gqi_zH2QOH2T&cbLtZohNnw}dXV4y);!6zZQzvv zkTgVU7Nn~G{yb=XqRfj^_EB;HBzfDZtXArgU*apc&89F7PNiIw2sR1={fTrBp024c z6)9EA(uQE8$sQEKtq3?K2Qg*I$%$T0=33T-?@CI?ayP=;RfGL;sY=U;@tHZv81mfQ zXbeUkdN^Y0sA+M!>rn6RnDU%$#OXB$uO}2-7LYnG0}UcSVWw>}4u4eR1r%L){1fWU za)K{&)nxNv_pI^{d`IXtT~d(ECfDd%0#$u#!W5<2RwjL_+aj%&z4>%Y3ybtV?;t)0 z3n|R3%Mh?*UuHXt%4iqtQjJIcY`c#hF}&w4am%{e;^$*X{|!CgR()^--Tr&Zes=rp03mZLD=cT3tGJ82)EZ(xs4 z`zNUBi=G$H+4=o=2`dao{S%~t0GbGt*N6|4bmPk~pO8*G%1_ByAbB|97Y?2WwDXX> zO|y4ouD~3*FQ)03`{~uuqc`mB9WFo8Y>hh~Aa^@klP~m8Ah*&^Wjp>;##-;J@*&WT zW;APiW=^*c>`^|k7Cp;J5=*LY-r`y8zySJ23xUFdjXDynx|(&fAZ9@{De? zO)X~>sPVUL^$a@CYvBer0jtz<192}Kp^t9_xrFNumQlx1K?csgY?(+RQtc9ZzOD(J zClE$=RVA7RO~j$;^AEMl1J_yNe_Fndf4qNl*DvJ5Mo^kq@SIN6hu9+?=L`|DM`)&Gc?!wDwXHQ&|@(pKgnQeLr{e^+|@zg<9g8|98(@BJM zd1s-rbamWuB#Y@Vkh~nG9DiDua*6$rQhL{ocz>W}wyDuYyy}%+HM*^<2tdug(Lp#s z&A8D0&9$#Yb5V3gt99T4ZkE^A&rf%S?WNi^(ud=|)fYNhCF}Ik8~|mTPG@#UR;tD{ z+#_Py#@z$EqQ^&Or-S5p&x$G-+ewM52|j=QMEdBK>aQL;I~R$c7!B$jSofmvd|oPl z5^l6bp;gDg*kn|VYI19T=I z+H9UaTGOv#8e*+v;17{%YmNVqcSZ2!C(P;7ryu%(+WDv~Q>URSYWO98o70{1;^I1?0Xr?LcG6O1 z9`3vOSALdOAHOg=h+a?{@-bwQoC3FyK-ygMrJh~V7K}>b34JtCP#NjWf2&n4(=2~e zC#N(pl~%IFPiKEaQXpbmzicu?(L_o#cjUQp73sRz;RliJI#+6bgf%($6^8798wH(2 zu9acm+D@bF3n>}cQ&-%oQDQMy)tna`mm(cl-mqlSKtTnQ%MmF~pitnt*qUk6#_#KY zFRyga)L-2U=AXrQw;)s#=8^(i1Sj||5*Pg3+#5L4jC_`kVAE4W8_nt!KG;oflENo0*ghv_3(I^A@p%Z&wk(=* z5H;5M#`h4U<`Fm$zQq3ZTE!A zdQlIOcwNV4wE#)Fi5L?yPB8&MTC5`c=070)hsZkjYjk#IeU*9{tpf~HjV#Y-Yyxe@ zgJnX4Cl+srng5ubJ;(6k32Yn0;`mMM;Fe41Y&T}hWNi;J%7S(8sjN@;Cc^l(r}S z^Wg3F!3nEUu2v2e)qncA!(})te=424yq*7T>VrZ>5=Th245CL=dBpZ!8U>0x7#(zyuZ%`!~QrA1z zpCLt;U%N^Cg`Ir-BfHoxFJ)ug7HsnH=pNI)OIROd!F=-MdQ*0>W6>)Q)TxyQzGvSV zXw33IasKCxUMIq8bhv2)coo=mRfO!R%O%cZu`N$K&P zP@a$Q*$Zx0dL8J(4lB8gj4&N8?>F=GP#;K5_$qd~Zi>9GppKt}HG; zS3HE2r5XcFri+p^Lr7QQP632WM!b?%V#HHSsBMGuLB9Qp-KaP%0&Kz z*x%&qxTllPE$V!imD2p7a^jYK_nrEfS?orAns@iM{*e&WviUD+tE41(ab1-l#f~lq zs-}|F?ZxJqCk6s)#)6+F9>ymgC@s|Q;KQW&CkXhCO%9rc!x@Y^2TrSOyEaf;-HTyo zd_D=R#ZAIQh1Tu?OSnuyB#eO`!D3FG#lJ>ECuTswVfiQieX7SjBs2Kt=Of5#F_xJ_ zGPYO3?Vzt35uh zqvMiXdxhL-G7S;jOO>>q4RsP}GnI5@L|Iv$QvdUp5x3nSm!g`}ThmR;a%z<&^L z1gik%&Bz#t5P(r6mWG7{K^4A$Z865kK{uhmX-BEHbh8j=k7LobQ2`AJ?XoUM;3MNa zj3k^lf@C%G^d&Gv>mY$9hLNVU9Y^$EpDKb(!4_7?b+&RS;796gw@X#}i17FR3vj%0 z82l_|*`EijB=p$d&}CA&?eqz7Ed_mUCVgz_Ct;)TDLmtTt@Xm;Ao4{DGHSD)9WouP z&gxbsia(n(u|2uie;4m9MQ10IPRk0A7D{^~!k&t1K+0t7EGJ&DNdd~8y+nE2K{LYY zE{9zsO1=JFGrt2o=H5FXnF^9awjmCod#s@7S#!aqn*C}@VrH;V+2f<%k_$(3Tv|`d zD)cz{cJh>A)FspQMX87AquQElEoJBrUG0GqKRy+qGj&|2Ts6%EYFy3oy)Tqj)P$S{ z761H*9$T=?=%bQGvFjwv3rfbv2DQk_NH!xT5F#N>*kRGwGXvAWI>>-DV^srXfnl|N z^)PNtqiB#2^m)Wr@a@UZmu;91Ii&dJq%CU$+h`myp*+Liw+K?T4=SF065|>#=XCo< zm5y^{-;HJDVN4sgmOF;TOmoghSGJ96r{%_|{3uRx-tH0aV(tEBG&#|&*9hp7O=JRa zCPmI>v^l=FCHT2HJxN+So(-&Z9$xAfWnzM z|MW=m>$&qRWiTrWZaIn0)s&OnO#PuHNM)c(f=1gYn3;5z@a`3_%Q&Q)#xd&(1%&Q=2lQ2n!mW zQ?AJ_b~=&rW5ljsTdtEeR5C@lZ7L;a_Qij%6+DO`IK3o?$sR^xwOfej2w$F5peRKIrBDoPM} z^sN$xqKcAint?nykZ8~W0|Qx_U?tHX zlu-^ewgsa?nvO;l-p|l{XxAfOiemo?OL%?w5`zind0iBVjyL%W^G=%3ym(N!-k?Ry z<#HFcH%p9@b!^DMpX!q>F%(eP)t6fw!E2`){Vcegq9Zyb?s7Wj8R7yn%yr;;pSNyR z0$01IK*WdoG+7e-=kI~X=@vcCKFwRKF?&*JFxTsUG~{ZwFP;du9h19}P|B*cFL@st z&vvwbo>kX*B6On#_L@M> zq`yWGZ_rf5lUO~(u|x4vw98n9zp#oT;N*ea5DA$!?K-{6J4$FFQ-`?6I`_5~n(yYW zbNVPzdgzkXqzwAgbu4119UBS5=+kE;SxL2Ro8ze+bTQK7SdaSqVjd%`oxGB>g2|M` zHeayWz+CdMO%rA)S2SY|j6QOY1Y3YyhN|}} zAC(zdSf#({a(Ytx?cy)?E#8qYxR_~;tXcDRBp=P-bFEMclw?^yd{j^;{jA@K=fw); zV5<#|E(|m5Ulxh1o+z55Bb|;QBVyG}9c?T=f;VNVJl`(;e4&locscv;Snj~lHMbbO ze^t^j3`<-`w(L9DtsJRRd$xWof%0*s{DY|R3M<@ZyN${KB4(x5x>RGU%=woz?Hkka z^Ve`Lnx^74)C}gJ_dKsDAlzW)AF#J;61Q6t-qltJ--!my!v{%ORdFJ=M`FP;YN0-3mFU<@MGs+~G2l8k3ceevg*i4%}v0vjZE3WQ7}% zM%%~F6%x75u5JIiW)eH1SYVyNk+1YN>UwEjxULc@pCWSb1+Gk0Uy@WHB_&kp#7!u> z(pG%>+zofq29BY}93Y=q1BvaNpA_MCRY(chT6VE{e<7QQ;JnX&e>Xj)#j95Sy2Mt( ztA|>x;pP&)V2#H1u_Q*sda>AF56}X6ass|H$=2(o-rkyVIspn}p-*HUxB<~=;Nu@z z#rD!E8zZ(yvfpHj8ipL!7X>Lu*lP%qIW_{z(Y00vn8YKup!==cmZO(@e@^b6mfMtz z^E)NWNqBz9Fpr@t5Ih&m+(6*hh`omugc66^o(S0|KK1nSRH&&ncG8lZJ)iZ0Q9A#* z0dNtzAR)!B2n=5^_W&>>e`y_0_}v$6k9N*!3GSYcwX?tNAp85ai>ze$n}d%C!rLYu z2<(Sy3n7WB9QV)NfFcQr4sknMgXiC-xyql`x@*Dn=6ERL62ch~j%R;>aK*x$6e1t( zZ9H~VQMt0=?dQm$uxmbhz+5m2>6yKn;vl-pJ`?xi=w$Cdkw5BnFugy*UBRqFu6bR4CWG zsGH)kU?5!;e<`sbvGfC*L?UWYYNCj;LF!s(1d10U2unn8J1xH#%FEd9#hl}xKVfCu zyqZnR8D^k*kiHQ7TY0!?+N6c#caYIlD*W7$BloIf?Kreq?*8~@%GV{ANdsfs@S5OL zPzW)J34OLxPrSeEQKPk|$y!1Bi2PIdVNtp9Z=sA)76z-1(VB*`wr&Ti8OR=`xmvRTLv&m)NJlV8)b@AyKe9n3ToBk9Pm1IN;**_h?mg9eSY+h)&Pm@6LB0K zIJj`Ra{H$@zTyU{0gO5h;_-_tgZLAGF9w}~*}*&dv1R+F=={C{k8!Ry)iGY^oQtvn z@!uOiq9unJNIMcB!R_DX!0d|eWnxX{ZSP!^OK7$dRajz%8C~|s=C@}&-b!E?J%fO( zL~iHIS~BrgrJRvI8UEdO6y~STYiX~Vf1lhrXmU^cL%7MA(=hIW*H21U{wtjBzk_1> zwPUMMZUKQ}Yt~!lmALdma?Y#f^L>Bv*sH825_Bx9lfKtirwb@B6o6i7LhkX0ASn<` z^LLcy{I-?`RG0$jnpp>P_NCp--gc!06N$8j4DR>OH3buF!%_~LiZ9J?1ryc%z)i(12vyAkoB8s1~uv*MaflAoR%yjc{#i4sTSH3YY@pfPw=xz8~l{(O|%hJ@aQTzCK&qt_?l<7son8Gt8ZHvD5RuxOfS@MIM^-JXR=Eb{;juAH}wcR2=(vwJWzuhqK z#^df*;ghTf1+rYk*SpKH(Uk884b^=ySY{kuyo=Q4KzebMmV8-bx{{+qvip~5jhdyw zLko;(9?y`}uNiPR|7?zB5UCSrOuH^UgL!geg#5)sy{B#}?vM%mpIf8l8o1yx*n8Q? z_9IJAd{(rr)*~Fu1x|=3?~R^mhfcC^#vAO9_U2YB(gbANB?Ta*JoLG3qT!d>B*@5F zhmAgGD7>&9e^HwNwj@r?+6s# z&gV|~WXmyid}_WrP5HUu)6<4xHDO;e_wp(02UU;z5+sHD;d~gWl^o8R+Al{V&VAxH zI@QO+evI=2d&0~a(E4q%v?WE&@cc1{K|!X2G_5;aRYK=ljyM?lzHH+&VM;MkIF3J$ zAQU0EgE?!k>>9S}I>svHG)vE-UOCHCuBLWrafTDVX>#n_e_;&R7N-XJd`QQ5FxZZO zTHbL`LKAXKO=fK!^Bv#3Kzvt&5q5E@K-4y|j&Oe!EaO2m=Wa?Wf^003tfWwnQ|wgk zb{o7PNVDYpVK_MIA;sOmT(F#;=@}jUK&GZT#yNqx%IJP^vv@g*v`uH zO!xCbsM=pxwkje!P#@AHhxBVhQjRAL4UXO$Vb$f?ub=f&H*+1b_B_1OIxAr&cO=Uw zCf)ah&J&UDNin#yXfMpwX32=gFWU-CkH~e)A_sJ;dGz(D9KKj4C49o$-SxVvbfr3jLcD*ZVAh15iD+fkmUi2F&BOHQJnlFWvPUlK2c z^HvMKiH&MCpg9 zooy8JmDfky8MrVb;6;`S7A2YmQfI9j%RQ`jcgF*lpF4boo600=(feK4MUH5Sj3Nw> zvB)dbT8i|+r#A;LG;qLbg<47~TbhukfqRZs;mLHFC@$=>?tBMg( z;f8sLkSBlQo`F79ir0hAGE)8sA0a6}s4_CvZWCBoS@?o;?tVkp?L7m%e1$_zN(W(x z2W5T)5SL~^`VD7!kM1+iSzC!Y0Eg(yG}tAsx&SLZCm7?qnQIR__zsati_P}97KFsu z3>4UEjQ^y;2BX67U+nPOh-VKqu(mLeOe33vxcug6uDXLvS2EXhjE7!+F-kK=x4pk0 zMO*)fVZleZ$~90=XS%?ycnkOtQdY-Nvy7Ha-X*n_^y|M4YOQL~>$inX=PR{-H4qaA zavTmd86U(W2ye6zYXhW_Z6YoXepav2UDau85M^@x++iQ4lH+vNZ{Y<`6#kj9v8cW% zIs=&3xq8Q3cZ4wQ)rpbCPR*-c&juzP^tUdp+&siy5rO=ASWStNN(luwvKaE8^=?(= z1D&dOMERO3+|*4aS8lfwtmWPhqqMGk@WZ1d8Y3~vnK0d6tkuj%n@~8fH&qeMzVk@w zc-?SWVO?D^!6?AhBipp{wA^b&sYvWe4JwK%L!Z&!4Ao=xkm4!V6GG)ECAE3Vmul9- zc}^Wyo4#$w3YM2!^KS1H8NpB=I)QB4WCUs<1tww)3hDTd2HW*88}t`PT5=RY@aXtS6OfX>32;Q@QPT^zKIei zsDu=bjN%PG_md`tD(~a{TsLwDU0YTar&ge4#ayd6weA3lI6&tg=;DwsDYvZ&M$U*( z+2H_F6Z?+4wL&)xlTDb|`P8iTxT=DuDtloe2H^d_LShLg9=uv0OVmVrc)$0^On6!Q zIaVNHj^CJ1pFOONn;W%Pg&W3CDAC!a3PIQt*B!_M;7#**xKg2YQqaFpba z!w&CtL%aSjlD<2f>i_-!*s`-_97S(sBzrp~JE5}2QFfBO!Z}9Bo>62JqKuOr**h|i z$gxLcpF`jcuA@cylo}R!d+!l_})XKx+GFr;1pjwa{}ph%VAylNIj`nvq-B+RQS~A_4Sj zV`Ed2@}!-f?^}KU*6ro4)TR4DUo!RlzY+2^=bsx!}cQrym{tKAv0)}MBYIry*&UT2ueULgdDOU)GqF$ZSU@Z`i30BjT+ z5ebbwRF_|-cFCPHotet|IjXpI!WpORv$o!4P~Ej!eyRG@%tX4oi`QUUui93^N+zpY z;O%ki{RK>vdc)~UydCz~6xeq3EZzLYo$QXfmUYgRA{o$rCpb?#$}bv@0+Ku0D{&6A z-4xO3^#g!sI(Om#EL3K3(uv5&K8!?XO^!TmAIcm9`Gr3&t=I0t$EhiKH#brk2p?g1 zNqC<_@)n-aVk!EKeGiCDg}CoR89RjlC`e zWb#R20KJsx`SCwU26F!#C? zJAfmRed}aCA=aoSIFUXk3I=ZV)we=CV6}le@`%@i%=anzZar|7_!@UhPqc_SbJ)Cl z@tY|Z4nEznx3Mzd?Q@!g|6WDB6>I3>qcHEBwmh#2A2Mf_WZ0{!}; z!7-cKVVx~1_9#PP)HixUt47tI4Rf%>avwLJ@+e&-GT@&3Fx_2y-xQQ+6r&yR6I

    (GQiHP;4o;}X)mr6op_TlwARAPcHV2n5APCC2rOEdD*h0#~~3 z*0r82CGNH4-roYye~fkSiL&RWr@gqaTkq!S`nz_#ADAmPR`lJqZe&tRM`R?zF^|)!`aYZFROcHc)#j18H5VnV@- z91PAs*7e1DdQ3YET&)x5e_VywPuNalk@#&q1jXJrW!phq{Eqs)64Ut~`oDtsIxeF&2a!I6IIi}sZxP?rkwP*m-}6yj zOV(PZO()L!`wRQbujiKUYp{LmRtdj%nj%AbZ95B{pHk$mZ}qP8X2>uosg+oK6=o`` z;H2ntORwP_y1NL{XwlL{4xY8YG5n|ZK=hwtoV#La_3|#egQ?_o(JXl-*;}vOsMpN3 zC_BavfrgY0Y-SM4b}_xyA?W~S<~Sv_ij!aU(REJ;$y!A9;5?y4$u|G|}im zX8?Aq#)V=8?{&K`$zShjeHswXq3=ar401GmGD){-{Y$fWJSPZhyDtw-C}vYPcP5pu z6*KMTcf4y&8FP2l=ntP^dXJxqU(3vVb7Il1y^7+)-_{~aO#1vb_cwU4j2V3*DpGm> zO0B^Wz)4$>?$87wifK*C2+ig?EGbD8!(Hfm){>e$>i0CuVDpn`ZZH@}bY2EeSQiTI znT12-(=S?k%;vVeeBVGVGr@G7zdAtwa?nV0pEn)07P?ADvF(`PyBDS6!AfIIT2G%PomHLwAvFY{(ljqjAq2bnNcVe!-LQ_s=lv#t zza(yMDQw|i8n%eYp*SvI(_)sYccJ=LGf!$MWK6vu`pMsOT0IE7RZ*m@ z5n3%3-b=oUtr@WiEj9cyb?D--$Mv&4_iz+_*~LOMJPFcUd$RVl*tIIc06X})vcCbd z^jLA~D}PE=sR6}34fBHpV1nR}w-luPlQ&uMF1p_V#c0Z~ z&X}fqSiox97D?omSUW=>%voTC%6!zDPEwTE&fM-WFDM1HXvmErTmh8QWCXwuHu)oV z>t6@&c5D?sG&jXtvdXZ8d@->4Nm!D>L}{wLOUmMP`}|t!pw!d#Wz4&4i{FN#fb1@u zLhIs`W0ocp(Md#N)jKeD5^&I#0>IU=mqhNHjYolp#GwyiP3jY3`$hLjrQgWgIeMh! z9}`UwSCR?}4akN1alo$F2g7gX!?rW|7&d=?`$VguB-1(jo9-gT@c6X;2Am!V8n-@B zw%h;;l$cQ(>wlx_c&J zXR90203JQ033L>~CM2udiGIRc-R_umiMA-Slkj}XM-?b3Vks;%U&0cC5^5qzfcxo2 z1O<>1xbDF&PQ1l{2f(EM#kl{&@2J^xQrNq(rO`>`kU#11aCUW#hyPWf@TQjNCy%!1cu0s>mKCWnu`dm`CQq0X7V@evKU`i`VBI}0q zk>^N%{s);wEfr&&K?2OWG#il%2YW85$>Bxj^Wm^HDK|t`YvC4jnfJXpzZmL%i@QKC zcZBI;P-^+xWd!-(t9=S+JrO%5fCY+dtF?lhh0Z*_!1VUQ&sCNc=2}OCtNhoK`Tg8_=F);A^D>5Uyx3-092k zD=VWuUi@ddE!2{ThnZZR`nptJA&~TSR6Y3yVtJ);Btjm?tx3OvcQSFqDOLms)ayLX zS`)Ig)MBCX`@AZ2S4*A(FERie%b_zcA_tuj8VEC7idk3eY;^?({%pM!Jr;)?*W1fG zweA||Lfk)b9Uz<2vded2^+WwLU5!a=PLoGsDXJ1Qxz|7(M^Q>O1zjB%Fn(kQwoQVa zmm;KFv2@Qh`IaKIrUI+phld@AWSTVCKh508oZ?lq+u}Qm5>w$FDnWp*vU%lzb=@cC zeEa#I^ygMZ^k{`Y+*Y?^`s0Ug`cM< zr>tXNkoeH14hKK!olL8# znXg~w9=rev>cWFO9HG05wmO1&4Hc(^P@QU2DUY8$omSy;wsMxc{q2R$O*g5c&rgKD z(;XxdoFgJ}M?GIAC_!|C$x3vfx0^?4TgMkeUR9B>jd%W< z4-T-JzkI}^8Ux%vh(I3|Qx@8=#?woJu8p^>T~h$IFTh^i+rJ^QFtr{cVrf==!BHYt{X}EEwAmU^*LcS5ZC?tr!;hq#ecyj0Xj<9Q%=)Does8tz}>?l4GIm?k;j3m^97U&dP<* z)-ep-nCh^Y`U_doQdnQ1fIXeS7!9q#5&{c+VtJOOn$c1l4J|V@BKgW&@k_V;u$2#9 zno$U!{27awBLtCWRxTl=L*civ?rCJfMLeA$4|AaAoIu>6Yl^o+?QRJT^Dsbf&f@gw z)*SoZk|&A<)Q!vS_VVeXgOU$4aUp%`mj3Eb3tt=X3ZGtSW#uKR;kNr0K1)UflsNvn zzxW|E>zL>HaA}N{FJI4I5@Z9Y+Z-FPLesN>l)6>FkJU_HxRUv#T>RG(uRx$e94Q;ev5HFjU2x!~+cwp-r0U@#wb~J# z`KpTYl_j4OU;`pO%xy7!>^)2dnS+!c;~)@a2m`U4R7q4=TPR-mdx})L6Yo~zOriY{sm}e}z9Adof3wz1tg>LmA zs?qf>1$B3Vb%ZzAl1~Jc)(=+V@`w7*p->S22z2N0M=DpZa7%QNtTBHora+OE_ zNk$Ivo^la^kiEwwa7@jJR1=}kUEnSF(b(&uMD=4f`7FCCH8#~;G10#$GzE|uqxrRA z4MnIU@)zj&jV_QaRGieQfFH$W!*MO?jX=HOXk{(bKj`e`5`Ei~gO+ckvPUc%7h&8=|nxV-Djl5mKGt~I8#}-#o*{km)|8Uis>kX$IgV&Zo9~;4__$ZK_pL)s={&$ zBJ;H^zk#j0bq}P0Mt}*7{YqFKVCCRlVAJV4NZ$dog2<`@gE8Fq(&!3|`owi7%L`v> zm-^oXjv*9wp$!Q`9pWP!_h%v~YV0tWQe(+<*J}@M^S^$z5d{&=Kd(4tCcW2`CUO?^ z7jfewSHpY=v!xlLqeG(ywupR7B;_cIyi+l>R5viF6Yb-4;luW;`*8P`#f zO6_6&s0G4lVI7vGBY>{^K&LOQIgPeFKw!Ghjo0bhFK5UBojS3!$}bp;H5Vu(#B^ z=Zo{B^5vYA$NY&DZbSF{X6BCJZvuAUABr1LM9!6dU@Fkb<%wi$f?eoA>AXEkn_j)+ z^pL8~Hw~h4Ir(7+{RHsK0RB*%qejz*T`o}W4+P+1nDi5QKaSaa_$j^FVP*yv)0|B_j1pm#i` zi*s@95$1-txGSUPS7QGC#MfQ1ReiQkpwvf1Q=f|YA#d(-Z-J=+KTfLA)F^trTb0zY zF?t?U-@8_;RW-B4dRHiS{pb7VjMtTgPmGw!4>DC;#^st`@CkiCN3KQ6nV=(-%B?+5 z>lSPmYKwy|5F*Lw5Fy$rx4c!$Qk2qsDZFK2NZ!wZhL`=_b75Ml7QUSUNFWsZ zV2nfWbtk*ym@9|gAHAV%8xf8 zRKTpl>O_q2g!~;ua$m9=P?eqw`^)Dh6>tr?JEVm1zb)ro#%kq zaYneigby(J@)=L_VK-~kheKgeLRR0`D0b`JnG1xZHLh`u(sTjYhk&+{J|QRy3RN#4 z8=o>P9;TYUVTb3ypo(g4T@Lq_skIW>KUQ`_SRkmM3#VnIYJ?oVVWT*X=(p~}SWL6) z$arzAVrR~*`OoN6$)7XaEJzAWXB{}5V}^EjeAw-YYVn3Kko}evDn%7xu2uJvF-TYi zk!$-7`bnoe-u7@Bqb$}w?eIR(tVTrg)xG|p?p3SJ!bp9BDPmevid3yBYKzY$7#m;q zVV~bQRa_n3t)B0B;yPdOKS+&z6zFq2?!85?&9=tKvi>OFMmIr19RyWs^Wn6i&HpwE zHqN-z;eE$8y=L!2WMf!GYLTOo`vTW4-Ki7lZ5>d|*a2j=f)9z$hnydgFX+Gb#N-`l zOFZVTTP!ePKlZqj#6Oy2$Z%wz#=@JDZcBcp{>qftU=Mu=A4cwX;Y`ML!b<%a`#G6+*D?e)Ql7biEqHoDdVfm>+E7%>qCEU&wdgfzWm`+2 zYrk~ufOdtN zGx$VoHn2g`A6&9Bj6eT7Af@^^m*qW+Lra`a%G=cLVG&Vx&6Ot($Q~Dkgyxr0nu6Wg zIZi2aDGxL??`fGC&{Ymk)Ih@N_LiMt?EZ8p*Zdp)~8rk5%X_{4l|Bwc}eJt!upAs!B>Fb4w*% z%(HEf1_&@Q>Xd2uM!eky$-?^zPx`u{)VBq?R}a%Lw6~Y$Jlr4A-8DRdSHRijQzb0% zk?Rgh4;udURd?HL{`FPq*FOvYL2a3Wtb{hA1wrbE*E#*<8jd!z)}HibB;?p7>DR|n z2^F4HRP#0 z!Pg`FyM%R!rGw7s+FtCNKg7xss`IG>$GFvr=PMkYS1^l?c#hulv<@GSQGt4!h4#u? zy<55FQ3l(5<1)MAf0Gdm5e`_PY*NRDH2vdz&BBgHN=laXx@;kYk~#?GGp0Z4K_#rx zr{(8=QASu~Pgl}13|(xEHGSSB^>k2$NiW>k^JYu7M1%doz=5pA5k612J#)1&_3+``!9`Jw(no`=rxb0gt1clZ z8ax#t5HW2FCX-CRW|6eg?GB#hw&gE7%e@5Z2GqIxMp7W4U9n&=P|w`UKSKkBeHB76 z!UkIuySl<3q1uXN$!S480e)1Y4yN?I)FBpYRP0)tz?}m2wm9M0-IwK|jD2mvuRXbH zsxL);9OCr2$QkC<4YB$OC31@xqpjBRqMKZsQXEqsu5rW(IVIL?J}PKCxT-z$sT!=1 zmX-qrvA%Rx2_jn;?q=HeD-K2&mD2bfkuz>xb3Q8JfV2yneo6R((<4%a=FN!5LPA(n zzciKUs)m}WTYEfaOX+}WwdhC4kM z*`B(&DMMH`C#fw?mG+q{e(WNfe4@RB7z10A4zATswY9 zMX4|}X|;Jbdu<5<-j0nzzqjgAt~6^oCic?WQzq{D9KXJ`bd4~D&3_9lbLLj+3d^H$ z*!CYlVO#-$UkU%*L6Y+44nlzO7R_1>g#xpe72~6}+cK{s7POLLxG+lGlnQD?DgrnF z;Z>+twsAr;P{YU=@+B;(i^zGj9%y;)-R|jK-iV{P6qWUL^C)N|UPVRoPXqYCZNeRA zvdM&%=4%dMH`+#Qz#1$@(Vb=Me{-^ay2#07WA}! zb8WJN-@rvd?_Ue?&`Nlds%AR9IWZBdi8ZXvYya_Z`CdHa_9QsFh6l=^YN|r(A^(z^N}R zz%GZM8!fI|Ik3W&0+?w4%ID?Cfz2sWZ^gY;!n}N0ecRwa8@}fw&UBArMVOrFL;y3O zqF_m}&%7bOm%OZ&?3LrOnWoE>mUeSQdzXGSiTqy#oYRslFXb~XsBV|}xV%85n)&_ua?|VCW0%((&6h8nINWh!D-MnE8&bDgvr35I!m+M* zwp1#`{+5_vga533dT(Uu{q-%_vQsPrqW~+q9OA1$x`gbxEMF*tbYEeAygn=4V!E#O z!ll^h0(Zmk4Oq91lPI|vmT+ub%0U+5BVxScz0ktQl=leP>w z1gQZ{ApZ9VQ@jD|Sz!rH?j}>APaD1^^UJA9xTp@6(zRs)dH-)l z+`=7n5HzMpy>UkB(dXz!DZ?a#=$xG9U^=?VDE-f5Nv7_#uL0 z9rHOV9-gH8-_$t=nI7l$M3W9bj=kL(QFO({^QID~v9bS0(-P4P4HHBu{(N~E=&mof zv?jVGIcOd@*wb1H83)nT{Hquy4q9*$rNx+_r<6)kZfQXL0b0i*XNRMf67I zUCijmm3Q*br3Y8Amg%XElGxmuwL(~5zFxB82dV{9J%!vT!!W&nvS>=HM8*XH_cRdW zIr2O=-$TY6g@g=0;wwXpX)r^&m2HSe_4G91z}gc|Kd1OSrBG@Lm? zA!tMTQYiahlc{RTg5*@JQJut1idVWK&9Y(2L*U*lVa5L^)zl8JhsM8;ziKGU#E8BGSS zXG;ChIA6SU-?K{Yyz{ualONiO7Nt*2q;pZ-l3F0z7lKFuA(96*tE60c%}J|AR2S z#hS(|7{4fO`_fGMALMmYOWED!z}}lS`eTE4X~PB}2-W*}M@;8Q=R9ji`^6wq_5pU$ zQ5wq{BOT-*6ylP$DK8@#=a*F!@Ya=Ya8)Kl&!5?uXhwRYsZ8WSdn*(tF0+4`d~#z` zM%V9hnn6mG%k|LLy>+`(PHzMP!P)E{LD$^Ugul8|z5TQDJq9_IjEQ z(`Q+6uGAS{;`Q#b$Urhcy-0X|PZ9g-Aqt`M6bE9eDnAb;~SFq>7SD2LszbeqNkr z3%Z=wL~iSveS`q>9twCS9Ba;~W(f0OjT*<6HnzR6x~jeS&Z1lMU8m&~aurp4sqsL3 zddLj>KDlynVerG%{-S5{)wD{oWzpK2y`84`GlFM?8UF9a1PlJ?K@3_iueZA1+75GF zW=OnweRJ5RK&(=XlY;bET>P4a*~d}{3mw;)1HsI*EuyRCX#clMb0QIsx>JxL_>=oy zc}MU@%5PL^HNgBnA^C(Gctxzwe9^6k~X*1GPsgbB#Hln<9~pE zxgiHVO)GowBr$l1(>%5A9aVOm8Li>hzw#8DGmSZB6#r^FbUx`D_!>DoyI17vOY)E1 zQg-NT^}l`W-4hlnVK0Rl5#>6I^Q0~ryI&3ol^XuNxuvI)BZL!)9rhW z1sgxC!XZkj^Xiu%1C_y>&#b!P zpHPEGn7p30iR3_3j3x_Qpyva$<*_2Vc6jacGMmZP(F=*p<9(?UrskEL3<}Z>uhZGN zXF_kiLfB21nvbhWqlQNwY_f%3=>j_I)r{QP9S~%a_Um>`2u@>KK3Z?R%GFIv>;t53 zquDC~UqLVh71!-Rz#J3qY{$!auZ@O!i^@G#96NpO?L0Ige*4DN@u}>>=hx2CWb%Q^ zmH|Icu*CD|;-GPw)ObPlptr9F4*KO#d0b61A1fW)POk75ikO+zt@%SX!No6#>!cUM zOK%L{5U~+aWvO`SM6cYGEdbRSL-HUKj7S^!zXT)1O5Yl5(q)`d&mNNT*I#abyXD7< z`!`%#S_=O9-_%xb=Mt6kR?}X}OiAxSf1R-3CL$+hqu7(Kl~AU2c%Vu^AixNyE1?4@ zmUM1F1+mydmC2{FFUE4peECo5iEJA;1eZDJuNrfWY8#|ebk!BlyJ0YMr#^Uh!D>SW zD641ft<=(hg;E*e5Yep2y)zqpF+rXfgjXont|i{VMs6im*nizD?~hk`baK*xYWAAhzbiePA36(L0}eK z0q~s%U%bMQu3meIk1Vs8@87+)N%{44l(I%W3yZ`7YfLWIjwpbYRK!&qv~d?4S9Vh` z=$TS2cjZrD;A930oat#UHmD_9p+>e(ds?LMsaV>u8sD-kQ+U4RBg%_!uJef%#dNr@ zO%S<2=2%q3#ZtWNMqis=11Z&8usTF8G0Q4RnEPh$buRypkYT~rttic7urWSiY`H~YtH6k7B*AqVi0xdRnK zK!hpj{eGjj2)wR-O8$U*y>%_rTf;YJI%9^BEm%N&rpGl$OfAT2K&OS^cl_5th zJ&k3QH~5B{B2CJWJ@8KXAD+R@R?D1IL5u~VFGX9k4;W5lQ+Ql$xU`>EfFpjtYqc(S z7Ka~NBaPgylFU`QyvX`GD#wXqg$v&bH%Cmv8dv&#Fhhg3ZXedwt~q%r4>YC5Wyy)Z z=Fj+&tR`1{FOtSPS|a5TT>_)s!V-BF z%Hq_P>YCbg@ue@lvYtpRe2xx6G2NBsO?MkVM^Ga^nY!Y@ux*GN%nahpZT9aM4HF#a zyk=ij6`S%wWVy@tEvXD_?@|+X89bHKy!qG942ZJGYA1pjt?Qq-WMq%k!?AXEAt?KC zDakz>I)*+9nC-ItB$v6|m0P2;F>zo3ds2?u?-cYvT)i;c6KMX#=#?+eKEdD6qy%vi zqWvXU1vMj$_XOU~!*s9)Qao&L6M5_ad5EXFi=HDhbZlfuz2jF`{m=Z9pNOt!9`rz< zD01&l7lefdDe1_H#}V#p6P%XuAhBT5r33%6((r2Pa@y>G&aKb1OWES)T;>SxKHhP! zKSFTKeKLcrh%=Z$P<9Il>2`}o(qYa{OIQbe794q{x*iuN`YsIC=_w?qh^MgJHKpvd zMFq`7z;G3(N%)BxZJ~sKD*T3Z+vm^ijcJ!ThOT6}Eb~7eE1J3GyJ+u z^;2QDQP(d6!j;T7tNy+$ASLX0Ofd8h$_DR% zm0n*N{8F`G8n?{XHn)j>pzt-}v8Z+$#69QT=0^0J%pzr!4$f!aonRWu(-%U%fivwR z>}iM@r;oM1Qs)Ts+oT-0lDXnBZXMnIRT+{&aUuv=jn&ueT!|CJm$2>vDrl^i56^zs zT9|X9`QeQ}ikUG{_Q|cB+#16WihT(T%v-`Mym;PfJ!Y}L{`usQpbo@$y?}1ac zrW{e}yC%QkJI{RPqQ)ZK#o2e3xyHfc_=Nm@P9=X@zixR70t_IVf16`i0jG9tW8l&t zx+nOU3-T1%d{@?QW|hJMsBeRtPsl@^u&`3An*(mREDG_JC(m6CfB70rbRZx_Z!&Kl>_#L#PX@eqn2(<=tGa|E-sSlB?ZI^-G)US1gLtGT z6S=MOg_)`P1{RaKhZ7|IWVO1QYmr$n&Sa z`6aex2INx(GWlc**ZCq*4WF@1KShE6DyrWRDAzs0I-56Rg-cz}FvpIL`+HvIp z-{+L{945h7-@br1#Q^8>@kv28{!QP)9wi_&LRHi`DlmDi4NY+&y7JwevSD8~N5!)k z4mVUl^AupN%L%bU7uTh>^T3;=`|QGB&3Y7DzL5P)V>&XF;kBiD*vS`KJkZI6k1oNN zc0VlWzZA6SZzC@DYC_TXBgdP=aT&lH`~iW`3B4q4B75u)4%YCvl2N9|>55s5^_4U) zA}Axh4ysK5onDHk87g=h=gThlTPx_l`OTm(c(Kpj0|*_&%(4`zL{ljunEVZ2y7nP( zh1*r~KtA-cN~+yq*=_C<3iYE!{SHV(G`tLnH5&B_Psew&{?Gn~~HL7ytH7M2$d_EkrFm!RDzwUA_ZEsYm6hoG;TJ~&b4LHgABOK_U z*ykQ$&;t-@g~JfL@Krb^Fp}bJ53h>Q#ie{utg1HNGBUp<40&krAdo>B%uFZzw7^7I z^CjUm*q4u+TYT^~e@!mEE>*RyT7AmU>#wEZ>nryg)u(!nI<+U&v?B=;Ua9~+iaqcS zQq%AkH7+o2@{w8=c(o|Y7@V%hSg zrCfXiy#si*RT0KMJ|SxdcV~AM^7*{qTj^80%y~O3jMYUv0(G;9R1Nwx0;e#2yGjmU zbimi$$7SdBh(g0xNr3ekK4f48YsH${DS{m@FWD)&H1*r73UABV{@g_L)8T5pWR`61 zpw_Um`rHJ({^$UWQ#!SuQUF5ukh^uWjj5KK%aKLDHLrXYzqqNFm_yu6q8Ck5E@9n4 zZA7ryNATemmFVmB0;NpF`-InLb*4L2K_zErx6ntpx+AC0UY5Q4>~$~|P15*-ry5vV zx+a8c1kfwQ)DT_4s3y7zMPr8#F_=O&*OWD8?JnLqF1yd1MZ^B(hRp>&k(A8<+pbR) zL&ycj-eQ(NrWYc3@Zmh^>Pinowj>tQuX?+EUOc{H;F5qi2;gj7|2kZCg{nf0G`+7C&+(+E^!d#|E7t~6KCh< zjyqUqU`jAS&@x15a^ZtbY^82WW5nDIob(>io61@~xS>5h8Ib0e=JmbZfdC>FTD+)QyOZ&bzO_5WWbwz@)Q3+an6ZUl9<} zmrhm0c<04}?oQ_XaX>=zOu_b4-bOP9BU~AVTntRB(>o~ZGq7f>G~{Z@v-F;`-$$tk-p0vxK|epX_B^BGvZZlzcbU=a z)}tFm6i+C_dLX11q>LHq{UPiG735cNLi)WobI*}IceP;kJc$J<$zwNTcgU}~BCZp} z@dPph%o_{WZ@@dR8EXXeHvcR|KMe{H2neI%wI+Uj=az_!PAXazU}9AyeOC7&gg!22 z-fx^pFA{746r1PnZ8{R3;X>ElZZR4A<3_JrFptpo0+-Mv2x$|~%Y|UTQ$Z+5(cl-@ zkqp906S-O+kjHKBUmTvTIRg|;A4e*nz`hMO+3WP@2xxK-;$q#bJiU|k{*9mjPAiiq zCGQ9Dw_%E2h9AuG!DPjFdE&1a(XN?Jaqmrcs1dG$MWpaSyxSX7pH#ROGay&VKPbb)DQbUlq()(6W|t%&S5aNXF_eo)cA>hB&)hrIew*ADfMBs$4T`my22u8bu)yTo&J}$FcwU( zo&x`5ML5=Sfa)|2{dq9Z4oPC(tw;9QB0Y0-E$b$WJ*fVhzEh0+^R80^*OjIz1EgX+ z>oW@1Hs{(+YlfRob8|m5D^EuL*sw3mM2Tkk&13^(!zgojFpwlR!=A7!vC;}3jgejf zlhCG<@~&=Z@?RJiYmb4tT;Q?{`>WKn#hcwcGhn}^6I~Wq4q)T(TH@8ejzEDGW z7+s9NwXs2d$6ZVe?tBVJK(ORaS$wuquOMBYl7DFZ{HEc4VZ{5`QNoynCKu1At5GVv z>M2p7WL@dm&VxMig$BYyUH*|}##?OM%3Y0OX`z&kUh5`skV?mVZ}0Z(!PQSQk}e(< zF)r67{V$7;?EbhMy~_-7n>$P=UVN!PPnJ-jy4?8GZ=C+i1Ps`-^Z2bqpII#-KUE~b z9;Z?b=I_HA6m#0XwJ3fJk_a!+9BAS_GZj&LCmEG{;pC}si#ZtCeH^|=uRQdO2t31M z9*CpjJ0%q%Fl>(DS=g=C6&@nku`yLTYu>h=>da*}S8Tu8dT}tdm_rhzC>islgas-w zcm1LOtkm^sB^itgYoK;G*RFkB8S^uV^yS@8yTXj}ZOfdRXF|d^=!d(Xy!&$Hk> z7s<_&!@yF`yvg3s;JABX{Gs;8Nd|l(8O#Vr@_1LX`=HN!w#j#S7{uOo(NneT-P(cl zJI{xPShg`<%X`(sA8Wo2Q;7&WQJufS&wN~=QxE0^Oa^wr`<1_&vbvI;dqmIkN$mJU zaKI>$$`F_F(pFgA1Wf;8C z_$z8NsdEp19Xuv8sQzg24Cu9q_~pKP(}CLoj}_=I*$AhSo!RT#A_@|nSbPonh9Fd@ zK>zuGjwmyfdMvB6^J>E9H(uh*2GxYnKr9yvf+HKSoO@~3clLjixDD^wtfALD;=ZQD zYhQQwx3H#V+>3d}fd3f9BKHsO)YJH2Ve{ik%(o#3i=o(b=QMVO$gy%-kGmV|x~?JJ zBbl2IOx$m+?=CMpq)s;aD+dj4Q&XkaKq5egu=lP5wIQ~T!y#9>4hjR0i+7#)xr2GS3c=VD{=bEmuzD$1@GaAthEEjGU6 z;X0CKsUxl8{hfw|3BEr4D*`dF359cgAMne#k>1y=rtwM1s}x;ja5xZM++^Z@Vnk~i z0g=;!hLNW|637fvSblMp#FHV=7*$6Ep*G=;|EdNLXc|-~koCoBo~(W7_-ttDwD-Qq z<;yDT%B9rU#Y54PaT7#O9}d|2Ha^mWu|{Yj%ts9&&c$Xo5;QxmQTzom^*_U8^Z!Av ztQQY`P3yA8qc%s^tp-;xK5H!p8X-8fp<}~$L>;uNMV6SBFq;zvL*-Q=TJ7k@3_W_4 zt&S72&>Z2;#qr{jO;AY*)&DD&A%vE0hGOiWBOza9>~!W3^2T(R&0Pun*%b2eN~$W) zAfXsTyI?CDTKl_xQLXakC?kZ4nOFHZ3PQs>IF%OD*?&{>JKMrbXYLatKoVIh^6)}`}8Ci;_Qo>I^rPefiJAlUF)#4#0sT8W}kiJ+TbDD znof`KxPKtsrv06E_G@>~ju!t4)`ZJ^!v{kjMXPQay{|r+Ch-Sh!OAbf+!M{KaRMLC z>psGuH$wL3*V8XPM)0-S90qOs9H@EU{qLn{o4)ACuFOoO>uCU4*%9HNjnT|HT zU#T@c%Bk-CTy?lrcl)Womhw1+>LsZJ_Ov(+-sltOgoUMSH`Y&OnX5OSN0`vJ1_}>t z<+@9BhduAm~T-|j90!PlBM>deLz4&{mz5^J3STQd(80CbJPZSqoit=%e+ZJXl7 z@4iO3atmY_CLkk_7-o)H3x6d@NFjfd#Q0$!U>nY*(;X`J{S1Y`bt)K24@| z>D8)u+GbG>g=6PiQc|}MrfRK3M0j`Ve~@2Nj)d z_LmL}{Stgttu{d-1E&snz1Q&iF9m)mna|Z&G~oYXLpELp{A8}vsLgjLq8Sp|Y1NuD zH%7+OwK@kDR zh4jDfyy#KH+m<(wJHDq;fXaC||2JPR@?$c2N?C<>_ZroZ2dZs_e4&Nlq|Y%5IvQKq zk_n#E=Wha1E`*^Hn^K_3c{27oH=or0aYOR9T!HXBLIBXS=gqr2D)dP|JM| zo)J#gflYq)X)?ZbRpb8JR@IH-a?iFIH^w3Ks)u{-e2>lL<#D_rMc=ARt^O@-Jk303J#usq5c}tM<%9Gq zX=75Ov@=d>Xn!c2IX>;ZLT9A$Lo{X^@^P?UG-{%OPrUU))Y!=O{zOVX50T5TlP5I8 z3p4mKSGnC30}=+7DSbgNyU8M>qq2P%<;b8|R6f`ODk z)Y6xy-#>r;u_D$t4+;TZ+^tLaaha$bG`*k~?#YqFf3ox8;7# z+;4?kB9~k?q8J;Ru}i;K-`^km&%=9rzu&Lt?VRU1uX@|q#);CSH=Wpm#Gd{9;U$Us z3rRnuc3<@P!*IKCz0}b45+@4LZ$N17_nTi z+!`g*7`LF3vZA8CaH5gFNAUO_0b@)o+6DZPPG)~QbUI}z|2WujmMoEMTR~dVg$O}( zb!YZETliG_E0^s7i|JpyVAU#l}B(qp&e@fh||FTUr&ZHaIQL!1z*B z#E>6O4EH!C1z?%%v5SDX=*^dye2S9|sJwDiIAu<(*cl2`GDTYbN>9o!5NS3d?pvK8p*Z8A(pat*9VkEH8wwEpZzZ< z)dfX`YL!qC*T~oWX56dd9)y%#2#Ig4TN5+m&;F>*mKS~$)KN*e+WbD~jN@O3Sv57j ztgX`Xu3YYGz9Kczq6>!nS0L`ZftxbgVE&c6h8<0YF*!YH){hPxD&IfeeWhC4TfKiw ztN4^b*98ab^GCZHM<&~RseLrXP*aVe3H*2`u74{kVIPZ!ZWNPoOAS4e z@=Ls*3bI=-W7R8P*H`@P@)!SrvCzN0T%|o5X#p^r9gL+Nt%S*mOQCw;j)bW&;Hyyw zQw8!s`Ib`dY^}By-{>5LnwFZog3b;7fcHL1cVncsoi#l2<|i_!=c!QQ#ky|QHXZ(E zJha3CM2?CT;Dj{jodLXYS| z=X3Tr(TgB^*6pUXx^~wmHu7hVd$NdbLSIa_@k|8_IdwM={lsDC&C&0F3$#uh6I2V9 zOB=S$PLTzZfg?6!IDhnFQc+kwzG{TL2KJ(Q76^Z^odm}pBoj&;wTh;6-t8#P^}uh&=xvl0vjZ8f&*)z#Yr0Q>1V-&vn|oIH9l^9qzF^bRn7yz0_7K4?ep z2Aeowyi+$^RqXKV7PXWMxpfk0XCA`k_Re52^5&H!^#;AO(!i7p%Sn|7b&v-mUp2sf zA*Ol9Hregr=9xnCmqi)U@u5wZRkM4w2-@01V1q6PM~}pE{FVlgkfA1BPl|IF#_;)r zZ~ILK7+DCVitHU50OS5GrGS~4vWkC`Wo~{UB)C(Hr~1yQt-88;k%Y}FIs|ak&NIgX zb@Qr73l>o{t*fb*l~*9uO6U><8lB;iz)*uioXlthoiLoY$-|lkLrr#)Fdz)|?^1n|wr?%wvFxn!Vda8j4C$o3zB9hMy!7au&{vfmP9N5Y) z8v7RNNjHpVFLR$|f9)g<1oU*->9Ms72m7(WG)b6I>sFL3)(79|RAoSHwhhT!6cfN* z(J(Cjy}&SfF_>1wY>N_hQKR%{|sw3X_7uj;Zu__ZNb#T7n7=p292 zvduRh5R;36X|fsrTC8N-{IvdD_i5H~kW*67+qQI<{DVW4y6BMr>>6^BdlySUcfk2j z8cgs5gfzKQc;`MZVTIhUYbGxXyfsaZyj_@e9_SX(Kc^Z$Y2U>bs^At&&~<;lmDl%m zQ${({Qd^&TmNsu5AN-gijp+uqP-6?<^_(a*j1S0PmG6J0?1#2#9t0!U0s!KDGcRy`!uGE!v)>YBTiwmu5>x28Ngy-VrTVLso&8P9yfmdg&?2@PQ}3mzcrX> zg#(Ypk&QZ_Rh2Atk(@A~kYO28RAHq6Rgltj{Ho$QxtGG4~xjZstcdf=(D zwJ^#;FTPpuKu^y+ETJ6Fx#j7C9Ge>yaxOO=egCk}XxP#)1B|=gqDdx6`4ReOWzk;- z6%8O|KZ}cft$AKmB!xO#hsvAQ=BKbw#>rw?X`7bD} z0nwdr2h&-#?}~szF}d5tC@h2g>fZpo6c*hkCnY_3u53tkBgtzC9QgNokd(8RoFcVo zO>@Ex!gCPW#c&kY>cU00!V-&IK;`;J=lb_~9w7AG8DnAv)Q+dxRrgPzc`X^{IVPY~ zbV?j+lLG&}lE4%lG2J5zV|4wt%@Ha2P~2j{LLICN&i-qjle8L72-CQlbosGLg>+Mz z3@i|?{-3MDCn3T1cH#C=Pew)C1=QC`F;pU1-jNo7$v=~$=z)}}k1y6c;{QzLr=(Dx zv4t+kUszDd3hqij4U3#WFU!#tw-cFM{C^>`u^nvw%pYD0yX(q+aQ0fzlD?$6ERAd^ zyI!puNA>4FOuWN)@u1@`M2U_knNH6p7gU`vWjl0MUyjjw4mW#hn9x;3p?|Q@Q>gCEOreNHEp=_)Ty#E6>r0_rAl;OLNrgA3hpXGGtd`m*X z1ahyxOS0$i`zhMM^XiG=unz`I;=?XpEZg>`)Uh+g7bpSx@2-U~$t{!Kv7r1@ytMZ8 ziP%;wzNZzTyjUL+y>HCcw*ltcbkr}gT- zh5)N!Wz=(Y$CS-gY8|M#w^XSX7?}T_GGKaQb{LlCJF>2 z9Z%Bi(n@QyYj?8pHup82#)#)S={7pX4K501(ov~rEdZr;SiWJOp}37++yoLwH2en{ z7+L@$mGRhtE?H#K+;BvvQah@J$9sK+?s3VR_EWbw z5~(?h^=mVN+Zzx*ltUr76(xW=S&B;;nPq2Mq~No3(VdsyJC)EW-WK0z7koh8v%B6} z+9pjJm9sdc{Lv|mu2U~@;G9x{(xPfn0vH8oH+Yhx9Lc3JS9vP&v6qV652#Q>z`dwolszWOx7deCEq5m2Ph&^2PuwuQ%_H!^DTzB( zVNmy>uV6l{r%!Bgsl2k*m9&;r8w6niF5OK3)a)3x9 zo6;xWK*5LjQQX$|iK6{|!Ur<6Bks8R>nl_7rx-6)mOhU2TX`=}oR_@#Za+|={KLuY z&YjG=(fzWAnjp;A0i(GhbY8Pas}w})6#4KI^qB0gy_9PQQ(NdBPj=?f2KlahzEc$y z?plGTMwz1`80qVVOA`IkXS~I|X7hxjfS-f5@IHdXMY%{_pk4j`J7=n^jLWCQ-8asq zrR{kK*Kn5)=KRsw-2Womd09kzjUb_QMq&Get^bt;q@9j~lH>qI9$n^$Npz(=rg!7> zlam$>-^4WgjXp~VJmF=*hW~|F?u?TP4kaBuT>$+%aiGZLpolYtOcFtxnw|C+0^7ad zy+hr@PN2ooL&bsZN%Rym;StjVcW)#HR=1Uy(LDnMMV9a{^C8ZD|1#&{jqDw)TS=`dh~F&=7C{0dN=b4xx({``6Pr|Bqj zfc-YR?|x#FZz~wNlO80{E>OG}F(@_Ec%CGV92Dhsj;Lxf(Ja5s1~lXX%r%1h37&03(GC4i-Z9#d?rj2!a^H$;fIuy$XIj2c-bL&1JJqBfX-$0ZOZI z)0VHOW5{NL(KyycaKK9jgQU+n`Ih%DnGt*(T0UxpjoQNn(2t=raQtfYD#X#Ta>n2O>As zGG!wJ_tcov|0bT^VX!5(gVkO%Y#NE{JTKTI_oFRWI`*?tU{N}Dn)oG7BK(LwTU0|* zIJED;H|)>BxSJ%h07_(E3^eKRhODMgOLnmgSxnnu5DMyFqlWDe7X!-B3>LV)Y|J^XI1vwV9;0VFeV(TmMAo+N9adJ^l&4*}O2=le7@l-aIxmdT7}3Gz;oMcf zuj2PMDw~bV2)2*0{=}P>DqO_#u5Ob{hG^y19*j}wq4o$26f`@JyG`TOgJ&+b*eu7= zg;bg5TkRTuAy#UCA%)hs)BfmL0;S=re~ZJh>(qGv`g)&oD^6vi%agdX1+8fs=h*|D z9OcQ11ayyg;=Eiv8QpEkKll5fF1>X2OSj4LGaV_rZs8lNuivxffh45g--B{Mjc3Cf zRyTh8fD8zr9_92Y!Z+~Hp_EVK8%tGDc)7kzuY~xvnNdK)px=Ft-Bhq^G&7~!kyIrR6`7BHS0*H>hK&U5KD-MGmC z-Pd*^)l71In5XuuA8lFtW|~4|;07B@cy@aMG@fx_^9xQFD3qsEh6CiaU*s=jzsI2+ zye5XIugiez^6XXDWz5cxRWcx4{4;a{`oIg-TD`90V&q-eG3p}&(hobcCR+#J>JxoK z5^<>Y)BW1_F{fE+QhMAuObhV!--M^k(C`3J3UL}|=Dz(4fiH~#!Bt7xgCJ@=oXIi` zfTbKj&yHGP*H>gt<_m4sLZNq)FFW7_77)M1o()wA!SdYmxmW!@!W60oB&*$6S8)}> z2Tj0Y2TF;@Xa$gAF|Xgto^EVmOZ)zCf;Vgk4QpG;vi&yf z*vR(_ORmHe{E$qyqYTi^u!TnLs%k1%u6_!gz3X5sTrYb{JZ0V(!|9nA-tL+X(y=7< zD;hsc-AFlr{LasxcE-j5S{F`r;|&Xu(eR$|u~!D0gVLje+9&e4R;Q|<86J$*n!V%w zwLQf=h;YmM-aeY;2)#FmjZ}d*EJ`iCD}#%x?)0}*GupLKU+S^@=;BZ%vP*Bg%LiR^ zJrnrh1#C_zS!g75H(QRW9$um;Hgr5uQ8q8YMTI1FL3Er$y9tC(Z? z!mY}Fi#SOte%)%+`=}^!^0e~gjePa;nB$`ftLa6lrlQ#F(~tu4Qq7v4z;&jUltk972br6yWecmt@;185bIgqD=*V4k7og$4M3 zU2sjF)GkcI&7U~=-`&>%GTQjo2mdqr&`)5b!`D|Nr4v3g|Cv(om99e|+Wx`C zGYuTQX+vW3UCW;u7%Mk8lW#^N7X`*tjwD&gfA4*7zjlzR~gQaopPAB zTVbRWO7ja!YbyzrTx#x4b{uqVZJAhZJ}hzyQrDe+zoGm0`u2uw46FAe#^sEEu}iiW zP-z!gM9{fU~qklfa_hr%%7y*I-RU% zTl`sXW@x_9*G@b4PE4?@rP^FeD$9-TbSSHAm^m2uv&Asp5{d8fV0=`sU>ReVconZG z9oFc>6_Lxk%Mri}YYM)YH0O~oMAD||gSz021I=cOD^+N<7_Eq|mhZ@)X+tMV$pC8^ z9#f=NH%i!6S+lGx+n^zQ)0ywf8#w`y^z$=^&K~ybWxJGMqWl_!lBi!hYM= zU&5}eQchDXX^tLkI%FgjiWedUY-02W%6}lPa`R}X;*TZu>F=}HoTv{igrEHpwfCai zJ3OEC--WG1>sdkh!nH%b^B%S$=3GZa_H0Z|hJ(#hXep%Y4H7z@9v0wN{HSVQOU*>M^@!;J+Z&{l z$X(nHH87`sgrgfY@1qWDIAAgTIBc!-Ya}z+n(?q{UG5t4B{<-c5OPvIK1~sb!;K~0Nh0Y z9g}?-CI^T>FF_MB=3e#!xV^!cM_t`XpSwP;!Gz8&@VeuiFME{y=9X`6h>lk)#7)b? z{3DNj@hpob9LFZ&yb#gwy1m!{;3fvERgFJM&aBvZbzK)fXh?C}6wf%8xnfv1$Gth- zfBeTkLikh>U3?Ya_Y4Bx5w86U87)Jg*I*|y>YG3wlf zrfK;XUh9oPGu=?T{SrdM2AZ5fc>)Ht{!sp~S2yyzdCN*1+-ua5SGn1VFeQul|xn%ktgWb0MwM#k=F zc){az%a3h89iMGI&I^*N+s~$1h6*rBRd8-RunzdKt*M@QRq~}Sk?a7rGD=8X-=MX$ z^@-z`Q`_HebFKo;jw%u126_U0DBYzb0+d{!I$t}|mKe+ANwe^Ky4sJ;a4}($X91gro4_>OetM;`2I*lPz__me)7&s;ysNH?gEMo z0H$NS))VOYqyK(V4Kiwq$?x_Fz8YPDvQ(uDX;Hc$r>U{}>=nh?@Pm_WXqXuDOiH{f zfsZUVL+yFDGyGP9)0`j)nX!=&>Ye-N@b)#BeKvufN4?NT7uv&DhPZt`h*R8-VoHhA z?t?QJ9jgu8-p%1m4a7yNA3>`}l{3@;o$!=B-dnl#wo5#j z7GOd|p{eD)4M#Pa2Xp)xruijoU(;{l6UqV(>Rn1_`uX^_6LSiU(!{zNb~dL->HY(9 z0tp78KLWn$eZ4jGOC+th&Ds&Z`QXTqx_iX4FIVW_Qq@g4_c0`tmx&Chq2EZENUl?d z8E?RJqLqG`z3tNnr(cv< z?Hk8rW7o_Az}B#viBE0)bh zY`ILtpt=^%cWKzT#iz8l3k2-+O8cLEp8qGfgBObX7hYW#CNxg~jt!oQpY;{!|GK4I zN4hTgaAg(Q{2H0(Sr$g+-1@&LdjsQ)(b4Za!lmM?*E6U7iHyK3aKhcN$-pMQ_5sxv z|0ncP2f1LYyWis){WZH+47k=DNW;=eK^1YpRe3bI~ez>+wR8Jtfrep(3uAw|9 zh4rQADe7kzxqZ-yM; zX%D~JJ@RbNCJ4vVdL6ygF?VGOve~ z(2RBE+oACSrX4m+{-OVzU;BDG_sL_>!ybS@FT{8SK%ta)edtuE2k905$^vh#j#v7( z98qVd5Ix1F2#gjR$G2Y5s@(6Q5W*S^s4HAz)F`#_QeWIALwj3NB;0j9t6EyeiqnzS z9wF%Y{^|6aNlrHq?!7({!-pX#i9hSZZrHC|)4%|Cnk){m{m=!0H{`=FVs>A}=ZUN8 zYWT?Y$7N;?_IBN~5jVEL8|pzcrs$wRk3`VTshXtmJJd{9d?J*;J!reQEfI>3Q%{Uto?;l0orhQ`SFU1ui82tH0Ra-(bf3^VAar+>UOV~ z@7!r42iF`F_lrm{B0ITZ358+8s38Og8-wwp)Gw2i7pg+W#=Z7#+H8w{#K{yX@J@)M zPP_dopkE?amSNpLocyA^xmlE@s^-foEYFto+Q&fZf`w(Pe(j7^`V-LJU8IWqlJ7u3 z^seY8vzjkUBr&qoX8&NLLBm&C$=;5IdfnqB^W?J;3LY~vcW~{{?>m&yS4bv%Lu z&ymR8p-Vqhi2jYmdHyk6;j&4a7=x&%sXZpwc7~0BI&2_n7y#v6mfUNOD%1wD6e2E1 zy3xZwxHwhZwn+4@kz)PjaNo~g33_1N7=ZMWme0oMrQcZf4=mpckun^GPM4 zf}-~u*SjOq()B-|x6mb|5fRDyl8jQg+XClWR-Od#{&eu_x;8%kxuGFp+fc%N>QSWy zdx3BV-H=*ER>gn%0Y*37DS`+pCPecL7vip7ucnu&Lthf%^$qsC5TK|8dDzy#c;+C( zs9=igCGn#cRLrzR&yPh+HDS{gzGX5f*tCYw`=7kD@i7H$5W)5Dki(KD;vN3^&F zK3m+1dd>eh8)oGw0)LE~DR`oPdVLW+wTmMl;2uorDZN|e4%FE07vqoYGU>@md&dMs zG}L5sAbmiwlz{**>Lqn~A}9Ww5{o|UIphgvPq$=j9qNXw#4ffJ=Y)HP7D1_o zKByhjhkEpNHrKymYw-P@Ht6JW2g32?&C!}HSI)XH-zQ+Sv0e*stUXGve+H$Hn%BS7 zF@?n#vcVRlGHF^qGzrw)khcPssQk3M48qxb1NkfMjLbUXIgI@;D&j;HBKKDZn!#TT9W$Yh?z{dfxgOHoHG`^h(Ykbsmb$z#@V^_ zeDSF<60|cHYl+CbNt<<(2m6LoM{p%=*Vib55SkZY5rs@ohnxOpXNOrEEg4sHP8?8EpUH+4SLwcS*vfEc!o^Ke7 z3#%6h?ltv7mRT2d75|765OjfAylbarO!I1YqN?y6WP?SFpJ*Y|-R5zZd%={+4nDJ5BUb_0ceT!J6{3h8Hxk7#3LaB<2;#RZP^ z8|h5~E-%mYeQ8>}m#(uAg(jIp<8i_$3AY7)O{nm9B+}!n+>cLX?R%;e_y5jW5XDO) ze+M0wJfiNG34vujw^?H+8i7Xj08C*tkO~WUp7|D6{Pp9*%A0v?=eO<8J>$Ui1*(+y zv3pAsWZ2TcvoT<=``0zGW9q;XZ{?pb<5}~M4trX@vQ{5X_-;Nal!y3w{Mj-A2UL%K zwPlQ`QiqWI)f})fDl_Dz?EGRNP}F%xxIL^SDIyB2v5x$OOrIHp&)iy?ZDF%2>qxhN ztk2^g9)vKHJ=Bqe>$(s!8|FysQ8!^^1bgA<^ddg`iZ&SE*hxoaW53x$ zzt2*ZV>)N#8AVv-LF0r6h`O^W5S}-!qm8`Tedk!{*| z{frNV28ra$jz-}eW!5Xjf~V6 z2m5lD>7nEIN!U0q_GHx(Enkmg$F9{Foa_kxl0DyJ*v|FYzg=RA2w`AwUiz0&2i;U`GkUmNJcL4Cn#7F#@}jHSKS77KQq9m7?h?wT@;!)zt$%J)L2R|#!c7rgRQ zWUF`4+&;0?{%%vwE!|DqXVdec-H%fjv}C0`?lPwlb!vBE31So|V)vJ^$*KYDBk(A% zjYBWK&4(G>3zF@=_ot^b>QBcyqH<^q7r($wHzsdI(*K*+CcVRjyhBDLB~5*`7#;4t zyZ@}8_vep1KS!Jo?E!Pb#(LXsgnSvHcCGk$ShH2;{YY(@3J7Wl)luCEm_7MKlWL;} z2l&hm_9w?)G|5c(>a13v>a?yht#A)ukzkCc5o-Dk3+kJC%foYPlO2C}Y~=&etk>%M zJ7w5Y`}@0hYVW1{)xyRX1W>*3hKsAQbr;St-eNV+=gqkF6n^@m=+nfponv`+1Dad> z(dYHoBRIOC{+(qqj(EtbYms^1|XBxO&9`KZU%r|I~RW zPU`y{$G*RICkjDGD zjwXuFlQcZFhtH~;3bE|l7@hJBdx}NwnRY zdi8|1ENcXJw)T3$4k&V}u*4SjE(Daz8#Co77*WBGAA6e~JT|Pu>6~Pm&IUij7QHB7 z&@T!;zjAM|ozHOCZ#?hMzBq`VDrtgvllD(vj)`?inM$xH?v`U&nZ2-vQ~67hr}_a8 z+>Rw?UXwY3G0)EWW`O6HPE~yTE0Zve@mPe{Yq>E^Gp3>`8Ki{>x&uCz z9F#z}yU!f_Houa#{Qc6l^8<45m8U!ZK+|IO63eShKloy0QY--*8~IVrKb(VId!Ke- zGi{w;)khr6`q&Fd!o|x*R)&U@60V4^YR_Gziu?c-2Gr%9mWgN%rpgcZ{NtLFWc{-D z#trlHl+qc8IdjA7Q)0YWu026hmXLsiJ|j{G>W zzOIzxvgRMww)cIH-!&7DRL49EbdgS4Oxgz3t#)C8;;*e~4~h-BglL7Qfu%X5BW2-g z&FG@w{QR6tx8VT4LT`~qO?BQ&2y4dcLo7SIPp3A6==^W5@P}F@eViXE<}2DZI3{_q zEW8b5GhMn-!eDSYO8VCen=|6IR+>fct4&!HqPubnUh{m{UXL2Xo!#{o4!uQXC4||H zcZq#ljiz6IH*h`|NzpoT{)f=Z^z+DJ(aWk%|L*!%Sp~ip35YuIo!B=6f#rRgcqdLc z^9~ria9;aj?AH+wfn(re^c&yM9^NxfcgMZ_!|d_aEdeee;+M}^hMciU?iDqiQ|Hju z+;!cMq`{eAK}z1#GsEXc~ z&)|2C$lJ}1|Lnh*J%B(?49JoWqxoL2YxF;*_w6&#x(qV4n05>`r?mjpq}jIV{XkaA z*QT~*DAmjs|2{qUHCyUt)Dt$Ig)?j2+&T0e#`AxQW-#VN8|)k1{+)+)p5*9mOa905 z@i)2envAT|M9$s&?__m)A7rzAm=~fibPz!NgZ&K!1o^>*YL&S6hSTqV-&usx+>yvx}NrU{D-Hl zip@KoS9*`7GqW>)YB!bCfZKN;6iaZpejnc01-JJ$W*F-~6GFcs(w> zgLzjnQs|oh`alJDi$<+Z^z(X+UcaQADe|#i)x^BBW6NJ#?FnIi_Tw%JBOYNN9PYOF znBKF~adwgA(!83{m9*_!GA z@5b@a?@s88x!d)8HsKbt$}?%9sX4pL^Zl?t+?D>G)7RJ%5;-45yM+RPxp=5N$<>}* zSxCm+rbfFg)#^s~W|zKt9@oWj%FIc_@$Q*SzU4!O(jR%ifv1-BVeK6Ev0wr?ozLV< zsR#|D-g-yBH5uvyi}C!Em03E66?}! zKta9;>r+GK&6**HfQ=mNen5f=e{Axzo!ApET}&N0b^0OUD7*2DE$qZCcY}d;ux2+s z(r*6Qd@F(pX|B$@5N8qf?mhCmZkD;fwJ2Ls*&*l~Hk{HYxx}P%2x&Ba~ zDvRa2l6QLH2i7*lF6JSiC8~enH|(fCj~6s02N&`78*%JFS@A0Ezj{)S@7pUE3R@el zZxm_V*Vc2M8iq9-+Xx^#E&hxsK#unygj7*--$(o?hdr--$*?!qQjih6dp8o>kS_Yf zpdWm}7xbXFI5#>JoWZbf^vg?<@(w_p<^685`Hcwqtg!`i+FhUEs3%rx&50qzpYBAnL-;d# zP3$1sQo5rejXe`b&8xdlxAIeOvqu}0q6aSqwOrP*P$O11eR28g0iMxgma_2 zm2Ml-x*--vkZcreFc8yG>(l{QMq`&GfY<>_AaApr(mle8BmljVPi08uKh`y5X!PcJ zldyNgWUVg+G=7>u*UzBDP#H>|LJNX=*T{`0GV5NA0Yyrwpv#U+z-nw5#|M)%m;Hu3JMXz(zg{wB|C8|LP`brg-6?V` zdGj}Lgi7fapFMLEKjY2!C`F>`qrbmL_R;EUk|CSKawMas1R<}90*lAPXqB)p3XnHImHytPbp^`Wqi<#D|QQl zsyTW1vkd+@dNq|7LXfIk6&s=RmolfWwlt0EpDF(NM#5r}biL^K$#jFFQoXmt!6Vv- z>tFLe@k!XvpuoVojbfWr;^8qcwA&RcyF82eaoHvcr_cvWgr zbh}1fCFRp zAfxbZ2Rk5qiPLH&VxW-0Np;FrUDG z8kYub4cX}3vJr%oQ}@I5TBCwX-KUAoO6jm? z>YEs|qq*fQqHD$`R~hV#7@QM25tQ*Tuu0K+hU^F^Re9NdK@?2~rQxypiytrK+~?`} zc>6l_T9&+$@d6&gXl7Jkl^>%YswSj6UQ0D*ihq;gk$HA_rNQ6ma2!Z7rMl?`kPJlM zyQdk5`uy634R-S9F2s>m!+%vGCZ{1~gRaB%$VSY%)ayZXLH*5b(-`y5(ds87|ML`G zKEf_a%AfXNa+Xy9KOipUHpNFw&BRWMSW%7KGqvfkW;2;c;{=n8JyIMFSzh4#MBM;b zbDc#?*!-!W9sXf|_n&?PFKR^HY{k|T!yon7$4BLM)$6k((mRM$SnUg7{bxfJBo$gy zi{B!*;esY_AE$4QIlwn~D1rBi3Fz8uqL~Tw#=A+2%Mi3qt1{UhpAu0HyGpW53dn~} zoBp(kvYb#+KIzWU@gTLi(iGx~JroWv{^z|Oy;9t;5lr9!LY`+--iR6dbzF{ZxWjDI6k=0YY;ygqn%Ht3$~@!=yLf6z-o zbb$-j^NWGHPa0Efhr#aToQ@Wn-9y$Gp8!NdvfdOHF zq0l{|H|6HnT5sVld>q}X@b`-&qs!-UPC25K7gj6#)iKt$y@I&;ll*e%VAqKkw?rSc zr>=MH4CA#4xcY|=PZ%6B0;RMf4H1d-D!}}lG0GDCPgj@EDzk}=zk|(}1B+)j8&?Ua zxH)cG-8ZA^V(K&(m^^$bDX;4kt^j@%w7lAF@b6UbYqhT^nPlD=vVCub(?gY+`R~!J zgUQkKd!=DtFRA!^y>a+2WH!iV%oA+9!KU}Uu=nC-<}%I(3tux_**9NKE}#G%aNJ$> zv%J30ON#qO3^2WQg~uUkwz@CEnS$P;mW0BJ+5O3big8nwxhsLy{ncg~JSA^-I1X$g zJ7|WXPirGDczDM<%EcUiep12XSZQhaJ%tDr;J0*|b=Q)4lo9N%)r;n|H`4RH?p>sn zE!LW zmmNV(M=!lIoik-ybS5JvtWEUD%%@Y^ZTVHO?l3`0Z9OBmHXqc)g)HW40WTA;Jg8%F zw*4mD5N{yEf!)K!@p|m;F(qfoI}OBJ`1~H#kiU>Qi*UFKda)?T`USdfFDY-#IoHYj z^vm83%7A3;qu*Coxhp!@fgHz?Her3n`eubVMVgv|$IaAOGhPQ=e7Zn0v9xY${r0-{ zO$CREAe)Nhvd>9+(mvZZQgcrfWGr=)s0RGB@+?yp3A3a!n9o_LE+#lw%2is*;?{;1 z0iFN{oRYRfzr}u3rpQOp3GaV%#H<7sKEBLto75C26XPPn*H1IE zd4BF(msNW3Ty|8*vnZ-xFJXK_|6-`$w{ov@pKjq*p7Qa1teg^Kg>3?d_XZLHIaNJHg_R&Q~3W8>U@m;0%P$7O_9@5qO%Te3=h`rsQf zZpwCVuK>Ch!sOTrasvTD&)vDE@NOSoBooieose#401{iHqVPS=n7QJ!D^`NeHEIx+-$*Qhy%PipY=qa(2|a#1k4e{*4d=>$N^X#H z5hk0bE>GlUm);_|$N%YGZ+;T$%$V0Xm>_ir@oo3>N4Cj^oZ@dit#9tA$70Mx?YUV* zCHQzCXoCfknSGf%{GlT4&QFsZ7~g!hjP>D+(DSq)-oij_`HCnw@yAkHk4!-q(E`6wk{<1E{Yo5%++1eU zTfQi@d^GEQ>O6^yYf}rgC!;b?MdKI5*K_7yX((Q-pcDrLux3hsa9d7$o@#Ir&Tk;) z^O}|vesRRxj%Ce6^T366`d<{$#Lbv5rBX{usl%#VzouRYblevTM0;hqL?m3@hU)T5 zNeEk|+l!ts9t*LY0s2)=6?Adxt;$df(q4)T`3z~-`1j9YPxyxHtn`;;iAemtFNL|! zRF>$r?b5I^G|AHZvpw!RNW~k0HGMh_k(*~OopqAPf1I75uTl50ov5uXy;r(GvI2jG zm}c#(n){Oa=}VwbcV)-56iTE0qo_R$i?+m~AR-4=1&#nYAAhXlGd#`?+8cIjsW%(X z>6|n9*<6eF6z1f8jjJbH>Tmn@8yt5E=k)Tq!35X+2)Jr7e!0W=_<@WZQ(UQux=wr0!}eQB=`-bJ^_Qfg_lW1@j3Fd~7zVD& zoW!~0v%9zH){!4Oo*ApG?0HSA(C<-FZ_Y|8-5+PaDcm5DB=H2`xeNv5kxlR&+vlZP ztMV?q3a+IYn?1OrRKjy)x(as>e$YFu8N0E2|6S3POqG_p({leqV?&# zU+*0H-Y(1ghideO?m-;@_7Xf?U5{jq<)A?WcRA|lorA;r{nuYck`UMt`C8JRV| zfVYW%o1l60ea_JD()WuHwnj*xuof5}9YT&!Fw~Y}}ek*w68$BOf@RAo1?EHC4n!D=xy&XC#D1L+`U5>j%w1Zt5)0e;i zWT@CcdI)?cKD4(WN`k$pv#gsx>)sF~Qw;Hv*%%0vF4gR0 zuGgEid?XYI;E(Al`!}g*f&5Kmk4f)zIcgUxq|s8HB_q8y;l~}P_fuX)sWW-tOR|&j|bhsPM+R#>B#m%YN~_SiKn!CqMaxv~VqGxa2Ixap>oo%}Iq) ztN+|QGO5$rB)TZEQpTFKZonxgUqUhZYy5Tk?pJMRAmAr(?|lbSV+AVxN}%&RqgtT- z%YsHD=gWM8onI}dCQmim6^O;b6g?@?r0wdWo0 zoJTH#fV`qdQXi{GirTlCo=lyaW3*aM)#rh`#`8*j{T9YSld9jNGO-GyuuB{anoJ&d zb6uIyIXp+sUe!%}z5vGgXB9~0bVz0uDf{Nr#z8v7wm=mRh0c(KiWeq5)8Ip;c1Etl5;>7Rj2G-# z^q_!$xrJOxAFC_v@Dh4pJCJ-Mo29gI+5WwPhcK@gwvJ-ge>e?7e^J9qz~%$^2?I+> zqXKk!Z_rLv$&81*jon6o#W{^0CPrO&LPc#t0`^MEw~&rwQB246{rM@Eg;6~FK7vPk z!B)m5OZr2K6m?dy=ajj#-`*Rxvd5=+;lK6nhPT7A8#z3M>W+3vU#JY)l@tlUHH5`b z`A8JIiSK)hg-=dPua2rXcO3ZT!be!5M8Y{hTo||=+_qG zxQkUE>qk8Etk#lsIovNgWH=L8z+HCGWJ~&(eV#g;4T}j5KqPvqiIlDfh!`bpoweI= zi-QlfWF$yASjov7UcJ+-v->d=JhTK(ngYey{mSR6vo)p;kL_HjA5A{VaE_MuNc)g* zU*JiHF$)XJ6-`(K2XODi+{q^zo*)hJC#ioV85uu$%G7R7lXnXBY5QsWpA3tq=t@}e z$U)15v64W>=wak&_yb_QUa_eg6Hg{924e#}*fO*=_l9`&mW;ZbvSQ8_rJ^~3eLpxQ zcWCUkT?-b6aqP3kT+QQb7^{TGjnCh{G5BLzLFbz)x7Me&8>a`M@V)2rp~Ha2ueuvO ze+FbdLv_io%g~V&1=d5>X9<{%W9{?=&0Umz`v7 zzvFi3{h;50bMz`Be|fFxNu|Zl1^uaMD;p@3PKYoDT-bX`OMZs-@XmQ&+FNARbc`2D369bq>tg7(cdSRJ^knq{B0ME9rvtd5aP@gnmx%fyFc z`;xDJecv(5b4jD!j21f+c4fW4Q+Cv1D|+ic$iL&qh=xS4=ywefa&zy!^-Q~q&%H$I ztLyZOuyb0kI@J>1Hu6gMoO!~~W0FUm02q!W$n0FWjptOmvUFLg*+XNI$4k0$yNk7Y zrOWku?PEgnmV5=4L3r6dER;wc3Tn%&2xcNO?<56s?&A-Ha$#AFAL832eRUs%>)d^A zE~rJvN4`fr+x)@JKmW9vQmO5nHs|Qker-zEPPqu&A-=luso7I`&Gud7U`0}Fi+=HR zype)gb4?igttUfpSB4G$a+<048!CfUA5`?q=S_ltgr6Id9Jnv^#`9mMP$@-i%y-tM zJydA)&$Cas$2(He3HNSn!adch2C7q87m(R_;(c|@jgKR3Z0m>Fz&8CZxpJIT7-;s$ z#x*^CRl?Z+vO|U%6BhM%t(IgFCnY^R+-ccTAC71i2w=Y`8_FR^TVdp^gy%;`8xMQp zmK$3}#iGV9%Qyv|%6f2d1-lexY>cpmP=6|Z*;F_9JbhCn;0q?H-!ZiI&7&R*sXc$4KUt(}MJdQH%&;rJ+cG{a22M?cG*+)dEA6si zhw+LXbB;a7+IX&C;dF-_KOWqAIo;GR5GF653>?R`=$>eCQjWk5a8L@7Ib4hmSNx*d zSK9n>M2!1fQ4~7hOZr@qXaI{&5H|f!NHm2#_Cj^IWKu#C(tASqHbk#yDle0nVa6cED%n= z%=Yu20YJ(iK<6mo!$6Ceg&=%rDypn-zct1E^IYspX8#Q0P6JeJKw0@-S;tZY@_A?@X-s7J$iK$p68IL|HWg5(f-L5 zBo<#B@(y6$UxK2yuP>dLm_&Es7ErP*)6(7D-pyweJg}Ko!rpiEac{W# zx+I1+Ga)cGgO~Q{Uf&lbSu*^Og-Xa+3yjxqBGodN(h+O7493%OX?x{E(Z7&WD5FJUKN zxkN_+85RI+`kndiu9UL6p6l;c5KX_~NU62~w(gfH)1ljGp!DGvoPYub;q<(LaBKu`0tB-*Piyy@yxOE>Y1LD2g1gx5p z?N>KyI{R}opag9;+J7!h=T6g_gaB>BwV}rod%D)yo(&bQJvWQyXDoTW@ms%Jw5xJl z93Cu*!R~3oCNSF}_SA&g zm<;ZMDgUF9{)?y1(46f`z=n+mdEzTw2R7fjUsb;NfSYSiO)KV?-VNYU`%lsgy*E-j zKM7krwQ<$khQC>l@Ir4R%F6oDRP4*WD;)rM$6VU4DnrM2@zqLtmAeO6REc;pC=N+P z?SntQ)EZh7`V9fPx7ds(9qz>gX$ZANU9ebVv%NY6ghKvdSFN{1pqLyZbu9MI0x8!+f5|VY~ zFyg;xNXhUU#t@NwW7P3=@_FF=)X?E|3h5Sb*LGStx|9YkRej-6gZ2}8xRd2M-G}tx zkS%d)@clLTb7a%MOLE2`-&&^$3+kw$JH*1^)7Vx)E6P^mqI3bbINZ$i_hq;wQ*KcX zNmB?g3{QuR)qbKflJ99h`;%0OJOWL9F zp~IMuYcU!;!9GNnPD55;x8{XQvJ$Cl!CP1r+D{_~A)kc(9$ZzwhHC)0NBC8;WWSaV zN#u^gY1?C|htth4WrYh%>R?S~%vTAOm$=T?>2|j2S~kTE3`^_Z{Gt%^BS2DOsRwfoFwqWHH)ste12oa`BQnMJR%8MTajOaYf;DEBO>b#Cx=^eOF zIP4CME2Xffo;JHj%I^{mQ_+D?5Fzbv&K^a_wJ32@INe1qRk+8W#MRp*ke(kDoef>X z9SySfPXGzi#LQX+Mz&%8V{eS($;XKUpZM;6;YYTH$F@JZ7AM^Mo4*VxP}*7ZdDqnJ zsnM9uchb!iR}veY&^x|@h%L@jCybVRY~*{SMens z?lY>9a~Fjv$C~}qIrbA-NAUpcFm3e~876OMp1op#T9sIl8%sgoB zAylrxH`~%Q$v`~^(|e~IPED#YJ9>-15;Ayb!d|EE z3j(#G1a){S?{!7!cRahFhtR6(7yhAh8>StKQbLz6KFf6Swb!%P>Ju4n(ZS!qI0Fs7 zDS48V)C;6qE!vBgweiU4tITd8-YB-*wVW?f`pc4A{0y=E&ce^bxbrlYNAZM2DjQ!& z|8N@|8Pf0tBQjVOKd>j~zdL=&e~q^n+~+zZBz?M$nAakM_1~i%@Ay8exU}(1-&)>4 zG5NZV#FJ7tk#JptB+LJ_;AgLIBTInrCW&%>ap)kQ98ealM`DeC`~7htKK1hyBg!ey z9DSEhH@R8-?q1oQ#$P@OkdTojV6NZ;=y1g5E~*+4msBZ>qo_J)6dgR9z8`n_VeL(+ z@-}5>CP(w>-#PU(!t9#RX;3L!9S!g&DL_N{`8R)jh4Qf}b_1SbttVvoPE>PDuh<2VAnr0T*~s- zQS)!4x-;h6s(WyQ$i(M2Y9a4Nvh8@9qSAcx>eOmTQf+QU-B^7dFdKUh7E=Y%a0LGd zCSbF{ojm=etRjc2Tr$$FltfA&`kxsm9oPcC>z0q$(W z39uWwevm`;9(}4E z9ew|*I9a>tk_9G50Y_(F88}D-IeB`L;1?omd6GfpH+nnQ>7Q|=Ue{8>ZNWBl_H^o{ zDPuvC(j@r;8)K@B{Atbjw;$~v|@2o zm)c!6a)fU5R+Dk5pCg-SoR&h@TcSdpo*=YXy9{MLSpCq}j{0m@_Ql>xpz_XUgZDpA z#E0`W*oxv!B&1DnZk;>DZaR_ncJ$XM?G&{>k0R`?nYW338(^^6p5#upp`M+8w@wTl zoYF~G8r6RmP-)Y0N1-fL8+-X`^}D|@4-!&FMAT8A+Ze#nNY)crO_z7tNsMbqY-B49 zwmPyD92hAv)JLhlWiNc^a>EA2-0S+c`Z}%HTGBM?fTQgsKbW(KqE$_rosXAxZna@} zIC|$piW;F>@wQ+GGHnMcm;{{b{A}8|vn4U?>k2d1u-A47|FYqsyzspAV_O1}3}=b{ zfL7HVSGz}IS)IS%R*!uav$eI9O6R6SC>xe@hOnh-!Vd%`m*=O?ADs1?%$8-`n1hjY z4-Rq{4LeF7uEH+5dRiG?{>xZ?;f~Muh|N3*qNG*UbYwq7e!^_HvZ%SHIq^{x`hnV0 zkubCL%zsCIWDIb~-ZnAzChqFle9Asj2$XCW3?54ik9?TbXNsmvIBz>21***6)Gw}c z?(;lKuMN9ngMU4KcyUtT_ZO~pttp0f_^BX*FD?>++WnbnLFQjdI^*WAA@{QDJ9_x8 z3lr#dCQJkE!DM+_*icGD4uFma0hy=1mr6fN02?06c}bW4gKRr1?X{HiBskv=p1!Kz z%)6f7gIB^o9-1@)I0Hg(J&(VB0?|!F@nQV@i^)7E(s z?x(J*4|K7N0q<>fU7%B0R|huY8`C0rJ>^Xx7QJaJ0g2;!{pP0hBH{Eq00~Rt5hP#3 z^{GpCYw*QW&-PceWLLbGIy!4vpddW&E4|$xCa@MfXhVoKi-_1zfeni*vomC`JD;jj zU8~u3o)2){X+OuJFdTM`?*zcb;mYn!_pf5u|G0TB8r@j&T`z2qDYO!aAGGkhz2juM z!9WX1$t%RO*6b#bCO8jqTUUiSwK(rV>}j=2M$%El_GVuwTZ#n$2FCI*Xkgp^wqkCo>Cpp#!n4o#VGk(lj725P)WbS~w&Su?o(ES>K&HbW&*IPqxuSA?nhaA?>^XtT zA{C8jZ@N3THK>MUS>2)IY7LIGng}9de)H?EwmouGE8{Ir|Nz%ro)+i_PHFhCiUC;@@W)TFyJWS`*-PK*TOMcA2 zOU7+nfxgY;zD%UCLM=h)y~zf5Hg(=I)s9N!U6_?Y}@>$3egJL`;eHfV@-fjL7Kdk3(|%{uR^g-QpD|_AeGaSY;`-|A$W568XI_5I zvru@d<{!kA1(g9qEMLg)K%NiQCWkEAB99F_m8;#Eg-YQHT8eTq>mow8ugEvk{8rZM z>k!z1z@q<$!~)d6$|X@vY>{;`zMZwmeSE^vWW>Ja6NB(9^H&MFluu$8qI98EbdT8V z0H^%)EmBhCV^AYKEIKDtDylcE$F{?2>e(-+`kemiqhF^r$i`7~zI`btS@Q2Irp|(k zSlcLLlXt-KK{@VZhkOORvO==fVtyo*A27B+n37@nX2u=lwUM_C;j>(;O6ljMJ{okr z|45gy{D*VTWxL~;hRl87OLUH1!bAt1oXl`%_B;5TDfuxlUD9vGwt$s8MF@W@un$c* z$2wrJsYZ)&D?x8|Hl_!<(%i<^T1#Iyrgsw2s=x}$2y#l)ve zmd*88RAzO?9RI`LiR46hLjdH|8AE|3HD6pT-pk}?Ku3P{PUONo51H{nD}Kc9SxHsK z^d0fNw{12CfK9dgd;ro%`*mswJ>DolRk50k7<(82n{F;4o~j ze(B=lDnK!xU<pnAxq=?@5kRVSl{F{CipAQlcaPch)IEpzDn^>^%1Zn4bZ&=*a*1fr)U=P=G*5l<)~nl^c|Y%oJdCJ^oNQ-(-DM{ReTQ(br3K~>*C?C7d$*Fz>2-Xa@_4+B z*V0}3z11XrX?>nnZ1C$B>^jvR5U;a8;Y^Qw0ly6AQ|^WaXxmTBF5sLeVnp*B5OKkX zCD>GcZ}ws2?!xGw^~%CT8DWnf%{R~L99#O)jE3n#dFimIx87oz$o)fupRlCH!*(^6H65^@o)Hzeo9^Jnh}8qc{@WJ?%60de4cv^gLza|*{ zN;j-mi+sG~m!(n+y+uTr2n*@e^3VdD!XE6ncdvv+<^LteYjYmGK8A*Nb$CBX;7qZ_Kb>DRwK&^nTb$b7Q+#w5A=pTnqz#=m^&&vMBDe zS2X@iiy4WwUFgy{w;AzU!cmHmf!?KtY)Q*0eaEglw+6nx_s{L3?cjl9p$FH&SMs7L zk=KbPMr5Fh>r%;K->jYq$(X*4F0i~%pGD9>8F4h{=E;XXfXK<4XtMUq5Y~qA<(Qwe zJwjY#|3MysA@`J9Q(f)ey7KQS+d_k8Lawv_W#J{1hyBd+4rp=cv(Pa-@irhr=R-s3 zH|Ni{!O%$-p!>5*JTT;XOElv6zC%AyBK}bPul>#7*(=X;Vlhr82+(n7fS1(v>Ze?Jab{f>;KV+mtfrrpAmFE@Z78i(V{==jdV?20CL z>*a$hRyKiQUsO8-1gan3P4zF#5PQ?3l7jro9NH5)2}U=FXyhpk#(AJ+2w0Rh_WyCI z!KU29sNj{MVAne!-Q+3!Ik3erLoe(H<)!$%f%e?!`_K#c*{7d{`lY^EAU=3m7e|jxj&tfm+1t~=_*k?%Vs))9xdWSLfQV|wHhpFkP#8pqQ8VV zznSWO)E(KnHE*9W$N1>@_CvECP%GkXTDwQzdC zj?;psAcvB+dymhc6%L+!S5sOXik{lvU&+9g$>b`kywruqOT}5ib>gmt-QftQAJhX{ zTW7K^m4TC}O}SERxR}JTIkGWqQ#8}>qST_is!J0Cs(Q+pu2u$of9V>87el;{6GW@< z&qrEwWOp}?O4SvQibXz9=yrdD%O<$E?+{#Y*M6b)ak?azs1~haYgD#OsaK$52%ixh zDCc(9ArkFtpOh$*)H!^W$qT&G7bJL5?M*AIMa7$@tsj!zMTHi`v}FYC;E4vDJi=wd zhu4?(e4b$wFe;D}^2w(*QS#Z&13XzobiCPvkL>^CDBf$PzFaE*LNb;capHsgn2gGn z9%Y-gp4XC65cl;>H>m#D2kiSrQjk5c&-tf}NVMl(D9aG0Z_d0c4-*U@}o^U>;_wgRETTikYcG6B&{b}{6!<_x{U=Z6T@|#5u z?k7SYSdo|z@Xy=$NCLyIb5|wdSGnE!Rwrq?o)1WrH$dIawk_gsj!+p`k5wgT#A4Nq zhn}a(Z0lfHtBLBs^l=bJ6{n~rQP1Xby%UR(>drr~UJnh(R>L&}>a`jF2Wf8kD4DRo zR1w<4d=G5K{673{UGE-l+2x>#%;0!@E!b_83QSzyW>@BOct4mnk~`(Vu_0)7uwW?j z#7YxdMq3=*4{BM9EA3%tJB%~*-wIXeKKe|K`u@{BNPl>{k||7EdfCmBk0Ug)hM#7T zK>+ww2p_ej#o6xK-?RZFvyU+vX}qnQJn>V}5A-88B` z$!qb#)27FH_P=+&-h(=v7dUf4%ac|3(W6tS1M^Mf_pR+>V7ce95KboxPm*|lvFwY& z6~M35S1KECg%546jj$R0@5;a)_B;qWNf z6kEmq^gVF@v@7vaEF7xY&LGX&HmliGFR^gon0ogo+ba6H9H~k1F4Jpq!le zzbOtI#HIA|%nW|jgNW0;M0NvAXNYblSdkpRh>SkumJGNWwa;InzNTsBgmSy>G%BR2 z8YGn7wd?;kKnM*S02;}~?=4Z7^J-Qf*6+o~OKzJVpdZ<#!e7>iF#Q?GqZ~~@kwut~ zh%JW&*i?zh`HeZ1ah&3;Y$xC&M+%P|z<(P(VT_VDsFryDKBd78o>wG5eL;RnrT=#^ zwLL{eFpx{_>c?+OALz@9He}B__kLM@>rZMlMXOp0EdgfV-|06(nnQL7m6Ka1F93o2 zKgb#Chze^g1qo(VtyLqnsJ#*`uaY#ZOD>yepzR7)o1w1V?5wd*>XnECL>ItQ0y=V4 z+nZL42sn<-jH8v}w=b<*|9mv@XuE)a94o-q$VBrXijcEVRU77qC+d4~qwT4KNB=x_ z>ZB*kNA|yD?MPc|TNTAEiofu@Pgod`gBD1HNN&qcz3gc_Pn_S{CSBaK8QcD_`02Z! zq~7H6gO)?{A*L&3J3}JxpYN_Cd#kVThYwhj8@++6~ z`1CO+Sc58U0u&5c3EGW}$-6LGF>T)XDQ~ydp3AXSbBv#35+l1LheNX$H8n{@TOX!Q}4_CILKdwks=->e?i5UdZ z7|%<#usBI=;VxO9s%V)Al9;ug>w?n|vMQa@L?ZeIR8lsW%|SEAl7~JwA-6IYPb3b_ z8she>kEQFj#zn7b!K zk!+X_%V38EG!^Qq!5?Bivk{QJQrBhvS=&vBhph|C;ZtYGl>Y>D-$8q4S_mP?Ib44O zAR`mtP|m&JlGq}$m>(^~HxaB}KDEKcZO*lNy)a$Rql_)O%KWsRS~%d({{`Rmv^5F; z!a|$uwy;n>U0>>j)5SYYf@aCEV0s!peH#L1PE?+Fvjz$LD;HEodb*}W$f$9u6w3QYi7deToRB}5yccf#EEL>Pn%AkKAfL?9I1JS!6S(ZW z*O95suO~qEpPs(DF~%BVAdW+w5zqNP z)?H-g??%*GfTS#P=#J`%%6|}BeD)j~YpOTpd?D?S&SHlNI9XsO7gAn?ijw5}I>S9Z z=%MQecXL8edm{%=P9pvwh1mIrGSdy3y_dA#3na{xd(mUA_3{+kuA!i493pHST& zQQ*mT9yE;WOCL#ySm7q|&tj?1^x5DdD=ymgH`)c*X=OAwR3_RH)nZ#0-cUTr`6T|& z8X6Nj(!TT24Z0?o$5$Ww%*^mUN|0|U+bE+mO1=jNVIeZAQ); zfaW>@et6)m)ZXa(tdD|N%s)51k;oWtCF4?`L8Gj3^P*_Af{b@E54+^w)v*tvKk87k zqBE+KMsU$gVVHE>GVQeR(o`6t79&KS_^iQ6v}*w95{j#y&oA8V1yEBjAeKK(h8?^nDmRi?7r7cSjxH{t zzSA}yN`+Vxd7fb_c*+V^t2Xw&L>MdG+M745U(QM%E`eJug&jkfh|=IiXLijol9U^T zs)~M^JcCXbH{{Jyzebts>JehwoJ?t$f2Xpr$c17~VgPk07hFIvuE-aO;P59Kqr~sj z+MGQ%Fl~q~{5?Dwr+Rx&TV`=Pu|N~Tlxi6K2A2HCVyAZ-%yQ{Il1&J#5gO7Y;4ueW zBiuLNlaVHkV+QV~T1qY7ExSg(30(|Vws>^2u385z0u>=;g2a~YsxZ+qAPN7yVk3& z6Z-k2L_?LrH_`?{Qw*1kB&=k84UhFMHZ;ctI^}I}$HDcMoc%>#u|R3zL}rZWwO!qN zV925e!c`H8h_i}7Or2y%%qU-MRW%w{G;FR4@CbO4@mp+4%+1kWRI<^Em8p@pZ$t7Y zkS+~j@z8C+t4GH01))1{H#UzeHs@*#Gos3NE@iB)%BK{*)qeH+X)h0BhS(`QIF>m8 z9h=x%$50}8Llte}6ob}L&&vJRS;IWimuy_Om+F1E7$ml~zA_BazUeg$5jn^MPwy5? zPh@SM=RzO1Uu`Om!YwpkR^q&>Q1SJi=%+c7{No!}pNF**p9C(S1G7kw^LX}Yj-1$= z4%|HKpDa9|2-!3 zV08MZC0kME`Xncmyip(ryRK3#gFwuWfq{XWmp86&$g`jpF=Pp`9$4g2?`IHrjJicq zk9zk`ze3AjxF%P|%KnAm&YYFUn@4^dCa3WEGJhJ?_CTC#QYR(}f7)*dwAK3~6z`(H z3YOE)SLeDp!rq^@?-v0V$a7k}oPVE#mghpQBTjec(GUY7D3XhYf{x}%_pc6Xxya8v zZm@(W`P4e4KOOu;x4ief1NZs69>JSDd_J!Q9PoRiXjUpm&2dDEhMEQr0y=7%8dlf(nDKxG z0J)UY$9Ku9T^e$u7l&&{0}D{GgCe@wmu}7UhB2O#H--kClmMJvZ0kLzmaRt&kJ$G5 z%cNr`Wc+*sbZd73H(9f!N|yc1Ju>IUJ)SbJnR!kAb2U4YQ#%b&=cc_kC^}`bz=r^u z6(EaMyrHt}t_*5{Ek*%Gyelh+HeBT1)?ZZj=?F?wsn6$7&L~-=ZBovlH-pok2%LG~ zNf$B7M@HxDi|ygcfpgw&SewvEk%kI56tPguo+)8d>qq8hPF{Pxmay6Ga_^0tv2?1h zhY);{X?|nYk;QnTp-D{WS#rp+mb=lC?ZbKPB+DPGwe=b6EoE~KQl@k=Kg~q%BwL1g zW9yEB!3)M$XNONK4Fbd^X&q`96>yhbO|oJ?Sr6JjJ{m5==fFS_J}kXQx=wrsr4Y!zB}HhWQ2~iNqi6XKGvdWk-Q>z z#*YoglwS95S90oEJq)xg2mUAOx*(sXMO;82+)d>U#Q3_R@1~A-A8r^y7R%p?CjxLU zcP!W;gv52Qp?TDLhe_C|A78}3j8gQN!hP}@FBcwu#qh=}r$Lzzc zPVZ9NjuN8^t2zDi9~549rRiQUCS*PgNBA0Z%^x6G*baj1x{ulZy*d}VsQ{k;db79<|Yykh=QyM2qv{FM4PTQdXjAH z2j4_z!JrV$jzE>^jQYH(DR|25VzVgnPdQVA92Z^?)g}u{$sOvT0@}vRgxLCmJl>l!y58e$;OHG5O6|ljVqAx!t#`XHu>lP`^-XWHZ7Yg% z;=NX0J&bcspH2V5wHN;Uc>?=Wy(yYw8q(%cZ%2hB0gn}HB-JNR|9SR{?LteOo1GQG zwMhGx^TV%OkoKYBHc(;1Z7B9+WMSxFgAm(9@ZHk&pth{?Swp3|mCrWU;+8KbPJEU8 zq&&Xzl!i{oN1qfyW$->${e@u+Hp8I}HZ4Z#Jj9HeTI(}V#d&fERayQmq1G!l&cioP zDdgm(Q+AII#IWS0X%O=Xm}e8)-lS>5cIMV3iLa0R#o$xZSgqkEqowptQJ$5j%p2E2 zZR{oI>(0E_+68hTs6IR)2hT@6ZxuQ~On-`pcZa5`VGLW>;KI&DCc_#_#WhQ6_ak0n8WPc*~1ukqw7L#mPb)T+*F`+ zeSXT98bznrK7lYOT{3G8#tV^{&j3Hk2=*$nCgX26Ky>1^VlENz(aoOCI zMH9DtBXfPa6vP6aU^+}Su25tr)MyAere8vrs>l3z>iTeVl9$H`#VvXpJFD^?f%XtF zv5y2`VirzC1anNZh`n_`!eAABJp54SFCG7M^#1)kO4rHBA>o{+FwkorF1kSl0W)WM zh%BkwjfvKfA?}8^h%6x4tTy>7DwZ>Sv|S`-=m}TkPkj?wF|{Nz4BZ>XpIdhmr=3Q) zuyVMDGLkn5Nu216Usi5Go~29;=Rb-%YCf@C5~Ed{*st&+H50bKUYY4!O62I4h`!;+ z=$$SiLbb-IP-R{F_gBLZeh4>M5`upDq^*sejAcDPW$UKFeM(wq2f9~52(;X0zUZXS z%m2|>bprT>yOY)Wc!RwP9int8w>^5a)+v4z+vTI-Q@Y0Dw7W?1Whj;+vh*Kh%Ew}? zh5LO+`Oj(Vsi~HOZ*3w{cO(7G1?1=)MUrkJPXmQRXcVSH9uS3P7bdpFm00;Vh_2(= z8R>pbOo!4dU7m1su2~MH{L|%*hiA}(s3TRc1fW736{KGM0a>doc&v`cBfGn0j6sKL zL{|6qvc4dN&cnDVy55T@Ll3cTgqyAMP5_(DjG_3+(m#Lg5X&H~2Y#yoA) z@9n*m%X~4`uu&xuf3^sI@*l*2DwBj)^!fW8ilctlfd6Q5A`SIYrHHfbEyHz*K6jey zaxUM6D?Csra){CtUdw^G|31qqCYBAos|l;a6ZLlE5Ugr~ZX{@@ofL^VFTM{HgLv^8@=xAV;abcmA<TY;;&|Thvf-~sA?1^Id1|iw z;?#l@Y1AwTtYDiSsFA&njgq)FG3>Ikr!%9!)wOWdn@Wkk{lwCvlUz>Zl;fb8fRo}* zU?f&RzB+Jk{=Vx`%UI!JH2O9+vh{1Gp^CPQhPf-HZtl%KFE8Msp&Kad`AgiLFcvhl zSBQ-y7W>#Y#N5_GO-V+gW>9Hn-op{&@RJ2E# zSj7lBE^bH+?qar%%Z-?K0*?p3e(lh_qYvCD%bPLPwniSG8q&71)^pz`t(hGkQ57LV z8ix&b3cGQ)f!|8l$#aYY>;kTU#(~QqkQ-fv=dKt59Sy^$74_A$I z90m7M{v`E!kuO2FfCAPlVor|a67Hqsfw20n_@zRJLF|)F%&W;B7uPAd*v|KyeGcJ1 zgL0Z60pe0pPf{cwW()t8eAAp{ms_&QCpfz?J2g8~+!7-r1JAxlR~#TI60*`qsC-(| z`s`qsyapnw4jf4bIlzW#$4e~l`Kte)0@kEpS z2)uyCnJLOWa%N!JtnH@7)hiudF7ng8UYs8)SQsQ$b^J}IKSAsruZ#V_yMw&b()Rr5 zdD>tL611H=yEv+1p;=$)^wsm=a10mDjD6|O*5bm%3Kd}MfKWKa^2=aIuixUh8T`*f zD#Hj-cX6T}$x1OM#|FN$a}O2STf1MI>#-OmzUs;)r`-7Twp0A05W2AE`W}+Xu?FdXBI|sy1uJow?3u%r^5XU(El-gcw zeQDj4%Vut+y&;^^PV-7Qp7GN%K}f}7Ie+`_u^bqoJR&C+xoMngZOqr7_>jF~-{b&K zRy11qxOe9288xiD${lEj-#!wUAH$f@tOr>{i&!LQD=f?217lS|H ztn50+oEI?Db2n;hdx*E6lWc;t2<--z{JyZMt4rxgox2=JBgbN0l=^<}Bx!XZnN!HR z=F#PcOVSZx*LZ<3$vqgck$Ntvbt&Zh&%_(^;8My*!IBk7OA8$N#Jl(yAt{Z^HSssc zx2y*Sk1T$JtQc9z3r@i@8ah+@osQvXpov=;ov(gFWqusu1t6w@%o}m=V?iN2IJs0T1A@Ujd{K{*0&y#j!ob^m z6R8V$qc0CE#5cHYZfHT`_X)?&5|s55z?yVOIu&eiQmi2kya+3+0yH9stE+~7HufKl z(BBkOL=q&*~LEH$b;976q3x}D={nW!nXQ-9>1J%N-v(GIdxx^VRp!vIRqN`Z`ON~ zu~w7KZ$7@g>I=+!>x*8^Ml;uTN7U{`bYrg1v#DKDV_2F$N0!`1Jf?oeH&*Q(Jl@k7 zx{%~QldO=igh&KY(MR}RTzJ!^%zzK>cGrKTP7R1<-)Q)*`Z&S!n)cJLPp(1OO*D-# z0(s)i^?)bzetxo^EaSPBs@x-=ctPUH6Yq%mQiIRi*x4)7LTPtswl}*&LA&Y@qsmYe zi1Qs@>}c7pJkhEj`!RlvUWxy(2BX&Q7J6*d4cg!za>DEu3C~lIVQJ5t0et|LgcPJQ zt>>Q(_Ezsrtc~9DMg0=d^SYR=FPaC%Dgwm8+1VcgVa4;}QUI#*YMz(Mv7TS^K!|l* z&8*a|X)v*Dj{h~P`9*`DVb<*wIrj9K4~_qhzkYNUdx_J$#r^6=5R4_j>;ro75qw@- z3nZZ_B%j;88TY9(r6p6qj8d?x#@24CpXtg6Z!X6ShnETBU)Uj+@Gp03bvG#+XO)iu z6>9i@mv3=N(bc_Ewo$Jc;$RAnx-`1|v z(l+8s@vca+n9Ek@+h8tIQj8k!!e3uzN9_@rI>u*Zl{=R%Y>Oy7ew3|aTFLFUBrFgI z!q*8onA(Q+c}D8Dqk!kZ4oiZnolWDB0ls3;t(*^EGm;E<}0!XmJD89HalNEW`Hsg_Qde zp6yFwmCr2tLB+p=``JuL>d237f+kYA-S%89&Trhc9HP%Nj49UdP{jv-?MTDQJ$dT0 zsR@hswfM6~+@vy89beWWc(5L0I!!l&USvG^qP{%QaHVDFVl@1%yoBrn2vlp(L~H>M zatWo#SBUAMFcgf*!{xgp=~5j_qMxVevsVLO83PBLo$WUh9It82wj=n;e`v6g<8Kr5 zy8tly+A1Zr^Y*C6T2>m@Ma3tU1iyCN`aNy%bZ*qXdKK+lfB?Q&9xaU$weoaoYtk2e za{cK$iL(AJp!@=v@NbbdteG}ZVU}Q(HBai zImS61TZMi-98b2>CLub@Y6?GDDXIEC;c;O~AiNXoShiT1*p@strJQd&sn$-W^R|2spLuLaRjfN>!!S?O zaKg|V+>P)6L>ujq#X{ybiOAZ4tXb>jCN==LQ&}2zw>Iub((M6$^6QHTzQ!-|i7lRM zRd9f6u}#d(6ODJ{H0a5O#|GEvOSi$_awdH?KWJ`o zTKbSXH4?Efjj#H?jOIzejNUi|D9pqPD2f20C|WRYIDSf=CS>5H#|st^^fs-3%(sr= zxyXS@j_QJYFZSAg6LO16^xm-cGsQ_BeaNITG#m@I7#DRg^GfI}l-W69aqg0}(d<_^%a%~ub7o}c2k zAm!mm#^bgIL!EagJDF4Uh(-MYt1m_L`6XBAEYGsAY`p{ulEqC}-Tc*!Wsk`lz$!KTZ=83U81Sv6O{&|+kS}F!#h0yH_;U%J&out@DK=HL%&Rh6Pw+X- zsJ`R{i9nj?0#7CP08qPoED$U}{sK$#+l@0HL471YyQ^YW@h)Y1iC@!4fhYGt12J;& zyTWL)CUg@C0OZHAllh&Ytm8_JR1w#PO&1T5ki4EF#@AWK^!MXT_r>E!>_j>2VtBK! zkf?TGJgO#EZsi)v|5|HQXv(B!{$`+$RK{;{(FgG1YM_%BNtqEs{S7+CU*_rcOrtrm z3r3$*U|bjx5gLkI`RD$4n67T>x70;V^&Ie*XE`;-7ABgC|E&5V*WbhO6wOH~5NbuM zfkfMoU)#Wb*aJ_<%dbMV;}YKMNnJhLoB#d<6@U`JV-mz%g;q*E;k z_V!Hdnh5sLT+|VOGs6QzNAhVXs>kx^XYFm0q`cP)+b*3ocHKT_ihTqNyfjv=eiZKU zc-f}XqbuDBMUP|j)S4?Pr zATz8h5hzHH81&Rb6hknE`3)A^TEzb&?9Jn$e&6uXv1HGZeI21FYnG5@Xt5@xvNM$s zLK4Q(j3q>NA(Bx@vQ^e>V_&mxSz=}^$&#^+VV2K%`u@&&o!9y6{NdGK&CL6GKhOQ# z_kCUWb#Yk(%=bRdmlLsMHeKT#BDA^XT|HM{v8*c0KcLzbNlP*z+!}_Xn$xZf^3}=ZBol@m^7AxNT;KJkAt$J5jdHxdd@hg;+v%wPAL8BlEA*UVCFQoY*P zHlt9M!1=3;WtlgUlLd0LL}QI0U!@2VWLpPsx8~{W_@Hsk&f_+Ddu~NfGD~GNFLZt$ z)s4QA;&QL`saEeY@4@hvBDgq)zJxLE9OR*wwxn%aCeH{n`8dsO}Fnol4cjX zZW}(tE)ih}h$^;X57EvAl%(o+z$Hr(Eaej*x4_VJfvn-NK)(~4@NAoN!~W#TTAsMs zs*c4*fS=50AG=wGz!_1UcR$6dkF3#|+jSm-LWMp&y0f-(iFPR3g>f}j!gP189nz`RJ)<^$=xb6XlT@x7sF51af_88w&7Sekw1m|6koaQ`rTh(}gZU z#n=21QT99huk912Pt6beaL>!RMxPSq^ET|hVXCdi!q5lv9sY^JDz{rk+@@S7-7m7h zZJ8T4)+R3T4*2u`2)eBxqm?~h;xzZV4y7oLe;lcJdndmA(be5yzP=}AbIG}z{r$J485z=37s6o{Ekd+ubd_@rVY{Ot zj`ZropC3dOd549C4sU;6DMr_{bGE7}hU+RJkw&bPKj33?kfUfOir+_yK4Ch7V&Q?; zX_mLOxUsVTCv8;-d-Y*knyO8(Z1hI_aR&|zfw>c{>If2%x`w#EfI%~J6W98toZVHy zOw&6$;wk-~fE5be2uE6QB`}$O5C4j38;-0+GVchsZ`f6v9Bf&rm%hC%KP=1{{o?bu zn%4a~Mt5et#&BdaB8Z5gX6qWhx7|<)Gad1^BFdy(2|_XQ_S8S`lMdo2yTpAB33B+h zE0{->Q40#B3_?+uC|=%|`x@@mb{%}UxVKKFhxgJwR^IdQ71>AH;>XkTNbr^;A0hih z+~Qn{*PR8ktQ#ZwO?_6I8%$-N=)1cn-8D@ANtcYQIdTWR+q2Y6BtLREYvI(CzM#E% z(VSPQ`t6zON_8^=Hr6^dyG`ed;R7w9o+n)M7COXgYW9IV`}51tI2trg$;FQU%tSdp z^-4nYGw@^8dZi_&aj_JB(Iw@MbbtnL!@ ziI*gRppM|uSo165b5d{-#g;SYGy$)*~>FVR%s3e2`E@z}zbntY-x~zN(8DRk|sS z&04EIe^*ugx$#t2Xu@*xZ38IF^gK8K(0C*Z$(U^N69}Rm$N#Z++DaS@Z%BXnA=51} zrFXF%eR@EGt{bu1B2xL~U;P_F<0b*1nb^@LamnLG;)%k;y(_G<<3}eTFY6^grya@o z17rhq0?g2aNobX=Fd*i>$F-pM`9Y%}zp?8Jo^DHzU=JiXY?6>t3#3RLWe!sOV41=J zJ9>VuIyE?~s+PXs@#71vx;Be2!q)cBZBY5KoMSxp6vR-FmXPwR&`xRRg47PIV-2p^9;in(QRZ9MOM@g+qh=N2R!to3!+z24y-dfFSXX(6J<&&?51Nw|OutHo&1# z?qLd@v@u87t447GfZ1xAsbv854rSMQHA9mn1uWGi7P=-|)umnLJ9YWPcQ;uvfL28e zqRwIjbzARiL&7)Ow_fe}+$dY74`yqKk)L790m;PJPa_VO1zgjMQd)susy5jZ-Gc%5HiPY?c7D z%oBE*R8l-pVZm8`Hrv6edJwhSwqgW0ImRcY5&NuLK#P4&ZV zJ|m|vUzs;2-_wTmHFs=YG)W6Ylp#WIpsi}ZS7&<9ZKbqypVB#JEGD5g%*bN^9egKV z1s|2&)FTTahgwvrZvndiBSx}f!F?uierCbeHpWmzVQG*??0i zY}1RZLy`vGu(C-McAQBQto+g01%z8o+U+LwQeK%?(qGQsjoUPA8~((+*OPPea*74Y z4E8MssJ3EY~X6j}H=p4mE9_4r0Qvr#?#u+Z443Z3Jn_kWuf}U!-U?;uXMX$vN2ZGjUG-dCy%o_WK6n%*dLZX$oH{@eWCx@D>M7Z)Hr2ge8|J`=_F^SH3cde53sd z$bb~gk0OL*(mvf`PlxYZCDDF@!kqtW0kPX-hTeQqm|6ENSd&NBlP6>3H!x9s$TJ>K z0xrSgWLpX^DICM8ZVB;vg*R0{8FJF?uLCTPFOs|ewx6`B7=iizkk&9>91!(9*HCr7 zn0C>;RPi#D=<`7W(3BO4kisZl0%$V3Y<2-_K9{i`ih+k%k>ZUOYcIN)ndNb zY^Hm8^M5A=xGKN?+_;>x+{iC9-)TN^pg}4J7oZ{)-69gkN=n9ckz9(!r3N|$R4p|= z1tP3W3TNINrgcbHnEoz;AQy_an#ppnIrYzaKvae}usnIecnm!T`vE2r#=O(GH0Oop zQW|<+^e6L{?c4nPYwD?00*{iO-p-{r81_-|!Y<@aPhh^HI=EOV_oyEz=dhL{t%o9d z^JxRRCS8nq*InB$h;7OEC;4>)75=ir${Nf)=&J=5k}TQSBkw#ZD)6!Tt5Th}Obv5y zaKXfk;OD&OB3qx_uoRX)W`ce}ZKg1xa1OS9|3NH#LQ!+}v|yMI<^_@y{C}ej8Vf;; z%d0@adisLFrsHKFDLb=sx?5Hzj%j`qdDV1O0YJI(q4n#voCQPuByLzc=3EOKkl|t~ zgZWlUP;4h_Sf6dPAsQyj6qSpUA9{|mm}ELXjgw6aOjA|Wq)Sik{tUFI8eD-xw=2ts zV6M(V$rp?`_xT&l_n1tH{FElzNXw6=n^rDvT@ApRyl<-5#-#&8*i zq#5Avy3@3j3jYWrTpyk}#3lDwzHE_8$0KtC-om)-3}r4p-b~TWQdqOMcyVD?a0L>P zo}SAFp$rXa?^jMiNoS_FcnAg9%<`pj27KU`9F`r%KsEbcmeI9mhX-vE(b}A0BX?XF z8HW7O)8@lJp+w_`syrZjKbfol>~Y>hf5*~~xWxXj1(tPS9rgg(j{auch86>?gTVsQ zp#_TjCxY3EHZZ>R_u=_yiO?5&uDi9olD0NNr-NOR-ax1ZQ!t2;z z+1^uHKkS6Q+#KcdG*V^_Lr7_f`&^shaiTLRrRUVAl)jhoyr*>^=0ddi=#F7azHx;%eP=vx^lm^x)r6sxTh;4GubWi@y=-&fy96jLhnw%q z5H{B1<+>-CGIWW%FaK`2y|HB2I^(3NqjYC45_p|xPzqhdLXa37E%YW`F0f^4f)Xq$ zXREO89hMO`C@%feq#Ul3>$5&3e*Uk&*Pq;G)vD_8Q>G=(SEJo(Ode^qrk6ZgP$Sg19hs{rLWJO?Lw z1FZqwAlx=5VrblX63oLmdj!_jDz5g9{c7Kl=NY}F>EkAwza$fm%Kl&gfNTe93G6;* zCd-71rUc;O?4--$%+@37Z=21g*2nDX;uP>6cZE#;7K!>y3H|An+;fJLfdSTH)o;Ky zblYMEcBoA%d8enE3>D|oO#>7n9yo+%drwN+&OjWE>wn9nPmA4T-urV6b#1Y>auZJ0 zLR=yG?gS<3^5f*HPkMFi7zg?Kc`0shS)3c!Jnwq*C(^GuBv4KyyO9hW0jJ1&7o)D@PfXR6` zh~`t(I$LL4{M^7-9B%)W{i|yMv>0Jwr&$(czC-LZ!1WKOu1ej2u|K_PMP76 z@w?)a!1ad8a3M_Yx0VL!z7c4cd?mS)18D;}#U0yR^NWbp9+P@9-#NvijU!F&rbj%P zSG9X2u~CsK#*FTJOEk7CrHe*v@mru((P3v~lMwEeAbg1v<;?gfJTx^f!2@<(8@7~zHlacmc4)gDwi1Q}G z!rlJ+m4DKDh%D4Jg-t9F42uqS_gn6cTQ%2cOYKh(cyLBow&YI^mvr7aIfEF{>uRa?92jnQ#n$4p=1Cf6PiO6 zR3MVm*lh}*7brgf@&%0(EvD6x}6r0`$Sr*4>vJBmS5SiHy8f_j_z_XNwFVs|h_Fv#g z8fn0yo_YYOk9KjFj~^>?5E-??94eSJxDKUxj5l#+Nf>m?KchN)ko}IyB)bq808IIh zYzVK2^`r|P3k) zXv~z5I4l$dnI6#9qE@yDlHk~F;0rwrL1@S%8;}3Ct}}HAmFkZm{{0K=iuaP506i@q z6cJ!m#k^0GvIl(zBJY-vKB>_wDg%YXHPcd zw_>>oOAzSmyn>DCxg2W7zkrAwM=>Ko_0}!HM9Qk@!EL{)yqZc<1-l3R!+_;p9|+oNlno=Yf-Djfx7n7XCWl zw(cY{Tgx1_ikmW=ZGnK_=1QAbWTXiIL|-`^DT9cCa(bRDGcUPz2FKH(uE}$an}w3N z{y-;&nbAdei2%m$XhpP3w0T$+Jw<#cu{M3FRPn(v*}Sp3uKFA5Qm`B7)*F0gHu%BL z+X~5{*}wVwAT;pfD7eQ!sQYi?|3;DlL;p~X$WCoQGEihlT&{!xyxV*IxROV8njDG5 zVA&+RPPT|s?*nVek58_+d==jq2NQ&qBsuuz5*~1gl?j#+0S<{lb~}m*v(GLlmVHq` zJ-YnS#^bKhB(s)S9)v%X#@bB2L=o5#+?**UEp^iPzD{er3;DY?tVfaei>}T7km$n6 zat-ou3Cy|N(?bz^sBdTtm7CK`&F(h{&hHA>FG*zkeVU#B*_yfAqxVe!p3QtdL^U^( zs{%BntB6X}7L5CFEVSx(3{5QT%A}IIg+oW=BOy@_ce^yxJU^*wv!77?F-}h7u~OPB z*nh>FM>}f7=YWq^85>e~yikc}V3cI{xMyMwEZI|M?>g&Whp0aFBA8dUJOaa|B?Xcya^`+bRjY0iz6nh{_}^MOkpzPX z1Gv2R`gNZ+G_AksqTSP2w#H^3qLp0P)8+!h)rRfKqC^Agn-&I;?rS5YZ6?A5i#;1+ z>h7PUPIm3H`pXYK$*&v2rWAZjfavX7CZO6(Q0~5w3*ywbHC$j^sy);G?AP}Tc1OIn zS8I^afd*TKw(4E#mB@8iVb}n*uR{gATF(v2YhrS(Q7Ct)Jd2td}iq? zfhpo+8&>c9rm-u7a7DRGp1Zrj=CE{$f~hQ+A%la-3W61MW)Zs`^Pc2dL2~HGoaG<- ziWhx;cFk6*HO>Bq@LRb8pPh)9o(g{u_Bfx*H?j8tu3-1MQQ}8 z6Lz+Wun@tS=!GvWteKFkq8BPke8`>>uTmZrX?!+ZA72Gl=MAlQ`eMqwBjR(Ydj@}w z=GX6MRgKJYPctUvirFkxQur*1nWRv%5#{QLPm5^v^d%|2P^;}@qFPAtwS*L@4_V*hentzOcvGVA+*EgZ1+%40R;375Q)_{j^KFX} z>G6HIP+ZYO*_LGn$HxgBrO8{nOtTDh6YfI!TRw~0oiI^1H!f57?o!j52<1KvNMz)uLJzozxTl=RG_9@NXH);ZX|zk1WlNf z4T2hRoHUM0PDViw7GFAZCfyx7W1^TJoaJR!J6d+xqBup=$3XXZdVd34c%x)}IY^k! zNVqe44a^wrXi$El+6<7Qh$}doEls>K2STFLqv3X!*R$F+RFLTWm)aVwik)tcm?8@z|++^=ynrriaU! zkpyiPV5Y@cKg0qd2a;)Q?qn(Z8Ao8LR`T~@jAlTbg3lF`epa@k0tN+yuw+OMWtJL; z@m7w8vbQKw9Hwbf)B@vi{nMVzw`+5a+`0L3f*Dm6?7TZICpf~I4k~9$w`WkqK+L!L zul1y$_b)4?5%Wc_P39cA1HXm$KS2PaoG5soY}ew+KY3iF(j_SC+WT&FftMgL5P#)+ z=f%AykMxK%`UFth)6#2vN#`(|8O48Wf~F*7>L--$#pUTBHj8aCT4f{^A`D%+O(8)V zN1%DYNTF8gbAjzGz6R$lMjOX=illqi*2(kE%l@DbR**Uo<+92w`h-in8zuQ@xEzAA zM5=+8l#A@2MMVcV401WvPie4hEpyv-x$AoCzTo~Wag{AUy-zj*{zDc5y|K9bBxH09 z6Z8)nheBF-NK4p%?gyt4iyhWEw2ImJ*{99>Ub=pBZN9$eUnEA{>?(R(CzAk_PMC4b zQ<%pvEC?U9!(dbj4WMe#Fv|(q(aN#|;ffC_4t=`*Jx>Lrcdu~Y%x9Ji5E|Av*4X(? zw5Otdf!6CJZ)=0oi`v<1TR$`fGW!^JEWCNmMdkAu@4xmNNdV-xvxR$q{%p|v!04j! zmL}Nzywta0mIT>uBp1P`+^=FoLV8?jzxTAc-F+5csYgxS!FO#uefos^)=mUhZmN-k zfzzZ7S$}Pj19`?%Q$(T!_zActF&(qd7e8IU_i#CBrt&up^ASE*1+v%Yryf`R5aYsr!&%q{qj$^TWP;_{yeL6J>&m#E0O z4hfEN*~tU*T6QskHK(|PrF`*0w@3C8<#;FOVZ#ychs_hpMYi{1B<&WAweH^3)~;Ol zBFa%ybT!Er5mJkHChiM5Yfj}S9Q+qK;!LyPN%s-s`2LgX0;T?+Ju?+eMx~NS@Jh^-$X^&mJ$fs~4uB zafjgh47eetnq`BK}r3e>|R0w1`U1vz5UaD&zlKG)kL}Mf`B_bn@nT9 zH|zcGH=ygge=q!Q8)bSnQO74G3IA)@5%p~Euh)))&FFz8*SgK6i*;USG7bvfti;@v zTN`LQVR>1e{NjEO|IszDnMA2ciby$xz3(e9*!hgwqA)707|g-C2cP43n9}?(fg@_( zeJmW7>v?XdT(tUzO25gy5OBmT{+~X^zkjK63`W6mwgl|&#NcVT7lqC?wJvk?8n}a^;6_tNmkjxQUdgnC%@~8K_8C`v( zvDUi(@fO~4Mu+%xMG?-p+{z{d zVQr$D9I(UjnreTbvpEIpQ`6?`!=iE0Nzyz#O!qq6Hd7-xFU6CK@o+HYPPDUxAR@xF zD;&K-a;N;S`MQf2?x=q=YlJMGKQAZx%~bE7P1h=tCWLMI9;tsyTl`J{R_v)~F_^gH z-~reon$|2aNe0&yVV@ zfpdag2pc4G_!&dE37x@UlhOfeyP#{9`Nd;(Cx?#J+0`k0J7b;qn4>Yf{3gTGj1)pB z7HC?ow#VyHL#Q5iT*D6l^U~%Zh3fC2k%HW{wW4r#rQ$ zYr8+OT=0+hc`tOj8))Fb!%-|@f&?3rot~&BW%vB`so65?NOPgg69{)>H;~Br+%l0( z9fTlRZe4qf2pJMLhL1lZ=f0`%xgWPP?N!eVjmYN+S*Nh$S#-}W>2Y<|U8w%@Co9GA z(mA?pmnWSZWSfIF9BADVpN**NhzpG4XsPNK{S-V81yTpq!Y?&8th_mpnO^bzmpUOy z#yE5wnsu4b62bJc3^ z=h5f_^VfQ1Q5DAb=U<%q-fbwofDs2mYpCkvj>TDdymNFYVP>UaY@c1AR@2I8ly$*o zkF)c!3j4@1M_vY%=?~`H_U3lcPX~|MMJ{#g_%V&R>$QF+o7~>I=vzY zJQ*}8;$NvXpx(4J8F3kZ1{dL{jaAolf{L7M)Ojnq7pel9Dmwx#Q2_Qow}xWU*Fo6e zmE%sQd25>2|G-PKzwoR6!d#)2YjdD2xH&-9YddvCu%nsFQ|{JVA=B1BX?M~|)62iR zlV?h?lf@K1Acw{Jb;PA+MAwwNvFYoJ&AMQhVYcx5ca}25L?Gl;6t)QUjTM3x>{pxH z6m)!!3W8_X!fPwrODzFHYDFUcdA7ja^2OHIw>35h>_(~8cv`RPKjysqcj-rOaZ@o@A~_Wvi1DloO0UcB z`V)1)b8xMr0ok&9k;}`TFXUqu)~io(ztN%0g2PL(b2M$OgY)jq6T=MY|9T29VZV>3 z{{Vl;AmS&|ee$Js+J!Ni?4U+8`lZz*uF)jtp>fR~oza~WExu}!*yOCdNpfQ_S(!F0 z68-x4c~3_(_ceb}BeKE=qgiZJ&1)uR=15NCn_frqBn)m)vmMGG2FFuU&14SHUTNLsRLh?GT?yL_uR&Tj2ZQ2X#n zW+%-+eB&r)x`uD^p!te*BHNjj&Z-lzcA2NG$eQ%&pZvM-2j1tdX2DV{5e;=bf7 zjtH5CPn1`VTfT7qFvxN9$n@NdD7~hDZk^*j4*wLcPJpE!@BH3;PrihRY6GNqf2`u! zQKfQM_@%KaE!l)<1qp2)Lu)J0AvNYdngpL-1tRCGZVYRfHdLEg|T2%ed< z0+|=>xan2;RWI?h@$be`crA&6BxO8&W)?8*irZ`L|5lYP{*oDoch-rz)T9=~f!2ay zLVA*^ZeBP9rF-Y0&4DS|8hit!0_AS`G9)o8vig_Oe~_yq2jW&ktKE#XIXZ7eJ!D^Q z8>kj#aTZ4w9=1XIY2CElo6P@B{=Y2~VkJ?C+Ct-|2$9bC5*qPWHET8P^?qzKP7yTv z9gUxEDVZ3)c9n_bx)sTFQ%{*#0A5#W80St;>o7lwxAo?_2+$|+(pKN+b#4unCnvjBnu3%T-LsbxxHKFd z-4z!U*3BgnVRJgz*mlv%88n_LzlD2T(PuwVX_Yn=>R?j762H1|5%E*ktPo2u!~%K9 z6(^}+?W+oO%MqzLMoA{!fB3`oR4?Sv@=#dx;t3jGA6WsR(<#`(H|~3&=%?i4^H*u> z!S^&%fmM^(!Sl6{JGUZw#8oZsf=7y`h>-63k`)n^oz@b3#-ZD?s z*Is1C-ATFovaR>Go&ivXq`m=ka|}ZmKjBI{jb&%~Qq0>@M98Fq)BW1CRc$Mt=+~Dx zH5qz!0l$-XWwFk9>yQu&ydq3#f?-;b#N7?MhT2Szzmi@LBjxR^?uTOq-CY?N^7~{z zqAvdjajA@iv6REyhX3hhwL^=3Ij%Q6)2vf-vhVU!sNRPdu&Tk!JE<(go_y(|x z?Sn9)%cSo8LLh4~9`Ib?Z}05<%v{gobtNU~c!LG23T%H*%)ff@0>PZd_8cVSXtpM0 z+_uOWT1M&G?DOUqJ7=oqPm>kAxC5REoo@dvZn(72;!JIZ`6NffCBoR>BcyS;f;K4E ziBq)DS1)IO-R@;Pf5IW}hmH67e<4#!f8;O2r zOzSCbMw;w_tipU&nZgezy3~(uDQS2F$g@wyU7x}and;W{{Airuei9l5e}}G>-KxQI zy}}5#KuMLY7d16QY$9dNv(o&QtGAkTqzay@FyEe-UMUK3Z+jhr3Y508L5Gu^9N0Qs5Ou zz=4()5=t9A=ZhVbIw^7T_KoxMWr#Ev%#(VIsDdL(0RLW3ZVht|q}924dty zR(HsCk0Wi8tYfn9jAglqC<2r`8Bq2H}IwjbY_nu zbx!7=D*qt)DMA#txTOXJkh2o^zi;j8z z)@b@E>~v>22WRorpG#kn)#~jLw}2ooR;!&*aJk3)Nqy2du>ITv=KG)$yF?of@Qpw- z1(aXhFa^fF1)>i1dFSYD4MjHt&i{O9@V}0Ujz2sD_%mRl7C8=H!Q%2Hr^B>eKQG#P zS$;G)OjT^}@{ET*D2#Y5KL1-71l+dFq^qJcW}kki7*H&yFb=5y^&Yl6xMmh{s~Ex@ z{%-R;t6zzJsV}gntLJo!7m_%8RoJQpRBmFaJ;KzQoyu0_$UIp>(%1a;7M4+3U#Pc? z@AAwQ#&B<~b26S4Wn7Xay_JJNO75^77LzCS??x0yBzFYb*VbHY){Dp^GS<)eo~SAN z^zs|i-J|6PCXhTGIs@^bZh$W?Zc;yoo!haF#mP(rh{NxWS114@vMKXtzXF6``I}%N z+!tKtml$$rftlJeieJs|?Tg_t6^qGm27S);MKCYt?T>9fdqE;O^pallYZbG!x%S=e zKQf+WYz+);zu)&(f{GW6FR#s8w8`Uo2tUs=GsmNG6bhalH!(_kzV9nq@Aw)P*8&$xi}b zS0(w?0Vzf4S}(%K*T0+3K=@*d6aj(b57>7fNbJxAr1UymSl7^d)q{5GZhQ~o$e!kt z@LfpXp8olpa@5r;f8c1qr9rdWk^G6bM{3xEg;%D1Dz?uKyW4SSL0>$;T$ZEPwk^D| zuF1{HFoj7+0kC4JuA56J?D>u+MaDk*Z~QZzzQl%0D~ z7-mPFs7uXjQ6!;hyvm}a8=}ol{n_q`3(^PGjnEB z`lpQ*vNHWmJx(kaD+e<^m(gE;`h7c|oS(}vt&M}Tkx*@y_|Y*ya#rAN(VsQoNO0%8 zR8nimp=|Rr_aX@LF{(M@Lzmm@)*(58b_ z3%fNAd$h9nRCF8H7_7`SaDY z!D4+Ylhv3pBvPAsB+0A2iIuEN8(gf?aYoE_G+3ZxAO37N-^h+TC%pW*I(7wm;}OI9 z4V`hFldGL_BP@2D)DoWnpDcU%9CgC@UG(piG4cKHW^9bttOo#8?H}XQkN1J zbz-J(yt8~!V<;OSf7}^ zYyDl!AcfIv@&;1>WBQP=HEx+LZ(Ce5vH}WqPn_$7!zHZBDV?b$5n& zaE}>aliEF~G1w_on+?XTRGf*n-O+PvQbX&5i?65m!xt7x`gc`T+9N~qI)EzKo;gj3 zBA3sunNIz<9-4OXXiROXLi3d0-A@I8?ETZ11Q3_40YWiWu)W+8SK0YSS+UT`%z+&G z>XALpO^_wNx6SbU&7Q?b(WEz(g)REvonNQXkzQe^6Lb}^g%cWjF7R=s>Yvh?Q|5@C zITsc6MCpW+@he{^Qj_)*3qN}G{hoffEo75eSLG0FfR)uOsBciZ(8NM!4drNWQ(YuFncVooq zx}SuIMLuFUlC}Lsx+W|3ME|dc^Eo~rSGn&?lF7SX$Do}S=}r+N*`dhFf1H&jn-qag zcFXsmFrNxv#ij3o0*9(yB9%F1eCHGHgCWwKgY7v>Y;wCidM3T6A&q2wy}D_1e`b5j zy{0C9!L~y3dI3}1o!n=VxjY6?URuvTd8SA>8blJ8p+ z{(AnAi7LP3e~=)(lZIqBRNECA8^xXkWVbJno@C`D72pLTWrN>`K8utqvU|1CI&Yew z#9ZM;z)HyFGkk|G<6l3=9TXOcrRV`#hB%2IInc^41! zS$}gpeKED{{Q8A^Dv#Y4`QQD^VV(aCPL$CG1#`p`hw6`$-hMJ=6W)q0OnX@< zy?S$9rBx#K=vn2k<(v!gCnO@|qZtwurG%VQ7>}aM9w@o+K~tJ8Bz18E zp2>$g29UhlI0pN9@!LT++S~7wqo;L{YWGK5WS8`jkHP%g*C1aVMEcW4;dRi6uu$^t zFdY(*ic!UHTqdwOW~2NSM^fwhqVH$S<#HT!A#JBepx^4E)w#rIqZ0H4biCpTVn&Il zpRpgqDS@kP-o;`|k~f*Rb76!#!!sc!E@|fPtTY1{D}SEVF%@o;bcv_Tl1ji#rflb8 zE$jtNb8Xh*M~f&S-vN$3^tTj!{)f>$qZ`4T4#(UCm6o9|-xFhOBDWMIALZ^K2Dvaj z&`0q)S^>*c5T;A82}kO9{BFy+Dsstl7V-Ui(o9%=j?-KaBlP?->KWaZ0rZnO*d#Zp z87z#8>sRzzI+USBNZ%RSd<$bWwGkAXkJ3LnVxoP^rcL+jZ3VQ_wtZOk7-sIng4KB{ z2GhQAexK=2NX=7&XNEqyOM1ixUO7<% zF1%Jd`(su-qom5A(C$ORyl&~~-FbeQ7eX?A0AWH#I)kWm8{;PLB_FrtI;rHID4wSL zr9XPc@buGGxxOV?NRZYlCKssNf(zrtUQdhEPJJC&7U21Vhv|)|EMlC9MPvPtT0E^& z8OatV-tw(}{4a&;gRUS?wNGiWL&^DpNIDjlUOhu5OiFUXF=qx2^(s$|uo}lTvrkpC zZKkdvDn1& zRVYVe`H3devV>ueFy+hgv%)POekb-k>qZ}Ei8vIU__F{P!V!2+|B<#{JEZA9;= zC#if^OAEn1VQqzh%n1ZzAIoS|)ikJfxWn{GZ%RgOXUfcAb9m;olo!v>IJ6Rn=>@(gblSb^hTQB* zu29jg1R%h@{~&XVIN3I?C~wdYx!b(;t~)zemv|^ZsOfh+GoGc*q8iQ8qswi`{0aK% zs0(EbEFzSnFzg!2GoR3m{nDp(Z!(`I z8>8B;BN<7R*sKIyL99u@$=kL&`q@E+o$3F2DCPUg>_3K}gORAgAE;NX~V1RZwSWoUVA0gQJHCXK{(W#s3mQCp-HAbtQ>2*0|RX-5H-;L&=Ih z&kTqCH}(H^dk!l9XCRP3atE_f*98BW(764+m3+NE)4_D}m*K!!wq^ zTLcG2a_=?+MV#t%8i|k>d zxX{LP0o`#*O3E^qzjle1VI*&u3*6LR60Yp|4BCYAsF}AkHq&B+G`0tb*;Z0ulQnh} z9hR@=?=Enp^zlhPRxr!e=lY?av5Kml-rDotslow^+7Af%TO+3@|4OB;F5R|@^{#$( zzU<1QK81pyTCalwq8cGNMm>2Z8TXs$li}@496Zln65shf&EvITpv)<|&ypEO6;yK7-po&2a5}FYPni*X^Hr;6S zt3CB^nFm@~}5b_xA8O5&gwv>jjOUKmWNnL)t zy!S7| z?wgCOhZR=Mx3S1~_e;Yb5PY&eJCqNW50!YPbuK;qmd$iG_I*Crf(4AmhQ^h?Vh{eS zFGx!0-zo9u1GWN2H#+Jv_A7_cN$5K7!$g<|hJgYf*FAUkoiFxO--!&Iyr1fDs_YxB zwhr-neyYsenh1YUQ(*1v^CrKm?|H1x(A_nHFo;7c`+=}G?l4jb|ewLBsm{3>|Fv>X~^^xpgk0CDKc+1?>JkEu8TN$ z&IZ1BJ(D=$_r=coVnB-e!<~1%T6&3Lso<8sVg=&NeSPjD%N2y0wQ}{=kFPFTKs55! zjywLubQe6%`3x!X`QuuDQamkmI-1j3O)c|0>qb(>Z*(Fb1gUjc*@C*CJSTb`>@*bb zHN5yKC%DOuLg1=pRlVJZ%xT1RA8g5~T4ZDk(}!?aelwiL&PwR@u<`ytQnvCo?)R;V zD@wTP+BVaa^glPq%2=S0IXs6kqrRQ%I`(}7+=rvJ|M3@vG82~RyNinb|VRz*!aNe!jRV3q2s{4AcErZSn%PHON5Ax1^_o*}dQmXSAG6(WkAc_tt1gEG^=?Z=# zMT&a;Zi;+}oKZbN-*;8=7&t zs~V~%UtX}V^W-WmMa=EwbJ0-?0bq0qm4M_Rp<9ocJGS8F=+4@7k3|2H(0+a12M&r*;2H6^?n~ql~TT3wrNd;d{AJ?Jl_FKS|V`jAwJl?Hj^T9bYi{Er1b|a)+Vg~~si{rUpXdGr_Jx+3ezFMC%q&_> zRX!VM*Tm+;1!u%C2S36O1!=k)&_sSkis&C4wnM0XVCD zK@>wx4-54V{^-zm5$z@3)%a%mnN`^*h7tzJaLeED{{O@NM%{)HETFs|4M1}1J+4vy z)b$31!@w*^!UMSaKu<03i=!eLz&4dZY8w_HvYbfJ3a8CicI=@aV;^%>U%qf&?%-Jm zs#X4QQ7T*@feobR^eOw=MSyhXd}fRS#SNNw9#3qXNXlkR@85hv{~-++dVn_7tT8cz zV7WPm9mgy4YR(>r7OedIX@m;(SH1^X=DH0(fq)SMNONR2&o2~9>PHQSM25C37-qal z=kbc@fb7btBo(&fT~GApC^pfb*h?BO`PUoe$CGVd?3>5d5e{AyTv)w$1b6>+IwXC5 zdeiem_j{L{^a&6x`fy!9S8s>LfFYmi-fA=*0y%9OBgwQ@KyTFAZMRd8?rv70gDX

    ebFMiFD!7(hiP=;!Pluw=$JhHEoq=WVhNHf zythRBjRebQfFaUENVoBekpVDz#898|v%wo@6Qdw@Le%LiGq15x2GA}G{w++ka+?zh z%hl!Ng&S&Or^Z`Mjo*vTn>k9lMwG66k8d&q`ojgY;mRJz&PAn;qE6?>y!zU=cX395 zG^iHMh;?VGQ3AUEjiNz~&7+mx*q5%$X$x1cNfgCnZMK3aJmVcXCy3cQqE1cY*m_J% zsE~BtRgMkbvV@zwx%78w=(o za{|*pZ=9-WNq5!TeAyV^!D|Bic%m5(OAlN4c8uP69yTN;2YdTUXqqZEy^NA&Q0RyB zN!n}!y+h;nJP}mPg6{P4xZ>h1eaW=p;YS^&L_|3*)unHUPwi{#U$6Z+d~#INIXqXa z#M#k&?vOO`&{zp}LeWb3cAVmDzg?xwG)Ps~AYy*W?eTIO2BP*sF_dd%SBUTA%^I6uTpT1A%ESw~NS|jJ;yM~M23AO` z@h(7W+3x}1WLmpN>X4&h?h(h)rSHrGI zvg>BAxCx07(;U=pxu6;!!+Z8TXMqKVi*X53W=kxvj_517h$Nh%~_dU*e zt@9iQ9o7B%{T8&tOQGk^mhcrbIRJ1rVu+8fK*A5|bWdp>I!9ul5+`eY(DOU_u;hc|I-gG-9aB%PZy> zAHU{$keK^EQ0wRexBlQ$F2DvpM1tSWUX(S3`J+voYT1e7>;i~GL(|+~e_uq!3|or+ z)6?;y-Wf)@#b}-VOz?(XNCkuY9{Jk8L6O2zYA768{KSd8j$ZyX7EjLUx;QX?vJ zRpkVs)6_7-&J99WOzmh>`<#5TaTvXnVJ7ApQto@x;w;;l!?GZSBp`JsOu1rRNL!h_ zg(L9jyW2*u0}boV+o2JUSj0Fplxd3fq`jnFn$@kU-I?f{4~6xAdfC5EQ7_>JjwL5B z!Sjcxy6Y4YRV2hT{T4YmNpIkHT$Aa=$BNH5ua|(S{VWDJ5_OKu^vKcAkWcwvQ}i)# zuo~*WyRE#;M{@*N0FKxCX;>l3lr>e^G|(uK@-yZ-yTvSyOwb8(p(7J`fh zb|TJH6tvV5y)FJ-2T9CBmw?I7qVzDyc_Fb!#FksF^X$_d^1hU&yTRhyaV zI#5eQ1)(L@?y*00d+@C26q|j`7@vI5k8>FuE;#^AA{~YPg7Sppo-n`9nT~JP#KK@t zs*EjfWeo|vy)>fJwr7zRp1s50HCjjw!g!+anM`pK6HPvjEo}SX$uqnB+|#dd#O5JR zK&xMVy68nGckx*>s7nxlIQ@h0xCc%;>tc@5E$Yk#GZF(DyTzR4?uRVgG4%#KA{O%H zx@!7m^2C?LXAyh(K*XixGbU#ar% z`UA8WGafrH`O}ZTXrJS6psvu&tcA00NnDs<&&$?Gq?t6^g+CiLXg76RSp{$iKSBpn zwf>Rqi`HWYqFxR^wn9$7sg$x-j?)^e8tX8D`BXi)dqXDY z+sS|~!x>rSDzl;#(cDb1#<^O+IIEr()q(*@t0a@X?7yTXhE;K7Sp#UF22}8zE(w(o zdv-y}+k7J8g?qE|fOTp9sS^%0<$RoAx=MZf>YSZyWjl8?acr2)0}N}_rn;D13PA3D za>1GkC#dmw1gX1Tw+-_*d6`l*aQpX?D=4xeYwI&(Czps&fE=gn5ca@8u>-@;}@WD%;(89$D zm(uIqkfWM$2Fz&mDj*vvzjZlF(}Dl_IAc*z;P&^|o$rE(hzwD#Q=w&Nma$`#ICy>U z^NK&1x|QzW2R1mP%1N`a-`BFwvw(o83Cx(B#5gD7VCjGUb9Mk9SP06`4iIS40UtN` z9LX2kIeWF|$O4tw!?XD;eW^u*=%poq~yKHji`+9GKLP93DHf?_=*e zBLy1s8+;(Ho*&hwVWt(~V`r*M^Ot+KE(gf_urI1b9@DTePJ1Uq04?xu%G;(_#2UFT znOoic1k?9-PK$%L0g?-b<{+CGm!}aOX;dkePlTYU0ODzm;97^!U-g)q0XES4}J)*zfoY=qCtLY=Z^Ke7?U>zrPx3ZlT!bMM@ zg15{5Uv0o-aULc1&jwx!Q`(+9cCmIKS=5_7k#lhJp&2y68{ph~kQh=@5EZuj8=U7I z_qelKIPhnF>WH^dke{96#v5I&nCHEN&t_jzKrndN%fXI3wM*{&T*TxI&1_v7-7UtAVk!5o*Wb-wToxASetkS5pWMvPDW+m=x*TU}bTIKY z`%SRviLv80!&QD`2w%1;U2^>={!;k_d+T;FV<(sOb$Bf}fv~);XZMAgPMEb=oHGcm z+ED4%{Pc*tpJM~{G)`}agpJvA{?5a8!c%m!tRur0c$}0x9X5%+>esG`$-ioW7*49b ziN1e>tV$j=HmUFka`v=+R{bUr9`sTe7x(gzr4FOjPB6SnUhB;_$&_o^iPxT{@t^&3 zmmeo&OQjKe$LOz#uI-3t2W{H)!Jz3cmSt9j5ZaDy*Nrd ziD@If{eTELRFGq>vg~-_N)8Cekfp+v2q-u3?AANx8XbJ`%lMfSb{ZoSBG1P)ITrbk zaahsUX<;q(4Q=&>{Re`dn_h{@r;llVRqt@%13DkhOBM8E1y&>YpUBgHbSc>i{n6>f zeEaz5hu++^iR<;pE^~?j5J8CDLS}b}aBqmSGpViI-#=8(TBR|kEI=!*P6)z#f8xx; z1-s+X@2x}VT4l3ABWAD5++A*Xy}u_s#mkNgHdPwcCVF=j7CnDIV;rvejO=3R&{HkcfX<`Uw={&lJ5)gmjQOgRv1sr47{h94Oq6LcvVfI^U?jCxZT;V zGlf+*gg=W$K24D0ys13Db>DeQ4I5&Ly-HOk3|zOFGkPX*Zp@|Zy;zh&-KUq*_&Ceg zOW|;S5E_)UX-84hx958hl2LkwXrsXB`= z4mY~WxUpuDd}HpVLYjlcw)dkoE-R7WPy>f^OSDOLnmBTnsZO;cA^8$D=z3$up1vi6 zYST6K-QKlld}E#~bY?f-Kh{dddcr?~JU0gdJE~5kdv}aj`qjnQ=-rTL_W4`+%Kj0N zLlzcdY;%F7ddy9R}ZN`#&Z>aLy?bQCfn;k^f~AL)c*|`Z`H1Ibutg8nm_n6l#2mj(F?) zMi|i3QO>AOc0^|oGH~AQB>2?##yN#iuXG(FVHrc)IPNE~6kU_UYr~V<=W`6uHq@(R zZvgJ%F!uB(WU>VDc~`orD{?O7X??$=W^r{D_{&}Hd((o(qtpJPo)mKd_;&i;=@7Ms zYSW|dO3&x<$gU`F+#@swk8LYKOnCmo2H3^ML@r?B8kxK!n+XjoX^6#I?A;_eBwy$o zjP=lYcxExl$^GcJ2vou(xpNSKsM74iOI5-La7TzQ?KxL58(Sm_b^+B>Xegn_#mKU2(7 zx?HvTV_nf;@jxVG$uPG=>Iu3GbrUh2*^R1$cNwkoiTp~|sYWh@*2q}QN=i5fm6*2d zz@vYf@gTkilL{zvAZ{Y*aB2d%h_-0gIaT0RN0xtN`(){6ak$J|V?&TG~&?bufay=v2*T;AJOYi-~wnCFrfk%K&Mh~2-!r5i( zjy@WFezB*;s=z6Vr~DU;+;S%||HQ5XbO+sWnwbN`*RY|w^w(G?Z#4ab{M2&ZLHtMH zJs9R(wF5?CPSh8as4=?rn?O^(FXZ(6R>`a1*i&-D1snITAzAhh-{H0Na9&kRhv6%3 z7=0wwyo)NQi%--yf5szD|Jj$=7&gEge?Gg7zR}Q!>X6W0=KvJ!KOv!s+sZEv=X;fY zcbS$~V2$jMIcBto32L}**yS=>6Vd84XVh#|uQBjn1d(_oX2%AkHI9RgH75f7w4Ar7 z#`A|M#he|99H^^Q%aut9*nIA!_brr5$ed6q_iJ(-#gD?Hoj|MfsNoe~XAwvKz_l^e zqPZiR71k%73~bkFq7}KUS^sPO1$A^B$7+6Bj2~;`toV)^T5t@25SjOXnhQdJC>P|) zm>0l9P(~^L&AJn#Cp$145m0syy6PDH3N(oz%nuKIGUu4p&6!`loxQB2e@i;rWc@oP zBy%RU7b@B&(nA_SBo#1uYsb%c=Py36cF~^q^UXe{636+S#e40q4o!|G9{3gcoTe75 zdtDc22GULWo;HMcg%R#nnszUl3x zWG8ng2k=oK``&mPdc$NEjf6+xfaie;`6UC_(_ zfH&z8%NK_-r1^fvvd7>h<~dvx@NIX;u05`^=E^%OZ6;x{?M_0^sZ9@E`Z&_YLN{z2 zttK=+rlM@Ks)B?r=D784PDxEC%OB*zLBZGIQqM3&07~A4v6GGIo3AG~2-dDF*;hs` z^-EN80;TWm;)MU0wDVGGT?{TMJ3Oetzztk&gXa1e%4UgCrH-)G4#0_s`CL=4S` ziXo&ig@zHvBH{S;OC0#1E7(fqBg-!jrF6;g#2p{40fMg7mT4Tfevx(G=YYqbe&%zO8Y+z`R(=MEAbZ#mS84{ zd!J=T|En~HaJ;`IdPcx$pBK! z?5qTnE0AE6F5ADnj?ch^X@Be;QuwNoFjc8gs$jZiV)9`JOL@$wYe5hYIJ-``5N86s zYtNKDfZ6kQPA+Ef^Cn80|Hz!(z{61?hRIn3dv(j*iP|dl?$-kRAzUBYA-q6rTNV|( z#k;BpZ)$2+_%d4ZH0T23LqyPpIgiJR&x>2@S<;3%szD;_>iMs=kL4jBuX~?!MIul> z(xbx8hMvHv#RRAcAcyCLmdMa2+KQy9Q7_>v*NbI#;=HK)S-gwE2Xl^&nO<>~pTXBj z7uztyF!<_1zgOPmb@MNu8Z(X{v>S5#&AEJTPYrm#!-ktd^K^FAHaf_A4vZH_RTsML z=*ID@Rsj3AJex5>*%4B!ZC1w}*4Y^sWTB0r@U?S-9Y;x&y&@n0kcw$kCU+4kdRm&WO>7^%$zDKb&sVd5S5c1p)KBOTLu&1vIk6S*`9SOMB&` zPs&q>A1m_ludj?Ya=t_VH~?x4a=kE;i;=2r=RpzB;b0jI{NT|}b{`BkwB`;aNW5~+ zhe#5>;K}e*H<5(cYl~|YaGupYxB9Gw-@+eTdd^E9y~QbpMXh7>rH8}K?atEj`RgTU}SKUZINXuhtfPY7(1zRLT}# zkwMf^j@~RWlz!7|z;Bpu>+h>?(gBGFzXym}RV}-E#?yM@IUG*E1|6wtIh5zfS_wfplf+W!uWw4%&00W+fI$DPm0OlaHub?njQ$Pyp(4-qxn8l}-%RaRE>t=Jp zuj(d+=pT1@9w-1LYC(n$qoC%uBg=fZNc%@o`NJXPTw+lk1x=KY3`Y*lA3NsA3tNyJ zzkIl_uOTZw(|ZttQb6&xv4H}o!8ht%tUjrHvo+XTwnzJ;%=UP%F+tThVUwW1&((|~+((Z$R+|EliwoTXn@0AW+e3K1=@o*1kE*mC zfT@rkP@3NMoOt}pEcN#m}nx*2OmDNoADPjtw^Z=S%p7C50Hyvub&S| z97{{XGv1!DY=t22A_oA%f|y)R7yTK*#~!OBt@BemWa4gNvQtvT6>kC3s)S$IXFjhx zJTXl`eefc3tWA&VAB;z(6!Tif(P8he%h@Vfpc<@0FJxm|pLcpDZmM54iVLP>Qp{5H zQGU?G)MM{i-?-HRPhaQUzkkt3z#@9pb)4CURJdz4D7E~|F*~Ph?t(sD6P$6bl9D#M zXlBv0vrS~!V`IL`KW^9NVm~}iW6R}atD&%^?MXVTkwx&B9{6L7H|&_PR!m9y`P&a` z_}Q~6=2)I)7v1yMVMNDrrRXEMqB->KWdTYjFbQ(g2iI%24D7C{r@OCU+R?ntB`R$) z^^oj7Hr)VLV1EGrR6#sW;NczWo|7O6S3GzNe@i{-GVXNY2P@<|ul{Zg=OSMxEE&b6 z7E-_Uq)oDUxJJ#f<>>8aJA#r@<#%}buDqP2T*X%|CUtxjydrbKUBUyR&be98fD8pK z!OetS_+#ExvCOopr#UP}Hl~)t2lkwc!g(}Vna8R|k; zfT8V8FATV4{OjR%K=WW8sxm#%(!z)*2mNfG*9H7 z<|VcT^xh)~?GKT+D20r&NE8m<*#;z4!BK<++5hqLn8{&x-XUXQWFfEEaQrY`lItAf-$fFQndx^y98V-oC#i&U_!d z{|PLY26IVNeM0=31hrE4e3_fMU-nH~l~_k%3*=&fxDJwZ4vJVs04zuJQ#zF9Mh_#y zh{2p#7}uIW5L0=AZ_0b*^^^KLxTl9z+eL2*IZEyK^;-7^FN95CtiZF%yJD$GydJVF z<1L+u?2^-$!S(_2WHJ=DMOojXnV=ba00=CF?&g!c9(x_wi0ZBDMd4KTn7WgpWjnW2 z7nH~?a)D`z5*LD=8EgO+|Hk7Lq5V^&Gq`CK9_%|Y-R^k5tg6rU>h2rQ<$kT?nnBaI zk-hK+`78CGV)e%FmdG#IzvTT4tVg+s0EmG}#YnVq$2zywQmq%l7t`&oHASmM6eNFI z5BU_F0;7y_F2xJe>1l@J8QW(a)hC(>{mq== zqpa7DsMTN=%u*32kH7~ROGP)v74LSOQf;akHduq_71v>j4d8{`Cr_r*eG&e_HL!GF zJ@HqqBTxAvq-K3NOvUGyMJ2a`cTxewk_#*YgC0?;JKT&;c`23q@n(E}K&y!;iljoC%9e2o_BTcWLZj_{8mR+Dyl!n&EX z9(j_|%xHiuI8fh=!l}B(s&8+&ehUtNmk^U)F9L1OZrsl>aFUbv3@@4nr;ffu0JX8m zx$zAjj7j<$n&e%x<}ll^B)jxgn@{PGnYgAN2k!IGMX*-OiqmV$<~dqoBrD~wmi&no z$U^<}(V<_D(*J9^%W@D;E@pCN0>|sguIq?}9!%mckynl1y|sL>+rnC&rd{gO_j)SM z14x=Z>{}^Z0yN7ls?vOS<}_iU0n;TB!hyXpvb*n_^Zl1dhLw|lp!~&Nvzymb55R%6fA^=G%SYjlx2~6d&$`VCjSQzc6F4)0BrGntw@uqlq-Sv;o!_kE zb?wJ+p*QR%+%YE(!kgtMd%3?a)#X?(<$gPv1El#|zz$}2Wt7ojz6v$1B8{TM1OkDs|oKCwyKk^@G-Ele3im8>`sru5f1lZ{_cR0z= zAP9XJ?3G4(z(+DPeOE31p2}QMbRf_8zO#b)c)NtR-0M@)y!Re;hYcbPCsvYMEI&}2 zZ(zu}nA>~z63dN-j5DnLVtB2WKdwSbB7yY>jgMl_sHG!lO22}$sZp2eCn6XzURpD= zp)7t$M%P^rdv4dVMHmb|h+O2OD)05Yvb)eax{ElxcF&jCeM!>UW~6VpjvH}!!!dh| zwKsU1E2G7p^KCTi0<4EG%`JTw%1bwjT9kNUe%vF~k=>j3m$28lN7#}d(RgniTyzD+ zneoQ>_yTQSD7vEkUVd?TV4wWw&k;^8Sy|1`YX+Bfh z;d}B5Y|1x3rXCi3{-$$~N9Zek(at=P;=`L>F?*=Y2Rf?N|kQzm&Y^hY}SmuX&UqgRMf(Hu@H5r{UD>D%yna@#>ZUaErm-@ z$jeOrVNo8f2b7`tDcXzzgp?x(LID2AY-v#<)`#ZTHpwWJ%|J}=EC$)Uo@5HVx`|Iq zOFd-;dk73ybI?h!L#FDnZlAu6wMkGN_TcrOvb_p}BP4_^K@pnr=r)T?gy_%}H&alA zf<31>Y?s^;g&$x@*ti}$`QdLPJsg$OxGwH_E4vB}l!?=5*t z8%k&nmfI>XjJsK7B9F%JeHEt`1GoW$c8>0V;)`}Cs67HzGiU85wV03~fz0Al95Ai# zez%AY7Q@j$tk&Qon1^pNpzHwx-46wBshV;9SK5{QUvZk`6d2X9jq^po4yqmmY-t(YMbeMko)QWc|T5bitl0W4^EqX=wbo!1sP6I#M%L6*v3yywc{=7w7;6vlg|d~6_^R*j~;!wi#0Jo6YqaPe|sQ1_uoHt)7j{4iT2ZjDlN36h9X-4 z^$H86dTrsdP=oqofUDzY3L_toO^z;cXkHYYZCJmO-AM7xh)dG5m%CP?u0(; z^v?C64R>-BA*lnEQkeLPRM1KMU%eHeR$q|Zq~0i>s8W8>PggOgT@t@-j&k7?+E=9s z&$ufR(X@+ClO22Bg?K1QoNfNnCk>!E6;;S7c+<6_><8iC?z!D#_-z$m(Xi7E*7F~2 z^X0_aC3h+4uImz=FdmLd zA@M9dc-xzKWD>!Kl7s~w%RVhiH+%otUKd>)wVinuYXhO*9LMfWcXD{-7!HQ z633mGcKjrz__Ta>{T(Hr+h^H)`0qVZ-cDs6vEx3qfJhmURYFm1{5;~c>MxXWAMk-M zzC>2sD5Y6MTb^$LKJLb>@1_IqMfkZVPYdPiW1VhRVOihl6W%ShW>Op(U+E|yuMqA; zLZ+9wt`}OAM^btc*YAmja;b#&_nkeFC&(Wy5&b9lpnxnHHdqpL<>Kp~#JB7&hYl;< zi-&ic{4o7_#>fZ&NExowY!ISuQcDS#L%^Ki6Y1^qvbLsR)za%0BYkA7=F{AuW}$&o zr!{%CiW;Dx$OP@GDF-$39aUn%va6OrWWCg^C7&Q>I-u}lIePDd%!BUGUTgSGAT|%g zAW8t0Jlmr9lWwZ44A05(cfv9d_v0^p0EILi6*z>Oq4c*>RTowHdN4;UAMIWW6&^)5 z$Ykmc1UG1WgP!@*7L@bi3Bg!08=fo%`vu!;M{l4gWhn+2KUAvnY2}9tCSh@&*YNfD`2wtqVIwMNy(iZ=$dZZmY~r zlrZWR>Il{O25D;p)O%Acz9p8obNdV8lw@U&HiF$WcJ=c*cDcmIS+ld^utj&P2 z-nH#b`JLh1i&XH6*afJgU=Xvwz;>mF4qX0O|6;}ID~-!a{<)md<69#}o>7qKKW2OA zhXLy#tJcqdYQpkSm3Rs|(xDfD{PLgqo;lHvYU~MrDYCiW%rwOPqEp}OI(2Mn^>V&I z&ddX_SV*QotllTmJXVeEJbvitjafM>ikYFufB>KP#YNY~xUSQt9@+CkG-sMD1XBm? zQs?-!nxFL6;8gC7vCscytQ?6HSR*r8M6uI>2nV5wM6a227~V0A_L-&y3` z;@SQJtmrPw{uX|SdU~G7z5qMA)+X_Jq(0rVe#%K8DqQkSppd=;(<9{zE2~WS*v^fk zw6jbcMidihgyBO!$(gyB)U|gs(m%LDj-BSB?|OOryN5r-e}57i`72fnLboKn$DBoBzUXPUvvOLI5*dbJ@Ub+R!}h$8D{=Znc=kNW ze%uLUBocofr(qUnM(N;e{E~}_ z!r*J)moBPx?b&PMuK%$56Q*9ms{_NMQBWZv_bx+Lby3ydzkHa7ZaH@WcO|4^tTUsU zsfw)*YQ#E_d27A_lVyLgX>r!=9`T&pr8%}x2W)FB4GuC>hrS?;7=<4;(--mo2a$o< zK)RqLJIoBLL{is>s=Ls@da$2SA6`(8D-t<@WNF&yE@(^vHiq<3r95Y_{+&0^iZb6^ zk5ZqsE33jDL|s%*487j6(}Dgrdqx{da(du>7`Ei%w5oq{Zoar0a)JtW4ZAUxo~^3P z{09M@n8M`ml}=b1tl7_0*!f4Y@9#EeM(K$S2X|r+(vcMoAlDrDqEEJs;x)6c#=u2JE+k{nOp zosNM#G6~)$cuX|F1lFCICnhR_tIuC8a)0sM<#$=3|Cx;k-wceMt_eb%C*XBz#8k2^ z#a+C$;*od5Sj4P<@L*tU)z2fNkc;JFF1qticODt0J%pbG&1Pj0K(s!pMGm*gla@dWn@fOB;xFH9NwQ%kP%XFZImiil&ePC z#VRohnR@iwAKS)FMWP*6uGfv0xhy{y*DrOB&3auP!967zcbP*gE$tt~9V-4*uVYB+ z15f*^VZ|-LsjYei#JH#mGH|M|(leI)iNBJxe~=GALbCV?3RIQE6C`w(h_n`Y{^8~> zQGBej2ye~3sEUPrOtd@^PIqZ1m;@^>AU3{`cL9&kqSO6k^P68nkdx7LTkyomceB47M(Z>?ijOowrk5BU<=WyJyKt`a~ z-6?;sA*Ll3EiBANhtqb3UO{!}Pls8|1?~Tz&%xvfyl#&O2w#*t6W(p4%Vj>Ju63rb zZo3js4so8EIuIC)odHZSn_>{99k>_l+&&z^es|3FuX9+UO80FFPSz2*2j9rt$uz$D=yW z0#@Cy#R}NNFzSR)&VX^E>&rgkHx)2k0yE7S=L8_%RxBBiMNREEC=+jd6`>{7Q&;r_ z#cyXiPETcy7n7b<5LpQBC`r4pu*$B=@2_h_>-LQ@pK`t-_CkoR7%+|tm`_DP{zi-= zrGsM6q5f9@cqg*F;RO045;f^>fBJ94w**Pl#b>fHzTmiyIo!vrq4SO$9liTiBL~{~V$trRJRN zpZ|j)Rcf2S!u_o_J6^NWX@!j?JG*diOA^)L1k9;KskYZh)olf30oCu@CziKI3}UHy z)bRf{xx$?!ZK0S!jgRTGPT zaAqPB!LSGRINo@m~^am0|}jk2w@IZ z!l$yef4W~jXZ6|j_lfJ)&LJ&_Vh*)E12M?_?sDXRDV1@yx<&ZJ(XU~ThBz1Bne#J4ZhRBnIC zS6xW{)gH=a7lJj}BYKiC6y})e(O_}QZeWUWm&s3Rd*d+2q+pN3a!*=5U9!`-5FR)9 zknxK?1-p;x&=6GHh+5EuI85Gqt-r;5p|nEkxep^g0}tj?Q;$@?ggDPy$4a(X2mL?F z9FQqI#TU*=o|qzXY7A-~$WrL>?&FP0{)`{Ki$^IrA+VZ zI5W9qQs!${x@G%$`)>6w`Lo^V09w5$knk%1D3zA5uF)$?4!x}D>tDUyf0lE2S z_!g6rHno)pDj(M#u`%p>rHPi%JjQ3wYk7}3EPKr*+mW3M0^xnugOo*e_*_HPF(p1q z?l+a1kQ;!Y%fh9*^E{vc6rs9f3q_t7AMybUC8c-MK;?pM>-YW6xYnJQUY`pOk|-+n z^9^=g=8@dIXc0Dlsyo1qd#RclgGG9IZsZ7T!8Y*Drnyn!1&3e$Dy9?ac5m5{zH|pF zhUPNI9LK>^TCS81yp6ROd7GjNv(1qD`KHN=Aa-+g`gaqw8s#V%4$s9%djI#*p3>#} z-wnne3!5*hXAzH$20wZw=wQkfcnN#;G$?SE=D|c~aR_Hec|r}RIsPdYrMre|XG*(a zrqL?CcE66^PQmyq=RWIyk54pV;WVE7o3M-iJ<8;I^d8f&m8`DuLRFhQ&k#0*`~^iB z`vdCUOH`*uiS$3npG^a>Z^w5q?eoA69s2|p_#!iTo>!GGnI5(%Ap6Trv?DR#@NbE{ z!>I`!zck{s-~x9Kod00y$5b7e!?*=swshWGJ`s$K2o}mKEH;yRYV7VdhJNajDi`97CQy3Hv~^KzMSQ%R9`buoBl}shfX$~*2DkXn zipjm!VIU&VgcVBrH9K79VooI&=aWcomYF>un&Ec?JpJn+980_~AQI^&uiXYzZhbgy zZV>(J5o_E?Uf&-UHvdYj&~`yPVg|an)eaSpPVJqO&gXF>^xX0td)?*~UGeNo*r};& zO@{{iZ4ihMR^?bebyRx~!iLWP9-ws9|?=4Wb)W{dUX%;arcjosG3-j1f znm$0&3xml|YI+3K-YuvRc_No6qC43KD);d3{a5nh1v@%v4ztm0K!r{iy>^s&gewK+M|{vOk(pfc5L8Bife)$noCLmf zm=^|je_<~X(E?wbXPKQ|6Ay|h&^jVhFp#OQ;&e*vqhW3uZ$-)hmLg8=pan$-FHk-# z3_X-SlG=+Dt81P!oni~a4e7d>r<_-DZ<2OBd&15*bY*Xn;Fd@=AT-=QY{*;D0o`3! zh>Zcg@)vuUPrBHn1i!Jr=N|lnjEDk#e|Q5Y7C}|IhV6j!2Vw+FCEcmEU4~CBMz6Hh z&S*cHxb0vybKJ(sfCWcvdfgkdLe{(e7fxIG2dRcnix4k>P+4c$lP$vyTR1jpx2SSb zhRIoul4!YCO#1_nBO~-(>QS0AJpgEJj1f)6{;VUsKjg&_LuK8c7?0y^D)9-iv1K)y z>b$o#Hs;j8F3M$&OKXvOD;8{L?@j!eaY_I!=*Wn^q5y{bn7NokmrT~#4tzYE?aEp) zphcBY1!!Ke;fz-i02@ZvA19>RV)FchgDV{t=xE#^6VPOi{1hGqA!drQyJ8x z1e|dyB@U*G@f`%ZnT{Ba`e>$*J8ob>eolL0yyx?aKG8*(K4SaqkMA@>n)6E}4wppy ztJW2)5B8XqXM88m-J-xzHdEWn>Ruuz`6WWPzBK=yWlrE24UB9Hn4euDSPCUl#mt8{ z1VCgl5@Tca$brm08n>+e5a_0UEp3@pUUs@VcVw@D9 zr(@Fe_)8Oh+}7Vv9%LFKCyOOffjmZ+hfQVw)DC%ipUO81b~$!d6>x!`8bhcM8dYWc6DS|2OS1oXNP zmx?FaZc&rTb_9Q7Fj?-RseB<^AUcs$otIGF;whjfNzBmctTb_90-pv`iq7Am4M{DU z2VGYRHM$HoY+xnpNCERmCe7pPhhpC8w7A=dg+9tUcA;>8(tgBLi`fT~Byn)pfg0R{ zV|x?;PqMUN3w08+mJQ3YG?0`Irb({B2hnt)j{-D{wP%tjubF?4RfL)3fBCBdIbnA5 zPhsFc$mdvNX5NlM6A?y!KS?+ri%jj-M0MWWwEe};9dexKEvtY8xBKlw-mI*m?dalz zDn(DcW&pr(& zxzdToisr`)Cy{0B~ z%ON|e)!$nvyyH_ALQ+Nb{XGDkna(9Zi9Dv|P@tVhJ13>!_{+muw&ReN{4bsz|UdkQM<}w?EH+*2}U=1$RE1m`I)347xxE7j#-y1SWkE(ySAnjF+zyQCvsc-Dwxj zFR4z$=N`QH@olZ?`wVt=NM}C^KI%_DmYX?!4jO{6XI>fR?8Veil!7g)hKM&jpxZUp zr*>YFp1o3^jaYf`bjcd?ZJ(Y4oA9QFH~${IjjGK9gepNC2U> z^x6~h-&I@YU-;2CXSTO~7|g;O0P6$+t5fUo0A*N@1|Vat$>$M(A~fD|BN%_^9+ar{ z50WPV`ioIUjSiHm^u3rPQk1Ffj_bis<_lEnK2_bjHPnA{8yO}{_iqdUrqL>Um;JNKJG)%y%l^1t*&Ew#iGami6=g zh5dQ87n7j|y_@5E^O=9`sLH3Q%5Hl3h4P1`E*RZ?Vnt_&M=P2bLx@DuOZo)PKD5O zoUwlAco$3crNXj{UCBT;3r%@XvP;x~3I`R5WGoKZJQ>n-yKZjGbYm=Lzxy>~sVIq; zJQV!bnR!GKwm201-}X*ulh3-Jz;VNtJp}h0k9*_x z<;oM=7gnCPeOvJ%&hAm@&2@D553P*%f7Pg`l<8vQql>exRi=Di@eYPI9n1St-EDS1 zPW;fz#_qLwOs+!d#{~swl2l8R%?3M$YJO`mrJs#C02PcLqFW(QyRIdCD^UCjahi6X z&O`DsWg*?DI~p)CV$>lt`^h85)bpFwz@u}*145!=@&qu~AEZSvhv%h?B^2XYLaI8y z>U5{7kloy|xBN7u`afy1d|~OjnWf2MqD<)cAsUu#0~D60P~5PaTR8W{t@vu=m<2VS zlAjGcy*S(E$Bi*rVaultcf!OP9jeRoEy44=A(`cXZse$|CIajo#Ke>9IcKH07fari$Y0n+9V0ggh4qVQ@V&w zfZ?lA+qWoCigZ07;5ZC(?p$~1(rz48=;rm#kri{j_ks5;)F!nWK*9N5|JSIYf{1)p z^*<*)>YHt?CQhjKJaxFZV8Ie4r!rTzeXnqzMsNo8SOKMYa`(A0>H*_jcz|)LvTeYH zFwUntjr#2a8tp?j@^%LAId@?8m8JQy4E7M%Za@iN6$s4FL3HS0yc9`Y_z=L}9V}z5 z=4ol)rSF*=|HsIA2x&wO2AWQe)XWO=#rv*6Bgcrtc1GfvhvCaR(x(LTZbire36`n9 zC{r*Zb{R%3_)#H6N!DM$jqS25Tme__fC&~|bPRE~yYrsoaxsgd)KI^27ZIt4{P_#4t=G{zR)_#QITt4x#B z-+~V`(S?pOFYk2&tT%$0gEfN|6<6Owcg&|l`H`&DeyCKe-WaN`L5UCzKmEy4#qOK6 zK!=kUgkc_Y4ZI6=aEFcY~FG4N~0^V*#qjD>1z&h%6E4twY8p6=^ncR8MADZ26(y?J2~lguZ+!aU9s&ctkD zc7yFXHF{(AnAdja+u^t^0`NiwDy6WlORoQis_%}c`v2oSLN?jiiXwY&j*@XmMrFoP z_9oe!V`Oha$w){<_Lf67*(>`PN#;4?bjoqQ_ucQ_f9_u%9uJP=b3UK<>-BoRo`Zj; z3C8B?`RR#4{M`|S*Nl&Os=6V4_Wbm%SN~+D&XW9&O9lCC>rL!^3{-A~pbn0@yYoC{ zYbmG}zaC}JjM=RhIpP|4xWz%1c((p67A#(W$APsu-@zf7Y>>gBLv%$vVq8M`mv%)_ zrfl@h^;{*Q*uwYpnmsNem522CH5Z|}S$XJ%up0y)hkG@PLcgyD28L8vnWZI3s!nZx zv#Ea6lE%PornnQ`*W1~fk9}KIyA0>>9d#Fi7svrr-SJW!(Xf1T;v&)NH!)z@{O1uV9!~?JTA%_4Ym5ZND>ETU^6>x zJ6k3N8!)GV9X*_`sI>9JW=&F`9-;Cw0_X*!+z``H8a0MW{P`mrp+|L7?_^hc%U2D= z_Nh-!$TF|?P_~JW`%pnnYvzjZf<1!=Ezf0V`V`my-dyXNy?B?Z0SSYtqX0J_b(#rC zGtLMS#1|+p)CEOpuvJ8^UHEDiY2IEtu0(O&0h28 ztkD#6p=@Gt|x>wAcjr`nhuG=kKtIYXU28 zPe>h{DL8s+Ub+1J1s21|`j*~f{4Ev~`DrLBhF5$h47wp2b@CIpG?**4W?&bW7GCxJ zx_xHlW4|1laicfHK{n43mYf`vnuW- zJ{LVEJILuX{rsc4)r~?*f36Dq{4ZO=-vy#HN$JhS^UZS*lc>710o39f{TagTE&PGk z^U*)|ME%R}%?Lh=Ot0C|Wxk~2qbZQu){itnkp|<%(U+9}gCtze{SQ)Fw*c%D%r>DL z`KQJE)z)BcVbJ7DFJuBYP6TmYg9`IKF6KFiB$_!L>XQ<~1+>VBNNUTBF?W#f%G{?Q zO{K^sJh&((DifzT=K(fLLkcgl?yS!+{c?3Hb(P8TD)}vL;iMhr2riD_HJ89%A|;TI z7LU)^(E9n&0{pR4Aaj$X2m@~?s-}0tMuZE_=Mo?#-uQ%nmQ2P*rz6O+=s<=E?SlxY z8Bbdl>gH?e2s4?KOIxBoQ-f8zVM{q5Hftk>&fi>C%C?U&Y2kbG+r6+&-TiODi?mzx z$QMWvLOOWu*k%oA80qkTkXPWlsgIg`G?vI7A*dTyhn`pAaqs+?i0G@b&qZGidsQvO z8)#GGXoGj%zcVBikrSo=O@EB1%SOx@@7>MLy`S$NYM2ETJvqk=J+hAOA!7(3_KN=b z4+8$mAej7Vm^UyJ(8WOLUo~Tj5um~)7rLm+V1;fd-C?own(=^btq%znRR^gIW7BYr z_+D@KKtG{)g8ioDizhqR<&8f-yUe7tWs)y~Ch0!3WnBTWVMHp_;9)R&<*a|57#{*T zOT#}eI=rK4kKCxs$kbT&%?Hnz;z`ZRYN*3{ig^*w8(csV>@L>fUSMpPwHS%kn`jBD zljii>%bAoUev$BRfM>mpdu2}Ko%o1O4U>3_M5}*>gn=iOKI7s8g^)33eIwKtfT2wr zD9{amF?Y1norC7DXZ7d{VChqK_M zmdFi&V{!QCs;DsZg=fi;SpC>oAh5n&)`xC@bZer{ACqgeLA&MWYIcPyiG&A}2oVB6 zBD%!)t%z@`Y+MlXQSM1Lu=mTVuxn2REi;XOUK9Tn)*az<8|b-)e~uvmD$uM8ZG!eQ zDMOck{|EUiH%al~9~`QO^ibVbJ}ASE_qC>!*t5pGdBnM^}QRxkk1&ln3f>XuwA z**rcp*)+7B=)Of;|8pOgw10TVDU~(&)gk>}rmWfvh08OOnZ64<$G`UB?Qo3FgCy_7 zE$Cp$MTiYh_2&V^Hw{-h-T3kIePucE+tp8k$(ufJkEwM$EXas!xhv)yLmnYi!FnR} zMRJK|OZVVMnY*&f-Ix-}BGIusP${~OIU!x@ zudTG^9NptS(!ZKmNY2vwP|I<+JdnN0g(3~wA7Jo*x9)jF1(cXrj2OBksMfay2Uyb2hJ<;tc4qor2RbUN)X3NQiT}{7qr$N0x zQ|$L%)&d-)xeb^aBbK4RCj8x)$f$Uy**xy!t$W!_R|W3uF{r`@e0i& z?P5d!|Ap-T7PK7ykFfsFvxdRw#N}OtdJ!7%RSDgeJs0+D)cHf-Pt>9VqJ_E%f?LZ60ds&09Yqnx)-{x?zyse8*!T!^MdKxu)`O#pEgPTMJDk4~cu8h$%1*Dt-S4g7aTb$Mab zyefOR!;?oG|-7pT&d$eDahdFPA%l4aqU8$?dp0C(X&+tI8KlOUb5q%NCkZtoQ#1vn>nd2)UaWkA&78p96rD?@zLoFjf4Fd{6}o=~8_v(V=&o!mpEbUC z<4|=&V3aTEM!Qk%FwKEOI`@%S5H*E(;cA-x$=~L8jIilpr zJx>S(*cX8zPofC(kQeE`&bZZ-^X6X%03|xkS zxlC7!qgeM&q-cFJDX8xo>0^oRXMk|a9&=Ib-?Kmz^aD-AF3_)3p*LAPLdzKj*9y>@aFE)BS@JOxv zA%>2jrc%qdV}^et84MxhUnIRoZZtz($8}W-b&2FFpfS9(29A%LKxeLMpnNpH-}~E} zS~mXa=U1I&x34jWw@X-HWV#(reBoSS^7vlt8=NyXwOlgd4A!Ywee+y&*H-wu&6EN) zjJ7zvzCNExMtRT_xb6w1SrKKSE?x+=FsD#?g>VSucZxfaTJ+pz|F8B@!UsG$ z$$htwD(nrHlEWhZ(y~J;>vJWc9aG8!?Jy(3OhW+!QMN$kr}v*3Jt%A(Z*=;f1q;Kk zW4I21>!J#wPPjDf{hT3YO*mZgepiN5=ITc5&NX2&Hthm#9c!q)>s;MceuPRMzx1YT5A>7vn79GM4&^7AY6b__rF;} z8{QJzyNT*i9R)2<%-W51459s{J5P7Zlln&w+5$^rO&?}8ZV9B*Q%$@J>c9K$MGt3@;iNTwphHy^B;m5hV-`yrv;Uyhelw*q^@RgQJ>Pd1l7UmhT8=eS%KnQBaw;ufud zY(?o%K}ZXwtFg?uN&tt81$h$quoMF=OI;~q31T_pCQLe7*=quiR#;AeoglZvC5^D1 z)c@t7kmAa5W*7M=uYFY1UxgaX@#YH+YRp=t?a`o7Yd}GtDLMhdIP^hK;2LRYI+gqm zs)Yh9X@$TnL+3$&W6L+mY*jGhuLIucp)*R@>hIt69h#ES?qmwMq{upPk4g8C;ULnN zeDI(bGj-@-nf=_r@y1mt+K;iOI>BUDbd7ZwMo=uwXu+LN@Zr}@#`|k9|Hzhh5$Di0SG2TfTe6KgIRKrzGcOz=A*<%o5$RUXP z6DLRVHxBG8@Pep8BbFe011#%t{BzIiHacYaOZR4Af+AZYRZ}GrK7Kt=t3SVSNf&Wl z5{R)DUY>BToe8TZEYHZI)nkheiRETxJqvx-NIMy>a&Gj(nLIk-T`R^mTD>tz%=?Mk z$gY+s!>wR42gW1OU*1G&WS~2J5++Ld6O$sZR73hll?uj6Dd(Oar2Nd2&UuhcHJ)=B zWRI?gnrPXQ7PfgoU(a*vQB!*7@uiqeS)t5D(U}S$h-oAD(pt}{ne!B+*< z|NXndMW;_??G~RVT$ioI@nHPUuLb!F<7ETxc`S@MfpJd1K0k_bh(9?Bs!xyrNA|!3 z$(#nC_3`CLvELINoXI07cmNJlq=0NOKeR7j(z5r&@|jq8PT6bTy${URI2;7Adw$2Z z-aHfi>q{k@^SPyN?fGj0Snv2U0}IEFbYaM)kbIGM!eW{rL&k`rUlwkO_|n3LTW@OV zb@g)8vu8h|Q6=Ya4}PR$&7H%~VCo}GdI0o7QR)PDM^mEoWOn@U)i!8NZsH#g;_y0e z7YAZyiM=PB`iKV3J}eh#6;S4>tasNS=Umf1j^s|khxf|kt69w)7^vmA?(|F`&pY**a`x_M-jwJlB_#onR&Krt zyw=hNQ%HM5Qd`RK(K_>99(KW*_)Jfb)*f1PcJUAtT?L_* zH#h~1%xxLHNrlo(GP?oA^YC6zFZ7{ZH?Pm_UC^n^hyB~OdVn&)idi?ozX`AUnYU9^ z`qI6%n)6|flEtCS(?`bL(j1ToQDm z`fl=ruNtOO#uf@B%3B#xqPSz+-$G#a#=Z$HxZdB@&ln2bd;n1+(fzrTofit=9M z+dyURZK_f+HrIMcwdRWW7U}{;9V2lHiZNnH0uqS`L43x?y*#hB5-S64bEn~LOMa%> zyBRr-HY1N?{ye)aknE5avH!OS{0})RJ?sa;TYB%a?K6X)&!!kaY+???9_g9}MEM>V z=@Ttf(SE0INy+l*%coH$8oc28+#)LCk9$<0$z@pjv=WIHPo5RChQ?_F?gw<(W9e&; z>#z7w4FG|%-|QH zIla2`YP!Mp)voPhgNsa|LQm?qlS{qoW1uq8Q6${YbUFSC^ujSPzSO+qxW)^2V=Qk< z>5A=_2KCZvxlFB22LU?eSJ4vFLsbgI} znn@ z9CK*&SzT21Wab}E$<(Z(zkC~#=A$_=G0$;M$sOR>v_MM_P*8(rKosNZvpfI`WME^{kU0%^|?JwqMP6a*_gD zgk1p9Gf?OC`1ZJ7IOi+gze565&BtB0-lcoN*!ize4w8}Ds!n*hpN0~t->AtV=0ehA zwf%UDo>q}ixKrv<@KB!CjPsTMA%ZX_D1=BBw2Vu_$9ZD*ySwylVazLr^1TO%Yily3 zdf!H`(2&H?{tFvCl>>JjFHznuV@sSY-$&YSfq1b1*ui9ZZOttgA0*gnQGoQxhlihYgjwN>u`O^syED#E(E`)+YR{aV>8K^*?lK8E ziSt??ge5fpX;&vW>OlqbPF=I)$0DNT6007OwAp;6APvkNFhb0oDIQdWItme39&Amf zZYs)DZAk3}zHGJm_9H)V@c!9fB2b;+;z$IHg()Re=c*S~^IJM6F$T*?&V4wnG`xodL~UD10IjFqJy?` zUV_d=eT4g9004TgLRpIfzK+VXsr+u_%{N|G=j7}S9mR^Kz+O)jt@?JXqy_nJAoh!WB z@=4VR<@V`E)ciaUE3jRCq7xWsSD9FH<8>N@WLOA9BFSiQgt_6HFsjD05*i%%)Z^Y3 z_R4GRYzGRX-L$+y>)QLg4kCs1V@<0JOLrUDr6m}*&I52 zSZ($2)$$ib{Sim)2X!RRsK_EThr4U0{ge}n=6YT21Z%gFsFDCGeze`CkeU<}<{m1A@3IE>-a3=>{PWKt zgLjQIj%akUZ>Fw1J4usgv=B0tZB5P?>PNI9d!!`9zh9(vinGX6rIGJ^$Ry`~>D@Hc zEk%~DU+cl!$NQ?r?V{1k^AP0-PdIt3Uw3QrXv(10*k-{^!id9(pJXK;*a^{w{33?$ zDh;aBkw&H&5nF1`cG7h9TKg3G(k(E8A}i=!iS!zeqJp$spY> zcoVzXc0eV64m;<4eA^GKQKUm%*&f+YkHK_kN#A)o3I@_r3VcweNO$i+p+Cqj_n!;6 zPZ^2`7=^#Da{J0!5Hss>Cwf@*wh~X|O<=aJ0cc=7Vj7BJdKliMt(Jwx6gKsMHPs={ zPn?!FES!w7vR5-+df&MUc}CLH^K%>CxPBl2v@~{@@uDq0W;Yc?Qz`s$c=q=OXFA%i z9qBS7B&t#QtmD$a|2-S&+>sQDidd(A-<<7~Mr2&Q6?l!d&A?(VRtK2a^WC8flLn`{ zXCdoF-sv|^ZA-z0YW)f&r)8G5?)||K2;d*)9%i2#;<=YdZSew0V#VC-@?YNPUN$4}%g5;#&dGMWb@fNDVV_ z6yC@HpbykTyy#{q-XF=e!WbM}VI(aj-*CNU$ufS$++CQOJy5B82lWvl4bKcwKZ^&) zV#EH3*Y(jLFQu2>k6)92uKNaEx+>&tD@?k*j`v$10OSPO!kEZIKSF0E;m>@PhB$Gg z=&I!NczKFRHJgn#E6GO75lWH$Uec+I+2~l@P|ZPF4M@~AMxu*z*?vQtT2c#_9%h?a zu)MVU=9r*$Nf#0&rE44{N0K0PxOHwl%&aTam!d^asdks1!S;@W?@zqh`oR;-IxY_1 zg7r3@*Pska#|K)~M#0YLY=h%TBw!>q50%qLy3?uC6^@jYCi;;-2pD&qACYoZy&c5m zsW%KI$u+al##>N0!kp;uoLz%)2t=kcm}v6dafdemEokhq4yp;t<8jovd&B6K+EAX& zkWLSOw6OL2qebA4q>f?0N#NVg@8GxkH5jJ1o2HJ`1g<4LZ0*W=*8j}Gk@2bc!B_pZ zp%FrPp$@Xz3~Z(Q5kRQXqax2mla`8X4C(P>dH=)K@+sxs@)kQgQU#q~BaksDFl$UP z_z(JL-+EtEwz~c;sOavjgy%+J>XNLQw`^r5qh-lbS^FhDjy>(L!E-rc9~^Y+37wim zp0@fa4>eWEMK1~O{A~B)`5St@&38_WsFiw@xBd>c=5YntZU$PsOEBn=UaG8=feA%G zj@(b8iBzyaSIJln(c3K8&XRtnArlL>lcgKf+s;Z)=^3Bekh8rAoA~q zEs{%zv$ zfuFbQxeUP~XU`#$>r39sll&O+?fPs+9lh_bVoX-jDQ==t#h`$9(}nzdO7h>_A4Qz@ zMNFs7xrM9BdV;6gZSRc&W}SS?gzqm_Vd7Jd0<>cs(%dSg#J;x)LKwc9|D50f@9tWd z-v*MxomT*ab{w3IUMMUc3DjryRFiF9Ys(s!ZPgK>pEf72r7|{PC`F;uI8%#+deS&| zfBG|a#r5%qF2_BP(H1YI&XjTXF>|o1(xEb?(1KS$8P9m2Ffa}p8kw~vj!duL?+CtG zFb|fFG!6~YB)V;KB!nr%FbV@0lI+A;1jB4+P~puMOjnxga}RW2v*I%&8DUr5oO<0l zW0ftz?LrEU8eqQ)KI*sFmR_Sc&fjULaPB31l+ES2W5)&sLnqs-ERAIjvO}aIm+hzt z-v-GRR>0aGW}{_Pgmamd`zG-&w8I8*xD#V@FQclq=X=9jW#e;eSAl%)=kmCsL)i~M z|H6Sv`ueeHd*V3r#)ZE6FO`9q?=8<$p7qgVe=&A_DOACh$U%$tYK792C=V z6Z@zo=CmVWjYiP@L8#z94Qs|oRbBk75-^vzPt|>O!Wj!Pi`}>2(MX!6nuHMZ6!9>< zJTgOne^;D0IkCuvi^Y3m#+Ntw(uiVfVfUtODG3N7z9I(x=DevyjDn%$#*Ejy4!!50E;jG{ed-4k+L=l>vST@n_%ZHZpy&@F zDKX^-88w!xEB$o+XFGX0Sk;)|0*QASIr3_C4^8`M0p-&v0-8GlHgW1jz3Yw6gA-J{ zxHTS7d2Nue>4RJkw)v&(uTp(&L3hzcC-O|7LnTRu>}ihf0ah>bo!~+guxb5o$(QgH7|e zPEzz@CY`%wyG3D}3O3Xp6RcPI36T!xwM96PJQ= zI8JTmYr+*_l8mu%Tv3vIMGkSfPsT_n4@=wD9@d~&FZ=-57Suu%G~9?~_0-$k(fEaJ zXy3#Y7lVHo8|G4Ti3eR5a2>ulK^z4pn${_*DGz-qysyhWdAXAKWxZ+S10QDgFQ)q^ zu>dF@)_+W+7?G~f7!4)7A~p$*G3paHI`_7Uy{(qJbLa4RLz?u>r~R*FE68F6Q(xB{ zL}U!re6Jx=`+^56_t0}wapn_nk@xhto<6X*A(*<#I+=c-!@@50Ee50~o+Lu4LBe-x zIKy{s2x+x{Asu!-MT2Lr+!n*u7P@h$H!#JOM3W%CbFvK1`jLWiQh`GEEO1v0KD>C3 zbSdz=-!|1$lz_PYxwbQuGDEQ=bUxo5=Wf;>WUe$y{IH z-S&8lwj%#9Xz5N>Y3eJ&{_gss0FDM5cW4eWX9fa@*PAip3GZ#VSaS5}W@lDKs#2rm zGsP3*fBs_5ybsya?NL`B`oF%kA6$W@U{EeBb?0VR3s%0bzMJP>1xs^4F;6;Ek4?sx ztR9hX+nkU;6q`r_(}RIEQath#enA_1SlHqJ&dMOjW3B&?tWHyLgiT8=;!2`^RI5;O z@=hllXAF*yP<#itFXWH=q&MGq)4H12sFyYGJ9Xv+U+4RL!^|Q|cqDRI%&!~5Moc2A z?6Glr_rQ7A+{_u5Z}Y}fT+TG7jP`F#lo^c7QQ|F6#K#e-pdTy^&&B1lKlk}PUUCoo z;xaW?niiD&{){YpMVVty<)6j>z%l-YcM6e-AhXaV=*p|mguQ|}?99zoh#jlGy3}3v z{dxKr{|y$lZ<-VQ+*_*fI`4zw zA$eF7{$^oG`5JMskh-~{J#o{WV)kjP-l|P;MooFTKm^Q8c(0pRzgC^{EyMUR@TOF_ zC{yFY*qdN$l8AEa1f8kpRQ7FcGffn2+Nm=7R3%I+_mg)mE=kc(>!~NB>Lm|cfvIx~ zdc0uEh=SmT!u!A5pC0w|EO$M8wztcW{X_41Yb5Kp;;Yp6C#jT`_};I#;EL_-&jrG? z*cTX=FW!wSJzd*S8@6&-O3IWOKyCeXn%} zd~|dv3SCG~+;MXkfc@lB6NjSC-Q-IpO4x=OOv%Bvn0vy0Q_sh4ynu-r$o;xJTKgcG zF(3Ua5qTMk&gPZJmtz*R@Nrc^Ycsv&eQZC2$zRngRyF?;c6q&RSzTPk!ov8a`8=fGsq;!?PpsP zo<>aOELeMv<=4uUirr%^%L-{=q9S7)BxBNDgpwkk6fM7J?a zI3sLj`5~LquCki>5|q@ts);X(NY+tXAn`Vw=01(!eI6jN`>cU6s zs?g352UywBhBF>nqftxC584v1raM!|e`3{bLM($f2tVUd*Py~bFbI7$kF)X7PiHp~ z)k)Xmn3K({w7BG(s#}dzMJaxU1lY>s6SgK2IFqef`WP5N_3Db1W-|Qnc=Xv`#1FT| z zD@d`Wcs)t4VjeY>2>IEx&Vg^~BVI$Y2c=nd&YrdSXViF=2YVTmuX@WTJk?QB-u(Oo z>V{f+DoDlN4`mj43n8ET6ajhuA0(&XW4EE?bcDS8XFm(<&5!<{_J7apS*7g17HVzF zD9bUo&m2E^2Kzl+RjG1Xb}2$5{o-X89pMgs6`N)VoEr?CiHx7k<`qAO>*--Xmr7-u za*E1{voaFJ z{yYt~7&>q{C_2|B7?w`g4!yDzBIYq#+djm83A2VirO*evPDD2t6hgKcl0 zDQh$qSqZGa2JnPypGDB>jv%Hd*8LPbWcne%2Tsror7FVppgd1P(Y+RkB! zNsXJ+UX2V_2)bDMviIvkx#~^h<-US4#YA?UXOuYkO{Bi^=@^9cpY4#+*%(id`tDzo z;kOK$7-&C`57VYBhpA$1%Qs3w9vt#5wme%(2ypmxES{?*xTVq5v587s=MM9GXRtBB zfj@t|Aonrqy|n>|8w%nsxokSsk*&nf8yew01X3VF6eEdJVUO_6-u}**U;TeuV&8T- z2G898oVV!U!1b^-A@_!kkGs|Y9C#}c?oK0X!-BU8-1}6#U)2NG4`S%6u>SFdMS<)g zKsZ}?`AgRgBCHM_05KJFV5z;ZrQ5qIKxF(6atZ&#YErI8zyRmY_2+Qo7axabMk|LB zhq}AsARjwIB+M{&X$_DwFw#uX@pjXiH8_asT0t%T z#&KU%N_Jhr`&mp8)!l5#Yv(+3{;uoQg_g%sdLctOz6P2IJDbsVOOl~8{opDHFcZ|* z45DHXoReYRSgy^Og}zm()$jz)KjlnIhDs}uOu_HT;jSxMmngZ-kDU*Gg6^ffTQbf( z#Pe&Q5Aut8*?>c$c1GZ!JEvZosm^zQk=_q>x3|rE*D+@5cLvsRVN+tCBm`17!x2+k z3HhS!@AMzX2nkB)_|C|YU87$cP}a$gGp~L%(wdP|A%PrsM&O;fggrOK0BE-LW;1*QpJ!!ky24pmWY1PD>`z|L~=_SZ_Ffjads|oxt!ObYjQ)#P1 zO(OJmxGM1!`XX0h9?7D1D==83mrSLgM76{7k%`E5jylC>2%^pvOkO(cY=-5_Mim6Z z#^%mUdDmh?8JL+eC0DkCBK6~2Lv&5B{mAJq8T{}$JwXd^gdOeWBeR=5ly4(EeQ+*w z%Fs}{?jjbt_$RA?@ia05 z>NZfaKquvX7XY;i(H-|H(SgPSIRP=DgO3{o*Cj7Si1;XbcjH{T&fOXeX@wK|4+{kRofBT4uy!k(>hg0!@D)h6^(9A58mv)YFAu8e zQ{7*f?Y%J1E#}Q4{C#Niu~B^IaU;^@_4=VL*ed1}1_U1c9+v+Ka41c_r4HO1fwaUz zp&?)!(X{X%gj>G+T#-0YD0T4>aSMh%lr>8oaZ0q_Uq1gl!>ZXW>p9YxY8l5B=a=`V z9`yi)&J4r_6g8TC^!E4VmRWUa5Y#(hEqx;B@Pfx8f@(8DJqnH&(2aj_?nFw`}WC^0^A&O~`&8tCvS?{Sdqzs{jlL&x9n4yr>vV*w1JzzYrct8)wbWAK~R-X zXTy&pTb)0=rIN4triyFtoH_;{-9~v6;Am-3*`Lep{JHifB;)(gx<{Dk4|krF2)}4} z0kZD*K@E0clc68Z{?nEUn~$PzVj$10pFLBB*}P|Nj8S`W#emV@o{MQ2dy?A5dZ7gq z^c7Gmz0NQ8bp=9U8h%;yM3zW3ShH&m9K4|}Wp%TjM_eZJ^LyWPMU)FkeEnbB_xwp` ze_W6K1z%J-o}{6`!mqGA=RtDwtKGR9POq35|DH7vKcMxJgYfWz@01@HRcijf*8>j zolHvyyZHEMKUwK+;D>K?36%h4A7vqm&A)GP%)BKj!NEZ(@^I)If2x!&!f$^%LY=RV zuQ70Noy}#zmItfY2fyOhZgUbG$kt+2&{sS1n!>$Anap=Gal4Za457Nc%AY=I@CKEb zVrE-LKKd+qt~9@YbVol|Y1}stz5ABoDR4)p!!8Wui4Vr9*xh%+(=bS7)hIt*lh;D53DE*|Vq~2XU2H!;X zp{}^jxcvQ{#KCQr+5$W=B@;aO^s#)2{x)UQAS*^{#bx7H&%OU!`TzebRbKQ)xne5Io~m>kaG#=Br@= zc#-v<0-=b%F(Y*>(PC3S3nl?oPtJ1%sVqdAHFEtMYy$ zhMTnFj5`W2htbP+0qGBa3IQ zX~nnIIm+H&EK-m(+cUX3`r90c;yh|AafR2LCs#Fz?pAxr%Qwf)D|3sENiGR^#+QD7 zC6X2Sjd?mkgZkn%6kV{Uj`i*tqZwGow4QlWl*ezKhlL>0Z%7IHk<{fUY+TkcR(x{* z^5y%YV@OZrH|v3QN)5I_?49FHfYGKNG$zFt7p|KzC0w&^v6w@P%XJrg*ODB~7!T^X zh`C5=x?q4`M!1hH<~j#zC(B^?iF3Ss0BL}Q^eOUmMMZ`F}{Pyq^f$}UzewR z7*ka@%>UJ+!&Y;&hi*uqITWdhYAA|-4rL-xV|a@bLI!^g?_cFq9DMqrEx zj3*0Ln4FBNpsY=`9IJwhM!zw-=E8>C92tS+=D`_nAd#6Rd4HU74d7Nl?(sE*;`R6M zVD*FIjId^J^GvzoHHO8^pKTY5r0@%CDtm0(7Xt&6jl#Bf_$0uwj`J_L^p{8H%g&dT zel>c*6x;yIMs9QzrN)aZA?7>4Sb?h_!8voN!L<9ky{wUao_MPXl|zwE#WZ~bWCMo8 z&!*GxD!*kAoB})7ly;ByM^)|XeTy5Ypt*8AxxS#BI~sP$GasdRWHcwr!b||R_NBeN z+dILQ9;1-58FV%Z=WOrs^i{jLy797Ahw1w3%TxJL^x-i`;}C`F_xpK<@2g8}v_l;O zIfq#=wL#lD9JEz3l=Ap<(6q2(onsDAF7T*;g}mxUnV*Uk>YH+voNG5t`k*vN^@dpgR2fLHJ{zBy?crwyg*4|-<4g}s0 z9(;HKXbd>9Zs`017uw`M$cc8C0A>qEj|ItjZcs+zxJr5a;X&4yy3b>4CA6NBuRTwK zJz2!eCDxugT4LJN^8GFh3u94SL=yb(9z_)9L0V#mN{7^& z6!fFtQ8a}tg&~s^P$2?iQSTiE=`fRy_2?Frhd~n_fTeA|S=9F*1madiqj4=LZezYl zE|9&8_jBQh<+b6IH40(KX!}_;tMks(EsN6qzB{>YlPLbBA>2*o8QMZ%@K4Y)b6S&m*TyYXs4^7 zt_3^o;@>Na9k_hCa-Ob5ND8LKp(d&kt6+TR@;_u+Hpb^}EGO;S&q>bQD_mR57pw30 z#zl(0JF|Rb1t6xd1d|lkRkV$CvwsGX{9wJor*M_ zF3kCyAJG%I-Z+E*^xGP%53KYt{R=q6uHE^=85{chtaokn1a>+9m_m_dlRD75D@?V0XRgyn2% z%c_?M-buUHRyunCOe`#TwKG%ALK^wZY!uP|=I z^51&c`2!Qo=t#FuOOZ*;u#WZ^n=Jkvb+yx))2ra z8D+t+6iM=)reB`YEU&_i)b0a=sHx86a#|S~CHXfS0Hx^tLZ^%={EU3}=JPwJ`u3dl zvBiQ8LbJ{CGvE9(jixbP<&yFZO`e?3SmsTJ#41#Sn$f1`1M`Lz!4rvN=hn2K-2lCV zHV&nl*@K9~lkAIV{x((LIgJ4OrUgH=#EC`u8%HhA?tj*?EkuLn%!@-)#NH zDYhBZ+ZWEj>W*vzdpYhSVyKIGx^Wrr<^4QZa-%a!k?uxk=GugaSkjz<&R(xT`fU~x zjL@Mw_<6t-MfIYhmQZ~LX-VznDg2n_L4WbosvF;)3XMuK%8s4)ppqjf1swvB2cYF8 zyTGFQ_@dgOeM%aVdtJ2AeJSFzW-59w`@hGYWN%*&ip*%{-T)QV==R@#!`tQg#&7`~ z47;sTePEX9#y0HkQQxXl7?90jpUl^}ed!+zvP)+OUYIz4YU7N%hhYgZJXK69w;J_) zR;T1gwl7>Q^^ zI9NPFugYzyE(X#{n4_*jb3@qsyyFqodMt!;PN{*TfGX;`NFqtr5yN z)(dg)%-mPgD*lPAH&18`*D{WpKex#HBB~n9E!M)ox?p77mzkKMjbads-{%bF_xA@hDug=RIF5?tWep=;0`_>aQcxu!1Ce_S8y5^WT zlzpx~#q@Qg!YET&9JccVKk?=+*MK%H#kvn6fgLY%>$)-j>FmwBQCb=J<58dC&d3;7 z8dkFWyo*9$V8l2-YK+-=gWNPqkg?j!l@e^|buSm2)D=k1)(w7H%cJP|IAa>cbPBVN zwye!Fqv8%^l$G9v_`sksNOxPB`O`GUAYgHDO7pFWPUB==C~A{}N%wj-_eXk$^17{R z2vWAF33b5!fjE{+WL1$&nCY_$O!U%z;jPB!lqZ@sv{GD3`yy~$M}_lT5pV;d6kMOV z=A>1J85VNk5;!;bXBamv_5OSTj>R98!NI|uu3`?_TJrlKj_Kg2i^XL@rJyqq*S={x zM&i4p>p}8BRPxb1Y}Weeh41v4x}x<=byGO+j_NYk(7eUXgy=y*FPW+;CH~agAmW@I zH++!^*yD~2Y_2LQ?)#fOveuFBTk`w2?@{x7s=4Y!TKGbG!WYiDaF9!2W44|0CLqxT zOyhq!&gc{d{QNE{xnBFlck8q6DnS4D;VF#}6C!f_pH6Nc=YeOfKui^}Jx9fIdX=zc zO3eKz+|!l`_R$*6zMV2Q1YznTnD09il*@a$qp>=eqH}WXv!R1=rKmtpfhchQn?oyo3NVU6hC%oX;&p&K$-03}hcK2z8ES=T8B(6|;_Gbz_z7%Gk2!X}b7bX;ziL)`NZMJ^h1*{( z;3`(LTPS!@MX>)6gdp z=yYO|+&>muy5^*W20pWw{d(IozHUH|)OeeWDn1Ha8|OoxnuSeDKUTRs^~a&xK3uHtRx)CGLTHEq-?VzH8 zB?Z)G5JA-)om5nNABPFAgndeq+4xuSBDuo)GGPOv2i{ly6a!J^BRo`7E^`SiTHN1WzNifL%4X9YksYXvd~A0ln3YWHcV?c3M5i_X zWr&t9@cx2gEc_4hXy&lAHEQkH$b$c6pCU`Jsrjw8+mJ(`+p(A52bh>%4WkP)K^c1- zcYW3_+#)E-dd5xgvUdZ_`;u6X%7H}LGbND8bOFUz)a)YI@t&KWp?$d+*F69CMLv$L zt-jo_HtJ87@f>2Bq!ofB!{F-f5(oJ(MteT*}1T`^J~APQ0`zMJO0Jrvg0@p=UKYyxv1qqF@;LUm%&M5 zF%~*i=HK~iA!zQjN-#rl?xgsiEA55QeLj_OGgCR7omm#G$Wtm$WMpoqztg5e?Hk?r zmlIg`{~xBlJRIsTe0xMDgzRL^5+&KQ4MVaeOREs0>}1atW-K9lC`z_M$iDB!zGlgq zogpgQ3>m{L-}m(Uz3+9sf9Q`c*EQyR&gVSmxu1LaJp0##89AE6>fyWn>jg28q+Yxr zn%b!2T<(@1%iXDNzG456fACBwoc=$ET@vB)At1uiuM>dlGfxiFJYvy^F`=#PJ@70U zeU|)FTJ)*+b|gb;ScsqQg|KPvJ4_4nw zyWc7;#1awjY3%wJN}=^~t;^0kLOWqh@A$p5*%-obPX2 zemr`hV#7tPJh<5k{6-qVneR17yg`zNvnw$32wwOxx2SV=gNqYw|L)ORk5{XXfM$;h zRfKJ#PoE^d0e^M2)(C~SB=}s9F49KUTjnJU)Rv^h(+V@!8LVWp%|BY~#b5h; zi@r?qEKQ~WZ3yGj+1%hOZ8ej~%K-?}smq2zmLa!i4D5aCSU7+?`vwsVzL+Ls|#&Cihds!OczXCOE%<%Ch9NJK6+$* zPUMX%2u$q4^+$jq*}~+iUHbe|Ryk9w8;niGuE04 z&Wrc5u$#8nve7&_{}eT;v0qq#yh-`7Qq%t$9o6;J?#UACi>PFFIsg zYSzzG)4K9}Csok5>IYDlro8|}Ada9rQ%6!4Dg5{KTGIOPOAUH3AhSw{x92}+udzCP zQG$BHjxdZ1zZI~78*Lt14KKXktO6}kc^fVnJ5e{{b8{-yeEf(ZL6suhdtIu)$>H8= z35)QBjyL+^u+3_KE#7J-pmEPm=UsXCFK(xE&Yt@|%%1UXI6t|uTja`{;(Op8qQ^1# z3wddlq!_FSXL3omc=+pHc1Zq&*7X?`k(Y9reAKc11pvV#ANS_OW)x(e`W3IMI~+`` z-8MWwpYSbN|CM)n>4uDYCvAHdIS&3bE@{5o2nUT(gtId~wwAq!L`|Sk@YTc&N(@lN18YfZE-oy}HQ}DxShdF)j~Z@~_}gs7 zn(OYX%E~kwu|Us<05@vi`bn5<@gEINLbBLii5vBx$Jyn~%1+7L(f;Jiex^VAZe|L2 zzBF4~DAu!k?tV{8WEKXrX@rX1lKz)_F>5)r+p7OTUhjXJR9KKS$j{yc@3?N5{;=$- z9d6GUsz|yss%<24W#F3E2?gXvMU(!6<(W+Wm zZsFumzIRjnAyaEH>;@APxDCEWs(@`N-rp@9DIi9OS%VAKSNX1$Tsh(?bKlXaHgt96 zHB>fdH9zMWd;3hIs7-R_?0VAN7!jU@dMa4A_4=Q{^;I8UT(Zdktr3hlrOs5vV(Yy!0Mx-EX=}=+U|EE6{aUGt7}t&5W7_F_)=^F z(f&eLB1foXlktN$Kc2h&Q$^k)X=9DkvE6;v^ixMImQv2XIlIi&V?r?_rD@n6F{>Zv zTgHn!#f+6~y|?~uV;Xu9(E=OngU^` zBEX6NZYS_yN#dPgwW)T|fc2h+4ExUr^@M`O(9!em=av=(WJI{;uiZRl&=mp5J0S^_8JK+#@fyNURYU z@vvRABiXF;_~lYrebv*lCssyo3gK5c8D4*8X%~bP%T}%{_bU%nRHI!4W8us&I8ijM*XJ?%Zx3#&+|7AH|9sZWU+3(% zF$3D$Uo{mpr;!HP5fRAyoH;##@Xk$TeA+R$p45vx!? z4ad_xW*2fJIZNXTNeRc*F-C3miy~5$t*j8lYc8*vCpv=__0B7KGc+`$d+wOeCg&A; zwG?$Bm?a2nqKz#`YjE`~S^87#!(S^`ngV1kOdD5}A#dco274hW4cs5qSF-0mHK!?9 zpDC%N*65fH+!Jr|klWP#P!-?8sr+~I^YOk8#5(Ez)Mu@WRzpQ?kmOLoD3{tv6Hkg; zPn6k__hX8~=g*QjN_*sJJC$MpkNFbfM0SEyc#}U; z7#sS>;VUBx^F3{IO2iHcS$9JILg|c? z-pzyWj8Y_=YD<)vzRZW~QBt1cMPp+d=fy8g*^%%@#hG~n6hlRvK~S}w3ag5G=ZuXX_kI{@#JX?Ecp_zw>dZMC^wdFU;vsAICOdK zEKI01n}8AuQ2c?t9!ruT9AQ6$KqW8n(GU=O_j@kN0PE zeZut=$&oo132?y!e$ZBRya$?^uM`uM+ddb;wI5Z-oY-o##!IL(y1MzBRr0-o?7-6) z5x0czZ{@Oewf?mFXbQ^kn>`SU2$Y3Z`N3z3HZ~~8jf~q85MchaRfY_ubgoqGeI(xB zMqX~gF~4?yAtm0;Vp&3tc4|p;ttQ^6iPj9g)mu#`S`NLB$mucL1$ZPV1ldg3%@UA; zcac)zQTXR&wevA&jfx{WBly0!1Vr$qs-F!RM>f34P)O8p|wgTIv&b9 z^5<^?vsp45EjZQ3~^2Q zx_q>cl3&Bt%blp@tZtqL#4B;hwL0=V@)KHLxQxDoewy<`usf%YIouch8mWX6TYmTD z$4dPNH;=;7XMWidm<$6^=j2(3xd+0b25K=K)bRHY$xu|MC?GI#nGnP=9yBhhKg+V4 zJSt3(GpV;lQg><=EOk?^@6evb*m$ML$kFO*DzC)lU=5O@+Bpc07z8^(y3e9%`mZH# z+^_qloClW5_1Yr37>Q(x-93)5)dO$kimp38NhTHU8t4MR?yBViAa68y5iYH_={?4A z#9z3P5OO9*ox8TC>$~2?uPNpqen>#>^~!=}5RPXI!!0&l^Zu_i7@j*kSuea@ zp#ub_c>K>ZPsT+5Fx{---1=ouF*i1MpF&r#`X3|?b@l~3rdQ5%RRWL+HRcmyoH^T}aIQNkG_{ytVC%MHUT;+xkgm9-(In*V0B zM(wTdGbX=gKowMBr#fjO+JW;Qq`+gPS9iC1QM3X5_oiuMu1Wg3em(JMSNm{}Lk6b* z(cC;r`waco8$Ec^G+7DNX$Tw*&PdOh^=NQYR%%io&5Bng4$WV=RsC&zNk`%RgQd`- zS82-pwBDNVZ;6bMtKr|+eMRZXO9ViUr+EkJQc~119}XVhYG0CIW?mJJ*O}~X_4{?* zRKMu6epcfnNM`(-01koy&w_9ja9tz063-K;aqzX3*BbNz7lD;0j^h>fdXg;zi|Q3~ zo5*L$+_E$rzCz)uu@KTVay{Ax!9*FcV2&c)Uq!Jjxujj}J@{RtUG(bko-=#3s)9s> z1N$D0qjG0OZ7?tRi;@X1mpLakaMDRf>&3(FN#572&z0RuRAON@V5_{F>Fxb;)sYId z`W29>gXz4m#10B~&CIU5@7?m=V4KLEa;Z-V(;I5?p$t@G;+3%3-woj!62M(g>6L<8 z&`q3JlGau#sc0TJQRl{$9S) zY^8KDd(wxobC9uJk^cL7QHRiJME}yMG>KJutyER#t;Gu9(%tx6ncGObmWEq6X*?kn z1ek|Ae!&<^rh!xRQ?N0XW_E?4me%=9P)j+8E!&d+)o{W zCda*!haO-x0|*jnxU!Xm;G2h$Ry#Si52O-r zM^ImoAGf2ZyC#qukkTZD2z(1c^2M@HeE>{WIrU!34LPx|hL<0-NC??^dm2NZm~H<= zC&5_!J@`l3(Y6ZrgJ_6J)(N7rv%RMYkqiJ)wseHUt*SZ zb5ZwGef8}JS7pa;w&|HluE&y%!Gcr}wz@Q~6XtS%1lT@`c<@nY(t=^Erv50(EToes zdbow}4Kx4tL0>4lyd+e+HvF7OykJ)?yzU5$aQb(E`>A3LX&daV(%K|K(}OZ1^02AKPWY)fj(P58)_=2FCI${@gRtdbxcG%#<$+$j)<@OLUnwG zs(*bOkquxTP^e5mo7QE5Su*Co&VS#axw;``tzKkNAE){SBU2F0=jgOM6-#;dv2XeO z1BVdr9;&I2@B5&^q(xKcp(R!t&n0*Pa3hv+mzPB2X<*AXvhS65~8u|y-11FJ5>Z%Z@jETz9rAM3a#meQh@bzD!tC~c%b3xGiu6(bAZ~dFUAR`cz%1Twkj<`K;y_cds*=mdV zm?bdWF{@{U+Nt~;xM$eB&wRDIR8u!#p{ZKq7aw^9lSB~J>t0A=c3}x{#W1xh-e==Q zG}N-rpX9w`E%lOoE?x{3DQA)a;5Okhs#iL?5CiQS=26_X3_Jq4z{b6fDA7gplawSy z*hmwkdBYbx0L4=@#v~TaNRrH52}tS@xIDS5u&Z%7BhX^)+yjJ-fp{f^)#RU8N9yt7 z?{puX^JRR=Y4Nqsbu~Sndr?9p(oLtt<9ijSszrQ3**x{iP^7yTMEvkfE%~S4Jyn}* z)oEjI_}D=%^EBdzBmNv{RxV+;?i126`%>LqUm-tC0G+%;A1 z6y3o673@b4#G=E41+l5U8nRgbMBkDulkOR|KZcxNaE5Nz{G9CHaqC>Hd=}fu6x*22GGCN2O?DqD zVeL*i2N96m_)3-mt7t};>}qEwf7%zp85h!~lS}eP+@3pnT^zje*DWlO%a8qy8YWa@ zKb3Os5DV)Y7K|s|D%YCtE#szM5Yl8)*VT2!#$m=nuOm4~hB&3}kHh(GAGJqv8V%bJ_YIijuc6mq=Ry^qS!z5nJh5GqqpeW4=!;HVLr!XNwl zeTr<|=iG6$WyyRos(!VNZ~ScWeucZKo{yL4S0>M$$BwwKXz63U4T*xzT;~7ANw$1< zcXfcj_D>=$r4w-;?o<(Zn$%MfWAP=g(uMgcP_F!jrf&$V4T`jS?~lDd6I#;XA-a|H z`G1nuq}tCC4A;2gV2D*Wgn7-30>8$(>Feb&j&Dp-w$2tebYevgzrLdpeEY^zvll3| zXc`E=u}NJyXB17S2{pYhk&&fye-4)wR3p1AXrnfj-|<|$_m$MAeO9!Bhgt+~O_=~n z@0<=-=}>F+C^-MG<5{j##of0T%&oP36;hYFuzjDE%|E6;O^v4l>jEMaX2~(|)oeH& zMU})=PbkERKb)EmvBucd*H3OFF4-i`>n1eR^k4FG;Nhl+^wVq!#1V}^?iz(YSdAcp zsdx=%t_!iAeS{s!&xl%>``j26P&QuE^H4b9ZKa^3-Rcp|#iJa;<=OuKAQ2YgJKw(q zNcL#ROun#k)oy9#x^WsgWFf;P538!?`EV;%YvYr$2$ate5M7^F%&V>5LyjQTC!}Cr z`G3q#m(#rpEi4}|_4>ooxn!$_cOtXG6H9v_xpo;4!bki~u<6`M0t7TxS__zcusxc# zN8`A%6z)DYNQK_=w74MUAI*g|we?rnfMh>@wNV=+ZBj6|Wf~K*qr2*ZX zIHBX;m|`z6@I?6bRn^KV4e`>XZ5-|*U8nJ8lEeUe>Mby3)es|?uT{_oAbR~SZho2X;fj*d@NJ=^f$Tdv#eF@{r4q{S zj?ma_Hi>gn>4S2O85sj34afwy9Wui0`x;kX*OAuvt!z%Jl3$Y7ifA)xNp z5+Xip^QDj zSn{N8Dz9EJ5U|!C77}}J=^5M1PSAc)4f*Xxoo%F(Ml`d<$Zn-U0-tORB zSd2fN<+V=5`XeSF?JE!o99Ct! zmxM>WTqZfH*H3cpl>Lw z0b(vx$XvSh)(&Kl_#DEjni=wbcHLyRim37nQKQ!byy_|6sd&(^P1@cAS3_~>9uy5pmi(o5$)i7`6cnpKTi<8t z@}$br!?&{0$k+MBydNQacH_|PyWl*yO&JD|Qql?wn1{Im)wuBNYQwG|HgRPY(U-(V zx>h^IRP6EDxR|3`JZ*&Ub@k=76gg^0pb9Ke7BO>${7K^sfDwB8vA;o}QXTMw;;Z;s zgCE6hMQU6|PPE^^<%CP?7JOb_>=SByC{cYPD|%;$`+WG2XHcS^1?0r9{fHa}3|i=s zQ%Ln$(6I8mnBA~YigvTje*7Gtf7sS(rzz_BCyaiBRMrwII}*$>f-C_={!05bk{ZDo zC*9lZnB=?QMpZ}T<{Y)`XVDU|R7eu89eH)XuDa#D;~RP4*t$ui(1{S`hV8vL5(_cB zLFoxIS1k6Hb@YTHpXE4MbqMGWjNM7BBkc!kVoL&;`;o%fJL$qle;IZEbbO=IlAbGY ziVHR9aBHbrNVJ-85#xE?`OvEQ*q`rLJt3lhsTD~H z!B25a;3gcWp@1`vy!6p{M)4zY*zxMa4Boit7h?JYV)`%&u$CWnc2@bD_j_zI10rz@ zP`Qoor{5nZ%N=dxZIyD0<(L*=|A)J0bhRtuHY-Y&T`0m; z5vHgrBaT`Yu?ad>MZKt-x5KHPEoN(;K~p#55Ywog5~2YK+Ct85h1x46*2XckNgC8t zHaE1j#!dw6Nj-bKai8y7S$rb*c^M$4B~6o?0L2&0fTSW_PQrL}yIJ0SRNE4@yt!Z+ zut!tk-N~NUm%JkpC=|7*%94nTCjibBO(_9dL6XIey$-f7+4j$9uXySa1WQZp^1~bXDn>@s*a#{Lvif z{3FMt58V*lT_Dm0tCF)}N^3csB&F$!k@~Wt@(=25MA5C_uU2+?x9&jL!wUjOwK(t% zuTZNgD>dWTzV{Td89=Ohxcj~Qazj(pxolmk#DRI})jVZL)$z795bK=PBJBQaS!l3` zNSGw%BftOM2+KIrcM2zIzwa%x`#u|Ev4>uh$=|^9y8>_Mf0jEZ6$C?rnQO>PPF~tR zZfsYdAUbJ=ZmyQ}ijrgcKfnQhwv%$E7gX= zw_~5E4#Y+{Q}f=&20~L29}o#hQ2#s4+7&^P@m|>K7?dF1llGEQ;OHy1gXywwN>m2d zB&lomZ)C;y_C{6uZ<9=OnRN*|tCw(k7>_85z(;gt0urxwUt?rbW-E=JS(GVr_Ak#r zl;th?{d%~>o+9&wVYyr;%)yej4Bs2HgQ(qMd}h$>YT?cpXU9b&_)H!^KO;%I z(?r<-SG)}&>*?A))WwYJRJYE_ea*7%OMqW}7tpQ3VG*@vJr7R-Rr#zgp$z*U1moXl z#R8))>n!j6?7ZvYqgXN<(P{J-HAPz{ji0|`MB zp_Fe(PI4hd;*S6y?#m}1`@CN>v2U(8Zd}9U4r!*IACe zKBWpD70=KTDDaTnO)%syN;FS|(&wg*p9em7$LoU3O0R+~%K{#5aY^M_n>g4}JE3X@ zzVCI8%EupxFE@?l4uaFnVizg4{YXHR5QjlsaK6X$+*jTBU~_5ic3Q0Yhqt@1_=rqC zlq%*W?gthbT?RpZ0s9(`e!3rxss*KAXT9R}X&vd2h5a$!t*szJ6!0wbK70ujHK0BB z2J%TyMddf*d9W^ceT+$vTI}VPpfyHE%gPxyH?fR)*W$ItFzZWbR^7^5-%6?OM{|z` z*_@aG7VtW%D~SdGss3Rgy*Egj`Okq%|J?-XP0Pm{^#PaSWCyQ2c*cKDGBYe9o&^C~ zH4eD*%G{wQ!2@ITXdgox=fn3%z9@DE&s)6V%>G$en@zsS!A1t!)Ik%<+&}h19#0P( z^>j$rr;uVKgK5P}3AYUyEUnbn8xA6yMQRfdL|fu`AP}ksegjwt2X28v=Zux^LY;$I zt}|1+oQ`~{StF}%-HWNX9JLAMy!&DKhE5b{c{mtb!nL-z<-iI_AytBfv4tH8W}O1p za1L3YTyMOb?p^3ad8QS7YDyGK$a9V@Ipn1Vpur)NP6&!o(204HJ#DDjnFAbjX5X-eXg=VMly3D5x7d+8o9I5{#>Ju}u`7p*$!K=5j_&MIML^LDlc;oaM@N>L=MLf4n0b%73UWq*mU_eK|-*VA-;=xk!y`8fMbs1>M4f4=Kk z16PvT7jewHMi#?&n17PXoiI!ByUU$ENzZ3|pA-D{_~D32k3HibZspJ34e)g3g&WiQ zfU)Q;iXiy%`pD7xd8teR;pw9VvVjPq*68fF3p%3jPhxe)Rqp;`VB1GPD0BZoDv!e` zX9@cqswSa|A1A*MCN|8Q5pEfeMa>`s{4`I)7$==TyS;vF3uv9STRVpse%4{jN#_Eq@08c);j31itgukVZ$&mCx!J(> z4;WqfgJIvnI@vr+5+Oup)o6Mmd9>{$+F&c!rs8^En zQI2Heu9drWgoNBcCE3zq^u2}zd?Ss!p0B+!ES!p;NfH}Pp)UXs#C}gjEQO~Q*pzsb zComYN@D{uA8J-zb2-kV|&O7PgXx>;=0C+ddw+-Xn35Jfi{&jd%JC6(3SfRx>7q5MW zBGaE(B^gtF9w8gHiPjtK1?0F^ueGFTL~Tw4%xs-^da|~}GNpP^pHBa{*z|Fzr(7Vo zUEv2%onnB%yG+%JV^RMPGMT#tBpfA&UnT*!B4K5>7e&00@bWiI(bl2)Q|8r=g$=U( z;>j(%N|Zxh{5o}^A`#I085ywrO`yF{i+7~ltVdVuOCFe+kU^}+Kc14YqKBXn#`5V} z%g7al*GK#-zrOr_8Wxzo_xf138|k-&z6}BNS$=7vv@P5X$E|TZ4#1q0>60<+7@h^2 z1DxZYqu7yS&4BZAJ%1b~O>O-lH^H_s`|@11`bg8=C|ufn$2thOZbxCqbErbaDV$2t z0YK|oR`Kt)JqV9L)tYtY5CU?NU|vcwWo0C_iaEuEcck9W^(juI*6^J(U$YXTo>Tug zkf8qc8@`%?t|s0ZN~Z|x35E9I!R+8k$a}}%8Khlu2Kp)dT(BuQk0M68ipy?$@d6Qb zEN59`{>W5T{&jzM!P+_51`xG`%%&Y;fpo#z9UCyANk(D8IM z)&M@2VR>b(a;jC!%}4Zk)ou6HWLxiZkFMZ-7pXc$Jpbp8jspmAUI14=@)Gv`6NZ{k zh{Yc#Lj|{T9Fy~;!@ZT?({Na0SC5^rQI-e;t6A8N)^j!xc zy>?=@&AbC8(g!P&3p50`(HAJ9e==TqTKtjvvS9IhpHEcbuAb!30nFR|ycpF3i9Tl7 zD$?ZqR#-NA2>lZ9J_PxYYyoPkTdzqB>&zUFom5*brW!D6Clk}w%RvFcx_WQF$}+Oi zLQ<4PA-bBX9`SJO?Xgg60RjR8IP^+pGdo8iA|_33VS9y97*@ADXLA9?a5?R-?*^X6 zZ$Y`?8p!S(tO+U-A*jI&xGtP~xAk`zq?o!qBZR=Wxr;KVQRmO=th3+Hncy%U% zsG_}^!$LqCe^)FMG;Ilr3%R)_#WY-Op`Rfy`|u41-;TI5w=yu{*V_ecB~24SWVIrE zSsFLnO?EV^nSsfES^86g|NX2f{PE7yz-8fL_B#w;S8wbwo9ZBGPrQMhwLJ-adPFuy zPJ`31qQeqCH-@>K!OUMF>ZVtHs!vZ zG;sx39{l&6WcwKyD&P?mx^3bG5*J|`n{%J=4tJX&>rtTM6$N6DQ(?-SkY&KSpZBv% zA2J7Mna)J+XKQ>Q=fYP%B5EE*V{Q8c#IVLWfuCK0_mxkP$@dKp7(v<2R7V1 zBk5Mly;W^a97$}_V00&f-CF%pj6KG1#Y(}HzRtVUAeeXQIL~bY2y!~O;Tg5u`-PWB zJkYj~r$l|q+&_Oki3+~QPRnYOzAa=kgO0L$=k=)uok z{TLW9F97u z`DVyz00L56n7_6n;8@0``I`SMVk_wJ1;n<^6qk1i+7JW@kaR?TQ^8wV<$kR#!) z9&^O*oEp8zRxS((jrtMbZ;t(yJ&$43wQF#YhNVjOHzo`{(v(vRm)$l4rJ@uKZUF26 zf)vG?MUd>DV)z{q2SN=IChy$&*x!jcq&_`izbas?(!rN$3RNdwM|G;89T8ll^Vq@! zSctuU`L>2|ozYDL|iV46N9D%DPl*B+#!`|4!M0Ya;m4OMp zZgYL2zO`dh;-*@03ZI~2b$n#QnKn-?Xt+ihIR*Y4F*h`Ze~GmY!!YyyKBX=G^jPny zuWQk_w8Lwa5IU-)ZwXT}1G}9x%>Sx)9C8{#)#^%ALj-GJmEx|E3`)2C(;OsfPads3 zGc=!Y3^ZrD@YEA}&*aV-P3Tjs8ilTqsNj-A*9sD#hD};$eM4-G>(SY(ONQ=BR=288 zT>0*>Uv*!|Hs~|SJyE03^Ag!f7YPj5Sv^7oww@vD>Z5i`mEHWTJ&_Og_p~>4uN8Rp zF`XOL^EwsBLh<9|4_gG;)dee){$}^MpfA7u{LDC;U;Xxg`B-#SY1|!9Gk8+WLnAm0 zo(9S~{q;rU*lEa1KRVSlLD;}3 z$C25N8DOlT=-|%GbbyK2aCum-KIQS39B2Euv4p%wUgU8T@yadWu>KcN)s=R_A%fU= zt87)^z_jEYLP2dvV$JZQ1o5?%P(i`Em1rbeV_JwXP57ThlS2d6Cw-zUoD`{#mE0h! zWg?ec4Y&WSBp7=U3ja&KKygEiB6fe{EIZNMpf`bE2elX+xv4~xM+~=)s4S0%ep7X`v^n-MR115VYps4$coHWh zN^_HQ&Ba>fa%4B|32v}lVE6QQtY_Xdvp$Qg17Go4JDhZdpjHyFuSrNR?_682=(klY z8<{+}oAiUUiu+*DRdx8FNL^F;cPxa=IRjr!M^*cM%3n5jZWhCT@P`>!E*AVffL$ND z*=WF>=LTDi=d-~fvf=-XDSwo#!TVX(%lt7hP1Cz1wW1sE+?@Fm+#{oAb?->4^ zGKr=|3iRUGy0bNA*RUJ&qhIIC@*8$4wM4I#2#m>Owc9AG84U8pudY&Wqb{O40j1Tx zWS{O&eLMfe{tK(SW%)N|O9B-;qaMY3v*!0z_OPg)WaM`+J2BBs>%J?zDcdOOQ5dYO8DJ zN_|2T^!Qt+h05b%v$@*DMi53t@sNS?qX#Pfq^}q5<`CsNu|9pCzn9??N3O#oR}UtZ zXZqHzUl+^Ryc{J{^eU&dBXyj~phJ;V<|uy2FM{y$^#29AA;G~wD$4sO31n(>T0P1G zyjKt7TCQ3AjAebu=Lbp3qe?P7{p*NHt_Yx&Ua4+th*Ws*yL9!~eClki17>&M;nkRk zgczwY=UMz;h^K6diTFwG#GY-$x%pd#|YK#dF9TaufI)ASJ(;qq-fIuR_^N*(t2r|GO-QZo6YlJ5aH#nPH$L!VL zPAGPHJd~qL(-R9*?!4dsMUC=sb|;#|A&8G9=-_O1v8af4-hl9x9)H!4Z|Mze<}zu^ zqE7QNUvxx0M9Itg{9b+FMWdcIbYO93o!aaR!|w7>bntjuZ%X#G(>fZ&|$< z5xg6PS?z0C)GefmTvr}-Jx!0mkC4-@UyA*S6#wNU_RzB;=wju-D9_^!mPK2kap*dt zAMqo4tq_b?o=Zc51+Zni(@9aSUiAhd9xDdVi+WV`MEEL$y;|NKDV|#Y({jx*-hJ4r z7(jrqk@I{;)v)V1g#y#SZ<`S)?zpDW?t)Q>3$;?VM6>Sf^F2zlGsBzO&AQ^UmB3X7 z`AqpQfY1wf(}~wqqrfiC$&C-y_4o|U?y+O}3p(NzK)`Z zhl#6Yb2MsFtSO~jAUa^Z+$cB!0Z2@pnn+24$U5^bZwVo9jZB#O``&H0jPs`%%MkW* zpB=oXiBBN9F4#y@&<@$P0tpresEAK=r-o8?z~3M>o+G-vh>f5y2H|tZN1BEk$z$By z+lVGcaLo3S-&mPLqpnXShwA3N(Et1Ah|mW9dxy}yY7)Lu3quMM;!xxd1um*?qdE9= zoMQLrpX0dF-jI^0W{3`e{M~`#0pRRmRGK8g`Y|$Cyb*gyVITK)}OgD-rXl zFWGZTH{|^Kz-Crp&KUhkVMFzf(0=i z0;C6qWjYFEZKB-#&=u=B5lMC*g;Ly`Z$0|#(o~*4nIyDd@SXqJYs0$$>g-`&b5lLm zp8iym=IZ)AP_aK%RQnrEujE@_HNQ&rm`*57a3NTY27rm5Ctbxt<6uynNKe`_FS-#R zc(u7HC&1>1p_5(hp7z21eI7A`Q6@k|C9{FJ0C(i@yh(Qs%ZepQYvRZ`t&nVKS3f3qv+ufWp2Tj)7UYSrDc<8r)e{-G@t z5^gzxb^)%%W;^?<6`|QuxUueS$u?$l>~wxctiHQ_lfk1ULj|UkDv0v0?z6_sLL4B! zN)_dT4qav-XMzD%bh|3fEhp-zjP~GgH0ka;x0wem*#^lN2O;I|r%gl2V`mMH5DRSh zE^_7(e6GK5nHRg2PzyZET$Y6@(@pB?CchYdxYI!YK%NGERbtTLIaR#3J`Hsz%9fcR zzS6-Qvr=;$-7XfaU(-Bu*F|Dy0!{_4nJ#^h$K4%%dxz9q`DN zn!Prh^jclPa$HG(Z|?i3#e6Q+6$;(O%S$f(8Zm^6emBQ`*Evr`*Ig7-$w$Bou$#!A5<9sL?+Uuf-`F(k zfpx{xvqTtWZl&f{4oxtNeF@?4&UcT$OTwdlmiR3!DkQ`W{vN zCxAiQgUva;d8R}$|K6gt`o?%*g>bZ}4%=B%`B3Q7LGe_qG>P36uSzf^!U+Cd6a~WL zbk!FY1?!I&&4(qQTzblTySg-mwIiY6_F;Cb&DK%$S~?hwOS`Nvx55MAJ^a#!?{;zx zq&&)5=P_IfH{}L--{=V)jvqmxiYHBAoTCQ-CMJ>@HtAI`$cE~9L=kDLM!TN;tbVG% zqO;NZ^iJ;XvLSV?-KyPsd?-?ye8m|+v|zAvCRV*Dm%4!+l>_FXRFlaIBp{_l;m?7g zCI_f1P9M9L;ej9ZCU!*IQqFPrO}@3)j9-6?_$Uq$P@V1J51{y-{wpnugnn?uuFm!c zWtm}ad}-Fm`TDzhu3)PBLcgSH;~|2;9toFSSI%Yr0gRm9=Tx&NzeAi~*6q0fymaHk z_3oyN9FklQ@8hk&(a22zva?J=F?ONv*xw>On!@*F(Br&pPEFlhV1CR+y+_x=XzbRI zIFUD0j6_NCe^s}iSAT_FL71H_EQkem9!n*f<9>8vP80^MC@oB#XhCwodBiFfe1Cxu zTpITIvTPN`-~OZg@*BD*IZNqgXMIBTg)-NL1icU-0R?X7S|S-|X>|raV{U6_kZPKh zal=N_m+4!6#F$XTB17(60oUNp{wci^7nz(#WTnVzdxu6^?g&9%#h!psgn;%s~7Q3)F2 zgo@sIeJ}gcKk4b7fqAYcKHo+^g|6}m=s*IGfMJ;q1p37*$K#L^WVQn|rX~2R1eO1L z)#k!vnyHp_f7STl;mSVtJo%h(?4!4>cX)2ajY|=(5AYHpZ{fTq--E%D-ZcT)O)*rq_A;RYb1DyNR8}*Q&Z$gY~UXB38%|Y z=5Y9+E&H5MqJLfNjGCToX5by3dF?}4+pti`YU*)L|G(s9+ql)O_)n9qsDeMo>CF#+ z=5yA|7koPy_F=dcW_#0ENoMdDtpTR}F{tLA$Z7Z)7&8&B2R2+kQnD7iT$P8g(*IpF zP``c6-MY5}J6Ck_*nVf34;7RD2MQ689-!-DI}T2&FTn zP-19w!@enN3tgW=Bldt)R8alR69TN$fksxq2ViX~sH>3wCW^tEF-lHF(v#eQSCb$3e)CHSpEKK zMe6NDcc81U_oSAnYn%BaXDepOaQe(}&CX82oE)r?;QZJsy5pa%X-Nly{m5**-2LcM z@xmg^M3gnJoBgtk?IW8%wu9#(Lh%BOAtyL-3cVQd$~*zu!<RK~{SP?@tKhQwRQ4n#FD|2FJ6ul&%v>`#%rV8~Fo4t-(a%oucpu8_gt!6={Dp3}G8SpTv$^)VsKL{&v5FtqKiO zt7B$}9#I>)0xBMDA^3=9!AR0Q#Su&MiSiw(GPl(aRvQ51yJvChA$>~&tNyB2YN#eW z<0^3PKOY1DLg+j zuGnU>rLncf^LX{06ZqU-Mc@MGGA%h>s+}c3?>0_67FBsd6OO(%%w80c8hR!XE{{zou|x4H zgiF{aq<|}e@kLWG45m}AmAACet&r05{Tokw+?IUh8(YC3kGhcW*kj;JLcH=MKu|m6 zejl}dtEKWiSHq9a->P6vEN^#o?+^T;qits=qd{-w5sqTdBLwCJD^2C&pd^vzjf=gD z-*4gisygUTY)9w~>v!VMpZ9j6{tE{egK$6Oz)Sa3=chiax2D9xMa>$s_x4BLh5lTy z8_LZlYI2-h0*i2+{1M4cg5ty@Jt&;cWqFp{ZwAC`Sz9ZkUa!jW7;2b!TKQ7(n7B%NsaWyFhDT#H+5g7v!nGN+agO_3biSrH#=2e}~B}QpgXOE}?|7TYxOI_P) zHWASA9Pa}bEi)S}?|A0(hIqttk1Kv2V^FcrNnSYdUTgWuX8}@*yN~dv5*rZJejj=L zPnG(M9HHt#hp~_~*Q5U+6uJ*Y$zUGB`Wl)Gn55UgnI~oV&O77rWB-S#_l~FffB%4w ztjr@L+mR7vWs`A8RuU@NPLYt6l@X4Sy@^U?BvQu7&d9MTdqnm*$KK}%ojB)w?pNR6 z4JTFD6GVfpBmyX7KaFu>$|QW=!qmuiJo_6?&wuexMHZ60S@ZRUL^ij`iz_kH3zhS#)QGmR=s5gjyYGEW?SC(>n#F z!FTSVC&KKNlfQbcUYWI<8(Et-(q&9=R5rK%;{*}NqD4v@@`6|kzy@d3uCoBT0}CB0 z)JF2L0vUh@k4E?+hTAv^)9IRWK(&3o7RU3jCC?-I_43SVZ;Bz`+;_fMD*t{7vESq9 zcZ<)g4t2prHNR9F9}SiO3`AI;&_zneR2ZDIAzN3Iz3o59VqMf&u>r016@lL!xJY&Q z+|scmIlqmcGQ!sf1ZCQS+5$fh87gfeMtqgNU!Au%q!x<~$}S9V2g(@wq+{4j@i8s= zF7A)}&*vwMXo>z11)8@F~=^DV)_}WrcE5VGww8fQ?RLV4bL_Vqi8a2qF64 zp78O)x32Fk_Ej)p*^eAU$+VGdjl5rtxs(3=ZFahUa;ms zOvcB6?iiFSFYx+x%PIUB( zh_NN+Hf`cumpti8Tll>J-MUQimV;TfcdOyQbTIO>SKnH##X@AnIsJ8Lg~+}@@^HMr zLxopuUxGzw8)9JzzQ%#Yzuf=u#msfD$!lCA6dJnxjSgFR_d!VN&nGmd0A9U$yBIt4 zWduU5`jh@~|7042+My=&b-*ALZA08rg5P(q4~Wg*o4dXOk94UA$C_I{uQrgL3!DjA zaYBbcNt}wu*LX#7G`#;oP#*cn11<>Y`9X&G0teQxPmY(Qg0dJG)uU8hu7`k`BaF(L1=AFBy-VrVS%^Me{9r5u}JtoNQerBe}deZBGmg&W@;~Cezu#@iv4%tc2;c{gfs> zRJPfD@0vEgIEz$yO8wlF5c^&8VFvweUme)HCA=wWh9C2?*XJw|-HYZ7h$k@5KK*=R zS>IY~!g=n4ufBZtAL*2b7jFu@rJBpvCK6wRMr)s(T}6Qrqh?sEM*tYw0(SO_z>|M~AD)DZtIczxdv>{OBH0Y(F0AIOFEAsPl2u>Kk<)Aa{F zv$1)!GONvIVo4T%=^;XxV{J?DA{25x=nv$`1=8AlB%|r{`1(}#t&L1gg=RCs$q|KS zr5nqu3-vMgqZLQjzG)oSlUtFG&>X;aT@jCrZZ!%dyLR7G*gQTy#@{G$#6JC-HvV4n zI!$&qU=QLV;cu6R{VBdW{py?r_5#3VCdCy5hGxKBV8H6!1yEaEK~G7n?Tr9!@AG79 z0&U9G)SjWAL*1U0Pl}$qefg1ej{at}f0mh=kS-`dv}6#tyB`OGRJDnblt!WP$__$X zz-d!+yw6u~@H>ZebWlcWOHGOIh<(x#YQ_vKuJbh2PvJz>&U^)e{Agf0^q2m}dAoUC zMR|`vrZuVSX(jw+>skpzA@n3p=o(b(a-&k0=g}VBtBvK$N^zeJ1Hx>=k1+kkhLfND)LKz z5?9c!Ju}A7c&!br&%mam4~#_-=fWnY(jcn%69?Wyc95-i4RJQu@hB~Kb6eS=}QeTi5A22G}oT8sx0q2(|_beeWM53~leKBpb9PrDVlpLDCLJ86AG8VAS` zCHr==Kf5)A#xA8yo93;F2Q_>J_sRn&ZI|%soFDlLtQs+hH?YQ+yZ(3|;JFTqQ$?~K zF$B)R863kK4uanYFLzzdNL-^4|MDSU9=I`nv<)J0bRFx|R5#YWX=hv1Jolb=wWam< z!^;raQ&-FRgW>2v}T?hs{vtpuuUu?vT2WM=z_8l*6lOHy5 zc!ePO4o$1gcVKEVIW}miZEQgb^m$H*G$omMWDs&8Irl|{xike_e@(Ah?JAx+kpu}= zyCL{S9OC(&w=zhoWJAsF6{o&1S!-L9myVR5$@ims1}syU5r9YZ>-cPzD1M9Kh9qs? z-XDK9`RwFKh0wQDh`1%Z`F&N|D0a42a{U0+!h#GHajmnuVbp}`=~hyFLVXe-Qmz*+Xh+Qtvxh}WIo zDN4NYuPwB%R<6Ya4vy6Scj@nr!;X-RaaGl1>dcsj3B?mzEW>V@a4PDKD zBLoSCH$(sWO-bx&KyL4y0$QHb!EdbLjt}1F4!Nb(1@CXu*fgmrfqiqYEqd7a#!ILUhlLFWGlss7zfNRL<9ZZcwS3~J&PG;r

    (EM#s`Y56NT~Z80;UMG?H35ny zXde5GQu_MvZ_hlDsWKL0?fQWlM1mo$m#BdmnJvccr)xR~YG)Rb^jflTy<66=r)07R zgl+C=4VFyZVm;fxPR|P=tASQLIyj>5&%GcpS)E8d%~#RSm8^B1W$zQ2Aa)tl|c6fBcrp~aPOd>AQn~nI&6knpXZBpB;<-f!DF%v zXeOf*DE;@QvhC9a4dE|RaB92WCT(MHFaOmOI~1z_TX4!s`Gus95F|Men<`1V-`?m> zv_3XM=!<&ZvUR<4KGMD_DveoqL)N}8wtp^Mii50k$sOt)ul*4lTDmHhm+ zFq2F7AW9@8TVd}`|NPk_8eha)H2&7e3=^iHX8-{UPR2dWkw`#)ska*U@>O2$Xbla%B|W7zu;g!cFAU_*nKY43cw%_rMYI|!8XS%{h#FY?ehQko zRUiECNug4~Ne42HrV2b4^R0{GG=d+z4E@WR;xPD8JduZ*x-xue8CWg!?G$|sHneV? z&_s}{g9IzuOiL>3C;e7kz11o4 zNldQMhpbD*`8@AuOO^ebnC(|s&-Maeky;AyXwe273lrq?2-!(ZEzBxl<7wP%X>Dw6 zXl`;B&6>TK6Jb-5dDiLceXAk>%OVCfSSs$WtHZH#>6OS^1$^Km6{2f~raR5JH)rXS z<7z)W=5tsmsjvLjiZd2(N__9=z@11@O7p+H|Z3~o@CE4YOX7&50T*7Kr*zdmJ+*w z_C-^wqWq2E9rMP^NI)*qjcBON5VSI#$$X;$X{)D<`zhv{o)gD>D zVy8L+d~fSqL^XP+%h{DBFHCi8#rmANQZ9BOI>qJHf$^T1EvbVHgaQwjqC7>#Z36kFtPZfwj|C%BeP2N9==waDxsJ#MAVlEUEPtGLuRi?RtgF6j!saxy zMZ&6InQq52$kSR!_KnQdV$msZ4`>{kTT|jeP&jr85}#%jcxAw^kw2!!0K@f*Usy#k zZIbF#x}X}MJ>3aqXy(J)oK)G5KfI0jc!XMCr!XqxgW3^vZSaP4{9f0ooas+br?zL7 z>T#DIK4KO@U~eflN(g?rB6WNLi76|nvCtW+Tq}cD8LsO{YqUAP`OzdTU_5ZM2H0U92md~SdU#&v=OJ!C6U5I?=l z-HqmS3^N+%uuJZ0F#lFrL7IEn>}udH+Bc|!c;QMdwycI46s+7pUM8Of^&tef1JIE3 z+AetffuD1Jr}S@0$j}nS_bA%rX^?$yVKuZx;9*SKd?a+qWdGOPv142H*P55uhIBrA z146C7H@iOTS#fJW9@l7fI`j)UKsldiR-3nNkuIaY3fFu<7-Oxv$P*-rG6?E^<@R73w_~S)b7PZUVHV#M(dU#{a-N_y`vn z>=`<=kuHeH#Y^No0Lt$35N}L$^GzqLwr1fxR(?k_J$vmnc7dMij^~5)+r|=V?XcmF z&7O!AkY9~AheaXJwoz@um?Fdnf=V813+1jlXGw*~I)6=C3z1cYUb;12dhLUNE3Z&H zOqVi`tceE>GeuyXD@y>Up5LW#>x9N)(a!#t!G-W`k<#g2JyEH*pH5czvX6zy*+|y~ zpJO*XGKpl08ITFOH;v0ZSi}9*+*EySdnL(i!SXH-b(`^e9>Hghn!+fEr^dOq%dv;4 z69fH2${#O^T(76vb!jlV6Z|wY&(hqt5yG6Ex%b#?hMvL*xY#6RB0aVs9?7;Rr}Pfd zRsH>OhYZ-IXY`LtCykXuw8QQnoIUI)WSyWe@}6EM(cwSt%vAz8rqA=;Fs;hqh-Ze; zcC>8e$;kDTH+p=e1*A;p$vTLx! zu?+cD0D{4t&zguVU3w+sM2FkEpxpf-wP(fuXQH|o)rML-YNf4neMj|pIyNXg|8BNV zRWJBisbFA}oqj53h7G^$5OMM!#ALEAGT>v^O))EJZ~>AGu(k(&ka ztFUbBxY@;**i)oIiKgW7V=|5YfbqC)NgWmK8y56jMgAKERYZ5EfqXo_TTznC5zeYduLx4&3@wZk=5eA!J^vt*5JZg)o&l6tpF!51OAAkgXsPqiMc$D zd$+&ag9k{LcRygXN`-50nK4v;-gF@(4%(ep^j$sb8+iB47laAr6c8^%cQORxpmpfEaz}EJGK(71mYWkHz5%2QvG1qjD=`wud^D1=AM z@^${$B=y%EB=o)d`nOYxt?*Dy0+^{eHusZcB*5nH>Ba<*ByIm|&W0bxJRxP(vkN4;8+&>Va_9~5af1DPvwG> zb?Oi3bzlH=iCBe4MbXmugT{>D92z3P&l zxMB=yDMQ-a3@2n@k`hNJQDV{Ll%!rp??le6pTv~KfZ9Hi!=Day|9Niln zwkdy5ly#l4F#kh7EhMZM+{B&WLS+dv#0RBndi`rs^>9+#S`Kw(?1v1(NoR|a90p)! zS86fUI}nI}!6-VZpc=6=P#LC1xcCkldANJos`}k>b9I8QKXc}%fZ%yo8ikYQwI7B|d!N$^Rkq%;(g(M6IZHi8GP#H_U;{Fh}^v zW62G5L1gLwkHa3g<^Qkcm_{ipw|dBQTgZ2|e9qorSfOySm@wzx92=N+raRmK+s7%n zF6gh8W0x@sEI72+jLQAwZL$l~x1qyp9*GY#^;*7P*z)UZfMA%Z{)ao?Ma@iLLCeDs ztk=85+6srpqkMecnB{9+5pB$pyR^#eOd(!|h*k>&AjS^AO<{~bRgjBPl5D;64Ef>l zmzf@}A=IzZujjtA?+6?7aozX*$`&g0#7_!SK$LvBn~kqMPR6gt0_3J^S2e>u$P4Kk zq-l00?qF6N6ltdj&+LERcrWHDO8@Mq_h7Y%s5)38Qb_Y0#*Cx*`-knTFU;pFysGmw z&kL)tDyD=>b)Tu;fGTezs3;<~VPeD{tX#rLYVE?D8~51!cTQKl^WvtzVYX2uFQ0+*MU!tR^+S-sbCgQT4D`sTobIXwa z0Wxm5 zOOK+M)2V{2tR&SR9AF|DK$Pmvuf_OQ_?-l+Y5NGFx1QX-wjfd`dYc=j|)vKpI5)wawLP! zRl+7>7}>iIvkSXJYyujLgob;&?mjq~TU*DHuU0c9GQQF;(U{ZcE|*FjHBuNJ;JLA` zJwsM~Lc+w%q8^k=tl(RfhCjkuHRQ7X;nlON@wpH&%$Z=+ciEpOHsC4UB3HBt0DsB8 z`vu8Y_;|>fRFHDxo!wk z&$^wCNWRQ=DxqKfp8blDj#esCTuAgwj0u76W2x=lftT!~L{-11#W}p14>8EAl$;|J z@iKC!(&fXVqx;nyN^v-|EZ&ZZVfpt%$P3fGC@bG(F#=-fd}CQE!lvzKbO_Qj-=<+* zBdkv*g`!0DQlGOB%vWbDZs-bRM(NNT3QAH*mI$XA^<314Ape{EKl# z@TjXF(=<)7&scn{+omMyLVPf3E7B@s*Za$Aq-fU+hUv_BwWPMe?c{MBLKOWJMn%|8 zr`c3dw08T`_{GfCg{5w6#DmF{*D8?{|3l&GxeSkkV!-WeA<>^|k*-X(@e#KT&|fXe zjFDcxPSIYS0hWP*VqSBrDFSa-POQe@f?)Ri2=M@(`RO1Cvd0s zB4^DViV_#zNJm)u=}>2ZUvlK+-7&j)vjUNe+1`rv#=Q|QYV7PgTh?O7%y?adT?vI} zB|qUBn%+L*$=885gW>P8ctcYpUA{yLZ2uB$I8wO8BA0q{{B}$RuE} zuv4G@WVUtO;CE-5r$yLTfq(Vhg;Kk$2?_r zTJowI_;5|Uy@8#2seN2+#fxh;4rtKaaj(VMM!&b{~ycO|^>n{ND zXq^D2I?&NZ`|pamfF00+-YvN8!E5`26Ueog*^T4Uu6(vuND*)?L)`{j6Rvbj?8le@ z4>-q0b7ko#FAq-Db9#Ix?5&SER>Hf4qw;eI^t-=Ly@O%LZ}9u^n*11<%X>^(7k8G1 z{DaS{D1>;irCJy-L$izz+d;W}Ww{Bb4-i!BfpKYG!Y(|PyV_+jSy}jws&`|d{XzZ= z*V@ltVcG->JUsPKjwife7xC*)#sW`m-PgpJbNRkNn|93Pf~UrK#a5`?10VMgc6s5v z(n9H+#sdSoHMj2)^V6%YyXvPJVS?$$%K(*~Gh?-z+0>ThF!^LNCmF|(H>n}9H%e=M zBefj@t$$_;`UoUOb1GxNzi_+y#}?D)IVoBvb;w=^1Y~q;UyWGI7a%n5>f`?`bH{6H z_$eVF-e#9qp9gVEX=5)iDsYxL*Kq&>DTKUl76}T2h`v4%S?FaE1uoB)JMGJ;mxy5$ ziE{vpijLr;jN&HRXYFmZs>(lhJyZVH{5;|2PDhe3mTK-TtCrLe6&zDu0I{)rqc`0l z%t1-`X4bYvatG2tw^S*h{_K%RRT5NjP&KV-Nc*wiDr_oZV7$1cz?l{LkN|?kgxJ_?@#3ta?!`8fG-hn!X6S=}C0;bl;HN zu@7VrSySpVW z_POU#H*#EG5!%GA32_m%zC#(V+;#h(1K^pH6kOCptBhwHUjhETh_? zdRw<-&QbDfv{+t^pD?S+R61A8^+dNzgzipE2hF)(Yv_xBb+-hea6U%xw_Vk*3=Ungitorn9Y1=_ zbs{tQWbRwfxWI?VPo6rFDq7(li~GRo9YIxC^EH1?XSyU$Z6TB8bJ-(E2GjZW@5@@{ zzx$4L$jz-X_&d0u?jG%vB_bgC3LKiDsJ%yGej0 zhN-((F1j}lY(8D1a5foLX5KS>ug+QK@K({zLFq~6W*ocbzV+uMjjHypLQP(qMprYAe3rjwBwnFw3m2&%K6`NKaAW~QmLgbt*{~GdysG%L{2He)Da!+C;lf$^N>ZinCa~h?) z2XprAMWu)|Qpt4jm2SLuW!_Y*k*%Ue(OBfX`XjaVs7N)`N(jG4 zc_^F52{ZBEdeoSx^*&4i-y4HNLbutrLT?rLxL#?9ef0c|TeoiJfdY@DmRcb*lz3US zLoU`)5HAtkYK2W_nQ?1QX`Z(YNOwMCTao))RFTeT@{+nm3~=f#5dvZd3XPl4xp5^A zIV!grU3U-m@{tEL2aP`%V=+q`Jw!v^wPa}CYW9?Sh~n4vvi_zH8Wb4$~8cGXv_FJsslCWdc28u?IY`T+-sv6+q>P> zIbD1^%VW^s;D*|{SciG%EVGE5KlwS}wS9=x+HX8$D~q>|rz_cc-y2!{6lM2a(CubX zQ=^7n&`2egjL+})CS+b=4d{$hvX3MHRt7R*7b19wC4}GDKix}o8~*R4+P!NoFI-8p z%Nl9wrMnh2Cy_^{kD)NmoN6e^x1QXq$*QSZWfS!Rx6J-JT_ju^j`>u;L}I`%FB>GP zM%5)K-JLpI``Q%u^Ss*4vQuj5$7iYx9a^o{VD;hEr+$=)Jm{`2LDh@^jSZODQK}T0 z*!iN|amKw-Wz8uvqga!wpfb$mm}z-@RuANk`rr!zA_3|UH0%OF?l^Ds5XQer*lG^^ z_N@og_~Maju3(8O%E0{AlVB|(4qZwGY~b^+M8Js1Mp9=bDDy}uL=B>k$!unBIU zNFagz4|1Mp*Kv=j)cw+N$a16Jfx#cP4{2;q9R{ChSoIwpa_<@w@~6Sb+q=(3GXF9$ zce8FXPZAq_jko*hhR8k7C%n-sQ5jku>pvhYu;C<02=EMm6mQ=)Jg^aqXpipO0Xx zLS&*yO|-3E?smIi8uCWl<%prBGn#rp@6fEj6s7bmc>T-Uzqt+OcDGXbxDC>*M-{%f z&7OsFAm4HsE11Qy*3v znMJaJN2dZ!gVJQFvL>2c|0#QvTn+~6B%E@bs95S|@?{3CZOz z?T3f|LDYaX@nyHlJz2$->*HSA|JUNq&VvFKyG(;Qf13)_I2ukchH~B|*e={^!Nx9x zy4=k?xozU(OQ%W9)0*kU82CV! z-i<{a9@hqaU#>ACyqg7U#^o+_(Yp0_$%4NB>N-EEl%-Lt7BE1%4)H}WNOdqoP{+@RdVq-~f&CLJqp42Ykc{JrUD!?0G4v9vUZ*iAy!@%XUx4q= zD>Nu^wXak8929K~h1t=rdNK2^NaerV1jXY${7BM&5Dzp1DQG-^DSZdZ_<644wnAk$ zL0~`3@3TQLF9}TWREQ`z%?k(`ddO1fOwoOcCV8X90+wb@v4VXh&Oi6?*B1pEeW14P z#^rqN?K!w2Y_s}x~umhH}SI(f_&*RjJIcPWRyHxL~2d4i5VKvvEUdy6sNan5%+EKs_sD&<0;Y zu1X>Wwn1ypr8d56NaI|V4zEOBMAm(b4KSk)3nzfutEoyqQ}<2OwymKdS!^ds{nh34 zLL549>0hN(|157RXZ!Sj&6#L}2>}sVz(a}vkvVq>h;EnqQ+8syMN^x#s`tTE2ve*? zo1%`8hd!5>uZf~(EK}qAlsrgUQr(nQS;^v}zQuR(vpld^%R*|%5o!rW6o+*nV%wwu z0A?mYM0MS}x`vXi7mt4(P7`z^7q3f`P?kl3T{(WJk?+8_rnhrL*Ps@AiNU<h$zjP(AR~BUPr8u% zO2Pw{K;C5kwp(Z7hULGvquwE%U_?p7E}uyFS!gF{7H#zj;o1iwyWY~BKg82k2U7%% zZ&$>pVbVgu!7)X8$jwY+0Is=%C9ogBX*X@dr&5a^Uwv2Elk-+(Lf_xnOKgmd@HwmH z1>Nl@x+3To==uL3L5HwqL@T@w287)h;N(YPCbqQa(~l`jrQYd2@tS&3x_O@GecCa1 zoUsX=(+w&1&-5~pM!cf@NzeGCPREno5(_p+GnbVmGjMDFe_?iMNDpDEP z2Hzpv`-DA}+O_>-*VLGcTcdqFXs&-QmHrj$sAlg5o&Shuc>3v0k{HqX6X@gFvbH;C zeNI&3k%1hB9s;+r?R3VwxB82stjrCdjo18%eWy$yQSoCtoa*rs>qopw5pE9J@MZ&X z^Y(a;*cQ94+>b7n)l{?|LN^T1wW4z#=U*i1;d~g~VNA;J=)(Pm?dV!3N0Wn#n}zN^ z#~Kb=COAeMLBh|0fpLgvhu=fa_!|+#m*SzvyVrJX80ec$4TYdP7P_iB3~P?5w12vbZMwk4is1ox&C^b za#0rZ3OW$a*ReVKU1XD}^!*BX6S{n4e-ws|;G5(?eb07r`Nr)CHq z(Jgdl9C&$A1bo=9&4xARz2}O(@Y*OtmMg*!9h9#Qe7bfEh!X3a=y;~nOTkjMFS~5R z{>%;rsjB*qcxM|+m-|cK&&`mBh)A}#A8%U%)(x6jTTpK26OQ}{%3^JY*c6$1W`q6r zmNVu>*ejBtm%G{g)KMd_84n7h>jx4uQR4$in&9)?JJ7#K>63@AyMo~>@ux3YVZ@jg zKMkk%k81}|HfyQz@X<*t;lWMC;grv-0Ml(LCiX=2-Uu@TjsCAy|LpLmMKw?>n4GuFpSMwgq%bjYZ0kfm!I?Z&Z#-jBshT19Itl+!D7?nf>ZjMZPAz{FJQ&u zDdslN`}IzAv8Mm%8c2(wFlH-Fou9BL@e-uRTOZqCuQ@#u%_@*skoZ_15fSD`Zql?^ zHk)a~O1?Qk7;26rh0_d)j=6@~p_m7U(5^#(;9PPeLG zU|XI1ALLpC5Wq(QY>mJ*FzcR|NIQ4q~Fp`DvOgjGjnd~H!p>sbX{L|k^3jaBFppz zh8fu|wOQ~BeO%=;qt|EKRv-Spq5i}6(*d7AW^eXDHxnh#l=<+r3sJj=h0v|5+gP72 zjX9f&y;kuOW9E&q<~Nd0ess}<4`ZeYSi;Ba6Pn5dWG_W<6mx#o`*r2k`KhrpMn(_5 z2I|vf-TDa$8bR5T%l`>y`iT5HK>g=R(wvO=x!Rbs=AgIw_toDZFW$Mgt^znTQdv2u%TLP12UA5MS_<=kB&hs9#s?SbgB#y5S~_C`I5Cun2`g6C z$;n$vKr$jR&qnDCwE*k7*bGE{booFY!)gO45|d$C&f%XQ1MQXnyuD6#|95XTgQg6X zGjVFvlX;Y|dKgXch;eNehzK6_*{O8y-E^(bRh#y0A5e%?F!M*0qQC6#4txqbOY|xu zseZ+?7UQgvUpRjJo);-+BjDgd88SwD3ki4$GQB8K4S*1qB!-qvh3bCHi) zGwlpHGwp5L54yKD3Zn(6r|FCOl~-VRQ=oT1vm%bo@Ti2nFx3Y^pFRAROoM#2noY%O z^n;WnO^kRVMRgzoLA}PPY_z)^@zVKE%W^S};&_8>e3upel$bT;pkgv)!Pp_7YUKP9 zCOMEJCbw=6-SId@J}#hdW1S_*wGl%;5kJrA=KIvzZ$7s33{q&_$quVfrT1_Ab!tw( zf!^H*B!&UXk9_sXW&Cgf%VLg?;LnP&e{cF`Rv~jmq|ozdC=Fl1F%;Bz9DL?ZdtP?1 zhgshC-GuDLhTp&qjASs_eqa1Up04OTA4t=5v=mQY3AYLzgxLh_;i2qr#ah9?hZ*o~+ z_Ph3K0pApJ`uQdNZ6ELpb0X(x8sqE`EWd2G@|2DhZ0$R|Grn_}1aZp6@Yu&03ddwF zeNiS2T5bK=^#K=x$OPI=?s+4Eu~hnRsKwgRZ2&c__ z7D7b*W4Ssn))UIFtoJ6*++D62S~PK{Bth1TA^n913|!$~9*#;s}?MrnmHuE))FeLQ{R8;$j$bu*>Xbjpd_#81hOBaJlAaRFd zrI`40+mO5BA|WM~@>Ro-S!#h(99pY_#IT%dFr~2o@0v~h+1hnU>|XX&wWE8M!by-- z$x2hJ>r(+zv2{~BvPyqvg3j)V1iwX#qJ~p-%7PMi$7P4&DqWRxMthy|Rnl&ShE-6lHH#7b33PXDMDe|48yL3EAAV;w zqgjU!sdnMj=r|=94`o6df?rD9DV|gs7}BR1HDWMiEQu8T+RsJ4j{-WW8=sT0UXrvJ zDrb6X3K6wJjg?4i)yK=>j-!@ej4#xiK^HzOIe#@U^zONlaaK%7Z5z?-3#z@%``h3E zw3-jL3si&&{DFx>LV8Q^&#*vYco*cFQTS^q-zh&F%y#mv&#&$OF!-%m9lK@RD-Wm* zU@gQrhh0-iXL3gnY3V^`B4Vii&u$CO9qyS!F3j$%NQ-n|nvvz-rTayj?sGHo3%z%% z)y6(aizC{w!-w-f$P(I&NDGMoPkDz<*aa+#CgP{#mC;s-k3A)u%R99R!Vc9H+3i`z z^`Vl|-I)8KjKtn=eaC4;^k-nq+=U|D{CP+yG5uteAk#Exd?sPc4&KdWupf%w`admZ zC5s|(`Yo^jGPbkU)^y(}>Flf(5LDge=n3G4L0iLJXvSVG8{) za6bmk*s53T=oX589`LCG_1>-2tmgWM;wMjj6h$3^thyM)5a_jePwgJVYabQkOt~~g zgK%>!As5~iO>}s?Drx)?*UNt?UVXVr>X5q^fxo+OYoc@ZU2iHr#&Kdli|)W%ZZz5Y zEnet0TUas576L+#&W=l+zIyLamZcE2L8a+B`)O)5EfYn2f3keaee3I_>%fgo501gR zih&oXgdZ*|KLu?yMfrbiwJEiEZGAlLYTlIfviU8#H5Z7V@ApDhyG_GeZrfl{Xad9E zM1k3W^&>e~3CZCY?AN<*IpyOsySIj0xR|9!JDAa{DC|kA|F2zL7Rx&V$={&EA(6j<1~j(+988mGd@4g-KHOkdbMo-0!cAj`NlZydn#;4kYehwD4?pP=th{VzsjjCAt z+M1`%t`TA&Hv4J#K#dpUszgP^_R?ud?p+G^pUR4aSHONvVCA}`pflOn9egn2mOJpM zTs+3vc!6r{Enz;cp%nQxdp{BaacY&LF#6-s*ag%M`crWJKv#oGXjS^NhhE+?7^8>j z!(WX)@TSP>T>xcs^r$Cn;(ry{;0TPjd|*csb>tIgi%wYT%49l=3aGnyK8}s%!9isr zSFk5cZ+<#2Vh+}rR!(Td-bFIYXv4O&IqH7OI_0i~TimFvtd;)!h4fh)&!7Hr3be5s zRc}o3h?KxL`si^bsnc!Oew+LCxz@vKYA&}~FXvWbN7&q0*tch0rt%&Qcla}Pp#`7r zQ>*PKL3-aezkyN{r|;IK{Rg>;rxXQws9us*$u{PP_;y{+2sy0yW~VoG$eTN7Ke4B@ z`PTbxQzF)>tx$~yBwPIWAHpVq3f&PVK3m>?<=oVWpZX}RQ1&pO_I1vSL*eHgbWPi2 zsk`GSJJX-iYqc%*)XZabek=5c3lYhb+K5e7;o$V0vEbGiPhwrU=FFS*iM# zKE4;!ceAA~m#OD|9Jhguo={{Ff9-A(qy$k2?sphnuoYMe)R9xulLPt#?K}ik_6{Vg zxWha&P5Fv*GzI9?`bF9lU@VjinK}5j&$@fk|LYcK&@Kh3SNC^j2+du+85@3&Yk{$% z|HmAcufc0lP3Gq^g)htZ)dPmGA-1t=IKFe%0#qwmb0mR_R2eZ(Ifq}0hChb!5ubHF zJ?Eb1sn{oC*D24ZR9)US_6wx1rQaZf7__?z3P|h?;ztS@IErwA0^Nc$OF+B9QbO0$ z#mDmm4eh@El`b^M95eU2%SeZ7XALfdvcGRpA^H+nI9rH_yO#F<+DQoLtcTrCZhb0u z1YsdFLm^N9c33x^@?SyKt`V4Bk9bdCT)i4D(WFKB?T^o&6^zBNKm@n9 z(|^4=?nys3n`*rl=)iLHO|)CSQ`|_<`JH%!%xX>UGSAcgfBb3FtEf(RZ1dEczz>fd z*~d%kza?UGwEGxyQ#)w9Eoq*FMxWgsLh`mB7#{;8XA*5i7?dE9to-iGfW^;`(~oLBl3(3^1UyTluj?=JNU}(A zL^4Rc#aR7bPa*uXey@h_65LN^f;DXL5(%x!vQ4Fk#dp`}8Zw=8E(REVU_nQhINJve z12=T!@_MIP93QH~OkmbA*zBf@10Ut?B@a&T8a?Xo{8I1BFIk!E(pV9WG4!4R-}@#= z1ftcyXjGyUB0kIozuv9Qjz>jR?bORW9`+E+-wR%poWkDp?zxk7t-9}9gq*t&A3-9a zyRvXo)%Im}y5i0k<0~nRI!`b4KJm>13B$@`TWz3eiuX9)_0ema*o|UZo3}Gz_tv6Y zH&^g@y;!ga`14bL5Jb_%pwzIA6g2h`5w4d?I8B_;q zRC0FMJn({X`%$kO^_Cn_tReA({;AsIt2mqMjeqiXCl$@Ugrp0|Uvs{_VB|0qwdb)b zH|u|GEU;i^8>d`a?#wkQzrmOCqel3Cjh^>`LDzzfE=>>@k@^%Cv2^lsrvnpif~6E; ze@@r6B-cLkysgWbX(AH)LY^XifiwLk%=UOBr2uc)0&uJXW|BU}jD@J?t{O`I&>-Wl z)M=TVMyQLKO53++ML&Cejpese5Nm?{k(xQ= zkZTv-kRMz8cnRc))=%y{XaX9Kg+aSf4uR2LTXoK37tLtx9OBDU31o-6Z25y&J-J2{5yR2gk4Ljkz5Fvoy{+M_G7Q^clode8wa=&m@kgw z*4(epd3~U{QC3WR^@L#)K=BdA|F6fZC0T~u;nui1-D*fNjS%L`kol+kuXjJD;bes_ zGB+LF$<%?(qPo684aZs;u)B)JHF3k^OiaE47Q%PUoo_#(Z~BfJ`p0LDBf4AcJk|cr*a`KRA|_@EI+7d=C=3#*S>J(hMquZZ6*( zuUk+xYnV9PwyvzKT)vwoIeHnOJ`mPUv@lq7ym#cqlSg)G@z?B9uQI^Q+pN7AbYB;< zS8-5_-kb6kQC ziuL{v;)9BeUN>sU3B23%tkBv1)+htt#SG`Q%R0T`m+}xm5VB86ZcOahFK8|cjd9L#A$6#FY4R)J2VrA<*#1-*jCXiUpdpO)6LAP z0br92naZEnDvZvgKsW<>BCdh(U1V$lg)teU_QtqDesS~BUf{vB=Sv2GH!crSxM^6! z%M0TH-JTGRGk{YCzQ2)@fr>W!IDmMKW5 z+)Mr5v8V@oGtEgwHYDdk)DjKgGhBa}J`nXffvlv%TG=G{@XZ5GTkg3`&FVS_O}5-u ztZ%+QQvXv$gY0nLxwhISWDGQHn|iPxZIbvuyCnpUJLE6i$Ir*Zw439KKS6g0A395B zO%#%%#YD4(@7`&d%Lk@5St@vEG8hP!M9?s8nqbvV;8=pcgGxSsd}3PnWV6}5sX>>A ziTQy1CM@CVC9mBqEz>~2_P9WZp(F@3{RML^2Lk*E^goE#h#*OuTo$H(s^gKTWW^nE zfqi!CYQ)4jqX_fNBF*v(seWem0)W%L6~62Bj@Op+zAgW}Gs=|ht=B~n<7jrJ zaK0%G4JlKPG5r|(66{DQDXGLlWRDNHaIfREr0bch=M0boi-^~xm*X-sKL1pjs< z#-N^?>UDExI}TT;mI*zQzLwSwq|7*wWM38ErOi$-OsS_XA)1+d{keaRIZnzg&+x9m z`3t)3g{+}TM|S&B1w3_gmr(nyyq`O~JX6JLv_3>xaz3n9+n~SLB*z3EtVQM4ysplx zT8q`b-uVv`JveUkzwWh`#5@H482*2!{~x~IGpeaB>J|>tRH{go5)=>>5kYzjMVhF9 zC>^2#(gdVR2?@Oy0VyI)k)i?tsY(e*6BTJfqz3}hC82~!ig!Qn_vgFg9pnCxUygH5 z&e?nIwdR^@&i(&*gRvux4+xCC)8r2+lp81>hZ(K@5f}G!jZJ~K=7QgAaBG>MKXbrw zEqxt~w_7I;N{)L52P?ntw0+Z*X~8XKn+`1PM3eY{CD0rKlYBqW2Qp)A2vPJDJmx(JQu67X6G0MWxyO5ni8Bt|$Nvl><`Z z5We6(2l*E3>iZ$QVH12-m`uLwDb|)Kz3W0|#7n8C7li(}GyVZ=QDn^P zIplZC4J^NfN%(`eHnif0G2c^$p37|elwQRhVW$?31>TZ2Cd=Zyv=qL|*ud%)4|nl8 z?>}yj=F@DGB#*FrD-@8%b?YnnPFr?aEpYB*IM2saG<|lMYrwpejORHcrB4;VDtSb7 zS|GI1PY#FTh7+b)V-W_pS5@rP#ld*}cytUrlxoh*^j-xpxXrr zME?#awbMG3GNye^Ml>}ZlwOIeSi|a3-?!$PT;cZCFOJfYmgtDsAyDWiFA@vz-FBDr zP|QuY9{M(%Yg&1y-tE_T-#DcuvgaS9rVru?e%&3aTIsOLXYbpN+N^CQPNud}zf{`U z-{k)~bcpIhHmx7s&MW_=Td_WwIWs-|dVtrj^xk!gICIwf%&2Q6%>&!MM7gEaM8rk6 zTC%b)^E5fwqRQTW-f%t;%P0{l$@Pr$DokwR;0l;(U{1~wy)-83)n)jbcJ5xWaqTg~ zU4}h{w?H0bz!S2MnL&Ma5@@H@X*0eox-@U`-od+VHs*BV^55$v^K3IpM~8gnZ!D@U z^b!*xC*MIJPatB^m|Qb(;TDw?ZF#B-A+OI-+9bso&aBW8*FfLToBQ}ZZC1ti1|@oi z&L;G@nFv%7Ry{t~?zTvHAOh0W-O3?P!6~~Ct0@x%9*>JG!`GkVea`c3=Qg6Lcl)$* zk2w9De81Phfox6J$@&Y7f(%B2^c*UhYDN2qfD^e$$pq{`is*R`Rr2-Hx(45p!_aR@ z!XF6X2O2abjXb5iI)Z@%wXhlMC4LOW(H=Qca6U@paD2Ny#Wd|^n$)Y4#WoVz zXBjmTP@XhR=zr2ZDO1DL3%7hlNIo#)G=y3M?vk>0bUT4!AJRW;*qHv6mES*q$vow^ zsZaWLRKIPK^n9ln+LQLG^AhHm)boDPgnub z4sros{&-DH6x)99?LZm8a7!#Z^Ld`x_q$|9r)Kf_hw!agB3Q`dzNd#(qJv!0#clJa zO(M&(%z&{j=ua^DjVh+>2vCi|NaIp5=`;40X=o9nrs=iW(5MsZZ4Xz)awx;073R^RqMJA4sZ}0jNYwoh5*Ol?cI$&=vY0g>&mb?Pu+Ttcm z3=!PgJpL-(o+HH0zO(z2j2{S=pY*5v%Q7Cot3UO}m3b97PG(fw^o2Ty3L7XYl)7XJ z-ha>d3%jRF;iqGvr#tyVX8N(}Dlsd>7OK=P%H3&Z%5eU%_1VEa26G+#j(9G_!_GfM zz;^J(yC%dcc@4pU>Bbv}KA+zj-`)gA&(-&4akRfXpa(LPgIAO~5@RH5b z))^u6?@E#;tqqhL0e~HqfL7$iHm3P6FT`5ymM3q;8EJgtb-jnL7dtqR?uC+NI?I<} zOq=SgaqYZ{bCwp(;UPY5`KBUHZePEfM{HeG6>BZ!>MPq`Ke`hz-6qF|&>{|}Gk*(# z>2^$7jYM5+id#9AJIIh6%>cvOeLDOMoaXq(r6${r79EYu>LN1~LTid79D5l)CUz}H zfs{t|$f7T}laK6&-x1N*8i;9!MN}Jje$5*6V*6Uv`{aa0D!%X@`V{pNIU7e)p}_mZ zgn%R@_cv&fpAWHL=r5#Rkcl$F%3!4RQPCn5kaDr8E$3HjpRBjq2y=>U7rf(sWO)0@ zDr?WIb9{RGk#47i)OUA^ebwxnm~FTS z{TrqQ)GQ|v0wdJ3T%SQVO~7vL!s8nBmc^uUH1{!yC%Qo*JnFOnCl87ba%zEB`!YhI znH*G&P;Vnx<-DDfY#2hM+Myb*W+|pVgY-b`J5|9ip4pii&>L-pN5Z)-@4pnR5%*@i zmH)<_SLl4RiDbZrZGOG!Qvn&-35+)S>fws)Z&nw5h$sC%zyrA z#B0pQE7+~dIJ>H~xtm94V|%@R0<;m1Hf*ndikv83*k*ua4|;`)R4o3O>kSe-wLKfZuJ zqwEG&+aC7favpoR3jZ3f%&GLhLlA_JQw*Wt2iBZiv}iBpp!K;~|yh^wug&T)xW zw02Di=Vo595EkT2-0L&QiHc#-Ui)}!#A6|U?bng8=5OBG{a@#0OikSvqnYnszs_*) z?tKU=gaQ6+p$RZ<5b{qcp;VUS)f=E73ZUnokx$9Eq<8u|w6BFx2(2-W!PP(1U~~OR zg^bM~e|B?pHZo0|(a${W7=YMI@UZP}JT#@Gku|ncVXZ*X4pGeM;;8UFLn+<BxB2?(2Ee!W&fejyV?pN(Auhm&}Zfow{A6UPU zx`Ub-IQc?G{|VXGS@6iC@rH9*_uw9qZW1yhB%lG4f@-$z1?zFT#DqNhKEyB3bmyc( zpKtl>D{Es|l8ZD`g9{GW6>rFG5jZu=A;Hr!yIjVEym+8V(^IQ+bg#{bGdk}}#npR0 zsr-MR%iS9ATb;$SU4G?fV9}Fy$6txy6(8`V@9k zWdM=kck9o!JVYRRfk{VZizj>Nb>M%E4yPM9Wd6SxtWx+zH~i0Ze_bF$w>^`rSfB#j?o|jDgA1 zLJrVlJ5v&%=6pvVD&edod%O?v2-;Q_&TIV;vb_5yWmu}*S~{M&?k)+u;HNMzIG1|? zc59G$gX2!W@SA4B4|EWB)>TAXikF&eyurRp5OD3#44w@`ufXeIA{gAePnEskV*)dS zr;8b^X<{gz>06b<0h+Jx=eAfhS~6QuZ>HWAn;N#GMh*>7U^!r}3QKh!EF++sF|KC6 ze3#s|VXI!bS(OP08F#v+r?q_EX;r##2zgH#bjZFisxC*%?Ei+6C0af+oMg)o_Nuuu zB3RXQ(q057nA9I}3xd*mZoRJrx-Y?G@K?VXFaxqM)JGZQfR=9bk!aJ-f4Zc2U<7>n5j%!@uR|e2- z!L)IL1_H=_yqa9ytpJHk77`ptvHl)LH5$#+=4zIt`{;;_H)Iy|L> z2PsS*SX4QNj8F|SlUsaqK<7DE<8hcRW+tVpEb}-E0MzQK&QuEfU%tx%;H}_r*{?C%2*hlQ7q?g3&oH=R?@hF*=8$6=#%rxDq}S*a5&*x z^}DRu?04LP*#!0&m!nNpoaDh^O$#H$59|vsF#C~fm0QvnSC~8UMmFG$eR~|_&JHk3 z8?YR(bo`3yet=YXUFFNXcDV~;c4RII`Z=3z*zN_vPC0}Hzyo9rYBz$}!fQP>E^j@) zd~Wgd(?K3i6G&mMbMf+0q;~KjdUS^@6_Hbp-F9@xn!l-7FzL+F+7NcmxXdE7*2Qye z$LR{}0c?6U(x}I4m&;iS18gg+cOuUW44@)Q8kOQ&A`x1ObhV}|(-Vp>Ud@k#B~zW$ zZ^#=r_@qbh2M&J_zhla1+Sa^LVi zUB_@oVS74a@c&{2{3DcLn4)0><3-OidF9{EK6B%)z+F^huKApfl%WxV>jqT?-G+Jq zOTjc+_rL|cKDl*4*`!n9R!wO;jek!c+O$Z2eLmQ!P>$#~SBdlwQ5A&HtNw^b|2`pG z>umcl$JSAh#p=#g;8%7WJ?Kl8QZ9PH8Ao*5m2t-xhGZ`89ZUNxrK87)b(bs*tVZ+G ze*(S0mvU?yEg1yEaZ_X2ihxjlx2#!a$uIS^^23}Bfd@a-!SV>AC?jW3e6UAeCENq0 zQ&XGD$g?kMeZ1u|qig1M6yj6MVj}O>22VEr<}#NIX~)+l#ye_FD@z z5ZkU%we|^~5a`YSn{+-&PTb^8F2^kYy<8(bzd~2DRk$Yo+d_*9kPPtE|4EfyOkops zGx%A{u{wpmhY9lknz$>|`(@StT=a>7uU7#k=s{lb@(w5159DH>y&)>cyv;Q-{~A1F z3`B9F6|^>&J|-SU9h5NZ zFK$B(=+n*NCRb{5-Ez+5^F63nGKv>dVAVfoPw-`;wn})=~ zvxC^J-;29TK11%m?_IOe766pjeg(k27NgZ(uHL~sl1sLj@5-)5icCnEZwQ_^*Bopl zw019EcY{lb8eU>{gCjd6ek2INv~6TPv`N^Fr&8@+_yT(bw#6luIRs{@7rA zEB;JD;}pC=YYp-`y%5_$)uiQh!VuPkL#h;`PlPs9 zhlRc3`7|M;1&7NlDWkO}7@6LXWuIbDVc8er#5g#_0_xJI@=lDx07vo5d%jEvP-$%RO z;<~Hitw6G-p6oL@-P3dATK@bZbGvd~wO{|Mdw0dV093$7^+yxIcvpr`nZ* z7T0TMzBhS9tA9*QPfh)nIl%NA&N0!i$eZb2d()98)!y^x=2;)g+uG_K z3Y@Mp#_QM?<>Mf%lG*UP-4u5Eq{>yJ0Ir@0-Lf40w+cF(z@l787pfn9fpK|5<^yq| zXWE^msvNEk`xSGbES!F!@fjp<;$a_G0#r~@j++Yopk9(xL?7nJPZ<)pcvcuM^Xuxy zl(3PS;1F^iIt}Qmibhb#<7=D0i%ZA?I?!Cevl5mug--AE%iHSY55>S^DAsBThnv}NGe6PCX+v3#^st%ioykoWA|p`cZXr>G#ukm_I( z#ZN9x^E6-6R9lOe*L(XWS>Dmp&raN_zS?#5k}jS#U1moZL%uBC|DvWMexZAsmq-1o z3FPC$R3moA8@k=Atia=*N~^5i25p~dxh2=MR2g4y*2E^obVY`Hd_E44(kBo>LB7SH z%_Eh#PFds_{8W$^n!`gt>^xDsL8-qiSa#G}Rwgg=7qu#~{*TV^G2l8+OGJ4NN!o$d$Mci|piv z3(0Po$kI|rGevw)O=l^#;V<-DKDM(e9g_~zp^F2z2ZBX}O1Iq*n6hEs4m@7k{4_!j z;v>~$aaeAX*84I!9k~cv;YcRWWPv+v_ZalP;~ASdEdE^bD9`e6$#rrGzC7@1P;281 zg#H|Z%gW8oM1Hr%X7;9N&Wm^Os6wtij^}ulVVPPOW<3o+wxS#Wacu1o71)09EXgm{ zIO){BiVWG7416rM(ZwCk&4E&ZH3)345RFLp3FU{;2(=22qsfe?0i@Q&4r`VZMS5*A z*S`!rxyK|g?wsm^tw!7hQN04;L4E`yY^N5#f_UOzrSqm zy^<+(VH^MkDL?-~$mf}Ja$2@x7Tey3@TmEqm84%x=y(YEEbDv^%i_}!T4Rx!!g$-u z0J@I#lIOfm_VGs3kLK#}Gw04*#E0>zc5lO@pbaQ0ugns53y+f^;0-|o@TpO}Tfu~H zu0c3T?ZwK;kq`XV0d2p3oKWqmZNR%xd1vr){ip0`lMD95Xup>Z$P> zoBY5XGs%Ph`VoY?rZO@mQ!);pTB9TjCMmbwi=OkRHvRPMGg;<&6O%qcgl*MRjOlY$ zQ09F{VZht^{0*cSPj7H|IHR6)>W9ihn4C}RiCR7r_88VP;rk75J{$m?C9XaU$5y*E z@#W&a6AR%-xqpqsOl5wH!e=Yv(Pf391}}&X^V4u3jSIGjTZ*YESL6a`&DNr6NJc_q z%Y|fKpR7q`=cu{-tcW25NRpTzH#cXKe8#V=#GMIgnz?6kT=<#doj)hTQt<^;G8rU5 z%ogMc0=_FuF6z;UVw#_#X<%dg@0CX;H@PD-WkT6+-TI56ABbl0 zNa%(@fz#_^*Y>G+t@T0{Hp%2)TDk)gna>PDhkF;IF?`w_PIkXQ^KuTG@VoO4A$0M^ z7v8<5(HFNhQkTtH^G1QFON7ii`q$WxF~EH(BYS&U&Ftg`SjxFdLh>I*PX7l ztBWPc2zwkFx~6@JASm6d9yIGe#hfuDtNi5MY1ZHXKuIOll|e5>3d}U2)WE0{MMeXj zp)N8xBB|iupOvf9~WSub61^*6n>_uhUjEbHsHggfUx3WCvBlcTh)*#dskXIClO)c2-(I8jQ|8 zNE5aqklqHp1|{6Dg(>4vGp4V1jOT8j{7@Wg&fGyy0NXNn^3uHW5l^2|MPs(r=|_5kK|@FrH6MM+*N>6%VZmhxI_G@ObNf zFPR~;#e~?}gH4SS{1+=y9vas6oYgn}Du{E5%2NHIaDlP^VkjCs4dnuT6v~cJfu&G` za9-OoMoq4^wKfCijM^e?47YR+CBzQ)`VS6h7a0GI(3;7Xgw^YSS-jeV;h?HUT}Hq> z_&(H`S6Ew625mT1j44GOgJ^><D^McDPA8w>VC+7 zt-TeZoi86;u4jnxX4A;S%&}jNm$Qb>v8rbNQb?^EfZVqR9Y`)8S{Z6h00`JGB!J8*$cBWf15$&+=3j%?6Zxcc0hB97>Meb!MHCRF|T0`LEIsKg3z;`o>VzW_r@%4 zFEsknj_t!KAaYY3p#;*-v2SfVFn^_JNKoI`#t6&UJ4}53PRy}{3Y1@% zs=%LBuu}RlKAXF&bhgv~Ad+s~`gA}_qIfBR!oO(?*0B4Y>O;61#LkKKcov4L=EF~5 z7QJea1HGRd7vfS&X1Hg2CyR~07l+(8zaV-Wj3bbKL!1Ost#PbWepz0G0U7zVEWqQb znrgS|%gN4+QTm1d8gs%o8hy#uVK;kwUxXG&<#bx?sqV!K9v-5^{|TvFgHXA71?>S ziB?0uW=9Q2Oy0zE?Pg2cq4U4}Tg{K9n@F>rx$wF6 z2`ePboHc$F?hm7$&LFj=3C(odo;)G$IJ25zHgDZm(3$zpUA<^BrDl52waWGe(TwTc z9ph!gvpLUqkE`)A6nY)%(~tkCx=((8!J<|98N+}$s=Ux`gg8)x6u{15>MB!Eo=_lm z>=;9OJZ9K>7+e)3>=mg!*d+M(=1TH~XFT0%KiKX&t3v2+^Do}1WxR;Xu%k=1dqRlu z&8=MmEn;($p0sVETOX8s=|+gxJrvpc$h&yPHmP`|_wZC&!tW%+;8Msz2A(GUxWJYTiWJCmb+mcHeHrRlXc77J754!j#Y8;ZRg|922(xC*%%pzwhk&Py`nNMY1Aq5*Lg+ zu$@97p0`YI*FV=eOq40*uJMv+7){gN-z*7KYFySq12gHpxt!kppLa=4v1 zDPl{8=0(}u45k#3mQ&wEK5GH!w=ONe>PvrEz))C5H;jBCVE`4?$-naKK&LzUvAU6gpo|$#*Yr#&^t!1_`8JHFf zAl^<3bfXB7=PfC$vpNcW3e4_y-9ALRO>N?3XIL|3MgI&0$Lh z6;D`TD^u6j=P}s}DGMJk1HMsb?p1UUrF#@SK1D27NVXc8l-aVLbu5$ifb|r*m7*tL zQ6;Cr^q(I>n(*C;pJ0%Ve%%AqKW8_z9iDPMjydJSa$WT}A`DRR?ndT=fe zi<@IpMh_Y72Lo9cuSvjmcuzO-a9&G4AOVf{WEjB`OW=>3)Ml#tS<^WP%??1V3Q<7=dh%|$zFiNvOxlxX&pP|%9OlM00NHAwje*<-Z0pmC!)M;T zI5T%B&nTq&L;+;48eHVd$1YJH5&|wTyfn^MWt2Yb7(!n6`?-(yA@32v@y4~y2h4|V zX`gj?lXt53Y)drX6w|5n;MaSRX3~Y(P7+|sZ3O&6sSO$W#F5njN1FP6`n8x?;GBM1 zbsavyy0uV?a0G{3zbvacS(K^8Np|msF1zW+M~43(Hd!$PxkmGnxFFmT#y6u6kXv;A zK?=NH`<39q`IceMx^np6B1L%tQ=3bWYkX0vf}7r=2vPXWkk!wqMwJ2IX)XZ3BnNuc z=r1YJde~m-MX~G2N3EssR59ER#tUjD?}LRL?MKH(nS%U(lb+}M57IZn+7lRlWYyX6 z%1c{tQVyZDBy4h7NmSb^dTIWijHLhB?mIB9au={i@~EeZEGej^Y(C+*W)K4s58g4|{og{71S);VuXF29-KJP>a-OT@XMRztX>CRO{ zROt{9+!ViHXaM9nfabnWX$<8Kke&nLtP;tg|h=ApO5uJ zgJa&E#eh-ld{-AEW5fXT2JL>4{^zx?LN@oKfn!l3dS#Pz7JQ=ZAXhvWKTsk%a-&M_ zdM3B1e|Exe4P8^aD5LRV$?{_zqf6?tA3PkPM}7~=jOz(qN3#uNo}ODt-Y#+hmHEqU zaq@ebm!uv#uxCb^Rf0OPYskj=Zu@|l`c2e=VZ-JelAHbmc1Bx!*3+9X+%xWpza_D4 z$#3)88ky3mS6aW>=+7!$g*GF)ZJnmv4Uy>yOGrMzFn=R)T#-=xE%ds;APu>9eDs?# zt2ASUJ0t$nMb^JikUG7~jbs>0KGIke*eW9K;ENOdmQeAX0(ll=H5I!Y-v&kG+Yau> z8#>OQ5>q2XHVdZ6ITQip81y(*+7FKs4lx8?Hbc+NH2nuuo(tkMj!z{z;H3q@k-w76 zsu_kIFF6S$X))8nc$K)kemEEPqAV$WS5bagvcBts!jl=M)bhynR(3austUwCS_XLA zX3_LBV0txf(d2StP|msV*etbNWhBEh!|!)R7_$4Hs24!!1u$pYTZ$a@>Rm?+@oc>$ zrsKj7g838~E!7PsgyLaAhUXP7X5bZSvFdh#0H!z|uPt zI}hb9oBJik$Xv0w9lR>Zsm|a~vdu~fMtIZ85Ynts?GB^@Wa@d_^7#I1f~|pSW>@Pa z<9zcuSwhvix>)<>iw_Xdb-Vnl)5**S)Y9rpl#_waMW%L|5 zyVOvT)JWeK{ox-l~v7Tp{2U|M;Zg5&(B!DB- zi$6k3x%iK)e?sdYzNb$>IrzF<)f;V@Tp}iGcfZk3%uwtXrtBB=fsX#4Q!eI*S7n&* zA7?M$<>b1t8$KKl6+^iVr`mC*T}cai6EZ&^;x>LqT*^bzc{l&XQyIoW5ivE8!98ft z9JZqeU~sj`Wq5SL)ZJs#z!Wkd0sWyy`+t&Ij%q2oi2L^L72A37f%MALPt3xAhAbLk zMBMBx5!ktcayOM8Z`Wn_%(Q1_V=@mqcI?ERkAF_A)<6(V|BW^fZp2y9-j!Wun0dW$ zDsyBfp&a?xx{4}F#^8OUiZ$!W2{_?;ueVbydV)UbHYLJKnc?s6yUiX0*&MAjNazQ{ zK6(X8KPjGE(ln5M3{pDC&?Pu{_0_f$;AwF^rj@Bln2s9J+PnaRN`%>>OEeDR7tx0Vd3Coi-VzT_x^kD_UQ~lA-Dv0hur?WJ z`5HvzQFuZsNtr-!hYd}36II+ilQ!{6fb^kCIpf%>^G%zoJ2i)#0fkXuir{EK0&Ljj zRqE*vg4y_tZOLzE-om*rr80Ew{UM9ZB6CWrsTLrPzp2eY4ia`uqGEZ92#RKxxMTmM z-5j_Ki@m=$jX9^yMxR(XgK>k2g=F*=$acN7#4h{2x8Jz%qru^FYTxo5{S&;oe~!_mIh{&HdW_J|J1*AE3i+VYKeFNAM** zB2N(i%+vQ4pC(96)F}4fEqJ)jd*hD+w`QEavYL1xlUr3O7YllWi+VG+-Q}n z+OP#BP^-9`s28YfP<09a33ao3YF{OC#kgeL9D9AuLDRDDnxxlZ$wRe=y#7yAMM&rh z)C05_eb!E{XU_U2nQgHZVX&y`vzuUk@>#dWO1X_t(Y5SooD0k9TSW#+CgsjK*w!fV zfg@uE`TD^a!?KIbO0xA#*r-jiPXjR(h!6aU-_DOR5@DgjREYO#9y#C@?o3fJ3uGTXWbxBdZv0QD1)Q{-ijD7UZNyxuZ8nxEGe+sZnuEBxbUIdn&?788U zPsC7@3Jz%@j;OVYQm!S9g&JOK6Wk8lhL|$ZCj~br{(641rI~c~1t+(upLm)IHz!1P zuv?K~Xq1fIUsyCFOQE)!%G{L;P>K7Spfl(xfBt+&?or4YBh4&{s8K#$N*Pns&+Nf< z*y1mE{UPln7EZnfdgJ&;25K`>5vfEo`3LE#1N^xozFG{y4fL!B{%dqUKn^VI%Q&KN zKMwyv(nnZ#r;NrhZ(-zMfvpH2DA0tZv+tnD+ejpR0bVE9V-}6#VC~z9J&!kQ9RDNU zf*Jqgb7tw9Xiws#O~I`(Umk_{JAF3_Q=Ol2^>5ICR!OumXrcFSl#rMJj6a$L&s91q z0;TA)e~|373D_2!-#E&6!xHwB%21^>7w9)GN(%lNisyLp9CRKX1|RtYCyRwq8xY@404QtSN6 zy2BojXX2Tm@~yMAX{UM0Z%?w{$N{vrO_6;xo@&;pfTGz*{&{HWHT&Qk4 z`tTJ^%f;Nk_Oa=|c5NjF6^;*84_AFm^Il=s z7h3M&{(*~w@R+G~NkS0a@J}#;p)1st{H`|uW3;~CHoO`IzqEkrzJ&68Zz_{gwK(cy zCpgz@0atl(*4+5|0#EJlHH9v>w~PhL{~!-h9Q0rOm{Xc&Z;(GeaGbtVm-2NozBE}@ zBGCV>$lzsvxk5ozi-so*p8)^<=ct6oK6-G0ECrTqve#12eJJ^z>oU9Bp;yKxsM}IB zwLnO8*A|>GC1>lk!W&HU_YYdqxBGi~IY@VV6J8hf6y8s7BCiv|NiWGO6!i`DZwL)6 z^k&|@hjOLG7yd|uT3{vxe_LCKs|nW^iiC}@9#G!jU$@5eQC_fUAuao5$l;o9B6#4t zai{|7cU&2!sU^9QL%%0)UN&7g!cc;}#@p4~S9t&zo25GOJhNLoX2p z)XbXf_rOPS=#nl|UfzdB?#5o0-DmIW-A?K&v+$lOHvYo;Er+Ir>b|H-d;ak8DqT7( zYH+7F2 zn|8lfgioJZ+vHKNxILLK$z30-eQj{nLqa5@{|F*O5u@cB!rWl-`hs9_JT(OyyyPw& zHHk?-Ly=p=Y##uPn#+W^j3}ziQVxA^T)?&QsdDb2EN?`n)7?iWJNN=3Re2dG&R_)@ z-$A)*UB_2cR)+aeh+~~U$O`g=n66pWcea~&`kXU*#RzY-9Yv(z=?PwoB}q=_1U|V| zcRp#3o)>n1^UT@HxbF3i%tXMrG~ZDuK~5J$u`*LaUXR%#2kJ)Mh~3z=2mIA_T1(TJ z`7Qh{&$ln8Mb>Nh0mGYcH!5Es7x}Iei?~Y(uYJG*?QYJ|)7NRAv?A9KiEYkgR-Xy# zBy#o$zTM*NyZ8d;PSX=LGY!qRX?`wYZ}4eL#E2KxA@RpW>{`rZ=Lp$r5mddGrU;zT zfy3Nulg*DNud&;`);WC3udOSuJSIBh*Zoijx7P>JptJGAmS)Ku^@W}vQt>U%XqyBU zj6PriYH^Xi(&q>hmD|!mV)de5ncBoRK#hbJ;{bVOnAD)l1CWtQ&%ae z_Ik-uLQ+=f3v}4-y{+fZ#VY==vjn6!(U$ayYcqWsSCZI_-_3~q?YXj8D57U*q#u)d z2+Tx~X4~^Si2YElOcZHXBl3?Z_Jg`;0Uj?$$* zff8Bf_#esf#nX-s4kj!1I;qCDcH-6iIY$_zS?g4fTEJ--ZB3uB^LhESs=PTPY;sid z^>I1d^1S=fE)QOt+tx?2F%<7Jkc_COs!)A$L|M%Go*DEnCr|=<=6YO04ZSi<5*>j( zPHeYds?i|%e!O+YUecy1WBY1}i%CwR@tjn;x!V`S1OHNP?Jah)+S|8BXwSg*-(d*mD;yLtsy<#demH{?5sfK<#iE*bwnYg>pDoD3UD{Ii z5&S}DjJ^NJmVV;iQIiqAnR?G;aQe8ABwktx3TQ__%Qls~xTs7p%Anq8Idl1gWLCGY zH*;0qgRe>K#^sT!;yi{rssMK`R9k*pc|jvmbl8rPvIwP~9tKh;-*EQOL?_Yuy1KC@ zg?=nWZ)GvpCLWSw;f%^m56&L!_lrL9TU!&^3j+nLFS{-tCT273;J*94ZqV<6T9Nm% z&*>rd#Jlo~w~tFRM(c<}#}B*21#s}5qIQPGA&HrqLI*5ZJNLQ){I>e$)J(6HcFAmR zrys4j5lX(eg<+*CNk=KoUFqrZeO!4v!N%Bb-P`P_dZ#6){X_o6+#j>fsn$PGEw^(h z0XAfK&n|uRsHnMeaXirA<5;YzPhL0@uI8M4x;<^?1Z&!C%umK6S%Td*Avm_wo6)QZ zPoI)SI-|O+tmzkqu05PesotOA1wmHb)!#@T z3xSST>s-2E(GnE}?7NIWz%gZjo$6$EE+H4zX`)(0okN8G+eGp>8gy%3V$}N;MbY)# z&#bwfd-A(Uzox%D#n;+oj_ko9^r=s7+b`URT%X?(kM=$7-b8ZnJ6;uU+IyOs80*)| z^s(Q+Lw>lF^?+|1o(*fNk|vR8MJ7%ax93nH3q_CC#GqicHxzN10n?;o+}=x{9m^YL zFZ@z{(fMTxwIe!Exa+kSLrMXS_s740L^-ED!mO>}aEZ5ul_WClXW=s&sr{|~ln%!s z-Qvf8XY@ikZf@ z`d*O<%&5)~AO7NhRY&bhmm*m93gIqG?VBWH!qaWv#htWIt8vI<@uQj+WdpLEwQ|Q&RIScmY+hFX zl;yx3K^_?0$Z?(`CQaC{ z{F1%WZ0b@}SDE;7>m6gsqDDNY8XuJwlA}bX>c2HwdZn-_6L6tj0Fu->BABH4eXlJz zU`I#rxy7*OktGR1d#){y9Ov0cSgc8988&7krFc6(+g`r6{{)3#uC{XP|6z`$EMMy2y81;_*S}!OJbCK1U zv2|>3Q8?#6Z>Q)k6gkMKrizz7)`=oZP^_o{w4&+*QJKYH46VrZt+8amyv@0fiC@cn z^WQ48T8Tq$L>02{0}#oH>e)@!z`xpj<%v2nl|noPclyYL{Bm?&hm~S#`9tF$D_s*v6j0aHE*%IY;QV=&%ilPYj*`s?((VN&PriF0WVEFvOey5dA98im6H-qN(w zGjs<&wQ#p_jCz*TE=_7pdX!s4U$s)<5v=>x@7ij$c;@;*Uw%LGqBv-dD_YhIWVY~@?V&Igwl`P)_(~SB^#ANojXz8oW zKv095=Z2WrcC47FdY4xxXq`cG{V{FB+k z(@%op{d~ky#t~&4w*TQ0jTJqdLB6;{eQ}r!+uXScF7l;{@vjg1=MGsifm-PE7W6Ld zGiZW2f1TlPfowI`U)4EFdRGhdNFE%9H~tqafW~h8FZ2LH5B2&5Fw4JJ#8?3g(@{xJ z1r7O*Mel2llL(`VbtfVA>86QZzv;i;_0-?@PqX`_hlBZM$W=kT5EdjG7Xq%me3m8StrQJ<|(D=P98NEE^N^j+;?qNE!_nY1212?%8);t(Vi4f##0Q}j|O@=f}M$+q)<8Gy9MyedZkE` z2`AT|&xO1v{W)iy0YcI?guIR5V5N&i5ns+2nqjx{X%|t8pbYM|V1*GrDuUDy^zi?GODGTVe)RIb%~lv^GU&>>+2ZO?V<`I~h90OI{PmzA-O^}uWh zd5hlv_a7u4M=KxjZONcrDlTg!0~~|dKzTQgJn*{y(yxHT3DNM(+JMIwOYpV%%Z*OYHul&$_cNva$yeqtUY;!Cn2 zHE{CoIPh>9*-@)#MHpwfRA}SS?{>}e-in)!%->a>+ND<4)81rKa&{-?N_@ZHo+}ge z*D2-7BvN5^^k*2{GXQ}1D0thmu^A2Yz2qv=?P~uwIDmD>)AG`;63*WAUZh{2{q`{S3<)QvS&0Oyj{rn>SH; zPnLZc{~HGcvGWZ0@^KpYVfdD)B>;+C&`YzaJX%8$_wcA0Us5sX4n^p9cghflhJIwe zt<3S`F<@sg-aVl=daikV)-AL9OYM8o6I!gcJbjGL+d*uJl^)+OIx~sisvknhpr@rQ z@=jHIobA0|Ys$P#EPld3v{>^xs{3zK08oI;I72b}2f3}HMD8Y{=qFwg4;Q(5Xx2+o zw8@+r8+SjYzFDhl#%}4;SM5x63RHi-gP1^8MIya^!5)^x!do6S5#HSj$Caejv`Z`s zQ!2gO(F@=0lO$wCKJ*sfoMAb*G&R$jiUSiuN5hmbXS$HUlCdbN0U#PiQYgs-3Y2mm zAxi5E9F9Ib8t&T>n2cOngI;e?Bd~uhD-^BV$0>ZNw@zKXvBjgM9N$IhSa#62+ z_@WB+vC~6tWI}N7X}@RglU{xx(=8C z)}#!AO9uI_7|Uu!Tm=_3CmoZInZ5>eGKVQjWUGaKx=fzgM4;^>8>teroSCgZzfSzV z{8p$ZOXm`&20q5264)(!13mr4!}!Mt=%TO4?2N}5&(L6^ruld049yE37BAhmu65!3 zbO2$MaBtz|B3Be?4>$`Npy|n3nA?p`is9@Tf1iT3m<}H`fNBTEz~vGC;jHBHCEJ7g z@;?-H_18v1$ZDRe@7orH(B_1N?HS5FvZ-zzVLl1}Eq_b#SMG5h_wlhq3pLruvWL z$FET+5!t&4B_opU@+m7Bk(F`F$jaWMdqwspL_$ME_KM_^y=7gleJ|O$*Sxu-->dKM ze1H4=&i9XdoYOhHyYKh&{d_&gV-!eDld^v9d5AJxs%?ZMuB8r&FTk~qej)E2?!EX2 zqE+0H`~cz}`9Z7k7Ox1^g3O1tr$k<-*#CTe!}1{CiF)f40SO!zmSTydyqr4iOa~43 zHz01Iu^awqtW-u&GJ0WWruX7o4XOx(cHi+j3DU)rN4EFO^DvmFOCl+~A{p-IBF;USGGRl4%~XAtmYm*y{BUOX zr?v0$LHcxr0&+P|NBuUrsBaIGO8)EvD<3{FbpI1d21If=O8F!u90uetBw#RlyUp{* z22U}^Ha{l3RGtJM8?K1pv#m_-Jv>8f_j?1;W-1^u0E+j?x%&(8DJ|X(RC*dl%>31v4 zmx8ypu=l1M_B|a^6rZ?W5#g}Kzi;H_ddw^=w8~0PH$bO!di-(uq^j;O+$kz48yT$rx_o^T8EW`(<2%L+Qi8?cE#Y*Q-sm z<(jzLNAJym5$$96&qB^{Y3V3c1Xkkh9j&ka8P-m^D^}hInm{Vc3s5r9OO?4 zL0f!N$JdV{P|w87??OX7OHR`jtUc+Zncz7Sw@ztJzyZ-292m{s!3)t)VE&_Ii3B7y zoR>0#sQ3C|bgp9=NfkVTHTqd$yU6RCK2#HupB7{0Tc$hmv&Yvb!!H)^3=X4Be6N1} z7)30&5^FiJ^HH{&$`X@01f*@c%D7&PRjc^=OajNOb^={0;Q@jvmaLzrLrL$3{Tr!S zAXn!PBa{(8?l^#lt`CccpCLCOTnl3;oHaPFD3XVt(?{2i?8UPw+^rve~36}yRfW$(OE%6m|erC7j7NEJmF_R+ErZvccmudvVTk zsk-3TB8Ny%3J8>(_v!UsD%zZlzS!w9LjfiZ^Ix2N1xHOOt?;0Uq0AY$4x&Ttb-uDRiMQ3!wp@aO@+I#l?tB0 z&Qpuj%Is02_$M#**jTHR&$4m;BP#mpRY~BNKy8z>R4MV+Xs1VdeVj!ewpv$GVPtU&fL~_)>kxxNi zy*NsoeNT0kRfj0y>9o=7=Xj6_%SJZR#UNZ^F;MPZd9Rd5L^rrd23O?`d3~$6_>3D= zs}VJ?X69LHLXNh9KdO*$1KgP8GfGk|Sz+lFe2mzJWg3Gg`XADL#$MMHbEd;`Qe4vO zS=X|I$m?1oq^X_9iWf_GFu4e>>T+6{Suwu_y(q6=N*N3uk4rLqd#-?;1=0_3;KoEi zt4GejjW$3Uh^-5bNIhi-u9-hM8hA*TK!Nh!gNDK>5GO;2qd6s~Ao<#4?I>eVYVb~y zEiCbk$Xf`O`q^=e!99kckoR}ba2rBy)?U1wMZ?Des_fR_P1q|zI>egT61ye{IN84t zafy8dMS!0OJ0ZMKpira1DVA2weEeh_;j)*wB+yfiOYCAr6UNQ*_P5QN^CN1SSXH}X zr9P(J-hGzu(+#S%m!}r1Cp%C6Ld2?whJvT@DTv+Q>!)TR6j1JUJm6W>0u(Ouf$ASp zJ*xf}j&DY7_`%|DtE&?hh$@Wqg_xU^A_yX_-L0Cx zw_o4}7%HETUdS^+*A`)92nx^Oms)?1?qu#y9(k8gg%hKka}NMImABDVUAs`b+Kh2c zwdANjoC-47lXTGSK21E6Bb1C47Q%TWZb6?SXHv0ryU>qYZC7xPjmn;x#fFlPwvDsW zoxYyq{-6~v@~o^jyN~7S zU{v8?^}>99(Uz8)e9{}Bs_`Y6(eB|~pm*hr!8}tSj*9q(XbeJ;aRTp5>6QeYwZVY} z{@ZBD0jS%_HRMt_1ES;ZJAwq}{9at)#b>Q%D`E7Msn3?1zb~hu+Zi)-|3vcRdpP|> zvH8w)?1Z;9WSv#OA(;4I@Bj1vLcjn({{JxmFjR+z-#*3*WP*F(1LDT%f9e;&3I%bd zOMm3{*bt~iaNZWDTWqMo!x0@uA>`E72Y(^3P-jZEmWJS90K5dzAp%{+1{e{k=MfuS zRf9bLJB9%9KOh8W{s)9WLvY*-4iajIJ#;lWSb_rDba#0;(qa{~?ZOmYR3vgo?JuOU z&KQvU?K+518L)Jw3wq4vcAP7+jQGO8-Md|c`xNzsP}0@n92*Wja0|`q3OxSfQTRQO z%JBD$+6E0VfR?3W7y(_vS@xLXIaf$-%e9+9DlsA4Z<0_yTXc3Th@RH2=H7zndz8N3 zbJA%szwaiVQ`hoR^X2^HEpZTb98G=&by1N<%K<)ysypT;7J4yw$z|fm`b~`bGuJ|y z{$JU_U5{CHlxWuaLC%40Y!1VLKPF34uc*9ixbDPMwd~o#%j^8m>7;|hs>D`(A`8g` z2o(yKP=N5fpXOecB=Zhcmm52#L3hJrwZ{ffT_`2<-T4rLLEYmZUeauLSZ;_;H&0Gbj!k&zbUDX2e^)hW8KkgY25d20pL8J)MBo`Hp+BDO_s=P9`n8;$h}6=( zO&Cxmok2DzEr*-nnJJ7{K}ardZ^BIel zy}RuyF0aAJ3~(kLQWwFm*~jIt_aRdSSA?Kh6sCI2)ESo z9tPO#JB?K9XD>$`D#{apVf?gUeP#0}TNjYMzK3oN9N&&{`G|Z~4m>=saj(jV2)doB z95a&(C{U73D;~%$T_o&##b)2W-Wa5S8MmIE~+tChLU8XtpnRe7Y z4BO=Yai!zh4P9U^l3@e^J`jD|6h5NGUQ^d!$V}$(?4-J&`*cQlSS#NCdwI^dbH*?F zJ+re|hV)-fw(XBSdG%J}xP^far!o1ZY6$TmAR686+4fbFUVxJrMD? zOn+5+H{fdgYCa?cO@#x#KodG7*7z)>lX#XTYs+F0{fI6`ZW#WYWC)&sVYnWSGa_J* z$5maf8YTKu(y{fn{nT!rZV~V5oUrb)jD{smr+}<7YTW`<70ED;Hn#2%R{*YSDU2y< zb8?T{@%$L==-6k{VaUMU;{#yX+vks~GZaCZhbDaaeNm8c3-HNA(0ve+5jz%vGiYW( zI(Si)RXcD`PDLnnP{zJ0s^{4=RrRk3i{sc)QdkyboQ$|R`sh!i0Q}(kap76YPb5D@VB-P7xkFub z+TY+h$5VZ4>wbrL?i9M)CIS3^R;7LCJP9%zMJ$X%yE+~MA(H1Its|Ei;z77SI zXq+Gq{07M^W_$?)O$?A`>9n^h(%;U>6_$?ZzQanj>}U5xgYKTv>EtxdAi#&cq2+hB z`9sZor`OAj`9W2ve>md~A^25yJHCmA=U%-$@XW9fY6HpF4PjAKK4~$USIRFcr`;^b z-O_;Gfb*xdsp7UTwNFYmk3iRos&?b~ZSTBe{31)QL@V&RYIXa#ikwLDBZ~KbfVnF- zG=BTIedA|$kY~mDt3RlFZYRHP(oAc|R{AUr*CWxr$Jsw`ZF>mo5pt>?&Cd2zceBC< zScEmB&nb9Amce$QoZRRf4}B&$yY8P*EM*<2%Qe*MTyS*S-xIou!mDBS;tEvo$8D-+ zSOfUUqiHsA>u;Y6tX_#NoZIoeIhS`-jzFIr7Xl>C^b!UUC!BDVK0$hI<>6!I?=yi# z%xGz}Nifj4yoM9>Pq=-TSljL~s9+a746hT=LR=CM0u^0ys|6+s3uAR}YRPW3b>yrY z+4JUR9=Q85o2!>g)uKjhH;VY6=bbPZx|}iN;zH)6l0qZY)4>~2s@$||ReI*J?!*_r zl->dMKi{qGF5?A|nBAw_U3Q|#HxDQG^83}gyOM9z-UKpY8Sb2lU>+5E0t4=4%!vqB z!FV88sVaEucBZPV&AiP#qC9f(3XPIYj6*g=e9Nd9{z~EBnR8jsD4r)w!I-H~T%c3k zm7;?$V(z&vv4ePttTF0ZN`MNeYU217(5^hO(W-m9D!pFHT-l;CZI3E>40g2X1|#$o zi6y%#g#=+lDyA`8-zX04Uw8dxGS7gcxwpEp^^iwV0R!4+Bh>ipD2XNaCy*F4ywa{R z=SnLTA|yYpD=^D_irTxp2^*B&c|(+;jM?1)WdAA#5)`izOk;(U&~q(!Gai|Hm-eme zvL?;v%rNZ*rZG;X5h^l2UV6uX=xG-m^so+wRwh1_Lk|niUJd(-{W||Lx=S&>X_wX^-Ejf)xRX|ZF^3Ck6iR-aJFZxur+ZgJ&t3z<1W2nAgw`=t zAH2mfA~C?SRjdjY>|ooJVJ(5GX}MW<%P3Ymc!Z12bX4ew_E*b7*l{WO1L?ts1p)#_ zNUdCQMd4qUL|XrOq{Pxv&bZI)v$PnYssk`cX~pYmPM|*ePySAcSOPKZ*nk|X8bCDP zM5E&Blb@nG(Nd{04GMA}4EGn-xKP_JQx;MZ*{bOy} z>V62?=30laSX1amxHVBPJPiLk3K~sv#**Ew#-#>wD?GhKGOpcD>-5d;d>rBJ2cSm5 z+02H8>wh6tdZ-OV1w0NuB#1K{jRV+}&QXHZ146=R=cD@vtsHj#+P|z*FDK}WP6q5x z*?2(mGczM(jBN2(3d0M$@G`RV0u1Anlklun=j_WE%KN>Ap0{3P2&sSqaZ|3qk z6dAp>^iUGx-q3zb{(xM51HFiJ-ixs)WHarWhKp2>uO``b^GUjk+`Ko(q1pUeanbBv zN=P5zD8fAe?(3ck25C$=3o@P*MI_vw;QTRMuMKaT6Dx%JK-8)zZ%3K%TJ+`!*Xov? zPYK-D=rIiD)7b?bA1#g$4d%KG>cR#X2_sfl79&2+r{Z~wx{O1tw`X?drrtKbEfGrZ zk=3AEFVK1fmfPU1#q{G7fQdJVdQ+l@U zIF{gE8Vq|xD93(=U$J)EM>x+ejNW>)@>R)8yjQN7s=e>APY;t~AKf}<=wV@0(j`pO zORG3zdHwqt!Gf)i$j~w9aw?Sd=mN(8(FVU*SiEG!+Am*JpW$=9dSp~a_g%uF2xF+D zFZ?#S9O1~!L+L+lOBQG*d?$=>=YlYK?ugZ7Yak0vdj;4@>oqq3XH3*WU6 z>Y$mmY-VW_3ud6HTpO>Hm6erK;I10|CWxLp&YQSVG_eC0-NwzKd(w4ywl1A{s6qYW z0EmAGWDU3u;-SZBgyP~2bV`K}hM7G$CAdPkfa2SoBBP*^8Eqz5LLH$RhX-gm5R}iA zdx=&A_WbCxE4^ZTujG$y1aUfo{I_)XN!k zx#8oXbRCisrY{pA?|r*rO1HMU{!R^m`M-@;AfyU$59xINktrIY z>_-jg=-v@;gj;ONQhK0`Gn$2HuLlC{ws>&XgYAxb)*r75N*|0j+?Dvq4MC-O%FAad=%6OlBUVa3lFmP=k>u)y}M@YWA57{u< z`><&T=KD+@_~w2vJ|Ah3C$(OsynD#Z zjoZr*k)$58rC_HYxR7-&(8xdhM~+oTx}WGl-J}ytgy~E%{2Gx=!E#NZFeUKl zmt55(-rr))Hs@tVPZ?^<7!`z`E|Vp2f*6IDB%NiL09c_eN?&gHE^r!V-LojNaLdqa zE_gdbE)S5@!7^GI4;uq~wx9o^I>lj8A=!h$W}m7tl};ev2R7=3D)~d&J~TSMKrVo~ z2qszpEdZkqfOOTz?HN^@)it-pSkcVi?{>Tx_s(DOe9R4Nnh2_XG!^-FaLnCA%}K{V z`p+J69AXg2%hmM;IG8DR2!BkXj0#+hx8#7aEwajuT&SpIIK{Mn!{mTN>zN%%4OOvD zI0?b@C70K2n(Fyc+g%Uuxw0oGe&g)fmHK>YjsB`ss(2x7j z60>wtS^P0~;_}04Mj72+es_@7XZ((B$)6~f!&N6+eQ=!^0L8yRf+7M|dnDI#^G@|W z`i1Mg``*wx?w*Oip|=cSfROvhrE4kDvmY>>x*b%wg0DrHDUW_Urkl)su?Oqr9Nm~A zIuQ*ifO&fM%|Gi+A-qCQB2sVz%_dp8Z~pQdt;l+G>VFYj|IEF zqyjEKSd9Oj{QsI>thGMV#Qg&=JSJ9=*(Rw-x)#MGPShc&E9`JO@eTd((Gr)_#kWCz zLMGjpBUeOx*&Or5#rTO9d0+`LAMkd!;GO%0qnDe09^Q!}CS4uae+r~lzFaJQLdyva zuTTZC;9L0rn!Xr- zyrqjLYP%I4{~yyA+yCY1OEZoYvxvf4L`q40w0v*yXsoXJTv15WXVr82%9~(e`BtaL zPJFyo>|@K--xYrR_4ilH=+Z%F>;?72@bB=nq1G)>zjq7LNmMVU12!G)YQNhfEt63Q-tbn{+GC_k)thM zUG(hE@#-IoqCYx-4pM&nlU&et89uUf=~-rvon%hWrEPC=8Okj8Bc}=d8`lHcRAGs0 zoAEqAd?dN^Q;3?xz5>Rx>Z3G?U1H_*&5RsV+LJVHi)#{E*B*KX+tatJ=8@El(1O@i z7h$8gMPd2~2(-bo=Ea!95SF@iaj&c3N*ju|>!juFa8LC<`CXM`E_!*0-bR(S{H=JIaUQ)u&$?d`xuIcQiNe)izDjToq{8Unku%>Ybvp z!05!a^WQAD#i>E387*G9DW|+EUo!gamLqGsFyEYQ^~q1TZ@2&H(|(Z?(THm)AJ|W8 zKoJu6y|$73u3jP_624#N^cIsF9a~EWN8#3HE@*&5` zwLqcQwdrdE@I`|5#*&1$5fD#>wn^efN|upq+X76}fxKj`7B>x}VPJuyf?)nFAtgn#V=WdzixdRX_@;YNPKU3?*leA$67_^OP* zJctmBib~P!U2bf`H(?dxZ8qFg4ZU<^>5Z)JHiKXKRZ$ya)oB%3_d(f!m!EpNpZX+!FY_^t^b02QkQf18hK6fX4SLF-r@7;!dL-HY(3y}QJC~U!R%-&#s zRbdGAb9&Mr$B!=i@mKtKMEUdL>9^Nssq{sSliM9%^pS*rBVe5G?;S zneRm&g!E!;R(SgGBt5chz6;zx2v!NSIM3R6n;Tkj$2mdHvNoFXU!?ics~!CvX=OpI zD6_zZ6hI?R=MJkaj6FnfbYot(8hqReIy;;{$E)`~|8oG9YX6;UW~#qwS(5zH_hVA= zy;x{${oHd-P5k1w64&FzM&7XJ_kM|guvw>16f)ype*sKAfWq?NAe5k~dZr{7%js;A z_kaoii))(0gy{FSC`}G%m@RAhFJ8kJCaHRb=M^R$ecKJ(zs2$eg<`eQEoBOfNq-&P zKXS(J76kM)YA!tzwS=(c=hhgDdjTzrI2kx9yGnmhy1qf?DkT{NvJvXe;3P3zKtG~P$`w!I zf1r5SSA8U^?}!vQN;YT`ha(K>6lqb1tv)I41TclJQ*6nZ4}+x@n_PKT@A@YQ_& zc#lEiN^HvACk^Qd>1hl?hiY4y@SlQ${P+6tVqH3_d|ORAU{$(5kv~Sa8@p3nwh4Oe zj=L09F6qmeyAq0t&l19aGx*o0L(COPI??3)p}!m072y9{_w0|kI;%IrY# zsMY7xZB^%9n7sEF@=ZWD8T-^(GAfsIO|0t9=`heRP*zv7*+iLRk8|;7X7j|1M1z07 zH1RaK4LuDDuNWhhr1Ta;?ht9Vc?_0zorwnI>{Eueg)a;hUA`YeeoC(Wa!jTD{h-;m zQ#gG~;%LN*RUB<)c|~YYjt@d-VpNQfTB>c@3Bx;J1bYR!3DR2l5|YpfsIk{FCQPPo z*jeP?8x^@Mw7j|a9Un#~y%g;F&6-A8Kj zh}*|j#Vm=_n9X!eg^`p!<~#NrRv@2xs#CIKhyN|HOF80`^FmB7Z7J6aulM9*~Mo zY)1jQt!JyPV9c#@_nw+Y1{bfZ*_LK@CfmR6mKG`R3e~8tGCC4rJ-`QUqz1RNQW6*b zd}TE5=5~`he_b|tSL)V*OReU!PkJ@iN2R!g>_2!iKpdTgXb#0F42TeC=+29kQpu7O zD@o~qTe&Qqw+vCfiWW3k_DK~{BlK$YqjeN?PIe%owxnxQS}bKjKX{E-00b5AzF>(Pu)aN^SD>%@e;zv5vHt5!YVHNf|P1<~3nb z6QOLaUL{iLSZPi-^lrk}SDMeCs|{&RUgQ#~>=a^^Lvi;2GS$%;@H7uv>s!dFZ34w# z@I%vMw%y{|7ix_fhUTp4V$ki&2a(L70IGY2qphxyoT?h0qrlRIx;fi>G3cD5U(k6E zn*wW4P^eP7ALt*elVd2d;hF>m2R!p#LT_of+C=!BTXoi!n+0L<9Jgh1o%VlAPT91` z^zg3H6#S5$6Fe3m4C3~d$*3+{1eWOo{?h%irwP_?Buz(+u8BTje#4yW=lx|RpYe$y zL&uH=)DG&9IH)o@>$j5MXxi(YzL8y1r`-_|jB@`htXfV@zeV3$5e%v~*8P#CV_lTT zdV%7{X5@qkTj05I+4-Js(C1#(w5NM)bdOMVY)6h%zfJhCJQ9!PSHT7rFRMT=RvkyT zy(vzNzie6jpjPLapXYmRnqO3g5J=OLUxkfJJJxu_iczOEA|3!jYM$dc^~ZmkTzfyo zxOugvB_LUVHK|!Z-yy1QG)~-4A5@5YHXtm+*dd(b1KAHua^{y<2Y4(5&S*5{QQ;5h zh3)Jm{sylzbK4v>OP$4=NSBO7`pSrGXs*<)d}yStC9LgsMIR32aHvcV?p~-JjuMRhE|M%D#%_$x8c# zTl`sO?KA}u=Xx?t@V(umT$|Hvm!~}&zB`y?NQhU;^Tvxk`Hm~?{ zX~#9d-GOKle!B&kD_N9kk?5Zx^U$W8D#Kej-(pj{5WGFEUo(Cz92q72cfK*1@n`qP zko1o)FASu3KCGq_x@l}w9BzisIp)MS{V+;xVaauR z)&DKk@5Q|rPiV7o4XDxO=On9!e<)ghF0n6o+(O{SF3nD0&u_vd@OKMD+mL2$jZ=wz zQcjR0)o+8fee@J!7!QQ?bi`q-tM)7;W#{HDajoZ284W14 z0}UrQvR1&NNQn+_hbe8RR22{+KQNYUE zmrnS*9TaCIm};d&E>+dv-M7U96se2F%6fMd4dLY2pD_F-7&uh;;{~F;?`_?dYtdbN zJTGFU81U45J^ujoEB(HZ5#Wx1oj7i8t#2cjz{M7=?&n-Iz+BMG(4A4PK6sP%FQEOH ziFZihSv*Q`VM6@R4#tYI1$H5v=FnT_;!xC1B2kPGb=-h2sCbWduh}r?xpm&>dB}~Y z7<=a%!VeRDy>1NXvu-CjXC^@YFeQ+?!SEqcZYVp5xg^|_b%B27M~16_jfW7OOCYDA znO?gHwT>~6XScxz#mGa?1eaLg;B|Go=&SS7et$fgRcE+*=8U+xO{0K;d>9V}fPI%! zg0ekuO}&BVRiAFkzg}~>!+g^r%>Ue4=&r~`rkiQ*e-0}@{Ajz4&w1fhJV|1>jA z^{(m3M-OF>E3r_Uge z)y(#)As9i#Y&XBK?j+%c{nzB*m+@+osa%h3P4wL#e;J%Sd%gV z<)bGXKWW|1GQTNvgGwanUmKhl?$^>#OOV74zM0LSx6qv2-=jEO>`@q8 zL!5nxqOO6*2fa6@(VsrnU6GOGy|wmAhVS!rO~|p(Vb!_>3}~5$b%#D|5lm3^sBk-d zwsyY}6`I_I>#vTn?fb3S0ZCC*MQxPqs1Z3x)`SM!;t2-8?#>^ z+p|BgVYjssKB;k!I=?{S97*$!n&5%p3Ycw8kx5^eS!ZnA3izh{2W>)50yFOjV0>D1 z2a?i9O|50-HT`IVZtvfy9xB_|>d4B9(WLd(LQ+wRw6c`4}_Fg&9O zaufiPq)-DCVAmKO9?_mJ22=B~kD`E|Wpl^?I) z>W)tI!e z+wtI`uF_La$cg;wp)uWwFdNS1zs&Y+5tC9UC!um`S$g5f3kY=>&eFi)UK^o!`R(nI z-`6U?`1eN->28g(WEl6i(q#2*7Q9D_3xkgEvQ~nmFIiZFx@_TI5!DQ&lYI_|O@&m1 z2NAxljK;cuj`M2O@fT9ax%zRY?91;i(onDc+Yim{B1{@|837|I#=%t^n*We?4B-t2 zts#}15XZRPh|xyVQxqs25|NJwk<1j-BZZv>SIomq0~Bi48`jUuFg`>*R2gwb4)XCD zo$GSGKhUB&RVj3%yhN^yAQ*0rrUne1beS)e0BX7-d{U6Qgq%;2b%&l`GO>NcD=6h2 z7V*uh=&PnkSO*Ogd&FZ|xqKeTpZyeQ4-k4j9XwVf=f>{p<84V7LdxIr-mk99rtG_* z!heZ4C5dPxe@kpxZQ|8gY%v++ zX2XSGPQMVx2V>ttZ(Mk}1Rrl>8yP3A02oAyz`V1() zJnsbuEG#v^_BuvoP~v--X&%G-%j3Eqo72-f86&y;g;QPzRI0))vh12iV zHVhS8>2}a^tg=iux2g4$;e|!J8fVxZ07QqjAWrv!^Szv7I9@82eO|hBjsPxf$sU`R zrtj*O{!KLK%+us{k;iFaQLvHc@FGgbQuPM;gQ{?4xb9S|Gh*ef^7v8xSNrifkI6bM zK0lRvBQnD0uSY+~uvS7t`sntSdMiu~eo`2MPya&9S`x<5YUfSNGn_5QIGg+*G{Q3v_HFiLKt3uc5F{7FdF)6A_?!f(`b6#TVG=4~Tv%7=Pn=^&o|!Oh zHJWoQBLo70TLtxoN*q@mzW`S;4>nyX`N4cC{4P!>S-MKPRo?mb2N9m62lT~Fjdw&! zd9Kb^HTdRxNJe-w>0pW>Y!9^l$46b3Hcqdd)(;RR+us@)O;OGfIEeR}Q}!3?)s*h0 zE4Ogy`)l*&0JDRr4Q&ZR2U#L?v|C+tqGEj1aB5G|V?xCt0b@DlxE^f|@dLxeF**|a zUx@j5=5lZJE$we{Zmiq?IW|ePx!+CG{jw6ednQ8clkO2a2}ewEceCF0>Ox1?^CTal zGW)jKJbWbdnnGwIXN8;#Bu-3!Kyf-tR0{;>``_@elq2a~*WGdbbSJhe^SW3cOVXs& zLuYQ)g0KAIG&mhLiw$QmGi9-)45R_j0PwGMnm+XKSez+FU$^P@j%d@#rk0hB+R!|r zOC42)oQ%%8n@-ewp#|G{3c#HFZ9Y%^S-nq>(~Crs>TW_93w|MMbXQX>r!D7|6&Z^S zHR;~bEh1wfKDIaDx9~~2H9D2B_d-ZuRsSw*^4((z0-5|-oz@0ERLFhA92?luJc+5d^sJD2#r12y*m#4_ zo2GQT9;+tN)tjQ~N>Zj2`TT_#`2w2DL#m@C5}SkhcmvRB>IqWTnzu;nxv}yzdTLUi zy+tJ9UWV)!V2q&3LkKL`SFLo+8dPD`6B9XDy467e-0%tnPS?QHu#SMmB%c3Py3+jp zXAP}qhn-2Lgp7u_WrVEH*f~mqXojMFh|^_O?d$Wwwouck46Oo z`!C5VuSdn0(D!X`TW1hPyASS;4OYTh6t54UWYaX4BNcpaq9dST(8o~rU}s};1=RKO zld?G*gooRbYt5`|P0I_Z--CJ_42xwV_p|zVV;kT|+l5E7kA_1+u4{UECW~Z%qlM+H zRc;Cd48FrGaDSXjVVg}?_6(b|r~OwP;|HM7U25hk1g;{a)d@q4vs=X4v}IpoD;J(0 z7#Ii^ikuNT0rE3oh(z0iKO2R>j;6|3Ze28z{M{=m9td=>V;&AY5rDJu%@AJ{|Q+eEQl*EoV!}U2ULuN&x6Lw%Kr%>)18nhFOP4xJ0 zOI&o)eB``i`qce#a+%mnM1GxzxgxhBEf#{>?=K-F+KoHNY=&kHzw!){)s*Y`NQ`d3 z<)(fa)exM)4>M_QO@Y3?QKy=~T*{<-MB1P^T_h(Sc}Q51vnf1-9~ZlWv(fSmtubO2 z47bGDe>P^um?+T|y5Won*R^Ykt>6R7ZMh*Kj0%sEDFxX-Rm%G1bbK?Q+0ADf-)AfG zQ_1hs?F@o@KGlR@??5mU4!V#mN68%6uCzo##jPL)TI2ggMF<(EVj-sy8N~5ToBk%P%6jv7qzU$f~rB7UG4O(_4T{<_~g`&CyMw!K6-rBPow4^nnFXhJ|j;2Fdq3Z%?4~lZNzTnXH;7(cNABT_*@v&N; zrq#{K4Ug>i`KnCu2+U> z2P!kJF@8w`>2W!dNeiw4pAoo*8_wC?#&IofHC9VyASM(BqIM|HVh0a=;kNS*fpW0O zG{Rsv?#i9BP0#sUsLP6nip2RN7J$LYN>HRcG8w@J+&|eSTfg7wvPef)EKI1rk(+wG zKTp-W{0~#Fp~o_&`i$Q?O-Cqda~n3oOkyv$7;g|vZP6+Q2F;gdT;2J9Xm1Ul&*`%` zXE>44)3(wCN`;36C!yr4ga%B-RsyeMP1!0VA2kEb*i)nuTpa%6v?&(het~9L4VkFE zd){J`{_*(jZIUB-^Gs0>UiGHnG$#afO3k61^?xW;)lK*0R5QX(J-i3w>a*FjiH;FC<<< zAx4mzU!wuQ52SxTyRcBM`Xoup7}UlwE4vzkXszz9+c>qM-!=sjW@Z6^fM6c`)o#3!>(P1#AMEpNsfX zS628*oCUc=x=;P+IA}+S$ZJKJ<{6E9)5UX`Cz`tQ_1yt{=w0Q`&R}si+UH#d z`HusNn4?^_$B~GmDuQrfCvqojl%UfZQU)}(ENgs&>xnjk)b44 z5F=qYwbW>N>!q`Vy$8xu-@o;{NxzTXskm~X!|A4w_m{J>&B96@JE8qOWM50ps( zCX{Lj20TU^7qmw-exl-C&0W_5mk)X(u8d_CPiHTADv1U9q-a28W1;sbfIG9CmDiI4 z>^(Now#BP*i>~PGBB>`jrXr$NN%7w`2Y#ET=R5jWWw%L!1%wERWkoQiO$6^81&+Ak zvW;xHB`tQ6@f%n3S;orLHF0mNhta}{&m39oRER9__9!fv!xkp+0Mti=;03gsf{~Z2 z*T>tlT#w{LQoToH^gJ(0YcPn3L1>OMkL#!XlP?`R5{iAkEZ%Wo?~Q2)v&?gT$gDP; zUvr1&w`yxjhnbE@K9f7)7!7UBBE}Q75goFUBte{e7ex_=>Us;aY{7khby|*gXB0rY z+;|`I$!xzvLaJNcN+@#a8k%X1bPJG?7mAqwPM|gm@wFD!8x46hn>-&r)u zq)fF~`(C%8v@oJJ0(81hfHWNxT~6UaU~Cjx*km6OOglG@Pu&I}8Mea*^D;dT`(H%w zKt@Fp2*s2W(ivpd9g5hWF`9p(Cla8>nCa{aWqyftla6f@!pk25nKO@4nQY9{^E}*7 zGH%V!w4Zs+h&vmiSoNCuo)P8|gtEqAxtgSZiB5;x+=O1}PzZ(90Zfc|J4h_$T&p!MHr;i z=sj~{`d>%^7%4U@6{m37x#sKexmo4LQE70CWVX`)jzTK>O_#D*BGd&L*Cvcxz_{@| z{ZL_NS^UWf(G&QL@alRl=zLXIAh?-9OXQke)UD~JSD z9Zbc4{0jPY6TekAe|eO)*|TYGS-p)cOUkwflEV^&I-{1q5KYpS5_AelEcs(h4R8Ak z$+{|m_yX0UJbVRt0DQgbb9=)Pg$Ld2BG0YK(-iFpXeD$evujZRxTrPZj$zDhENGkgU_Qpx2t;lSaIFK#R=WLLoj;M=g}>6MFS5+#ZSjLl;G`mcS3n$_sXG7rVBLf^B3ZG3K&6?>X!&_H1LQ{7$YI|$LY&Q z1-U^bbFV#xJbpHI(Ra?2Uo&AAiewgM{{w28GqHGu*wh!{EX(-P|Ijm&i-)r@LxazR zGNAIW{B4IIV%)o9sAUAH4%P|oFk9+4wB+a(WI+6V#JN+6V?8`m;))U4Xk{-hTqjJR z@YAeY%`FsbzKENqv1Lk>2qS8wKKaDpUxhk+q3hJBXv|VHe@ki`SaR_JqGDEb{WY^2jxtyLkK*xqkviMlc2iuM@ic zQXRy>{1}AJ$c?ND3Q%K0rsf#JWp2>mDMdo*$V1fKT`Mb+`_lnSYs0AdWj#nhN7WF= zrlH`rDIUCm|GvfkAln1g2^rlqj;9XM=Kz4Ky4MDUM-ffj(a?CXwnD}&ULKRm04g_= z@^hO-Uz66ZCV#U3($?jFTy-vX57D0U=UgHRS44X>3eva-n6Iddx_M zZ#|f?v3~T;UeCViz}#GO$u-?qd0zs5tquG9+W!`O0fYYk0P@g&Kl%*-e{Z_}yQ6q( zMZNJ3zj+;onWn<`7dH~N*y4&cEY8Q!0bi28@Ja6&_*(Z*_@m*QT}}tpr`KfEqqPl* zUdh#C6Dpi;P2VXap(8lT=lSk`^*0~zKm7z!kK_LUeE$F{0RGs1A^4la{tfUxx8i>k z-@~S9T79IlPjNd1jy2jqGU0LdhP21u{WKlmg!iab4a@L$EA5`$2Q^@~k@YuRmg ze)VmxE#OF{$8~0n#(Cs()MxqDexHMX=q8^30DV8*{zBm5>f>ijU!@95R#RrD8?LsN_T@z8gH@2$Z zzPA@MG?14=$X8HGw?l$6l^}mJKl0K)_rIk!K8NuBv;qBre%O90@ZW^LW*>>SUM19F z)1uUTKdNcg##R8$cX??nFhYa)o!x){bQvcA5` with no remote authority. VS Code's supported Windows CLI form is `code --remote wsl+ `. + +## Root cause + +`resolveExternalEditorLaunchSpec` does not distinguish a VS Code launch targeting a WSL UNC workspace. Orca already has a shared parser for both modern `\\wsl.localhost\...` and legacy `\\wsl$\...` paths (`src/shared/wsl-paths.ts:1-20`), but the editor launcher never uses it. VS Code therefore receives the Windows-visible UNC folder and correctly opens it as a local Windows workspace. + +## Non-goals + +- Change the Open in menu, settings UI, IPC payload, file-manager behavior, or SSH/remote-runtime behavior. +- Infer WSL identity for ordinary drive-letter paths from project runtime settings. +- Rewrite user-defined compound shell commands or add remote flags to Cursor, VSCodium, or arbitrary editors. +- Install or configure the VS Code WSL extension. + +## Design + +1. In the external-editor launch-spec builder, parse the target path with the shared WSL UNC parser when the host platform is Windows. +2. For direct/executable VS Code Stable or Insiders launchers only, reuse the existing normalized launcher-basename check and translate a recognized WSL target into `['--remote', 'wsl+', '']`. The exact allowlist recognizes Stable's `code`, Insiders' `code-insiders`, and the direct `Code - Insiders.exe` basename without matching unrelated `code-*` editors. Matching is case-insensitive and strips every Windows launcher suffix already supported by Orca (`.cmd`, `.exe`, and `.bat`). +3. Keep local paths, non-Windows hosts, non-VS-Code applications, and compound commands on their existing argument paths. The existing main-process spawn and Windows shim handling remain unchanged. +4. Replace the temporary reproduction harness with focused regression cases in `src/main/external-editor-launch.test.ts` covering modern and legacy WSL UNC forms plus unaffected local/custom-editor behavior. + +## Data flow + +- Worktree menu selects VS Code and sends `(workspacePath, 'code')` over existing IPC. +- Main process validates the absolute existing host path. +- Launch-spec builder resolves the VS Code executable. +- On Windows + WSL UNC + VS Code, the builder emits the Remote - WSL authority and Linux-native folder path. +- Existing Windows spawn wrapping launches VS Code with those arguments. + +## Edge cases + +- Modern `\\wsl.localhost\\...` and legacy `\\wsl$\\...` paths both preserve the distro spelling and convert separators to a POSIX path. +- Distro names and Linux folder paths containing spaces remain single arguments because launch-spec construction and Windows shim wrapping preserve argument-array boundaries. +- A WSL distro root maps to `/`. +- Windows drive-letter and ordinary UNC paths stay local. +- macOS/Linux behavior stays unchanged even for strings that resemble WSL UNC paths. +- Cursor retains `--new-window`; other custom editors retain their existing single path argument. +- Compound commands remain user-owned and are not rewritten because inserting flags safely would require parsing arbitrary shell syntax. +- SSH and remote-runtime workspaces remain blocked from local path opening by the existing renderer guard; this change does not alter that boundary. +- If the VS Code WSL extension is unavailable, launch behavior is left to VS Code and Orca retains its existing spawn-success contract. + +## Test plan + +- Unit: demonstrate the pre-fix launch spec lacks `--remote` for a modern WSL UNC path. +- Unit: assert the fixed modern UNC launch is `--remote`, `wsl+Ubuntu`, `/home/...`. +- Unit: assert legacy `\\wsl$` and distro-root paths produce the same Remote - WSL form. +- Unit: assert direct and resolved Windows VS Code Stable and Insiders launchers are matched case-insensitively across `.exe`, `.cmd`, and `.bat` suffixes. +- Unit: assert distro names and Linux folder paths containing spaces remain intact arguments through launch-spec construction and Windows shim forwarding. +- Unit: assert a Windows local path remains unchanged and explicit `darwin` and `linux` hosts do not acquire WSL remote arguments. +- Unit: assert Cursor and another custom editor are not given VS Code remote arguments. +- Integration/Electron: create a throwaway repo in the installed Ubuntu WSL distro, add/open it in Orca, choose Open in VS Code, and verify the VS Code remote indicator and an integrated-terminal Linux probe. +- Adjacent smoke: open a local Windows workspace in VS Code and verify it remains a local Windows window. +- Repository gates: focused Vitest files, `pnpm typecheck`, `pnpm lint`, and `pnpm check:max-lines-ratchet`. + +## UI quality bar + +Not UI-visible in Orca. The existing menu, labels, loading behavior, and errors do not change. The user-visible acceptance criterion is external: the launched VS Code window must identify the selected WSL distro and its terminal must run Linux. + +## Review screenshots + +1. Golden path: VS Code opened from a throwaway WSL workspace, showing the Remote - WSL indicator and a terminal Linux probe. +2. Adjacent local path: VS Code opened from a local Windows workspace, showing a local Windows terminal/environment. + +## Rollout + +1. Add launch-spec regression tests and observe the WSL case fail against the desired arguments. +2. Add the scoped VS Code + Windows + WSL argument translation. +3. Run focused and repository-wide static/test gates. +4. Validate WSL and local launches end to end, retaining local screenshots outside the PR. + +## Lightweight Eng Review + +- Scope: Kept to the launch-spec seam; no renderer, IPC, persistence, runtime-routing, or settings changes are needed because WSL filesystem identity is encoded in the UNC path. +- Architecture/data flow: Reuse `parseWslUncPath` in the main-process pure argument builder, then leave executable resolution, Windows shim wrapping, spawn lifecycle, and renderer guards unchanged. +- Failure modes covered: + - Modern and legacy WSL UNC aliases route to the correct distro and Linux path. + - Local/ordinary UNC paths and non-Windows platforms do not acquire remote flags. + - Case variants and supported Windows VS Code shim suffixes are recognized without classifying custom editors or compound shell commands as VS Code. + - Distro and folder names containing spaces survive the Windows shim as distinct arguments. + - Missing VS Code WSL support still follows the existing launch contract rather than adding a new partial-failure protocol. +- Test coverage required: + - Pure launch-spec regression cases in `src/main/external-editor-launch.test.ts` for WSL aliases/root, launcher case/suffix variants, and unaffected branches. + - `src/main/ipc/shell.test.ts` plus the existing Windows shim contract to prove remote arguments, including spaces, are forwarded as distinct values. + - Live Windows + Ubuntu WSL + VS Code smoke for the actual environment boundary. +- Performance/blast radius: One regex parse per external-editor click only; no startup, polling, watcher, terminal, or renderer cost. Blast radius is limited to direct VS Code launches of WSL UNC paths on Windows. +- UI quality bar: Not UI-visible in Orca; VS Code must visibly attach to the requested WSL distro and run a Linux terminal. +- Required review screenshots: + 1. WSL VS Code window with distro indicator and Linux terminal probe. + 2. Local Windows VS Code window demonstrating unchanged local launch behavior. +- Residual risks: VS Code without the WSL extension may reject or prompt on the valid remote launch; this is external dependency behavior and should not cause Orca to fall back silently to the wrong Windows environment. diff --git a/docs/kill-all-sessions-also-kills-empty-terminals.md b/docs/kill-all-sessions-also-kills-empty-terminals.md new file mode 100644 index 000000000000..425eb3349685 --- /dev/null +++ b/docs/kill-all-sessions-also-kills-empty-terminals.md @@ -0,0 +1,203 @@ +# Kill all sessions also closes terminal tabs + +GitHub: https://github.com/stablyai/orca/issues/8001 +Branch: `bug-kill-all-sessions-doesnt-kill-terminals` + +## Problem + +Settings → Manage Sessions and Resource Manager expose **Kill all sessions**. The action currently calls only `window.api.pty.management.killAll()`; it does not remove renderer terminal tabs or dispose xterm instances. + +The main handler is narrower than the UI wording: + +- `pty:management:killAll` snapshots sessions from the current and legacy **daemon** adapters, shuts them down in parallel, then polls only those initial IDs. +- It does not inventory SSH or runtime-hosted terminals. A degraded local provider is also outside the management adapter set. +- The nominal poll sleep budget is 6.5 seconds (65 × 100 ms), but adapter round-trip time is additional. Daemon requests time out after 30 seconds and connection setup has separate 5-second steps, so total latency can be much longer. +- Failed adapter listings are dropped by `collectSessions`, so counts are not authoritative when an adapter is unreachable. This applies during polling too: an adapter that listed an initial session and then becomes unreachable can make that session disappear from `remainingCount` and be counted as killed without a confirming listing. + +Renderer exit handling then preserves two important startup-failure states: + +- a sole, freshly spawned pane that exits before any user input; and +- a freshly split pane that exits before input or output. + +Those guards are correct for direnv/shell setup failures, but they cannot distinguish an explicit bulk kill. A sole fresh-spawned pane remains if the user never typed, even if it produced output or lived for a while; typed/reattached panes normally close through the existing exit path. + +## Goal and invariant + +After confirmation, every terminal tab that existed in the invoking desktop renderer at that moment is removed, including dead/no-PTY tabs, and its renderer resources are disposed. Terminal tabs created later are not targeted. Initial daemon sessions still receive the existing management shutdown request, while current non-runtime PTY bindings owned by the targeted tabs receive exact per-ID shutdown requests. + +The target is the confirmed terminal **surface ID**, not a liveness inference. If the same targeted tab rebinds before cleanup completes, it is still closed; a newly created tab ID survives. + +## Non-goals + +- Changing **Restart daemon**, which intentionally leaves panes available to reopen. +- Deleting or sleeping worktrees, closing browser/editor tabs, or killing the daemon process. +- Changing the sole-pane/fresh-split startup-failure guards. +- Promising an immediate OS working-set drop; GC and allocator behavior are nondeterministic. The deterministic contract is that tabs/xterms are released and observable daemon/exact-binding shutdown-request failures are surfaced. Runtime-host result propagation remains an accepted gap below. +- Turning this issue into a new cross-provider global kill API. Exact `pty.kill(id)` calls for current bindings of the confirmed tabs are in scope; inventorying and killing unrelated provider sessions is not. + +## Design + +### 1. Snapshot terminal surfaces once + +At confirmation, before `onKillAllStart` and before the first `await`, collect and deduplicate terminal entity IDs from both `tabsByWorktree` and terminal entries in `unifiedTabsByWorktree`. Include the floating-terminal workspace. + +Keep this immutable target set through the async daemon call: + +- a target already closed elsewhere becomes a no-op; +- a target moved between groups/worktrees is resolved from current state and still closes; +- a terminal created after the snapshot is never closed. + +Do not snapshot all terminal IDs again after the daemon call, and do not retain the confirmation-time worktree as cleanup authority. The target ID is immutable; ownership and active-last ordering are resolved again from current state immediately before cleanup. + +### 2. Keep daemon shutdown semantics, then close the snapshot + +Call the existing `window.api.pty.management.killAll()` once. After it settles, resolve the still-present targets and deduplicate their current `ptyIdsByTabId` entries. These are the renderer's current binding ownership records, not independent liveness proof; do not pull IDs from `tab.ptyId`, deferred SSH restore state, or `terminalLayoutsByTabId.ptyIdsByLeafId`, which can be restore hints rather than current ownership. + +Force-close every snapshotted surface through `closeTerminalTab(id, { force: true })`, then await one existing `window.api.pty.kill(id)` call for each captured non-`remote:` PTY ID. Run both phases for management success, partial success, and IPC rejection because the confirmation explicitly covers closing the terminal surfaces. Use per-target/per-PTY settlement so one unexpected store or provider failure does not stop the remaining cleanup. Already-gone PTYs are successful no-ops in the main handler; other exact-kill rejections are reported separately. + +Close targets outside the cleanup-time `activeWorktreeId` first and targets currently owned by it last. A tab moved into the active worktree or a workspace selected while the daemon call was pending must therefore move to the last partition. Let `closeTerminalTab` choose the existing post-state for the last local terminal: editor, then browser, then `setActiveWorktree(null)`. Do not pre-clear `activeWorktreeId`; the sleep flow needs that ordering because it leaves tab records mounted while clearing PTYs, whereas this flow removes the tabs. Add active-switch and active-last regression tests and only adopt sleep-intent/deactivate-first if those tests prove a respawn. + +This is not one backend call end-to-end. The coordinator issues one daemon-management IPC, one renderer close per unique target, and at most one exact kill IPC per unique current non-runtime PTY binding. The explicit exact kills make local/SSH shutdown requests settle before caller refresh instead of relying on React unmount timing. A mounted transport may race that request and issue an idempotent duplicate during unmount; count that separately in live performance evidence. A still-bound daemon session can receive the exact retry after the management poll, so daemon toast counts remain the management handler's earlier reported snapshot, not final process truth. Runtime-hosted tabs additionally issue one `session.tabs.close` flow per tab. + +The coordinator must live outside the hook (for example, `kill-all-terminal-surfaces.ts`) and must not gate cleanup on `mountedRef`. Navigating away or unmounting the invoking popover/settings component while IPC is pending does not revoke an already confirmed destructive action; only React callbacks and hook state updates remain mount-gated. + +### 3. Do not add a post-kill orphan sweep + +Do not call `pty.listSessions()` and kill everything returned after the management call. Exact kills captured from `ptyIdsByTabId` for the immutable target surfaces are allowed and required; they do not discover or cross into unrelated sessions. + +The management handler already targets daemon orphans in its initial snapshot. A later broad sweep would cross the confirmation boundary by killing local/SSH sessions or fresh sessions created while the existing poll was running. It would also add provider inventory fan-out to a recovery action and conflict with the main handler's initial-ID accounting. + +The existing explicit **Kill orphan terminals** action remains separate. + +### 4. Make completion and failure copy honest + +Have the renderer cleanup return a bounded summary: target count, targets absent at completion, failed close attempts, exact PTY kill requests accepted/rejected, and daemon result/error. Verify absence in both terminal and unified state after each close attempt. Toasts must report renderer cleanup separately from daemon counts; do not show **No sessions running** when terminal tabs were closed. + +Because the management API suppresses adapter-list failures, copy must describe daemon counts as reported, not claim that every daemon process was verified dead. Returning adapter errors is a follow-up unless this PR chooses to widen the API. Exact `pty.kill` rejection counts may be stated as failed shutdown requests, not as proof that the processes remain alive. + +Examples of states, not required wording: + +- all daemon targets were reported exited, exact shutdown requests were accepted, and tabs closed: success; +- `remainingCount > 0`: warning that management reported daemon processes not exited before exact binding cleanup; +- management IPC rejected: error that tabs closed, with daemon shutdown unverified and any exact PTY kill failures called out; +- no daemon sessions and no terminal tabs: existing informational state. + +Run `onKillAllSettled` only after surface removal and exact PTY kill settlement. `closeTerminalTab` returns before React unmount effects run, so surface removal alone is not a sufficient boundary for Resource Manager's `pty.listSessions()` refresh. Keep one confirmation dialog and update its description to say that terminal tabs across workspaces close and unsaved terminal work is lost. + +### 5. Provider limits + +`closeTerminalTab` synchronously prunes host-backed local mirrors but currently returns `void` and discards the promise from `closeWebRuntimeSessionTab`. The underlying helper is already awaitable: its close request has a 15-second timeout and, after success, it awaits an eager list refresh with another 15-second timeout. Its boolean can therefore settle after roughly 30 seconds, while close-intent suppression expires after 10 seconds. This change must not claim verified runtime-host completion unless the bulk helper propagates that existing result and aligns the intent lifetime. + +For this Windows/local bug, runtime-host cleanup is best-effort and an explicit accepted gap. A follow-up may propagate the existing async close result through terminal-tab actions and align the RPC timeout/intent lifetime. SSH must be exercised if the fixture is available; otherwise record live SSH process absence as an accepted gap. No provider-specific local filesystem or process assumptions are added. + +## Data flow + +```text +confirm + → snapshot unique terminal surface IDs + → pty.management.killAll() daemon current + legacy; existing polling + → resolve current target ownership + bound PTY IDs + → close snapshotted tabs, active last renderer/xterm cleanup; runtime-host close starts + → await exact non-runtime pty.kill IDs local/SSH acknowledgement; no provider sweep + → toast daemon result + surface/exact-kill summary + → caller refresh +``` + +## Concurrency and consistency + +| Case | Required behavior | +| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| No daemon sessions; dead/empty tabs exist | Close target tabs and report tab cleanup, not “No sessions.” | +| Daemon session refuses to exit | Close the confirmed tab; report that management saw it remaining before the exact retry. Refresh may expose it as an orphan. | +| Adapter listing fails | Close target tabs; do not claim all processes were verified dead. Existing management counts may read as zero. | +| Management IPC rejects | Still close confirmed tabs and issue exact current-binding kills; report daemon uncertainty and exact-kill errors. | +| New tab/session during the wait | New tab ID survives. No post-snapshot provider sweep. | +| Target closes or moves during the wait | Missing target no-ops; moved target closes by current ownership. | +| Target tab rebinds to a new PTY | Close it because the confirmed surface, not the old PTY snapshot, is the authority. | +| Pinned or split terminal | `force: true` bypasses a second prompt; closing the tab closes all of its panes. | +| Active last terminal | Existing close routing selects editor/browser or deactivates; no replacement terminal spawns. | +| Two overlapping invocations | Cleanup is idempotent by tab ID. Each main call retains its own initial daemon snapshot/counts. | +| Binding changes after exact-ID capture | Surface close still wins; transport unmount kills the replacement, but that late kill is not in the awaited count. | +| Runtime-host snapshot races close | Existing close intent suppresses stale snapshots temporarily; host completion remains an accepted gap. | +| External/mobile session creation | Sessions created after the main/renderer snapshots are not chased. Existing PTY-exit publication updates mirrors. | + +Orca's production UI currently tracks a single desktop `mainWindow`/renderer. The main daemon action is process-global while renderer cleanup is renderer-local. If multiple desktop windows become supported, this action must be broadcast from main with an action ID and per-window acknowledgement; “shared store probably mirrors it” is not sufficient. + +## Tests and reliability gate + +Add an experimental, `protection: "partial"` `terminal-session.kill-all-surface-cleanup` entry to `config/reliability-gates.jsonc`, owned by `terminal-runtime` at the renderer/main contract layer. The entry must name the focused coordinator and `pty-management` test files/commands and include non-empty assertion refs; otherwise the manifest checker rejects a partial gate. + +- **Invariant:** confirmed terminal surfaces close exactly once; later-created surfaces survive; no broad post-snapshot kill occurs. +- **Failure source:** issue #8001 plus the sole-fresh/fresh-split exit guards that intentionally preserve dead startup-failure panes. +- **Deterministic oracle:** the initial tab IDs disappear from both terminal/unified state, non-terminal and later-created tabs remain, active state is valid, exact kills are issued only for deduplicated current target bindings, all exact-kill promises settle before the caller callback, and no `pty.listSessions` sweep occurs. Provider inventory absence is live validation, not the renderer-unit oracle. +- **Diagnostics:** emit one content-free bounded summary with target/absent/failed-close counts, exact-kill accepted/rejected counts, and the daemon result or error. Runtime-host completion remains unknown until terminal-tab actions propagate the existing async close result. + +Required deterministic coverage: + +- snapshot/dedup across multiple worktrees, unified-only terminals, splits, and floating terminals; +- pinned close with `force`, while browser/editor tabs remain; +- terminal added after the snapshot survives; missing/moved target behavior; +- active-last post-state for editor, browser, and no-other-content cases, including no auto-spawn; +- coordinator ordering for success, partial result, zero sessions, and rejected management IPC; +- exact binding capture excludes restore hints and `remote:` IDs; late-created tab bindings are not captured; +- exactly one management call, zero `pty.listSessions` calls, one close attempt per unique target, and one coordinator-issued exact kill per unique captured non-runtime PTY ID; +- invoking component unmount during the management wait does not cancel store/provider cleanup or invoke mount-gated callbacks; +- existing `src/main/ipc/pty-management.test.ts` cases remain green. + +Electron validation on Windows must reproduce an empty shell plus an established terminal, invoke each entry point, and prove: + +- target terminal tabs and `.xterm` surfaces are gone; +- initial local/daemon PTY IDs are absent after settle, except daemon IDs reported remaining and exact IDs whose shutdown request failed; +- a terminal created after confirmation survives; +- Resource Manager and Manage Sessions refresh to the same result. + +Planned provider/platform accounting: + +| Row | Planned status | +| --- | --- | +| Local PTY / daemon / Windows | Covered by deterministic coordinator/main tests plus the required live Electron run. | +| macOS / Linux local and daemon | Shared code is covered deterministically; live process absence remains an accepted gap until run there. | +| SSH | Exact request/settlement is covered by provider-contract mocks; live remote-process absence is covered only when the SSH fixture runs, otherwise accepted-gap. | +| WSL | Uses the local exact-ID path, but real WSL process absence is an accepted gap unless included in the Windows run. | +| Remote runtime | Local mirror removal is covered; host completion is accepted-gap while `closeTerminalTab` discards the async result. | +| Mobile/relay | No newly created session is chased; shared host-tab disappearance and live relay shutdown remain accepted gaps unless exercised with their fixtures. | + +Screenshots are UI evidence only; they do not prove PTY or memory cleanup. + +## Performance and blast radius + +No interval, watcher, or extra provider listing is added. The existing management call can wait for 65 sleeps plus adapter latency. The coordinator adds at most one existing exact-kill IPC per unique current non-runtime PTY binding; record both those calls and any idempotent unmount duplicates as part of the performance evidence. + +Repeated `closeTerminalTab` calls are not O(tabs): target resolution and store cascades scan/clone multiple maps per close, so worst-case renderer work is superlinear. Measure the synchronous close phase with a representative high-tab fixture (at least 100 terminal tabs). Record close attempts, Zustand writes, duration, and long tasks. If it creates a >50 ms renderer task, add a focused bulk reducer or yield-safe batching rather than declaring the rare action free. + +For resource reclamation, prefer deterministic counts: zero target `TerminalPane`/xterm instances, released listeners/transports, and no initial PTY IDs. A repeated open/kill cycle may supplement this with heap/working-set evidence, but absolute memory deltas are not a stable pass/fail oracle. + +## UI quality bar and screenshots + +No new layout or visual token is needed. Keep the existing shadcn `Dialog`/destructive `Button`, compact typography, dismissal lock while busy, and accurate consequence-first copy. The post-state must never be a blank/crashed TerminalPane or a wall of dead empty panes. + +Required review screenshots: + +1. Resource Manager before kill with an empty terminal and an established terminal visible in the workspace. +2. Resource Manager kill-all confirmation with updated close-tabs copy. +3. Matched post-kill workspace showing target terminal tabs gone and refreshed counts. +4. Manage Sessions confirmation or post-state, proving the second entry point uses the same behavior. + +## Lightweight Eng Review + +- **Scope:** renderer surface cleanup layered on the existing daemon management action; no daemon redesign and no broad orphan/provider sweep. +- **Architecture/data flow:** main owns its initial daemon-session shutdown; renderer owns the confirmed terminal-surface snapshot, exact current-binding shutdown, and tab/xterm disposal; runtime-host close remains behind existing routing. +- **Failure modes:** partial/rejected daemon kill, exact provider-kill failure, no-session cleanup, pinning, splits, cleanup-time active selection, new/moved/disappeared tabs, same-tab rebind, overlapping actions, invoking-component unmount, stale runtime snapshots, adapter-list uncertainty, and future multi-window ownership are explicit above. +- **Tests:** deterministic state/coordinator and main-handler tests plus Windows Electron proof; a new experimental partial reliability gate records provider gaps. +- **Performance/blast radius:** one existing management IPC, bounded exact per-PTY kill IPCs, no new listing/polling, but N close cascades require measurement because current helpers are not linear or atomic. +- **UI quality bar:** existing dialog primitives and truthful copy; screenshots prove both entry points and the terminal-free post-state, not memory reclamation. +- **Residual risks:** daemon adapter listing can stall until client timeouts and failures are treated as empty; terminal-tab actions discard the runtime-host close result and its 10-second intent is shorter than the possible two-request close flow; a binding created after exact-ID capture is killed only by transport unmount; live SSH/WSL/mobile behavior may remain accepted gaps until fixtures prove it. + +## Rollout + +1. Add the snapshot/coordinator and deterministic tests. +2. Wire it only through `useDaemonActions.runKillAll`; keep the coordinator outside the hook and update toast/dialog copy. +3. Add the experimental reliability gate and performance count/latency evidence. +4. Run focused tests, typecheck, lint, and max-lines ratchet checks. +5. Validate both entry points in Electron on Windows and capture the required screenshots. +6. Force-add this doc when staging because `docs/**` is ignored by default. diff --git a/docs/readme/README.es.md b/docs/readme/README.es.md index e1403aed2df3..08c63240cc64 100644 --- a/docs/readme/README.es.md +++ b/docs/readme/README.es.md @@ -36,7 +36,7 @@ Supervisa y dirige a tus agentes desde el teléfono — recibe una notificación cuando un agente termine y envía instrucciones de seguimiento desde cualquier lugar. -[App Store de iOS](https://apps.apple.com/us/app/orca-ide/id6766130217) · [APK para Android](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) +[App Store de iOS](https://apps.apple.com/us/app/orca-ide/id6766130217) · [APK para Android](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) @@ -227,7 +227,7 @@ yay -S stably-orca-bin Vincúlala con tu app de escritorio para supervisar y dirigir a tus agentes desde el teléfono. - **iOS:** [Descargar desde App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) -- **Android:** [Descargar el APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) +- **Android:** [Descargar el APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) --- diff --git a/docs/readme/README.ja.md b/docs/readme/README.ja.md index 22e461eb611c..b62d2fd2caa3 100644 --- a/docs/readme/README.ja.md +++ b/docs/readme/README.ja.md @@ -36,7 +36,7 @@ スマートフォンからエージェントを監視・操作 — エージェントの完了を通知で受け取り、どこからでもフォローアップを送信できます。 -[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [Android APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) · [ドキュメント →](https://www.onorca.dev/docs/mobile) +[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [Android APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) · [ドキュメント →](https://www.onorca.dev/docs/mobile) @@ -227,7 +227,7 @@ yay -S stably-orca-bin デスクトップアプリとペアリングして、スマートフォンからエージェントを監視・操作できます。 - **iOS:** [App Store からダウンロード](https://apps.apple.com/us/app/orca-ide/id6766130217) -- **Android:** [APK をダウンロード](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) +- **Android:** [APK をダウンロード](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) --- diff --git a/docs/readme/README.ko.md b/docs/readme/README.ko.md index b2fc4857112f..dc4bc8355fed 100644 --- a/docs/readme/README.ko.md +++ b/docs/readme/README.ko.md @@ -36,7 +36,7 @@ 휴대폰에서 에이전트를 모니터링하고 조종하세요 — 에이전트가 완료되면 알림을 받고 어디서든 후속 지시를 보낼 수 있습니다. -[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [Android APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) · [문서 →](https://www.onorca.dev/docs/mobile) +[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [Android APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) · [문서 →](https://www.onorca.dev/docs/mobile) @@ -227,7 +227,7 @@ yay -S stably-orca-bin 데스크톱 앱과 페어링해 휴대폰에서 에이전트를 모니터링하고 조종하세요. - **iOS:** [App Store에서 다운로드](https://apps.apple.com/us/app/orca-ide/id6766130217) -- **Android:** [APK 다운로드](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) +- **Android:** [APK 다운로드](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) --- diff --git a/docs/readme/README.pt.md b/docs/readme/README.pt.md index 6c3fc52354c2..5d268491ef09 100644 --- a/docs/readme/README.pt.md +++ b/docs/readme/README.pt.md @@ -36,7 +36,7 @@ Monitore e conduza seus agentes pelo celular — receba uma notificação quando um agente terminar e envie instruções de acompanhamento de qualquer lugar. -[App Store para iOS](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [APK Android 0.0.22](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) +[App Store para iOS](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [APK Android 0.0.25](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) @@ -230,7 +230,7 @@ yay -S stably-orca-bin Conecte ao app desktop para monitorar e conduzir seus agentes pelo celular. - **iOS:** [Baixar na App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) ou [entrar no TestFlight](https://testflight.apple.com/join/YjeGMQBA) -- **Android:** [Baixar APK 0.0.22](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) +- **Android:** [Baixar APK 0.0.25](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) --- @@ -238,10 +238,6 @@ Conecte ao app desktop para monitorar e conduzir seus agentes pelo celular. - **Discord:** Entre na comunidade no **[Discord](https://discord.gg/fzjDKHxv8Q)**. - **Twitter / X:** Siga **[@orca_build](https://x.com/orca_build)** para atualizações e anúncios. -- **WeChat:** Escaneie o QR code para entrar na comunidade. - - QR code do WeChat para a comunidade Orca - - **Feedback e ideias:** Lançamos rápido. Sentiu falta de algo? [Peça um novo recurso](https://github.com/stablyai/orca/issues). - **Privacidade:** Veja a [documentação de privacidade e telemetria](https://www.onorca.dev/docs/telemetry) para saber quais dados anônimos de uso o Orca coleta e como desativar. - **Mostre apoio:** Dê uma [estrela](https://github.com/stablyai/orca) neste repositório para acompanhar nossos lançamentos diários. diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md index 4c538b08f22a..497e98fe9193 100644 --- a/docs/readme/README.zh-CN.md +++ b/docs/readme/README.zh-CN.md @@ -36,7 +36,7 @@ 用手机监控并指挥你的智能体 — 智能体完成时收到通知,随时随地发送后续指令。 -[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [Android APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) · [文档 →](https://www.onorca.dev/docs/mobile) +[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [Android APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) · [文档 →](https://www.onorca.dev/docs/mobile) @@ -227,7 +227,7 @@ yay -S stably-orca-bin 与桌面应用配对,用手机监控并指挥你的智能体。 - **iOS:** [从 App Store 下载](https://apps.apple.com/us/app/orca-ide/id6766130217) -- **Android:** [下载 APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) +- **Android:** [下载 APK](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.25/app-release.apk) --- @@ -235,6 +235,11 @@ yay -S stably-orca-bin - **Discord:** 加入 **[Discord](https://discord.gg/fzjDKHxv8Q)** 社区。 - **Twitter / X:** 关注 **[@orca_build](https://x.com/orca_build)** 获取更新和公告。 +- **微信:** 扫描二维码加入社区。如果第一个群已满,请使用备用微信群。 + + Orca 社区微信群二维码 + Orca 社区备用微信群二维码 + - **反馈与想法:** 我们发布很快。缺少什么功能?[提交功能请求](https://github.com/stablyai/orca/issues)。 - **隐私:** 查看[隐私与遥测文档](https://www.onorca.dev/docs/telemetry),了解 Orca 收集哪些匿名使用数据以及如何退出。 - **支持我们:** 给这个仓库点 [Star](https://github.com/stablyai/orca),关注我们的日常发布。 diff --git a/docs/reference/git-compatibility.md b/docs/reference/git-compatibility.md new file mode 100644 index 000000000000..c943bc9ce5f2 --- /dev/null +++ b/docs/reference/git-compatibility.md @@ -0,0 +1,62 @@ +# Git Compatibility Policy + +## Scope + +Orca executes the user's Git binary on three kinds of execution host: native, +WSL, and SSH. Each host can have a different Git version, so compatibility +state must be scoped to the host that actually runs the command. + +Git 2.25 is the core-workflow compatibility baseline for command selection. It +is the oldest line that covers Orca's baseline use of porcelain v2, `branch +--show-current`, `restore`, and sparse checkout. Optional features that need a +newer Git must degrade safely and cache the missing capability. Orca does not +currently block older Git at startup, but new command construction should not +assume features introduced after this baseline. + +## Capability Rules + +When a newer Git feature materially improves correctness or performance: + +1. Keep a baseline-compatible command or parser as the fallback. +2. Detect rejection with a narrow predicate for that option or subcommand. +3. Run the preferred command through `GitCapabilityCache` so a rejection is + remembered for the native host, WSL distro, or SSH provider that produced it. +4. Retry after the cache interval so an in-place Git upgrade self-heals without + restarting Orca. +5. Test the first fallback, later calls that skip the rejected probe, concurrent + probe coalescing, and execution-host isolation where applicable. + +Do not branch only on a parsed `git --version`. Vendor builds can backport +features, and wrappers can report a host version that differs from the binary +used inside WSL or SSH. A behavior probe plus a precise fallback is the final +authority. + +## Current Capabilities + +| Capability | Preferred behavior | Compatibility behavior | +| ----------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------- | +| `worktree-list-z` | NUL-delimited worktree paths | Line-block parser for Git before `worktree list -z` | +| `rev-parse-path-format` | Absolute repo metadata paths | Resolve legacy relative output against the scanned repo | +| `for-each-ref-exclude` | Exclude remote HEAD before the output limit | Request extra refs, then filter remote HEAD in Orca | +| `merge-tree-write-tree` | Derive real-merge conflicts and no-op tree proofs | Omit the conflict summary and keep conservative branch cleanup behavior before Git 2.38 | +| `merge-tree-merge-base` | Supply the already-resolved merge base | Use the older two-commit `merge-tree --write-tree` form | + +## Why Not `simple-git` + +`simple-git` is a process wrapper around the installed Git binary. Its custom +options and `raw` API pass arguments through to Git, so it cannot make a newer +flag work on an older binary or choose Orca's semantic fallback automatically. +It provides version reporting and subprocess queueing, but Orca already needs +its own WSL/SSH routing, cancellation, tracing, redaction, process cleanup, and +bounded output handling. Replacing the runner would move—not remove—the +capability problem. + +## CI Contract + +PR checks run the capability contract against real Git 2.25.5, 2.38.1, and +2.49.1 binaries. This spans the core-workflow baseline, the transitional +`merge-tree --write-tree` behavior before `--merge-base`, and current Git. + +Keep the unit tests alongside that matrix. They cover concurrent probes, +native/WSL/SSH/relay isolation, and error-stream shapes that a single real +binary invocation cannot exercise deterministically. diff --git a/docs/reference/terminal-hidden-view-parking.md b/docs/reference/terminal-hidden-view-parking.md new file mode 100644 index 000000000000..eeaf17877eab --- /dev/null +++ b/docs/reference/terminal-hidden-view-parking.md @@ -0,0 +1,115 @@ +# Terminal Hidden View Parking + +Status: Shipped — Phase 1 of the terminal model/view architecture, kill switch +`terminalHiddenViewParking` (default on). See +[`terminal-model-view-contract.md`](./terminal-model-view-contract.md) for the +invariants this design extends and the full phase list. + +## Problem + +Hidden terminal panes keep a full renderer xterm instance alive (buffer, +scrollback, DOM, addons). At many-worktree scale this is the dominant renderer +memory cost, and it forces every hidden byte through renderer-side write/skip +decisions. The main-process model (daemon + runtime headless emulators) already +ingests every byte and can serve restorable snapshots, so the renderer view for +a long-hidden pane is redundant state. + +A previous attempt shipped and was reverted the same day. The post-mortem +finding: parking unmounted the pane component, which also tore down the +renderer's PTY byte parsers — and those parsers are the only source of bell +notifications, title-transition agent-complete notifications, and tab titles. +A parked worktree whose agent finished would never notify. This design keeps +those side effects alive while parked. + +## Design + +### Park policy (renderer) + +A pure policy module decides which hidden terminal tabs may park: + +- Cold-park hysteresis: a tab must be hidden for 30s before parking. +- Hot-retain working set: recently visible worktrees/tabs are retained + (5 minutes, bounded count) so quick tab switches never pay a re-hydrate. +- Eligibility excludes: visible panes, hidden-measuring startup probes, + activity-portal panes, tabs with pending startup commands or pending + activation spawns, floating-panel tabs, and any tab whose PTY is not + snapshot-backed (remote-runtime `remote:` PTYs and SSH PTYs are excluded). +- Kill switch: `settings.terminalHiddenViewParking === false` disables parking + entirely. + +### Park mechanics + +Parking a tab unmounts its `TerminalPane` React subtree (the overlay layer +renders null for parked tabs). This is the same teardown that tab-group moves +already exercise: transports detach but the PTY session, daemon model, and tab +state all survive. The xterm instance, its buffers, DOM, and WebGL/addon +resources are released. + +### Parked watcher (the piece the reverted attempt lacked) + +While a tab is parked, a pane-less watcher +(`parked-terminal-byte-watcher.ts`) keeps the pane's side effects alive. Its +consumption mode is decided once at watcher start: + +- **Main side-effect authority on (default):** the watcher is purely + fact-driven — it registers exactly one `pty:sideEffect` fact consumer and + parses no bytes. Titles, agent working/idle/exited transitions, BEL + attention, and PR links arrive as main-tracker facts and drive the same + policy callbacks a mounted pane uses. With the hidden-delivery gate also on, + the watcher marks the PTY hidden so main stops renderer byte delivery + entirely; the DECSET 2031 color-scheme subscribe arrives as main's + `2031-subscribe` fact and the watcher replies out-of-band via + `transport.sendInput`. +- **Kill switch off:** the watcher subscribes to raw bytes through the + dispatcher sidecar mechanism (the same mechanism background agent launches + use) and runs the transport-level byte parsers with no xterm — OSC 0/1/2 + titles (all-titles ordering, live-path normalization), the title-transition + agent tracker (completion notification, prompt-cache timer), the OSC-aware + stateful BEL detector, the GitHub PR link scan, and a dedicated DECSET 2031 + byte responder (`parked-terminal-mode2031-responder.ts`, whose + `subscribeToPtyData` registration doubles as the delivery-interest signal). + +The two modes drive one shared policy-callback block, so flipping the kill +switch never changes notification semantics. Main's synthetic +agent-title/permission frames feed the main tracker directly and arrive as +facts; the legacy synthetic `pty:data` copy exists only in kill-switch-off +mode. + +Out of scope while parked: OSC 52 clipboard writes. Terminal queries inside +hidden-dropped chunks are answered by main's model responder +([`terminal-query-authority.md`](./terminal-query-authority.md)); in +kill-switch-off byte mode only the 2031 reply is answered and Command Code +output is not scraped, matching the pre-gate status quo. + +### Reveal + +Revealing a parked tab remounts the pane subtree and rides the existing +reattach path: fresh xterm via `openTerminal` (unicode provider activation +before any write), daemon model snapshot > relay replay > cold restore +precedence, replay-guarded so snapshot-embedded queries never answer, then +`POST_REPLAY_REATTACH_RESET` hygiene, fit, and PTY resize. The watcher is +disposed before the pane handlers re-register. + +## Invariants + +1. PTY reads never stop; parking only changes renderer-side view lifetime. +2. Bell, agent-completion, title, and PR-link side effects keep working while + parked (watcher parity tests). +3. Reveal shows model-correct output (visual gates: hidden TUI restore, long + table, rendering golden) and accepts input immediately. +4. Sleep/wake, pane close, and PTY restart while parked must not leak watchers + or strand parked state. +5. Memory: parked tabs hold no xterm buffers; renderer memory scales with + visible panes. + +## Relation to later phases (all shipped) + +Side-effect authority in main (Phase 3) replaced the watcher's byte parsing +with the `pty:sideEffect` fact consumer; the hidden-delivery gate (Phase 4) +stops hidden byte delivery in main, moving the parked 2031 reply from the +byte sidecar to the `2031-subscribe` fact; the model query responder +(Phase 5) answers queries in hidden-dropped chunks. The watcher's byte-parser +mode survives only behind the kill switches. Parking still excludes +remote-runtime and SSH PTYs (no local snapshot to restore from); the watcher +would return as a byte parser only if remote-runtime tabs — whose bytes never +transit local main — ever became parkable. diff --git a/docs/reference/terminal-model-view-contract.md b/docs/reference/terminal-model-view-contract.md new file mode 100644 index 000000000000..79fb55575f3f --- /dev/null +++ b/docs/reference/terminal-model-view-contract.md @@ -0,0 +1,218 @@ +# Terminal Model/View Contract + +## Goal + +Terminal output should have one authoritative model path and many disposable +views. A renderer xterm is the fast interactive view, but it must not be the +only place hidden, remote, mobile, SSH, or CLI-visible terminal state exists. + +This contract defines the boundary the shipped terminal stack implements — and +that future terminal work must preserve — without changing the query-response +behavior that real shells and TUIs depend on. See [Architecture +Status](#architecture-status) for the shipped phases. + +## Terms + +- **PTY stream:** Ordered bytes read from a local PTY, daemon PTY, SSH relay PTY, + or remote runtime PTY. +- **Terminal model:** Main/runtime-owned state derived from PTY bytes. Today this + is mostly the headless emulator plus retained read transcript state. +- **Terminal view:** A renderer xterm, mobile subscriber, remote desktop + subscriber, or CLI read page consuming model state and live output. +- **Snapshot:** A bounded model serialization that can restore a view without + replaying an unbounded byte log. +- **Transcript:** The retained output contract for `orca terminal read`; it is + line/cursor oriented and distinct from a screen snapshot. + +## Non-Negotiable Invariants + +1. PTY reads do not stop to protect renderer performance. Backpressure may bound + delivery to views, but terminal state, notifications, titles, and agent + status keep advancing from the PTY stream. +2. Active visible terminal input/output stays on the lowest-latency path. Bulk + hidden or background output must not delay keystroke-sized foreground redraws. +3. Hidden views do not own unbounded output memory. Main's hidden-delivery + gate drops renderer-bound bytes for hidden-marked PTYs after model + ingestion and emits an out-of-band restore marker + (`pty:modelRestoreNeeded`) so the view restores from the model on reveal. + With the gate's kill switches off, hidden bytes ride a bounded renderer + queue whose overflow latches the same model restore. +4. Returning to a hidden or slept terminal must show model-correct output. A + stale or replaced view may be cleared and replayed from a snapshot, but it + must not show a warning fallback when model recovery is available. +5. Snapshots and live bytes have ordering metadata. A view restore must not + duplicate bytes already included in the snapshot or drop bytes that arrived + after it. Main buffer snapshots report the pending-delivery start sequence + (`pendingDeliveryStartSeq`) so the renderer reconciles live chunks racing a + restore without misreading foreign sequence domains as duplicates. +6. Terminal query authority is singular and structural: the party that + writes a chunk into a live terminal answers its queries. Visible renderer + and remote views keep xterm authority. Chunks dropped by the + hidden-delivery gate are answered exactly once by the main model + responder, from runtime-emulator state plus renderer-pushed view + attributes. Replayed, seeded, or snapshot bytes are answered by no one. + The daemon emulator never answers. (Amended by Phase 5 — see + [`terminal-query-authority.md`](./terminal-query-authority.md).) +7. The transcript contract stays separate from screen restore. `orca terminal + read` must preserve bounded previews, cursor pagination, partial-line rules, + truncation flags, and total counts even if view snapshots change shape. +8. Local, daemon, SSH, remote runtime, mobile, and CLI paths must either satisfy + the same model/view contract or explicitly report that model recovery is + unavailable. + +## Current Owners + +| Responsibility | Current owner | +| --- | --- | +| PTY byte source and local/SSH delivery | `src/main/ipc/pty.ts` | +| Hidden-delivery gate (hidden marks, delivery interest, drop accounting, restore markers) | `src/main/ipc/pty-hidden-delivery-gate.ts`, drop sites in `src/main/ipc/pty.ts` and `src/main/ssh/ssh-relay-session.ts` | +| Side-effect parsing and the `pty:sideEffect` facts channel | `src/shared/terminal-output-side-effects.ts` driven from `OrcaRuntimeService.onPtyData`; renderer policy in `src/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.ts` | +| Model query responder and view-attribute bridge | `src/main/runtime/terminal-model-query-authority.ts`, `src/main/daemon/terminal-view-attribute-responder.ts`, `src/main/runtime/terminal-view-attribute-store.ts` | +| Hidden view parking policy and parked watcher | `src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.ts`, `parked-terminal-byte-watcher.ts` | +| Daemon PTY state and headless snapshots | `src/main/daemon/headless-emulator.ts` | +| Runtime headless state, retained reads, mobile/session tabs | `src/main/runtime/orca-runtime.ts` | +| Remote terminal subscribe/multiplex/ACK semantics | `src/main/runtime/rpc/methods/terminal.ts` | +| Renderer xterm view and hidden restore behavior | `src/renderer/src/components/terminal-pane/pty-connection.ts` | +| Remote desktop runtime xterm transport | `src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts` | + +## Snapshot Contract + +A model snapshot must include: + +- terminal dimensions used to produce the snapshot; +- enough ANSI state to rehydrate xterm before snapshot content; +- bounded screen and scrollback content; +- title and cwd metadata when known; +- source metadata that distinguishes headless/model snapshots from renderer + fallback snapshots; +- monotonic ordering metadata for live-output reconciliation when available. + +A snapshot must not: + +- include unbounded transcript history; +- answer terminal queries while replaying into the model; +- overwrite newer live view output with older model output; +- hide that recovery was unavailable for a PTY surface. + +## View Contract + +A renderer or remote view may: + +- write active visible output immediately; +- budget visible inactive output; +- stop receiving hidden output entirely while main's hidden-delivery gate owns + the bytes (model restore on reveal); +- request fresh snapshots for restore, mobile subscription, or explicit remote + snapshot recovery. + +A view must: + +- keep live-output buffers bounded while a snapshot is in flight; +- apply generation or sequence checks before replaying a snapshot; +- refresh/repaint after replay when xterm/WebGL needs an explicit paint; +- keep side effects such as title, bell, cwd, and agent status flowing from the + PTY/model path (the `pty:sideEffect` facts channel) even while renderer byte + delivery is budgeted, gated, or parked. + +## Transcript Contract + +The retained read transcript is not a screen dump. It must preserve: + +- uncursored bounded latest preview behavior; +- cursor reads over completed retained lines; +- `oldestCursor`, `nextCursor`, `latestCursor`, and `returnedLineCount`; +- partial-line duplication rules; +- `truncated`, `limited`, and total count metadata; +- bounded memory for long partial lines and large output bursts. + +Snapshot optimizations must be tested against this transcript contract instead +of assuming xterm scrollback serialization can replace it. + +## Required Contract Tests + +Before moving more runtime behavior behind the model/view boundary, add or +extend tests that prove: + +- headless snapshots rehydrate rich alternate-screen TUI state; +- the daemon emulator never answers DA, DSR, OSC 11, or theme-sensitive + queries (the `session.test.ts` pins are permanent); +- the main runtime responder answers queries only from live chunks the + hidden-delivery gate dropped — never delivered, replayed, seeded, or + remote-subscribed chunks; +- hidden renderer overflow restores from model state without duplicate live + output; +- sleep/wake and worktree revisit restore from model-correct state; +- SSH-backed PTYs follow the same snapshot and ordering semantics as local PTYs; +- remote runtime multiplex output remains ACK bounded and can request recovery + snapshots; +- mobile subscribers receive bounded snapshots without unbounded pending live + output; +- retained terminal reads remain pageable and bounded after large output. + +Current coverage is spread across: + +- `src/main/daemon/headless-emulator.test.ts` +- `src/main/daemon/session.test.ts` +- `src/main/ipc/pty.test.ts` (hidden-gate drops, restore markers, + `pendingDeliveryStartSeq`) +- `src/main/ipc/pty-hidden-delivery-gate.test.ts` +- `src/main/runtime/mobile-subscribe-integration.test.ts` +- `src/main/runtime/rpc/terminal-subscribe-buffer.test.ts` +- `src/main/runtime/rpc/terminal-multiplex.test.ts` +- `src/main/runtime/orca-runtime.test.ts` +- `src/main/runtime/terminal-query-responder.test.ts` +- `src/shared/terminal-output-side-effects.test.ts` +- `src/renderer/src/components/terminal-pane/terminal-title-tracker-parity.test.ts` +- `src/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.test.ts` +- `src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts` +- `src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts` +- `src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts` +- `tests/e2e/terminal-hidden-tui-visual-restore.spec.ts` +- `tests/e2e/terminal-hidden-view-parking.spec.ts` +- `tests/e2e/terminal-parked-memory.spec.ts` +- `tests/e2e/terminal-sleep-wake-restore.spec.ts` +- `tests/e2e/terminal-output-scheduler.spec.ts` +- `tests/e2e/artificial-opencode-terminal-load.spec.ts` + +## Architecture Status + +All six phases of the terminal model/view architecture are shipped; the kill +switches noted in parentheses default on: + +1. **Hidden view parking** — "Park hidden terminal views behind a byte + watcher": hidden terminal tabs unmount their xterm after a cold-park + hysteresis; a pane-less watcher keeps bell/title/agent/PR side effects + alive while parked (`terminalHiddenViewParking`). See + [`terminal-hidden-view-parking.md`](./terminal-hidden-view-parking.md). +2. **Parked memory benchmarks** — "Benchmark parked hidden terminal memory": + renderer heap and live-terminal counts gate parking in the perf suite + (`tests/e2e/terminal-parked-memory.spec.ts`). +3. **Side-effect authority in main** — "Track terminal titles in main with + all-titles ordering", "Move terminal side-effect authority to a main facts + channel", "Complete terminal side-effect facts coverage", "Finish terminal + side-effect authority migration": every local/daemon/SSH PTY byte is + side-effect-parsed once in main and delivered as `pty:sideEffect` facts + (`terminalMainSideEffectAuthority`). See + [`terminal-side-effect-authority.md`](./terminal-side-effect-authority.md). +4. **Hidden delivery gate** — "Gate PTY delivery to hidden terminal views": + main drops renderer-bound bytes for hidden-marked PTYs after model + ingestion; delivery-interest registrations exempt sidecar byte consumers, + out-of-band restore markers latch model restore, and + `pendingDeliveryStartSeq` reconciles live output racing a restore + (`terminalHiddenDeliveryGate`). +5. **Model query authority** — "Answer hidden terminal queries from the + model", "Bridge renderer view attributes to the model responder", "Align + query authority contract and spawn-time ownership": hidden-dropped queries + are answered by the runtime emulator plus renderer-pushed view attributes, + and hidden-at-spawn PTYs are marked before byte one + (`terminalModelQueryAuthority`). See + [`terminal-query-authority.md`](./terminal-query-authority.md). +6. **Skip grammar deletion** — "Delete the hidden renderer skip grammar": the + renderer's per-chunk hidden-skip eligibility grammar and the 10s codex + startup query window are deleted; the kill-switch-off fallback is the + bounded background queue with overflow-latched model restore. + +Treat every hidden/slept/revisited TUI glitch as a contract failure, not as a +local repaint quirk. Renderer fallback paths retire only when their kill +switches do, and only after the equivalent model path has platform and TUI +golden coverage. diff --git a/docs/reference/terminal-query-authority.md b/docs/reference/terminal-query-authority.md new file mode 100644 index 000000000000..e05b57688367 --- /dev/null +++ b/docs/reference/terminal-query-authority.md @@ -0,0 +1,326 @@ +# Terminal Query Authority + +Status: Shipped — Phase 5 of the terminal model/view architecture, kill +switch `terminalModelQueryAuthority` (default on). Builds on +[`terminal-model-view-contract.md`](./terminal-model-view-contract.md) (this +phase **amends invariant 6**), +[`terminal-side-effect-authority.md`](./terminal-side-effect-authority.md) +(Phase 3), and the Phase-4 hidden-delivery gate +(`src/main/ipc/pty-hidden-delivery-gate.ts`). + +## Problem + +Phase 4 drops renderer-bound bytes for hidden-gated PTYs after model ingestion +(`src/main/ipc/pty.ts:1426,1515`, `src/main/ssh/ssh-relay-session.ts:931`). +Queries embedded in dropped bytes get no reply: DA1 (ConPTY 1.22+ blocks +waiting for it — `terminal-conpty-device-attributes.ts:22`), CPR probes hang +TUIs, OSC 10/11 leaves `claude /theme` blind while hidden. The pre-Phase-4 +hidden skip latch had the same hole (only mode 2031 and the 10s codex startup +window answered), so this is not a regression — it is the long-standing gap +this phase closes. + +Contract invariant 6 ("the model must never answer queries") was written +against a real bug: the daemon emulator replying ahead of the renderer with +default-xterm values (the OSC-11 default-black-background race, +`headless-emulator.ts:86-97`, pinned by `session.test.ts:163-190`). The danger +was never "the model answers" — it was **two answerers for the same bytes**, +one of them with wrong values. Phase 5 keeps the singularity and fixes the +values. + +## Decision: the delivery decision is the reply decision + +Main answers a query **iff main dropped the chunk that carried it**. The same +per-chunk hidden-gate predicate (`shouldDropHiddenRendererPtyData`) that +decides renderer delivery decides reply ownership, evaluated once, +synchronously, at ingestion: + +- Visible/unmarked PTY → chunk delivered → renderer xterm auto-replies via + `Terminal.onData` → `transport.sendInput`, unchanged. +- Hidden-marked, no delivery interest → chunk dropped → main answers from the + runtime headless emulator, via the provider input path (`provider.write`, + same path as `pty:write`; daemon shell-ready write gating and the SSH relay + write apply unchanged). +- Replayed/seeded/snapshot bytes → answered by no one (replay guards on both + sides). + +This is structurally exactly-one-responder: a chunk is delivered or dropped, +never both, and each side only answers bytes it actually parsed live. The +mark/unmark ordering, unhide-before-restore, and restore-marker IPC all exist +from Phase 4 and are reused, not duplicated. + +Rejected alternatives: + +- **Fact-based renderer replies per query class** (the mode-2031 pattern + generalized): needs a main-side detection grammar per query, a fact round + trip per reply, and the renderer cannot answer CPR/DECRPM anyway — the + emulator is the only state for a hidden pane. The 2031 fact stays because it + is subscription registration, not a state query. +- **Emulator always answers**: re-creates the OSC-11 double-reply race for + visible panes. Never. + +## Mechanism: forwarded emulator onData, not a new grammar + +`HeadlessEmulator` has `onData` wiring behind a per-write capture flag. +For static and model-state queries, xterm core **is** the query grammar: the +runtime emulator runs the same xterm version with equivalent options as the +renderer pane, so main's reply set equals the visible renderer's by +construction — verified empirically against the bundled headless build: +DA1/DA2, DSR 5n, CPR, DECRPM (including unknown-mode `0`), DECRQSS (including +DECSCUSR from cursor options), XTVERSION, kitty `CSI ? u` all reply; XTWINOPS +(`windowOptions` stays default-off) and XTGETTCAP stay silent, matching +visible behavior today. The headless build has **no theme service**: OSC +4/10/11/12 queries and DSR ?996n return nothing even with the `theme` option +set, so the view-attribute class is answered by responder-registered parser +handlers instead (below) — never by core defaults. + +Forwarding predicate, captured per chunk in `OrcaRuntimeService.onPtyData` and +attached to the emulator `writeChain` link (the mark can flip between +ingestion and an async write; the decision must not be re-read at reply time): + +1. gate enabled (`terminalMainSideEffectAuthority` and + `terminalHiddenDeliveryGate` both on) AND new kill switch + `terminalModelQueryAuthority !== false`; +2. the chunk was hidden-dropped for this PTY (`shouldDropHiddenRendererPtyData` + — same module state, same tick as the drop sites); +3. the write is live PTY data — never `seedHeadlessTerminal`, + `maybeHydrateHeadlessFromRenderer`, option pushes, or any snapshot replay + (main-side replay guard, mirror of the renderer's `replay-guard.ts`); +4. no remote view subscriber is attached to the PTY (runtime terminal-RPC + subscriber records / `mobileSubscribers`): a mobile/web/remote-desktop + xterm receiving the multiplexed stream answers with view authority, exactly + like a visible local pane. Legacy JSON `terminal.subscribe` streams **do** + register as view subscribers and suppress, even when the consumer is a + read-only watcher — deliberately conservative, because the stream may feed + an older live xterm view and a withheld reply (the pre-Phase-5 status quo) + is strictly safer than a double reply. Consumers that never register a + stream (CLI `terminal.read`, automation observers) do not suppress — they + also do not answer; that bounded no-reply case matches today's behavior. + +Everything the emulator emits outside a forwarding window is discarded, which +also swallows unsolicited core emissions (e.g. native 997 color-scheme pushes +triggered by option mutations). + +## Reply classes + +| Class | Queries | Answer source | +| --- | --- | --- | +| Static | DA1 `CSI c` (ConPTY override below), DA2, DSR 5n, XTVERSION, DECRQM unknown → `0`, kitty `CSI ? u` | xterm core constants + kitty flag state | +| Model-state | CPR `6n`/`?6n`, DECRPM mode table (?1 ?6 ?7 ?25 mouse ?1004 ?1006 ?1016 ?1049 ?2004 ?2026, insert), DECRQSS DECSTBM/DECSCA/SGR, kitty flags | emulator buffer/mode state — for a hidden pane it is the only state, hence authoritative | +| View-attribute | OSC 4/10/11/12 `;?` queries, DSR ?996n | responder parser handlers + renderer attribute push (below); **silent until first push** | +| View-attribute (via options) | DECRQSS DECSCUSR, DECRQM 12 | xterm core, from pushed `cursorStyle`/`cursorBlink` emulator options | +| Silent | XTWINOPS, XTGETTCAP, ?15n/?25n/?26n/?53n | nobody, visible or hidden | +| Mode 2031 | DECSET 2031 subscribe | unchanged in Phase 5: main emits the `2031-subscribe` fact, the renderer replies (`handleHiddenMode2031SubscribeFact`, `pty-connection.ts`; parked watcher fact callback). Emulator-native 2031/997 output is suppressed by the forwarding guard | + +### View-attribute bridge + +Renderer→main push, `pty:terminalViewAttributes` — one global snapshot, +not per-PTY: the composed terminal `ITheme` (from +`applyTerminalAppearance`, `terminal-appearance.ts`), +`terminalCursorStyle`, `terminalCursorBlink`, and the resolved color-scheme +mode (`resolveTerminalColorSchemeMode` — the same source as the existing +hidden 2031 reply). Pushed on renderer startup and on every theme/settings +apply. + +Main consumes it two ways: + +- `cursorStyle`/`cursorBlink` are applied to every runtime emulator's options + inside the replay guard; xterm core then answers DECRQSS DECSCUSR and + DECRQM 12 with renderer-true values (verified working headless). +- Palette and color-scheme replies come from responder-registered parser + handlers on the emulator (`registerOscHandler` 4/10/11/12, + `registerCsiHandler` for DSR ?996n), because the headless core cannot + answer them. The OSC handlers see SET payloads too, so runtime OSC + 4/10/11/12 mutations (and 104/110/111/112 resets) from the byte stream are + tracked per PTY and layered over the pushed base palette — matching what + the renderer's theme service reports for a visible pane. + +Staleness rules: replies use the last push; a theme flip is stale for at most +one IPC hop (subscribed TUIs are corrected by the 2031/997 flip push). +**Before the first push main answers no view-attribute query** — a fabricated +default would resurrect the default-black OSC-11 bug; silence is the +documented hidden status quo. + +### Kitty keyboard flags + +`vtExtensions.kittyKeyboard: true` is enabled in `HeadlessEmulator`, matching +`buildDefaultTerminalOptions` (`pane-terminal-options.ts:50`). Risk is low: +for the write-only daemon use, keyboard state never alters serialization; the +change only makes the emulator parse `CSI =/>/< u` pushes instead of ignoring +them, and lets the responder answer `CSI ? u` with the flags the hidden app +actually pushed. Snapshot parity: add `kittyKeyboardFlags` to `TerminalModes` +for emulator re-seed parity only. `rehydrateSequences` must **not** push kitty +flags into a renderer xterm — `POST_REPLAY_REATTACH_RESET`'s deliberate kitty +reset (stale CSI-u Ctrl+C hazard, `terminal-replay-cursor-state.test.ts`) +stays authoritative. Slice 3 wires the re-seed consumer: the daemon +warm-reattach snapshot threads `modes.kittyKeyboardFlags` through the spawn +result into `seedHeadlessTerminal`, which applies them to the fresh runtime +emulator via its own `CSI = flags ; 1 u` parse (outside any forwarding +window), so hidden `CSI ? u` reports the flags the hidden app actually +pushed. Paths without a snapshot (cold restore spawns a fresh shell) answer +`?0u`; protocol-conformant programs re-push. + +### ConPTY DA1 variant + +The provider kind is known main-side: mirror `isLocalNativeWindowsPty` +(`windows-pty-compatibility.ts:59`) from the spawn record (local/daemon +provider, `win32`, not WSL). For such PTYs register a CSI `c` override on the +emulator parser (the main-side twin of +`installConptyDeviceAttributesHandler`) replying `CSI ?61;4c`, still gated by +the forwarding predicate. The override is installed at emulator creation and +retrofitted when the spawn mark lands (daemon stream data can create the +emulator before the awaited spawn response marks the PTY). ConPTY blocking on +a missing DA1 is a spawn-time hazard; the hidden-at-spawn loss window is +closed by the slice-3 `initiallyHidden` spawn flag (races section). + +## Suppression: when main never replies + +- Visible or unmarked PTY (chunk was delivered). +- Renderer delivery interest registered (chunk was delivered to a sidecar). +- Remote-runtime (`remote:`) PTYs — never markable + (`isHiddenDeliveryGateManagedPty`), bytes never transit local main. +- Remote view subscriber attached (mobile/web/remote desktop owns replies). +- Seed/hydration/snapshot writes into the emulator, and option pushes. +- Kill switches off — no marks exist, and `terminalModelQueryAuthority` is an + independent off switch for the responder alone. +- The **daemon** emulator: never, under any setting. The responder lives in + main's runtime only; `session.test.ts:163-190` stays pinned verbatim. + +## Transition races + +Worst cases, per direction: + +- **visible→hidden**: chunks delivered between the visibility flip and the + mark landing in main are hidden-skipped by the renderer write path without + query scanning. No reply, no duplicate — identical to the pre-Phase-4 hidden + skip behavior, bounded by one renderer→main IPC hop. After the mark lands, + main answers everything it drops. +- **hidden→visible**: unmark consumes the drop latch and emits the restore + marker; the snapshot replay is replay-guarded, so queries main already + answered are never re-answered from the snapshot; post-unmark live chunks + are answered by xterm once (restore-queued live chunks reply late, not + twice). +- **Split queries across the drop/deliver boundary**: neither parser saw the + whole sequence → no reply; the restore marker resets renderer cross-chunk + state and replay hygiene resets the parser. At-most-once holds. + +Safe-side rule per class: duplicates are structurally impossible (one decision +point per chunk); where the race costs anything it costs a missing reply. +That is acceptable for state queries (DSR/CPR/DECRPM — TUIs re-probe or +tolerate silence, as they did for every hidden pane before this phase). The +one blocking-on-no-reply sequence, ConPTY DA1, only fires at spawn. A visible +pane answers it from the renderer xterm. A PTY spawned hidden previously had +no answerer until the renderer's hidden mark landed in main (one IPC hop +after spawn). Slice 3 closes that window with the `initiallyHidden` +spawn-record flag: the renderer declares hidden-at-spawn on `pty:spawn` +(never for remote-runtime transports), and main marks the PTY hidden before +the first byte — pre-spawn for +daemon-host sessions whose id is minted up front, immediately after +`provider.spawn` resolves otherwise — so the gate and responder own queries +from byte one. The pane's first visibility sync then re-marks or unmarks +through the existing Phase-4 machinery (unmark emits the restore marker for +any spawn-window drops). + +## Invariants + +1. Exactly one party may answer any query, chosen by the chunk's delivery + decision: delivered → the consuming live view's xterm; dropped → main's + model responder; replayed/seeded → no one. The decision is captured once, + synchronously, at ingestion. +2. Main answers only from live PTY bytes parsed by the runtime emulator — + never from snapshot, seed, hydration, or option-push writes. +3. View-attribute answers are renderer-true or absent: no reply is ever + fabricated from emulator defaults (the OSC-11 lesson). +4. The daemon emulator stays write-only; daemon subprocess query writes stay + zero (`session.test.ts` pins are permanent). +5. Reply parity is structural for static and model-state classes: same xterm + core, equivalent options, no hand-rolled grammar — the only overrides are + the documented ConPTY DA1 variant and the view-attribute parser handlers + the headless core cannot serve. +6. Remote views keep view authority; main yields whenever a remote view + subscriber is attached. + +**Contract amendment** — `terminal-model-view-contract.md` invariant 6 is +replaced by: + +> 6. Terminal query authority is singular and structural: the party that +> writes a chunk into a live terminal answers its queries. Visible renderer +> and remote views keep xterm authority. Chunks dropped by the +> hidden-delivery gate are answered exactly once by the main model +> responder, from runtime-emulator state plus renderer-pushed view +> attributes. Replayed, seeded, or snapshot bytes are answered by no one. +> The daemon emulator never answers. + +The contract's test bullet "headless tracking does not answer DA, DSR, OSC 11, +or theme-sensitive queries" splits into: daemon emulator never answers +(unchanged pins) / runtime responder answers only hidden-dropped chunks. The +side-effect authority matrix row "DECSET 2031 reply — query authority stays +with the view (contract invariant 6)" gains a pointer here; its reply path is +otherwise untouched in this phase. + +## Test strategy + +- Responder unit tests beside `orca-runtime.test.ts`: marked vs unmarked vs + interest-suppressed; each reply class; seed/hydrate silence; remote- + subscriber suppression; ConPTY DA1 variant; kill-switch off; mark flip + between ingestion and async emulator write (captured decision wins). +- Parity harness: shared query byte fixtures through a renderer-configured + xterm (onData capture) and through the responder; assert byte-identical + replies for static + model-state classes, and for view-attribute classes + after an attribute push. +- `session.test.ts:163-190`: assertions stay; the comment is updated to name + the main responder (not "the renderer") as the hidden answerer. +- E2E: hidden `claude /theme` reports the configured theme; hidden TUI + blocked on CPR/DA unblocks while gated; reveal shows no stray reply + fragments (`?1;2c`, `rgb:` …) on the prompt; Windows ConPTY golden and + `terminal-hidden-view-parking.spec.ts` stay green. + +## Cut-offs (shipped as three stacked slices) + +1. **Responder core.** Emulator onData wiring + per-write capture + main + replay guard; kitty flag enable (+ `TerminalModes.kittyKeyboardFlags`); + static + model-state classes; ConPTY DA1 override; remote-subscriber + suppression; `terminalModelQueryAuthority` switch; unit + parity tests. + Main-only — no renderer change. Ships the DA1/CPR/DECRPM unblock. +2. **View-attribute bridge.** `pty:terminalViewAttributes` push, cursor + option application under the guard, responder OSC/DSR parser handlers with + per-PTY palette-mutation tracking, silent-until-push rule, `/theme` e2e. +3. **Contract alignment.** Invariant-6 amendment in the contract doc, test + bullet split, `session.test.ts` comment, side-effect matrix pointer, and + the Phase 6 prerequisites below recorded as accepted. + +## Phase 6 (delete skip grammar + startup window): prerequisites from this design + +Phase 6 is shipped: the renderer hidden-skip eligibility grammar and the 10s +codex startup renderer-query window are deleted. Kill-switch-off hidden panes +fall back to the pre-grammar path — hidden bytes ride the bounded background +scheduler queue; overflow latches the model-snapshot restore — and never run +a per-chunk content scan. + +Accepted and shipped in slice 3 (except where noted): + +- **Mark-before-first-byte** (shipped): panes spawned without a visible view + are hidden-marked at spawn via the `initiallyHidden` flag on `pty:spawn` + (spawn-record flag, not a renderer round trip) so startup queries — + including ConPTY's blocking DA1 — are main-owned from byte zero. Phase 6 + removed the codex exclusion with the window: codex spawns are main-owned + from byte zero too, the responder answering their startup probes. +- **Attributes before spawn** (shipped): the renderer pushes composed view + attributes once at app start (right after settings load, before terminal + reconnect/spawn), so spawn-time view-attribute queries no longer fall into + the silent-until-push rule. Per-pane appearance applies keep re-publishing + through the same deduped publisher. +- **Daemon shell-ready write gating** (verified): responder replies through + `ptyController.write` → daemon `Session.write` are QUEUED pre-ready, never + dropped, and the queue flushes at the shell-ready marker or the 15s + `SHELL_READY_TIMEOUT_MS` bound (`session.ts`). The codex window was removed + with hosted ConPTY golden coverage, unit DA1 parity, and the kill switches + as the safety net; explicit spawn-time e2e on Windows daemon PTYs remains + worth adding. +- With the skip grammar deleted, every chunk is either written to a live + xterm or dropped — the delivered-but-skipped no-reply gap disappears and + the only remaining loss window is the mark IPC race. +- **2031 consolidation** (optional follow-up): move the subscription registry + into the responder (the headless core cannot serve 997 pushes any more than + it can ?996n) and push 997 flips from the attribute cache, retiring the + `2031-subscribe` fact reply, the parked responder, and the parked-tab + theme-flip gap. diff --git a/docs/reference/terminal-side-effect-authority.md b/docs/reference/terminal-side-effect-authority.md new file mode 100644 index 000000000000..852a607d5bfa --- /dev/null +++ b/docs/reference/terminal-side-effect-authority.md @@ -0,0 +1,252 @@ +# Terminal Side-Effect Authority + +Status: Shipped — Phase 3 of the terminal model/view architecture, kill switch +`terminalMainSideEffectAuthority` (default on). Builds on +[`terminal-model-view-contract.md`](./terminal-model-view-contract.md) and +[`terminal-hidden-view-parking.md`](./terminal-hidden-view-parking.md) (Phase 1). + +## Problem + +Main parses every local/daemon/SSH PTY byte before renderer delivery +(`OrcaRuntimeService.onPtyData` in `src/main/runtime/orca-runtime.ts`: +side-effect tracker, OSC 9999 agent status, headless emulator, tails, URL +watchers; SSH feeds the same path from `wireUpPtyEvents` in +`src/main/ssh/ssh-relay-session.ts`). Before this phase, the side effects +users see — bell unread/notifications, title transitions, agent-complete +notifications, command lifecycle, PR links — were derived a second time by +renderer byte parsers. That duplication forced Phase 1's watcher to parse +bytes, forced main to fabricate synthetic OSC title frames over `pty:data` +just so renderer parsers could see them, and blocked Phase 4 from ever +stopping hidden byte delivery. Phase 3 made main the side-effect parser for +every PTY whose bytes transit local main; the renderer byte parsers +(`createPtyOutputProcessor` in `pty-transport.ts`, the parked watcher's byte +mode) survive only for remote-runtime PTYs and the kill-switch-off fallback. + +## Authority Matrix + +"Main" means parsed once in `onPtyData` and delivered as derived facts. +Remote-runtime PTYs (`remote:`) never transit local main; the renderer +(`remote-runtime-pty-transport.ts:74`) stays their parser permanently. + +| Side effect | local-daemon | SSH | remote-runtime | +| --- | --- | --- | --- | +| OSC 9999 agent status | main (parsed in `onPtyData`, emitted as `agentStatus:set`) | main | renderer (`shouldOwnAgentStatusInRenderer`, `pty-connection.ts`) | +| OSC 0/1/2 titles + working/idle/exited tracker + 3s stale-title timer | main | main | renderer | +| BEL attention (OSC-aware stateful detector) | main | main | renderer | +| OSC 133;D command-finished exit code | main | main | renderer | +| GitHub PR-link scan | main | main | renderer | +| Command Code output scrape | main (per-PTY detector beside the tracker → `command-code-working`/`command-code-done` facts; the renderer pane keeps the done settle timer — it must consult the live status row) | main | renderer | +| DECSET 2031 color-scheme reply | renderer view/watcher — the 2031 fact reply path is untouched by Phase 5; general query authority is now per-chunk structural ownership, see [`terminal-query-authority.md`](./terminal-query-authority.md) (contract invariant 6 as amended) | same | renderer | +| DECSET 2004 paste readiness (`agent-paste-draft.ts`) | renderer — input pacing, not a model side effect | renderer | renderer | + +## Main-Side Tracker + +- The side-effect core shared with the renderer processor lives in + `src/shared/terminal-output-side-effects.ts`: all-titles ordering via + `extractAllOscTitles` (coalesced working→idle transitions are why last-title + is insufficient — issue #1083), `normalizeTerminalTitle`, the literal + `cursor agent` title drop (`CURSOR_NATIVE_TITLE_LOWER`, + `src/shared/agent-detection.ts`), the `createAgentStatusTracker` + transitions, the stale-working-title 3s timer + (`STALE_WORKING_TITLE_TIMEOUT_MS`), and the stateful BEL detector + (`src/shared/terminal-bell-detector.ts`). +- One tracker per PTY on `OrcaRuntimeService`, lazily created like + `agentStatusOscProcessorsByPtyId`; disposed in `onPtyExit` (cancels the + stale-title timer). +- It replaced the chunk-level last-title extraction in `onPtyData`: titles + feed in byte order, so `lastOscTitle`/`lastAgentStatus`, tui-idle waiters, + and pending-message delivery see intermediate transitions instead of only + the chunk's last title. PTY/leaf records keep the **raw** last title + (worktree `ps` and mobile tab titles expect raw); emitted facts carry + `(normalizedTitle, rawTitle)` like `onTitleChange`. +- No deferred drain in main — the renderer's setTimeout(0) batching + (`sideEffectDrainTimer`, `pty-transport.ts`) protects xterm paint, which + does not exist in main. Main applies synchronously and batches the IPC per + flush. +- The stats `AgentDetector` (`src/main/stats/agent-detector.ts`) keeps its own + last-title scan, untouched: synthetic titles must never reach it. + +## Event Transport: `pty:sideEffect` + +One batched main→renderer channel (`window.api.pty.onSideEffect`, +`src/preload/index.ts`). It is **not** routed through the pty dispatcher: +the renderer fact-consumer registry +(`terminal-side-effect-facts-handler.ts`) subscribes directly via +`window.api.pty.onSideEffect` — one channel subscription per renderer, with +exactly one registered fact consumer per PTY. Events are **facts, not +decisions**: `title`, `bell`, `agent-working`, `agent-idle` (with title), +`agent-exited`, `command-finished` (exit code), `pr-link`. Each carries +`ptyId`, main-known attribution (worktreeId/tabId/paneKey from runtime leaf +records, same resolution as `emitTerminalAgentStatusEvents`), and the PTY +`outputSequence`. + +Ordering rules: + +1. Per-PTY in-order; facts from one chunk are emitted in byte order (status + payloads, then titles in sequence, then bell — the renderer drain's order). +2. Deliberately **not** synchronized with `pty:data`: side effects must keep + advancing while renderer delivery is ACK-gated (contract invariant 1). A + completion title may reach the store before the visible xterm paints the + final output; that is acceptable — attention/title state is out-of-band UI + state, and today's renderer drain already decouples by many batches under + timer throttling. +3. No attention replay: facts emitted while no renderer is subscribed are + dropped. On transport attach/park-handoff the renderer pulls a title-only + snapshot (`pty:sideEffectSnapshot`) marked `replay: true` — this reproduces + the eager-buffer behavior where replay restores titles but is barred from + bells/completions (`suppressAttentionEvents`, `pty-transport.ts`). The + store handler ignores a replay title older (by `outputSequence`) than the + last live title fact it applied. + +## Renderer Store Handler (policy stays in the renderer) + +Notification semantics, all preserved across the authority flip: + +- BEL marks worktree+tab unread unconditionally — including the focused pane + (`onBell`, `pty-connection.ts`); pane unread only behind + `experimentalTerminalAttention`; keydown clears unread + (`onTerminalKeyDown`, `pty-connection.ts`). +- BEL's OS notification is delayed 250 ms and yields to a pending + agent-task-complete (`scheduleTerminalBellNotification`, + `pty-connection.ts`). +- working→idle starts the Claude cache timer (null settings = not hydrated, + treat enabled) and schedules completion with 250 ms grace + 1500 ms max + wait + detail-wait store subscription + (`AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS` / + `AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS`, + `agent-task-complete-policy.ts`). +- Completion unread is suppressed only for the exact visible foreground pane + (`isVisibleForegroundPaneKey`, `use-notification-dispatch.ts`); BEL unread + has no such check. +- Dispatch-time liveness/staleness guards + (`dispatchTerminalNotification`, `use-notification-dispatch.ts`) and main's + 5 s per-worktree cooldown (`NOTIFICATION_COOLDOWN_MS`, + `src/main/ipc/notifications.ts`) remain the final gates. + +These need live renderer store state (PTY/layout maps, pane visibility, +settings, `agentStatusByPaneKey`, repo labels), so they stay in the renderer: +the pane-independent per-paneKey handler module +(`terminal-side-effect-facts-handler.ts`) consumes `pty:sideEffect` and +subsumes both `pty-connection.ts`'s callbacks and the parked watcher's +callback block (`sideEffectCallbacks`, `parked-terminal-byte-watcher.ts`) — +one policy path whether the tab is mounted, hidden, or parked. Main holds +**no** notification timers; only the stale-title timer (parser state) lives +in main. + +## Synthetic Frame Reroute + +`driveSyntheticTitleFromHook` and the spinner tick (`sendSyntheticTitle`, +`src/main/index.ts`) feed `runtime.ingestSyntheticTitleFrame(ptyId, data)`, +so synthetic agent-title/BEL frames enter the per-PTY tracker directly — +**not** `onPtyData`, so emulator state, tails, transcripts, and stats never +see them. The decorative-frame visibility gating +(`shouldSendSyntheticTitleFrame`) stands. The legacy synthetic `pty:data` +copy survives only in kill-switch-off mode, where renderer parsers still +need the bytes. The visible xterm renders nothing from titles, but +`pane.terminal.onTitleChange` feeds `registerPtyTitleSource` +(`pty-connection.ts`) → renderer serialize-snapshot `lastTitle` (mobile +parity); main prefers its own tracked title over renderer snapshot +`lastTitle` in both serialize paths. Under main authority synthetic frames +no longer produce phantom ACKs for bytes main never metered (`ackPtyData`, +`pty-dispatcher.ts`). + +## Migration Switch and Double-Fire Prevention + +Authority is structural per PTY kind — the predicate is "bytes transit local +main", exactly the `shouldOwnAgentStatusInRenderer` split +(`pty-connection.ts`). One renderer-consulted kill switch +(`settings.terminalMainSideEffectAuthority`, default on, mirroring +`terminalHiddenViewParking`): when on, IPC transports and the parked watcher +do not register byte parsers for local/SSH and the store handler consumes +`pty:sideEffect`; when off, renderer parsers register and `pty:sideEffect` +events are ignored. Main always parses and emits (its internal consumers need +the tracker regardless); main consults the same setting only to keep the +legacy synthetic-frame `pty:data` path alive while the switch is off. Exactly +one consumer per fact at any time — decided at transport/watcher creation, so +no per-chunk race. + +## Sidecar Consumers and Phase 4 + +Keep renderer byte access (input pacing / raw-output consumers, not side +effects): `agent-paste-draft.ts` (DECSET 2004 readiness), +`launch-agent-background-session.ts` (startup-injection pacing, onData +passthrough), `automation-session-observer.ts` (onData passthrough), and +`parked-terminal-mode2031-responder.ts` (DECSET 2031 theme replies for +parked tabs while the delivery gate is off). Their duplicated local OSC 9999 +store writes are gated off under main authority (the `onAgentStatus` +automation callbacks still fire; only the racing `setAgentStatus` store +writes drop). The Phase-4 hidden-delivery gate exempts PTYs with an active +`subscribeToPtyData` sidecar: registration is auto-surfaced to main as a +ref-counted delivery-interest signal (`pty-delivery-interest.ts`). With main +authoritative, the parked watcher is purely fact-driven: byte parsing exists +only in kill-switch-off mode, and the 2031 reply comes from the +`2031-subscribe` fact when the gate is on (the byte responder sidecar only +when it is off). The watcher file is deleted outright only when the kill +switch retires — it returns as a byte parser only if remote-runtime tabs +ever become parkable. + +## Invariants + +1. Every byte is side-effect-parsed exactly once, by exactly one authority, + chosen structurally per PTY kind. +2. Attention facts never replay: snapshot/eager/attach replays restore title + state only. +3. Notification policy (grace timers, yielding, suppression, dispatch guards) + lives with the renderer store; main emits facts with ordering metadata. +4. Side-effect facts keep flowing while renderer byte delivery is + backpressured, parked, or stopped by the hidden-delivery gate. +5. Synthetic agent frames feed the model tracker, never the emulator, tails, + transcripts, or stats. + +## Test Strategy + +- Parity harness (`terminal-title-tracker-parity.test.ts`): shared byte + fixtures (agent title cycles incl. coalesced chunks, BEL inside/spanning + OSC, CAN/SUB cancellation, cursor-agent literal, stale-title timeout under + fake timers, OSC 133;D, split PR URLs) run through the renderer + `createPtyOutputProcessor` and the main tracker; assert identical ordered + fact sequences. +- Unit: main tracker tests beside `orca-runtime.test.ts` (lastOscTitle + parity, tui-idle waiter transitions, synthetic ingestion); store-handler + tests reusing `parked-terminal-byte-watcher.test.ts` scenarios. +- Pinned tests that flip or retire: `pty-connection.test.ts` callback wiring, + `parked-terminal-byte-watcher.test.ts` (retires with the watcher); + `pty-transport*.test.ts` stay (processor remains for remote + kill switch). +- E2E gates that must stay green throughout: `terminal-attention.spec.ts`, + `droid-notification.spec.ts`, `terminal-hidden-view-parking.spec.ts`, + `terminal-parked-memory.spec.ts`; add main-authority bell/completion cases + (parked tab, focused-pane suppression, kill switch off). SSH parity is + exercised manually per the SSH test procedure before each slice ships. + +## Cut-Offs (shipped as four stacked slices) + +1. **Shared tracker in main.** Extract the processor core to shared, run the + per-PTY tracker in `onPtyData` replacing `extractLastOscTitle`, parity + tests. Main-internal consumers only; no IPC or renderer change. +2. **Authority flip.** `pty:sideEffect` channel, renderer store handler, + titles/bell/tracker authority to main for local+SSH behind the kill + switch; parked watcher stops byte parsing for those kinds. +3. **Inversion unwind.** Synthetic frames into the tracker, off `pty:data`; + OSC 133;D and PR-link facts; mobile `lastTitle` source preference. +4. **Long tail.** Command Code scrape to main, sidecar OSC 9999 dedup, parked + watcher shrunk to fact-driven mode (deletion waits on kill-switch + retirement), Phase 4 delivery-interest registration documented in the gate + design. + +## Open Items + +- **Daemon checkpoint `lastTitle` is write-only.** The daemon sleep/periodic + checkpoint (`daemon-pty-adapter.checkpointSessions` → daemon + `Session.getSnapshot`) persists the daemon emulator's `lastTitle`, which is + derived from real PTY bytes only — synthetic hook title frames never reach + the daemon process, so that field cannot carry hook-driven titles. Today no + restore path reads it back (`ColdRestoreInfo` drops it; reattach snapshots + surface only the ANSI payload), so there is nothing to fix. Main-side + consumers of the renderer serializer's `lastTitle` (mobile snapshot reads + and the headless hydration seed) prefer main's tracked title. If a future + consumer starts reading checkpoint `lastTitle`, it must route through the + same tracked-title preference. +- **Kill-switch retirement.** Once `terminalMainSideEffectAuthority` is + removed, the parked watcher's byte-parser mode, the renderer transport + parsers for local/SSH, and the legacy synthetic-frame `pty:data` copy all + become dead code and the watcher byte path can be deleted outright. diff --git a/docs/source-control-push-failure-ai-recovery.md b/docs/source-control-push-failure-ai-recovery.md new file mode 100644 index 000000000000..136b7e0031a1 --- /dev/null +++ b/docs/source-control-push-failure-ai-recovery.md @@ -0,0 +1,368 @@ +# Source Control Push Failure AI Recovery + +## Problem + +Push, force-push, publish, and sync push-stage failures flow through the shared +remote operation formatter in `src/renderer/src/lib/source-control-remote-error.ts:94` +and the editor-store toast paths in `src/renderer/src/store/slices/editor.ts:3716` +and `src/renderer/src/store/slices/editor.ts:3821`. A local pre-push hook or +lint hook is not an auth, protected-branch, or transport problem, so generic +remote guidance sends the user in the wrong direction. + +PR #7787 proves the behavior is useful, but the prototype needs tightening before +it is maintainable: + +- `src/renderer/src/components/right-sidebar/SourceControl.tsx:1938` and + `src/renderer/src/components/right-sidebar/SourceControl.tsx:5799` repeat + push-failure predicates and feed live branch/file state into a prompt that says + "at failure time". +- `src/renderer/src/components/right-sidebar/use-source-control-recovery-ai.ts:63` + imports push detection again instead of consuming one derived recovery model. +- `src/renderer/src/components/right-sidebar/source-control-ai-commit-failure-launch.ts:24` + and `src/renderer/src/components/right-sidebar/source-control-ai-push-failure-launch.ts:24` + are copied launch flows with action-specific copy. +- `src/shared/source-control-commit-failure-agent-command.ts:6` and + `src/shared/source-control-push-failure-agent-command.ts:6` are identical + command-template builders. +- `src/renderer/src/components/right-sidebar/source-control-fix-split-button.tsx:21` + already contains a reusable split button, while `SourceControl.tsx:6415` + carries a second inline version. +- `src/renderer/src/lib/source-control-remote-error.ts:148` currently treats + any `isSync` error as push-like for hook detection. `syncBranch` calls the + formatter for fetch, upstream-status, pull, and push failures, so the renderer + cannot prove a sync error came from the push stage without an explicit marker. +- `src/renderer/src/components/right-sidebar/SourceControl.push-failure-recovery.test.ts:2` + imports prompt helpers through the large React module instead of shared prompt + modules. + +## Goal + +Add first-class recovery for pre-push hook failures without growing a parallel +push-only subsystem: + +1. Toasts for push, force-push, publish, and sync push-stage failures say + "blocked" for detected pre-push or lint-hook output. +2. Source Control shows a concise Push blocked panel with Details and AI Fix + only for a failure snapshot that is both push-like and hook-like. +3. AI Fix launches the configured `fixPushFailure` Source Control action with a + safe, provider-neutral prompt. +4. Commit-failure recovery and push-failure recovery share launch, + command-template, split-button, and dense error-panel primitives. + +## Non-goals + +- Do not fix server-side pre-receive hooks, hosted CI failures, or provider-side + protected-branch failures from this entry point. +- Do not bypass hooks, add `--no-verify`, push from the launched agent, create a + PR, or assume GitHub-specific terminology. +- Do not add app-wide persistence for this transient failure panel. +- Do not redesign the Source Control panel or the Source Control AI settings + model. +- Do not fold unrelated launch surfaces such as checks recovery into this change + unless a tiny shared helper is already needed for commit/push recovery. + +## Design + +1. Keep push-hook detection and prompt building in shared code. + - `src/shared/source-control-push-failure.ts` owns normalization, bounded + scanning, summary text, Details eligibility, prompt truncation, prompt + rules, and changed-file list bounding. + - Detection must stay conservative: explicit `pre-push`/`prepush`, + `hook declined to push`, hook-runner output in push context, or lint output + in push context. Auth, non-fast-forward, protected branch, pre-receive, + submodule, and generic transport failures stay on the existing remote-error + path. + - Keep the output scan bounded at 64 KiB and the prompt failure-output + section bounded. Also cap prompt file lines to a small constant with an + omitted-count line; do not rely on the git-status cap, which is far too high + for prompt context. + +2. Make remote-error formatting sync-stage aware. + - Extend `RemoteOperationErrorOptions` with an explicit push-stage flag for + sync, for example `isSyncPushStage`. + - Gate push-hook classification on `isPush`, `isForcePush`, `publish`, or + `isSyncPushStage`; do not use bare `isSync` as evidence of a push failure. + - In `syncBranch`, pass the push-stage flag only inside the two inner + `pushRuntimeGit` catch blocks. The outer fetch, upstream-status, and pull + catches still pass `isSync` for Sync-shaped generic copy but must not render + blocked hook copy. + - Carry the same push-stage fact back to the renderer, either by tagging the + thrown `Error` with a narrow exported marker or by wrapping it in a typed + error that preserves the original message/cause. `SourceControl` must set + `syncPushStage` only from that marker, not from `kind === 'sync'` plus + hook-like stderr. + - Keep submodule push messages before hook detection so submodule guidance + remains more specific than AI recovery. + +3. Replace one-off command builders with one shared recovery command builder. + - Add a shared builder that accepts `{ actionId, promptOverride, + commandInputTemplate, basePrompt }` and renders the existing Source Control + AI command template for launch actions. + - Keep compatibility exports for commit and push helpers if nearby tests or + call sites still use those names, but make them wrappers over the generic + builder. + - Move prompt-builder tests to import from shared modules, not + `SourceControl.tsx`. + +4. Capture and derive push recovery state once. + - Extend `SourceControlActionError` with the raw error, a push-stage marker + for sync failures, the branch name at failure time, a bounded status-entry + snapshot at failure time, and a per-worktree sequence token. + - `runRemoteAction` clears the worktree's previous error and increments its + sequence before starting. A catch may write an error only if its sequence + still owns that worktree, so a slow failure cannot overwrite a newer retry + or success. + - Add a focused renderer helper that accepts the captured + `SourceControlActionError` and the current branch name, then returns either + `null` or a model with raw/sanitized detail text, summary, details flag, + kind label, and AI prompt. + - The helper returns `null` unless the operation is `push`, `force_push`, + `publish`, or `sync` with the sync push-stage marker and + `isPushHookFailure(rawError)` passes. + - If the current branch is known and differs from the captured branch, hide or + clear the model instead of launching an agent with wrong branch context. + - Pass that single model to `useSourceControlAi` and `CommitArea`; neither + prop construction nor `CommitArea` should repeat the push-hook predicate. + +5. Use one generic recovery launcher for commit and push failures. + - Replace the separate commit and push launch files with + `source-control-ai-recovery-launch.ts`, or keep the old files as one-line + wrappers if import stability is cheaper. + - The generic launcher owns connection resolution, SSH/local agent discovery, + saved-agent validation, agent-args validation, agent selection, terminal + launch, focus, and success/failure toasts. + - Resolve connection without collapsing local and unresolved states: read + `const worktreeConnectionId = getConnectionId(worktreeId)`, use it when it + is a string or `null`, and only fall back to `sourceRepoConnectionId` when + the worktree lookup returns `undefined`. If the fallback is also + `undefined`, show the workspace-connection error instead of launching + locally. `null` means proven local; a string means SSH/remote. + - Validate saved CLI args before agent detection or terminal creation. On + Windows, keep using PowerShell-safe planning through + `planAgentCliArgsSuffix(..., 'powershell')`. + - Action-specific data is limited to action id, base prompt, empty-prompt + copy, unavailable-agent copy, and success copy. + +6. Keep the recovery hook thin. + - `use-source-control-recovery-ai.ts` builds the commit prompt, accepts the + already-derived push recovery prompt/model, keeps independent loading + flags, and calls the generic launcher. + - It should not import push-hook detection, resolve agents, or duplicate + launch plumbing. + +7. Extract and reuse the recovery UI. + - Reuse or replace the existing + `src/renderer/src/components/right-sidebar/source-control-fix-split-button.tsx` + rather than adding another split-button component. + - Move the dense recovery notice and Details dialog into focused renderer + modules named for source-control recovery. Avoid `helpers`, `utils`, and new + max-lines suppressions. + - Reuse the same notice/dialog component for commit and push recovery with + action-specific labels, summary, details, prompt, saved recipe, and launch + callback. + - Keep normal remote errors filtered out when a push recovery model is + rendered, so the user does not see both Push blocked and generic remote + error copy for the same failure. + +8. Retain `fixPushFailure` in the existing Source Control AI action model. + - The prototype already adds `fixPushFailure` to + `src/shared/source-control-ai-actions.ts`; keep it as a launch action like + `fixCommitFailure`. + - Verify default settings, normalizers, global settings rows, repository + override rows, labels, descriptions, and variable chips all include Push + failure fixes. + - Do not create a push-specific settings store or migration. Existing + `normalizeSourceControlAiSettings` hydrates missing action defaults. + +## Data Flow + +- User clicks Push, Force Push, Publish Branch, or Sync. +- `runRemoteAction` clears that worktree's previous remote error, records a new + sequence token, and starts the editor-store remote action. +- Git push fails and throws. +- `pushBranch` or sync's inner push-stage catch calls + `resolveRemoteOperationErrorMessage` with push-like options. Sync fetch, pull, + and upstream-status failures do not pass the push-stage flag. +- Sync's inner push-stage catch marks the rethrown error as push-stage so + `runRemoteAction` can preserve `syncPushStage` in the captured snapshot. +- The formatter classifies hook output before auth/transport fallbacks only for + push-like options and shows blocked toast copy. +- `SourceControl` catches the same error, and if the sequence still owns the + worktree, stores `{ kind, rawError, message, syncPushStage, branchName, + entriesSnapshot }`. +- The push recovery helper derives one `pushRecovery` model from that snapshot. +- `CommitArea` renders normal remote errors or the Push blocked recovery notice. +- AI Fix builds the `fixPushFailure` command input and launches the selected + agent in the owning local or SSH runtime. + +## Edge Cases + +- Auth, missing repo, protected-branch, pre-receive, non-fast-forward, and + transport failures must not show the Push blocked panel. +- Submodule push errors keep their existing specialized messages before + push-hook detection. +- Sync failures from fetch, upstream-status, or pull stages must not show Push + blocked, even if stderr contains words like "lint" or "hook". +- Create PR intent remote failures use the same `runRemoteAction` plumbing; if + CommitArea is not visible, blocked toast copy is still required but no hidden + panel work is needed. +- A newer remote operation for the same worktree must clear stale recovery state + immediately and prevent an older in-flight failure from writing after it. +- Switching worktrees or branches must not show another worktree or branch's + push failure. +- External edits or another Orca window may make the failure stale. Do not add + cross-window persistence for this feature; rely on local retry/remount/branch + mismatch clearing and list this as residual risk. +- Source Control AI hidden for a repo still shows the blocked notice and Details; + it hides AI Fix. +- SSH worktrees must detect and launch agents on the owning connection, not a + local fallback. +- Windows launch planning must continue to use PowerShell-safe agent args. +- Very large hook output and very large changed-file sets must be bounded before + prompt generation. +- ANSI/control output must not leak into summaries or Details comparison logic. + Details may show sanitized text while preserving enough line breaks for + debugging. +- Empty custom command templates must stay empty so the launcher rejects them + with a clear settings error. +- Prompt text must treat file paths, branch names, and hook output as data, not + instructions. + +## Test Plan + +- Shared unit tests: + - `src/shared/source-control-push-failure.test.ts` covers detection positives, + auth/protected/pre-receive/non-fast-forward negatives, ANSI/control + stripping, bounded scanning, details comparison, prompt output truncation, + prompt file-list capping, and provider-neutral prompt rules. + - Shared command-template tests cover the generic recovery builder plus + commit/push wrappers, including empty templates and prompt overrides. + - `src/shared/source-control-ai-actions.test.ts` covers `fixPushFailure` + label, default template, variables, normalization, and action-list inclusion. +- Remote formatter and store tests: + - `src/renderer/src/lib/source-control-remote-error.test.ts` covers push, + force-push, publish, and sync push-stage blocked copy plus sync non-push + stage negatives, auth/non-fast-forward/protected/pre-receive/submodule + regressions. + - `src/renderer/src/store/slices/editor.test.ts` covers the `pushBranch` toast + path and both sync push-stage and sync non-push-stage toasts. +- Renderer model and UI tests: + - A focused push recovery derivation test covers operation kind, sync + push-stage marker, branch mismatch, stale sequence ownership, snapshot file + entries, summary, details flag, prompt contents, and ordinary remote errors. + - `CommitArea` tests cover the Push blocked notice, Details dialog, AI Fix + visible/hidden, ordinary remote errors, no duplicate remote error when a push + model exists, and unchanged commit-failure recovery rendering. + - Settings tests cover global and repository Source Control AI action rows + showing Push failure fixes. +- Launcher tests: + - Generic recovery launcher tests cover commit and push action ids, invalid CLI + args before detection, empty template rejection, unavailable saved agent, + local versus SSH agent detection, successful launch/focus, and success copy. +- Checks: + - Run targeted vitest files above, `pnpm typecheck`, `pnpm lint`, and + `pnpm check:max-lines-ratchet`. + +## UI Quality Bar + +The Source Control recovery UI must match `docs/STYLEGUIDE.md`: monochrome, +quiet, dense, token-based, and consistent with adjacent commit-failure recovery. +Use existing shadcn `Button`, `DropdownMenu`, and `Dialog` primitives, lucide +icons, `card`/`border`/`destructive`/`muted` tokens, and the existing action +recipe row patterns. The Push blocked notice should keep the summary readable at +narrow right-sidebar widths, avoid nested cards, avoid new color values, show +stable split-button geometry while launching, and keep Details as progressive +disclosure for long hook output. Dialogs and dropdowns must remain usable in +light/dark mode and under SSH latency. + +## Review Screenshots + +1. Source Control after a simulated pre-push hook failure: Push blocked notice + with summary, AI Fix, and Details. +2. Push failure Details dialog showing hook output and Fix with AI. +3. AI Fix customize-launch dialog for `fixPushFailure`. +4. Ordinary push auth/protected/remote failure state: regular remote error, no + Push blocked notice. +5. Sync fetch/pull-stage failure state: Sync-shaped remote error, no Push + blocked notice. +6. Source Control AI hidden for the repo: Push blocked notice and Details, no AI + Fix. +7. Source Control AI settings showing the Push failure fixes launch recipe. +8. Adjacent commit-failure recovery notice still rendering correctly after the + shared UI extraction. + +## Rollout + +1. Tighten shared push-failure classifier/prompt bounds and add the generic + recovery command builder. +2. Make remote formatter/store sync-stage aware and update toast tests. +3. Add the `SourceControlActionError` snapshot/sequence data and one push + recovery derivation helper. +4. Replace duplicated commit/push launchers with the generic recovery launcher + and thin hook wiring. +5. Extract/reuse source-control recovery UI components, including the existing + split-button module. +6. Verify `fixPushFailure` settings/default/normalizer coverage and i18n labels. +7. Update targeted tests and run typecheck, lint, and max-lines ratchet. +8. Validate rendered Electron states with screenshots before opening the PR. + +## Lightweight Eng Review + +- Scope: Reduced from PR #7787's push-specific parallel path to a shared + recovery layer. Keep the feature limited to local pre-push/lint-hook detection, + blocked copy, an inline recovery notice, Details, and AI launch. No persistence + or provider-specific recovery. +- Architecture/data flow: Shared code owns classification, prompt text, and + command-template rendering; the editor store owns stage-aware toast formatting; + `SourceControl` owns transient worktree-scoped failure snapshots and sequence + invalidation; the generic launcher owns local/SSH agent discovery and terminal + launch. +- Failure modes covered: + - Sync stage ambiguity: only the inner push stage may classify as hook-blocked. + - Auth/protected/pre-receive/non-fast-forward/submodule/transport errors stay + out of push recovery. + - Branch or worktree switches suppress stale recovery models. + - Per-worktree sequence tokens prevent older in-flight failures from + overwriting newer retries or successes. + - Empty custom templates, invalid CLI args, unavailable saved agents, missing + worktree context, SSH host detection, and Windows shell planning fail before + terminal launch. + - Large or hostile hook output and file lists are bounded and treated as data + in prompts. +- Test coverage required: + - Shared classifier/prompt/command/action-model tests in `src/shared`. + - Remote formatter and editor-store tests for push, force-push, publish, sync + push-stage, and sync non-push-stage paths. + - Renderer derivation and `CommitArea` tests for Push blocked, Details, AI Fix, + hidden AI actions, stale branch/sequence, ordinary remote errors, and + existing commit failure recovery. + - Generic launcher tests for local/SSH, invalid args, saved-agent unavailable, + empty template, and success launch. + - Settings tests for global and repo Push failure fixes rows. + - Electron validation for all required screenshots; no separate E2E is + required if renderer tests cover the model and Electron validates the real UI. +- Performance/blast radius: No polling, watchers, migrations, or startup work. + Runtime cost is one bounded classifier pass over at most 64 KiB, bounded prompt + output, and a bounded file snapshot only when a remote action fails. Largest + blast radius is the shared recovery UI and launcher used by existing commit + failures, so commit recovery needs tests and a screenshot. +- UI quality bar: Match `docs/STYLEGUIDE.md` and adjacent Source Control density: + token-based error state, stable split-button geometry, progressive Details + disclosure, no nested cards, concise copy, light/dark compatibility, and + visible disabled/loading state under SSH latency. +- Required review screenshots: + 1. Push blocked notice after pre-push hook failure. + 2. Push failure Details dialog with Fix with AI. + 3. `fixPushFailure` customize-launch dialog. + 4. Ordinary push auth/protected/remote failure with no Push blocked panel. + 5. Sync non-push-stage failure with no Push blocked panel. + 6. Source Control AI hidden: Push blocked without AI Fix. + 7. Source Control AI settings showing Push failure fixes. + 8. Existing commit-failure recovery notice after shared UI extraction. +- Residual risks: Classifier false positives remain possible for unusual local + hook-runner output that mentions push context; keep tests biased toward + preserving auth, protected-branch, and non-fast-forward behavior. Failure + panels are renderer-local, so another Orca window or an external terminal can + fix the problem while the old panel remains visible until local retry, remount, + or branch/worktree change. Electron validation may need a mocked or temporary + repo scenario to trigger a real pre-push hook without mutating user data. diff --git a/docs/terminal-main-owned-state.md b/docs/terminal-main-owned-state.md index a9c3165e7cfa..e3e7a125988f 100644 --- a/docs/terminal-main-owned-state.md +++ b/docs/terminal-main-owned-state.md @@ -1,5 +1,9 @@ # Terminal Main-Owned State +This document covers the hidden-output recovery slice. The broader terminal +model/view boundary is defined in +[`reference/terminal-model-view-contract.md`](./reference/terminal-model-view-contract.md). + ## Problem Hidden and background terminal panes cannot rely on renderer memory as the only @@ -51,6 +55,13 @@ already reaches `OrcaRuntimeService.onPtyData` before renderer delivery for local, daemon, and SSH PTYs. That path keeps a headless xterm emulator updated and can serialize it. +Since the hidden-delivery gate shipped (`terminalHiddenDeliveryGate`, default +on — see the contract's Architecture Status), main drops hidden renderer-bound +bytes after model ingestion and emits an out-of-band restore marker, so a +gated hidden pane accumulates no renderer backlog at all. The overflow path +below is the fallback for kill-switch-off mode and for hidden PTYs with an +active delivery-interest sidecar. + The renderer scheduler keeps its 2 MB background cap. When the cap is exceeded: 1. The scheduler replaces the queued backlog with a small warning fallback. diff --git a/docs/wrapped-terminal-file-link-fragments.md b/docs/wrapped-terminal-file-link-fragments.md new file mode 100644 index 000000000000..ac1e68ec54a2 --- /dev/null +++ b/docs/wrapped-terminal-file-link-fragments.md @@ -0,0 +1,115 @@ +# Wrapped Terminal File-Link Fragments + +## Problem + +A file path hard-wrapped between terminal rows is not clickable when the continuation row also contains sibling content. In the reported three-link line, the middle path ends the first row and continues at the start of the second, while the first and third paths remain clickable. + +The provider builds hard-wrap candidates in `wrapped-terminal-link-ranges.ts:172-224`, and both hover and direct modifier-click consume them through `terminal-link-handlers.ts:106-135` and `terminal-file-link-hit-testing.ts:100-109`. + +## Root cause + +`buildHardWrappedPathLogicalLineCandidates` trims and joins whole physical rows. A continuation row is accepted only when the entire trimmed row is a path fragment (`wrapped-terminal-link-ranges.ts:195-203`). A row such as `transparent-...png · validation-screenshots/03-after-light-theme.png` therefore stops reconstruction. Orca probes the two incomplete middle fragments separately, rejects both as nonexistent, and retains only the complete first and third paths. + +## Non-goals + +- Changing file-path parsing, filesystem existence semantics, tooltip copy, or open routing. +- Joining arbitrary prose, spaced paths, or multiple sibling links into one path. +- Relying on xterm soft-wrap metadata for output that was hard-wrapped by an agent or TUI. +- Adding a new IPC method, bypassing the existing existence cache, or changing local/SSH/runtime routing. + +## Design + +1. Add a focused regression using the exact three-link/two-row shape. Make the existence stub return true only for the three complete paths, then assert that provider calls for either physical row return the same middle link and exact multi-row range. Assert that no candidate/link spans either `·` separator. +2. Reuse the existing conservative hard-wrap fragment alphabet. From a possible first row, slice its maximal fragment suffix; append zero or more continuation rows only while their whole trimmed text is a fragment; then slice the maximal fragment prefix from the first mixed-content row and stop. The only suffixes accepted without a path-name character are an exact POSIX root (`/`), one backslash for the first half of a UNC root, a bare ASCII drive prefix such as `C:`, and the complete relative prefixes `./`, `../`, and `~/`. A boundary candidate is emitted only when it covers the requested row, has at least two non-empty row fragments, and the fully joined text passes the existing path-start predicate. It may end at the first proper prefix slice of a mixed row or at the last available whole-fragment row; the latter is limited to whitelisted incomplete starts and is skipped when whole-row reconstruction already emitted the same text. Existing whole-row candidates remain responsible for ordinary/deep hard wraps, including a mixed starting row followed only by whole-fragment rows. +3. Slice `columns` with each fragment so ranges retain the original xterm cells. Build the async-staleness fingerprint from each source row's full translated text and metadata as well as the selected slice; changing a sibling token must invalidate an in-flight result even if the reconstructed path is unchanged. +4. Generate at most one boundary candidate per scanned start row—never every suffix/prefix combination. Preserve the existing bounds of 20 possible start rows and 20 rows per candidate, logical-line deduplication, and longest-non-overlapping-link selection. The existing builder can emit up to 210 whole-row candidates in its all-fragment worst case; this change may add at most 20 boundary candidates, not another quadratic set. +5. Keep existence validation in the provider's current local/SSH/runtime path and cache. The valid reconstructed path necessarily adds its desired existence lookup compared with the broken behavior; do not add probes for arbitrary suffix/prefix combinations or change existing overlap/cache behavior in this focused fix. +6. Verify direct modifier-click fallback from both halves. This path shares the candidate builder but remains synchronous and uses its existing cache/known-root preference before `openDetectedFilePath` performs normal routing checks. + +## Data flow + +- xterm buffer row under hover/click +- bounded hard-wrap start/candidate windows and conservative endpoint slicing +- whole-row candidates plus at most one boundary candidate per start row +- existing terminal file-link parser +- existing local/SSH/runtime path resolution and existence cache +- mapped multi-row xterm range +- hover tooltip or modifier-click open + +## Edge cases + +- A row boundary immediately after POSIX `/`, drive prefix `C:`, the first `\` of a UNC path, or complete `./`, `../`, and `~/` prefixes must reconstruct the complete path. Other punctuation-only suffixes and bare prose tokens remain ineligible, and the joined text must independently satisfy the full path-start predicate. +- A continuation prefix may end before a separator (`·`), prose, or a sibling path; none of that suffix may enter the reconstructed candidate. +- A starting suffix may begin after prose or a sibling path; its original xterm column must be retained. +- Rows containing only one path fragment must keep the existing deep (up to 20 rows) reconstruction behavior. +- Soft-wrapped rows, Unicode/multi-code-unit column mappings, known worktree roots, and spaced paths must remain unchanged. In particular, this change does not broaden fragment extraction to whitespace-containing paths. +- Full-row source fingerprints must reject stale async results when text inside or outside the selected fragment changes. +- Provider calls for remote paths must still use the owning pane's runtime environment or SSH connection and the connection-scoped existence-cache key; fragment extraction itself must not assume a local filesystem. +- Incomplete fragment combinations remain filtered by the existing filesystem existence check. + +## Test plan + +- Candidate/range unit: cover the exact suffix/prefix slices, original xterm columns, full-row fingerprint changes, at most one added boundary candidate per start row, and no candidate spanning a sibling separator. +- Provider integration: add the exact reported three-link regression to `terminal-link-handlers.test.ts`; across provider calls for both physical rows, assert all three complete links, the same middle range from each call, no incomplete or giant merged link, and that the complete middle path reaches the normal existence check. +- Direct click: exercise hit-testing on the first and second physical halves of the middle path and assert both route the same complete path. +- Compatibility: cover a backslash/drive-letter wrapped path and a remote-runtime or SSH existence call, proving the reconstructed path keeps the owning connection/environment. +- Regression: run `wrapped-terminal-link-ranges.test.ts`, `terminal-link-handlers.test.ts`, and terminal-link parser tests. +- Static: run formatter/check, web typecheck, lint, max-lines ratchet, and relevant repository checks. +- Electron: render the exact text at the reproduced 133-column terminal width; verify pointer/tooltip and modifier-click from both middle fragments, then smoke-test the first and third links. + +## UI quality bar + +No visual styling changes. The exact same terminal text and layout must render without overlap, clipping, or altered wrapping. The only visible behavior change is that both physical halves of the middle path show the same pointer affordance and tooltip and activate the same file, consistent with the first and third links and `docs/STYLEGUIDE.md` interaction guidance. + +## Review screenshots + +1. Before, on the base revision: full Electron window hovering the broken middle path at the reproduced width (no tooltip/link affordance). +2. After: full Electron window hovering the first physical half of the middle path, with tooltip visible. +3. After: full Electron window hovering the continuation half, with the same tooltip/path visible. +4. After adjacent-feature smoke: full Electron window hovering the first or third complete sibling link. + +## Rollout + +1. Add the failing exact-shape regression and range/click assertions. +2. Implement boundary-fragment candidate extraction and cell mapping. +3. Run focused tests and static checks. +4. Validate the exact scenario in Electron and capture screenshots. +5. Open an unmerged PR. + +## Lightweight Eng Review + +- Scope: limited to hard-wrapped path candidate reconstruction; parser, routing, cache, and UI styling stay unchanged. +- Architecture/data flow: the shared candidate builder remains the single boundary for hover and click behavior, so local, daemon, SSH, and remote runtime flows receive identical ranges before their existing existence checks. +- Failure modes covered: + - sibling links accidentally merged into one spaced path + - only one physical half hit-tests + - incorrect xterm columns after slicing + - Windows separators rejected + - deep single-fragment rows regress + - extra remote/local existence probes on hover +- Test coverage required: + - exact three-link provider regression from both hovered rows + - exact range boundary assertions + - direct click from both halves + - existing deep-wrap, Unicode, stale-result, parser, SSH/runtime tests +- Performance/blast radius: preserve the current 20-start-row/20-rows-per-candidate bounds (up to 210 existing whole-row candidates). Boundary extraction is linear per examined row and adds at most 20 candidates, only where a mixed continuation stops whole-row reconstruction. Resolving the previously missing complete path adds the intended cached existence check; the change adds no IPC method and does not alter local/remote routing or cache keys. +- UI quality bar: unchanged rendering and style; consistent pointer, tooltip, and activation across both middle fragments, checked in the real Electron terminal against the style guide. +- Required review screenshots: + 1. exact three-link full-window baseline + 2. middle first-half hover/tooltip + 3. middle continuation-half hover/tooltip + 4. first/third sibling hover smoke +- Residual risks: local macOS is the available live Electron environment; Windows separator and SSH/runtime behavior require automated coverage and shared-code review. + +## Terminal Reliability Proof + +- Reliability class: `terminal-link.path-boundary-reconstruction`; the broader manifest entry `xterm-addon.boundary-containment` is related but does not register file-link correctness, so this remains an explicit accepted manifest gap rather than changing that gate's scope in a bug fix. +- Product change type: renderer runtime hardening with deterministic regression coverage. +- Invariant: one logical hard-wrapped file path maps to the same original xterm cells and owning local/SSH/runtime context from either physical row, without absorbing sibling text. +- Failure source: the reproduced three-link line where only the first and third links were clickable. +- Oracle: both provider row calls return the same complete middle path/range; direct hit-testing on either half opens that path; root-, drive-, and UNC-boundary candidates retain their exact xterm ranges; no emitted boundary candidate contains `·`. +- Provider/platform matrix: local and SSH provider behavior covered; Windows separators/cell mapping covered; daemon and remote-runtime use the same builder and routing but are not live-tested; Linux, Windows, WSL, mobile/relay are accepted live-validation gaps. +- Performance budget: the scan stays capped at 20 starts and 20 rows per candidate, emits at most one boundary candidate per start, and rejects non-path starts before reading possible continuation rows. No polling, timers, listeners, subprocesses, or new IPC methods are added; only the newly valid path reaches the existing cached existence probe. +- Diagnostics: the full source-row fingerprint rejects stale async results; deterministic range/provider tests are the regression breadcrumb. No new product telemetry or raw terminal logging is warranted. +- Gate status: no manifest entry added or promoted. Revisit only if this parser grows beyond bounded local row reconstruction or the regression recurs outside the covered provider/platform matrix. +- Rollback/demotion rule: revert boundary-fragment reconstruction if Electron shows sibling-path merging, incorrect hit regions, or material hover latency; keep the exact red regression as the behavioral oracle. diff --git a/electron.vite.config.ts b/electron.vite.config.ts index ca69fc8a7cd5..dbe2fbc02b33 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -2,6 +2,7 @@ import { resolve } from 'node:path' import { defineConfig } from 'electron-vite' import react from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' +import { createPlainNodeEntryGuardPlugin } from './build-plugins/plain-node-entry-guard' // Why: the telemetry transport is gated by two compile-time constants that // only the official CI release workflow sets. Contributor / `pnpm dev` / @@ -182,13 +183,16 @@ export default defineConfig({ 'stt-worker': resolve('src/main/speech/stt-worker.ts'), 'warp-theme-parser-worker': resolve('src/main/warp-themes/warp-theme-parser-worker.ts'), 'file-watcher-worker': resolve('src/main/runtime/file-watcher-worker.ts'), + // Why: forked with ELECTRON_RUN_AS_NODE so @parcel/watcher faults + // can't take down the main process (issue #7547). + 'parcel-watcher-process-entry': resolve('src/main/ipc/parcel-watcher-process-entry.ts'), // Why: electron-vite cleans out/main in dev. The dev CLI imports // this path for `orca agent hooks ...`, so it must survive rebuilds. 'agent-hooks/managed-agent-hook-controls': resolve( 'src/main/agent-hooks/managed-agent-hook-controls.ts' ) }, - plugins: [createStartupDiagnosticsBootstrapPlugin()] + plugins: [createStartupDiagnosticsBootstrapPlugin(), createPlainNodeEntryGuardPlugin()] } }, // Why: compile-time substitution for the telemetry gate. See the block diff --git a/mobile/app.json b/mobile/app.json index b50147f0497f..db8326a3dbce 100644 --- a/mobile/app.json +++ b/mobile/app.json @@ -2,7 +2,7 @@ "expo": { "name": "Orca", "slug": "orca-mobile", - "version": "0.0.24", + "version": "0.0.26", "orientation": "default", "icon": "./assets/icon.png", "userInterfaceStyle": "automatic", @@ -75,7 +75,7 @@ "allowBackup": false, "permissions": ["RECORD_AUDIO", "MODIFY_AUDIO_SETTINGS"], "package": "com.stably.orca.mobile", - "versionCode": 5 + "versionCode": 6 }, "plugins": [ "expo-router", diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx index ad94114bd660..d1c5ebff14aa 100644 --- a/mobile/app/_layout.tsx +++ b/mobile/app/_layout.tsx @@ -102,6 +102,14 @@ export default function RootLayout() { return } handledNotificationIdsRef.current.add(notificationId) + // Why: RootLayout never unmounts, so cap this tap-dedup set (FIFO) rather + // than letting it grow one id per notification tapped for the app's life. + if (handledNotificationIdsRef.current.size > 256) { + const oldest = handledNotificationIdsRef.current.values().next().value + if (oldest !== undefined) { + handledNotificationIdsRef.current.delete(oldest) + } + } const path = await getNavigationPath(response.notification.request.content.data) clearLastNotificationResponse() @@ -169,6 +177,7 @@ export default function RootLayout() { + diff --git a/mobile/app/connection-log.tsx b/mobile/app/connection-log.tsx new file mode 100644 index 000000000000..cc19497e080a --- /dev/null +++ b/mobile/app/connection-log.tsx @@ -0,0 +1,221 @@ +import { useCallback, useEffect, useState, useSyncExternalStore } from 'react' +import { View, Text, StyleSheet, Pressable, Platform } from 'react-native' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import { useRouter } from 'expo-router' +import * as Clipboard from 'expo-clipboard' +import Constants from 'expo-constants' +import { ChevronLeft, Copy, Check } from 'lucide-react-native' +import { colors, spacing, typography } from '../src/theme/mobile-theme' +import { ConnectionLog } from '../src/components/ConnectionLog' +import { loadHosts } from '../src/transport/host-store' +import { connectionLogStore } from '../src/transport/connection-log-buffer' +import { + useHostClient, + useLastConnectedAt, + useReconnectAttempt +} from '../src/transport/client-context' +import { buildConnectionDiagnosticsReport } from '../src/diagnostics/connection-diagnostics-report' +import type { ConnectionLogEntry, HostProfile } from '../src/transport/types' + +// Why: getSnapshot must be referentially stable when there's no data — +// a fresh [] per call would make useSyncExternalStore re-render forever. +const EMPTY_ENTRIES: readonly ConnectionLogEntry[] = [] + +// Why: reading the log is most needed while a host is failing, so this +// screen also *acquires* the host client — opening it kicks a dial and the +// log fills live instead of showing a stale tail. +export default function ConnectionLogScreen() { + const router = useRouter() + const insets = useSafeAreaInsets() + const [hosts, setHosts] = useState([]) + const [selectedId, setSelectedId] = useState(null) + const [copied, setCopied] = useState(false) + + useEffect(() => { + let stale = false + void loadHosts().then((loaded) => { + if (stale) { + return + } + setHosts(loaded) + setSelectedId((prev) => prev ?? loaded[0]?.id ?? null) + }) + return () => { + stale = true + } + }, []) + + const selected = hosts.find((h) => h.id === selectedId) ?? null + const { state } = useHostClient(selected?.id) + const reconnectAttempts = useReconnectAttempt(selected?.id) + const lastConnectedAt = useLastConnectedAt(selected?.id) + + const subscribe = useCallback( + (listener: () => void) => + selectedId ? connectionLogStore.subscribe(selectedId, listener) : () => {}, + [selectedId] + ) + const getSnapshot = useCallback( + () => (selectedId ? connectionLogStore.get(selectedId) : EMPTY_ENTRIES), + [selectedId] + ) + const entries = useSyncExternalStore(subscribe, getSnapshot) + + const copyDiagnostics = useCallback(async () => { + if (!selected) { + return + } + const report = buildConnectionDiagnosticsReport({ + hostName: selected.name, + endpoint: selected.endpoint, + state, + reconnectAttempts, + lastConnectedAt, + platform: `${Platform.OS} ${Platform.Version ?? ''}`.trim(), + appVersion: Constants.expoConfig?.version ?? 'unknown', + entries + }) + await Clipboard.setStringAsync(report) + setCopied(true) + setTimeout(() => setCopied(false), 2000) + }, [selected, state, reconnectAttempts, lastConnectedAt, entries]) + + return ( + + + router.back()}> + + + Connection log + + + {hosts.length > 1 && ( + + {hosts.map((host) => ( + setSelectedId(host.id)} + > + + {host.name} + + + ))} + + )} + + {selected ? ( + <> + + + {state} + {reconnectAttempts > 0 ? ` · attempt ${reconnectAttempts}` : ''} + + void copyDiagnostics()}> + {copied ? ( + + ) : ( + + )} + {copied ? 'Copied' : 'Copy diagnostics'} + + + {entries.length > 0 ? ( + + ) : ( + + No connection events yet this session. Events appear as the app dials this host. + + )} + + ) : ( + No paired hosts. + )} + + ) +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: colors.bgBase, + padding: spacing.lg + }, + topRow: { + flexDirection: 'row', + alignItems: 'center', + marginBottom: spacing.lg + }, + backButton: { + width: 36, + height: 36, + borderRadius: 18, + alignItems: 'center', + justifyContent: 'center', + marginRight: spacing.sm + }, + heading: { + fontSize: 20, + fontWeight: '700', + color: colors.textPrimary + }, + hostPicker: { + flexDirection: 'row', + flexWrap: 'wrap', + gap: spacing.sm, + marginBottom: spacing.md + }, + hostChip: { + paddingVertical: spacing.xs + 2, + paddingHorizontal: spacing.md, + borderRadius: 16, + backgroundColor: colors.bgRaised + }, + hostChipActive: { + backgroundColor: colors.bgPanel, + borderWidth: 1, + borderColor: colors.borderSubtle + }, + hostChipText: { + fontSize: typography.metaSize, + color: colors.textSecondary, + maxWidth: 160 + }, + hostChipTextActive: { + color: colors.textPrimary, + fontWeight: '600' + }, + statusRow: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + marginBottom: spacing.sm + }, + statusText: { + fontSize: typography.metaSize, + color: colors.textSecondary + }, + copyButton: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.xs + 2, + paddingVertical: spacing.xs + 2, + paddingHorizontal: spacing.md, + borderRadius: 8, + backgroundColor: colors.bgRaised + }, + copyButtonText: { + fontSize: typography.metaSize, + fontWeight: '600', + color: colors.textPrimary + }, + emptyText: { + fontSize: typography.metaSize, + color: colors.textMuted, + lineHeight: 18 + } +}) diff --git a/mobile/app/h/[hostId]/agent-history/[worktreeId].tsx b/mobile/app/h/[hostId]/agent-history/[worktreeId].tsx new file mode 100644 index 000000000000..50c62205cd79 --- /dev/null +++ b/mobile/app/h/[hostId]/agent-history/[worktreeId].tsx @@ -0,0 +1,18 @@ +import { useLocalSearchParams } from 'expo-router' +import { MobileAgentSessionHistoryPanel } from '../../../../src/agent-history/MobileAgentSessionHistoryPanel' +import { firstParam } from '../../../../src/source-control/mobile-source-control-screen-state' + +export default function MobileAgentSessionHistoryScreen() { + const params = useLocalSearchParams<{ + hostId?: string | string[] + worktreeId?: string | string[] + name?: string | string[] + }>() + return ( + + ) +} diff --git a/mobile/app/h/[hostId]/history/[worktreeId].tsx b/mobile/app/h/[hostId]/history/[worktreeId].tsx index 8ac0eb8a89b4..19198e4e5f1a 100644 --- a/mobile/app/h/[hostId]/history/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/history/[worktreeId].tsx @@ -1,207 +1,28 @@ -import { useCallback, useEffect, useState } from 'react' -import { ActivityIndicator, FlatList, Pressable, StyleSheet, Text, View } from 'react-native' -import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' -import { useLocalSearchParams, useRouter } from 'expo-router' -import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react-native' -import { useHostClient } from '../../../../src/transport/client-context' -import type { RpcSuccess } from '../../../../src/transport/types' -import { colors, spacing, typography } from '../../../../src/theme/mobile-theme' -import { - fetchMobileGitHistory, - mapMobileCommitRows, - type MobileCommitRow -} from '../../../../src/source-control/mobile-git-history' -import type { GitBranchChangeEntry } from '../../../../../src/shared/types' +import { Redirect, useLocalSearchParams } from 'expo-router' +import { firstParam } from '../../../../src/source-control/mobile-source-control-screen-state' -function firstParam(value: string | string[] | undefined): string { - return Array.isArray(value) ? (value[0] ?? '') : (value ?? '') -} - -export default function HistoryScreen() { +// History is now a segment of the Source Control hub. This route stays as a thin +// redirect so existing deep links (and any cached navigation) land on the hub with +// the History segment selected. +export default function HistoryRedirect() { const params = useLocalSearchParams<{ hostId?: string | string[] worktreeId?: string | string[] + name?: string | string[] + origin?: string | string[] }>() - const hostId = firstParam(params.hostId) - const worktreeId = firstParam(params.worktreeId) - const router = useRouter() - const insets = useSafeAreaInsets() - const { client, state: connState } = useHostClient(hostId) - - const [rows, setRows] = useState(null) - const [error, setError] = useState(null) - const [expanded, setExpanded] = useState(null) - const [filesById, setFilesById] = useState>({}) - - useEffect(() => { - let active = true - if (!client || connState !== 'connected' || !worktreeId) { - return - } - // Reset prior error/rows so a successful retry doesn't stay stuck behind a - // stale error (error wins render precedence). - setError(null) - setRows(null) - void (async () => { - try { - const result = await fetchMobileGitHistory(client, worktreeId) - if (active) { - setRows(mapMobileCommitRows(result, Date.now())) - } - } catch (err) { - if (active) { - setError(err instanceof Error ? err.message : 'Failed to load history') - } - } - })() - return () => { - active = false - } - }, [client, connState, worktreeId]) - - const toggleCommit = useCallback( - (row: MobileCommitRow) => { - const next = expanded === row.id ? null : row.id - setExpanded(next) - if (next && client && !filesById[row.id]) { - setFilesById((prev) => ({ ...prev, [row.id]: 'loading' })) - void client - .sendRequest('git.commitCompare', { worktree: `id:${worktreeId}`, commitId: row.id }) - .then((response) => { - const entries = response.ok - ? ((response as RpcSuccess).result as { entries: GitBranchChangeEntry[] }).entries - : [] - setFilesById((prev) => ({ ...prev, [row.id]: entries })) - }) - .catch(() => setFilesById((prev) => ({ ...prev, [row.id]: [] }))) - } - }, - [client, expanded, filesById, worktreeId] - ) - - const renderCommit = useCallback( - ({ item }: { item: MobileCommitRow }) => { - const files = filesById[item.id] - const isOpen = expanded === item.id - return ( - - [styles.commitHeader, pressed && styles.commitHeaderPressed]} - onPress={() => toggleCommit(item)} - > - {isOpen ? ( - - ) : ( - - )} - - - {item.subject} - - - {item.shortId} · {item.author} · {item.relativeTime} - - - - {isOpen ? ( - - {files === 'loading' || files === undefined ? ( - - ) : files.length === 0 ? ( - No file changes - ) : ( - files.map((file) => ( - - - {file.path} - - - {file.added ? +{file.added} : null} - {file.removed ? -{file.removed} : null} - - - )) - )} - - ) : null} - - ) - }, - [expanded, filesById, toggleCommit] - ) - return ( - - - router.back()} accessibilityLabel="Back"> - - - Commit History - - {error ? ( - - {error} - - ) : rows === null ? ( - - - - ) : rows.length === 0 ? ( - - No commits. - - ) : ( - row.id} - contentContainerStyle={{ paddingBottom: spacing.lg + insets.bottom }} - /> - )} - + ) } - -const styles = StyleSheet.create({ - container: { flex: 1, backgroundColor: colors.bgBase }, - header: { - flexDirection: 'row', - alignItems: 'center', - paddingHorizontal: spacing.md, - paddingVertical: spacing.sm, - gap: spacing.sm - }, - back: { padding: spacing.xs }, - title: { color: colors.textPrimary, fontSize: typography.bodySize, fontWeight: '600' }, - state: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: spacing.lg }, - stateText: { color: colors.textMuted, fontSize: typography.bodySize }, - commit: { borderBottomWidth: 1, borderBottomColor: colors.borderSubtle }, - commitHeader: { - flexDirection: 'row', - alignItems: 'center', - gap: spacing.sm, - paddingHorizontal: spacing.md, - paddingVertical: spacing.sm + 2 - }, - commitHeaderPressed: { backgroundColor: colors.bgRaised }, - commitMain: { flex: 1, minWidth: 0 }, - commitSubject: { color: colors.textPrimary, fontSize: typography.bodySize }, - commitMeta: { - color: colors.textMuted, - fontSize: typography.metaSize, - fontFamily: typography.monoFamily, - marginTop: 2 - }, - files: { paddingHorizontal: spacing.lg, paddingBottom: spacing.sm, gap: 4 }, - fileRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm }, - filePath: { - flex: 1, - color: colors.textSecondary, - fontSize: typography.metaSize, - fontFamily: typography.monoFamily - }, - fileStat: { fontSize: typography.metaSize, fontFamily: typography.monoFamily }, - add: { color: colors.gitDecorationAdded }, - del: { color: colors.gitDecorationDeleted }, - empty: { color: colors.textMuted, fontSize: typography.metaSize } -}) diff --git a/mobile/app/h/[hostId]/index.tsx b/mobile/app/h/[hostId]/index.tsx index 16baabe91774..d613bff4575d 100644 --- a/mobile/app/h/[hostId]/index.tsx +++ b/mobile/app/h/[hostId]/index.tsx @@ -1,20 +1,11 @@ import { useState, useEffect, useCallback, useMemo, useRef } from 'react' -import { - View, - Text, - StyleSheet, - SectionList, - Pressable, - ActivityIndicator, - TextInput -} from 'react-native' +import { View, Text, StyleSheet, SectionList, Pressable, ActivityIndicator } from 'react-native' import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' import { useFocusEffect, useLocalSearchParams, usePathname, useRouter } from 'expo-router' import { Search, X, Pin, - GitBranch, List, SlidersHorizontal, Layers, @@ -52,10 +43,12 @@ import { useActiveWorktreeScroll } from '../../../src/hooks/use-active-worktree- import type { RepoIcon } from '../../../../src/shared/repo-icon' import { PickerModal } from '../../../src/components/PickerModal' import { ActionSheetContent } from '../../../src/components/ActionSheetModal' +import { buildWorktreeNavigationActions } from '../../../src/agent-history/worktree-navigation-actions' import { ConfirmModal } from '../../../src/components/ConfirmModal' import { BottomDrawer } from '../../../src/components/BottomDrawer' import { ProtocolBlockScreen } from '../../../src/components/ProtocolBlockScreen' import { AuthFailedBanner } from '../../../src/components/AuthFailedBanner' +import { MobileSearchField } from '../../../src/components/MobileSearchField' import { WorkspaceDetailPlaceholder } from '../../../src/components/WorkspaceDetailPlaceholder' import { getCachedWorktrees } from '../../../src/cache/worktree-cache' import { setCachedRepos } from '../../../src/cache/repo-cache' @@ -182,6 +175,7 @@ export function HostScreen({ const [showGroupPicker, setShowGroupPicker] = useState(false) const [showFilterModal, setShowFilterModal] = useState(false) const [actionTarget, setActionTarget] = useState(null) + const [hostCapabilities, setHostCapabilities] = useState([]) const [confirmDelete, setConfirmDelete] = useState(null) const [confirmRemoveHost, setConfirmRemoveHost] = useState(false) const [routeActionState, setRouteActionState] = useState(() => @@ -513,6 +507,10 @@ export function HostScreen({ // format is in place to flip a switch in a future release. useEffect(() => { if (connState !== 'connected' || !client) { + // Why: drop the prior host's capabilities while disconnected/switching so + // a capability-gated action (e.g. Agent Session History) can't linger for + // a host that doesn't support it. + setHostCapabilities([]) return } let cancelled = false @@ -524,9 +522,13 @@ export function HostScreen({ return } if (!response.ok) { + setHostCapabilities([]) return } - const status = (response as RpcSuccess).result as DesktopStatus + const status = (response as RpcSuccess).result as DesktopStatus & { + capabilities?: string[] + } + setHostCapabilities(status.capabilities ?? []) const verdict = evaluateCompat({ desktopProtocolVersion: status.protocolVersion, desktopMinCompatibleMobileVersion: status.minCompatibleMobileVersion @@ -552,6 +554,17 @@ export function HostScreen({ } }, [connState, client]) + useFocusEffect( + useCallback(() => { + // Why: opening the host is a strong user signal — reset a backed-off or + // trickling reconnect loop (and probe a possibly half-open socket) + // immediately instead of waiting out its timer. Deps stay empty so this + // fires per focus transition, not per connection-state change; nudging + // on every reconnecting↔connecting flip would defeat the backoff. + clientRef.current?.notifyForeground() + }, []) + ) + useFocusEffect( useCallback(() => { // The embedded sidebar drives its own polling below; focus never fires @@ -1114,22 +1127,16 @@ export function HostScreen({ {/* Search bar */} {showSearch && ( - - - {search.length > 0 && ( - setSearch('')}> - - - )} )} @@ -1161,6 +1168,9 @@ export function HostScreen({ sections={sections} keyExtractor={(w) => w.sectionListKey ?? w.worktreeId} stickySectionHeadersEnabled={false} + // Why: keep the search IME up while tapping clear / scrolling results. + keyboardShouldPersistTaps="handled" + keyboardDismissMode="on-drag" onScrollToIndexFailed={onScrollToIndexFailed} // Why: edge-to-edge — the list scrolls under the system nav bar // while reserving insets.bottom keeps the last worktree row reachable @@ -1348,20 +1358,14 @@ export function HostScreen({ actions={ actionTarget ? [ - { - label: 'Source Control', - icon: GitBranch, - onPress: () => { - const params = new URLSearchParams({ - name: actionTarget.displayName || actionTarget.repo, - origin: 'host' - }) - navigateFromHostList( - `/h/${hostId}/source-control/${encodeURIComponent(actionTarget.worktreeId)}?${params.toString()}` - ) - setActionTarget(null) - } - }, + ...buildWorktreeNavigationActions({ + hostId, + worktreeId: actionTarget.worktreeId, + worktreeName: actionTarget.displayName || actionTarget.repo, + hostCapabilities, + navigate: navigateFromHostList, + onDone: () => setActionTarget(null) + }), { label: 'Sleep', icon: Moon, @@ -1601,21 +1605,12 @@ const styles = StyleSheet.create({ padding: spacing.xs }, searchBar: { - flexDirection: 'row', - alignItems: 'center', paddingHorizontal: spacing.md, - paddingVertical: spacing.xs + 2, - gap: spacing.sm, - borderBottomWidth: 1, + paddingVertical: spacing.sm, + borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: colors.borderSubtle, backgroundColor: colors.bgPanel }, - searchInput: { - flex: 1, - color: colors.textPrimary, - fontSize: 13, - paddingVertical: 2 - }, centered: { flex: 1, alignItems: 'center', diff --git a/mobile/app/h/[hostId]/pr/[worktreeId].tsx b/mobile/app/h/[hostId]/pr/[worktreeId].tsx index 2e0530b0f4ba..682e4d3481c3 100644 --- a/mobile/app/h/[hostId]/pr/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/pr/[worktreeId].tsx @@ -1,30 +1,29 @@ -import { useLocalSearchParams } from 'expo-router' -import { useHostClient } from '../../../../src/transport/client-context' -import { useMobilePrBranchContext } from '../../../../src/session/use-mobile-pr-branch-context' -import { MobilePrViewPanel } from '../../../../src/components/pr-sidebar/MobilePrViewPanel' - -// Narrow-layout full-screen PR route. The standalone panel can't ride on the review -// screen's diff state, so branch/head SHA are resolved here from git.status + branchCompare. -export default function MobilePrViewScreen() { - const { hostId, worktreeId } = useLocalSearchParams<{ hostId: string; worktreeId: string }>() - const { client, state: connState } = useHostClient(hostId) - const { branch, headSha, status, isGithubRepo, repoLoaded, loaded } = useMobilePrBranchContext({ - client, - connState, - worktreeId - }) +import { Redirect, useLocalSearchParams } from 'expo-router' +import { firstParam } from '../../../../src/source-control/mobile-source-control-screen-state' +// The Pull Request view is now a segment of the Source Control hub. This route +// stays as a thin redirect so existing deep links land on the hub with the Pull +// Request segment selected. The wide-layout dock opens the same hub with +// initialTab="pr" (SessionDockColumn), not this route. +export default function PrRedirect() { + const params = useLocalSearchParams<{ + hostId?: string | string[] + worktreeId?: string | string[] + name?: string | string[] + origin?: string | string[] + }>() return ( - ) } diff --git a/mobile/app/h/[hostId]/session/[worktreeId].tsx b/mobile/app/h/[hostId]/session/[worktreeId].tsx index 994798712f4f..18a393cae28f 100644 --- a/mobile/app/h/[hostId]/session/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/session/[worktreeId].tsx @@ -24,6 +24,7 @@ import { AlertTriangle, ArrowUp, Bot, + ChevronDown, ChevronLeft, ChevronRight, ChevronsRight, @@ -35,9 +36,9 @@ import { GitBranch, Globe, Keyboard as KeyboardIcon, - ListChecks, MessageSquare, Monitor, + MoreHorizontal, Plus, RefreshCw, Send, @@ -61,17 +62,25 @@ import { useReconnectAttempt, useLastConnectedAt } from '../../../../src/transport/client-context' -import { classifyConnection } from '../../../../src/transport/connection-health' +import { + classifyConnection, + verdictDisplayLabel +} from '../../../../src/transport/connection-health' import { useResponsiveLayout } from '../../../../src/layout/responsive-layout' import { type ActivePanel, canDockSessionPanel, resolvePanelAction, + shouldShowSessionHeaderChecksAction, panelRouteDescriptor } from '../../../../src/session/session-panel-host' import { useMobilePrBranchContext } from '../../../../src/session/use-mobile-pr-branch-context' import { SessionDockColumn } from '../../../../src/session/SessionDockColumn' +import { MobileSessionHeaderIconButton } from '../../../../src/session/MobileSessionHeaderIconButton' +import { MobileSessionHeaderMoreActionsSheet } from '../../../../src/session/MobileSessionHeaderMoreActionsSheet' +import { MOBILE_AI_VAULT_CAPABILITY } from '../../../../src/agent-history/agent-history-capability' import type { ConnectionState, RpcFailure, RpcSuccess } from '../../../../src/transport/types' +import { headlessActivationNeedsHostRenderer } from '../../../../src/worktree/worktree-activation-result' import { useMobileDictation } from '../../../../src/hooks/use-mobile-dictation' import { triggerMediumImpact, @@ -84,7 +93,7 @@ import type { TerminalKeyboardAvoidanceMetrics, TerminalModes, TerminalWebViewHandle -} from '../../../../src/terminal/TerminalWebView' +} from '../../../../src/terminal/terminal-webview-contract' import { isTerminalOscLinkRanges } from '../../../../src/terminal/terminal-osc-link-ranges' import { useTerminalViewportRefit } from '../../../../src/terminal/terminal-viewport-refit' import { @@ -100,6 +109,7 @@ import { isTerminalLiveInputWithinByteLimit, scheduleTerminalLiveInputFocus } from '../../../../src/terminal/terminal-live-input' +import { dismissTerminalKeyboard } from '../../../../src/terminal/terminal-keyboard-dismiss' import type { TerminalLiveInputSender } from '../../../../src/terminal/terminal-live-input-sender' import { isTerminalSendRpcAccepted } from '../../../../src/terminal/terminal-send-rpc-response' import { useTerminalLiveInputCommit } from '../../../../src/terminal/use-terminal-live-input-commit' @@ -851,20 +861,16 @@ export default function SessionScreen() { setActivePanel(null) } }, [canDockPanel, activePanel]) - // Session-level PR context feeds the docked PR panel and gates the GitHub-only - // PR entry so GitLab/other providers do not open a GitHub RPC surface. - const { - branch: prBranch, - headSha: prHeadSha, - status: prStatus, - isGithubRepo: prIsGithubRepo, - repoLoaded: prRepoContextLoaded, - loaded: prContextLoaded - } = useMobilePrBranchContext({ - client, - connState, - worktreeId - }) + // Session-level GitHub remote probe gates the PR dock icon so non-GitHub + // providers do not open the hosted-review surface. Branch/head/status for the + // hub are loaded inside MobileSourceControlPanel — skip the unused identity RPCs. + const { isGithubRepo: prIsGithubRepo, repoLoaded: prRepoContextLoaded } = + useMobilePrBranchContext({ + client, + connState, + worktreeId, + includeBranchIdentity: false + }) useEffect(() => { if (prRepoContextLoaded && !prIsGithubRepo && activePanel === 'pr') { setActivePanel(null) @@ -938,6 +944,7 @@ export default function SessionScreen() { useState('idle') const [createTabAgentOptions, setCreateTabAgentOptions] = useState([]) const [showCreateBrowserModal, setShowCreateBrowserModal] = useState(false) + const [showHeaderMoreActions, setShowHeaderMoreActions] = useState(false) const [actionTarget, setActionTarget] = useState(null) const [markdownActionTarget, setMarkdownActionTarget] = useState>(new Map()) const initialModesSeenRef = useRef>(new Set()) const deviceTokenRef = useRef(null) + // Why: state (not a ref) — the connection verdict needs a re-render once + // the endpoint loads so the Tailscale hint can appear. + const [hostEndpoint, setHostEndpoint] = useState(null) const clientRef = useRef(null) const connStateRef = useRef(connState) // Why: measured once from TerminalWebView on mount, then passed with every @@ -1006,6 +1016,7 @@ export default function SessionScreen() { const viewportMeasuredRef = useRef(false) const terminalRefs = useRef>(new Map()) const liveInputRef = useRef(null) + const commandInputRef = useRef(null) const liveInputFocusTimerRef = useRef | null>(null) const sendLiveTerminalInputRef = useRef(async () => false) const sessionTabActionSheetKeyboardHideSubRef = useRef(null) + // Why: hosts without aiVault.v1 reject aiVault.listSessions, so the header + // entry stays hidden there (mirrors the gated host-list action) instead of + // opening a dead-end "update this host" panel. + const [agentSessionHistorySupported, setAgentSessionHistorySupported] = useState( + null + ) // Why: stable callbacks (handleFileTap) read the live value via this ref, since // the capability probe resolves after the callbacks are created. const browserScreencastSupportedRef = useRef(browserScreencastSupported) @@ -2410,6 +2427,7 @@ export default function SessionScreen() { useEffect(() => { if (!client || connState !== 'connected') { setBrowserScreencastSupported(null) + setAgentSessionHistorySupported(null) return } let stale = false @@ -2423,10 +2441,14 @@ export default function SessionScreen() { setBrowserScreencastSupported( status.capabilities?.includes('browser.screencast.v1') === true ) + setAgentSessionHistorySupported( + status.capabilities?.includes(MOBILE_AI_VAULT_CAPABILITY) === true + ) }) .catch(() => { if (!stale) { setBrowserScreencastSupported(false) + setAgentSessionHistorySupported(false) } }) return () => { @@ -2450,6 +2472,7 @@ export default function SessionScreen() { const host = hosts.find((h) => h.id === hostId) if (host) { deviceTokenRef.current = host.deviceToken + setHostEndpoint(host.endpoint) } }) return () => { @@ -2507,8 +2530,12 @@ export default function SessionScreen() { if (!shouldRecover) { return } + for (const terminalRef of terminalRefs.current.values()) { + terminalRef.prepareForForegroundRecovery() + } // Why: iOS can resume a live WKWebView with a blank xterm backing store - // without firing web-ready/reconnect; replay scrollback to repaint it. + // without firing web-ready/reconnect; invalidate the native readiness + // latch before replay so init waits for the document's pong. recoverActiveTerminalAfterForeground({ activeHandleRef, terminalRefs, @@ -2536,6 +2563,7 @@ export default function SessionScreen() { clientRef, deviceTokenRef, initializedHandlesRef, + connState, tabStripVisible: terminals.length > 1, textScale: terminalTextScale, terminalFrameWidth, @@ -2684,6 +2712,11 @@ export default function SessionScreen() { timers.push(setTimeout(fn, ms)) } void (async () => { + const reportActivationOutcome = (response: RpcSuccess | null): void => { + if (!disposed && response && headlessActivationNeedsHostRenderer(response.result)) { + showToast('Open Orca on the host to wake sleeping agents.', 3000) + } + } if (client && created !== '1') { // Why: mobile needs host-owned tabs hydrated for this route, but should // not pull other paired clients, especially desktop, into this worktree. @@ -2692,6 +2725,7 @@ export default function SessionScreen() { worktree: `id:${worktreeId}`, notifyClients: false }) + .then((response) => reportActivationOutcome(response.ok ? response : null)) .catch(() => null) } if (disposed) { @@ -2713,12 +2747,13 @@ export default function SessionScreen() { return } void (async () => { - await client + const activationResponse = await client .sendRequest('worktree.activate', { worktree: `id:${worktreeId}`, notifyClients: false }) .catch(() => null) + reportActivationOutcome(activationResponse?.ok ? activationResponse : null) if (disposed) { return } @@ -2734,7 +2769,7 @@ export default function SessionScreen() { clearTimeout(t) } } - }, [client, connState, created, fetchSessionTabs, fetchTerminals, worktreeId]) + }, [client, connState, created, fetchSessionTabs, fetchTerminals, showToast, worktreeId]) useEffect(() => { if (!client || connState !== 'connected') { @@ -3208,6 +3243,15 @@ export default function SessionScreen() { ] ) + const dismissSoftwareKeyboard = useCallback(() => { + dismissTerminalKeyboard({ + clearPendingLiveInputFocus: () => clearTerminalLiveInputFocusTimer(liveInputFocusTimerRef), + commandInput: commandInputRef.current, + dismissKeyboard: () => Keyboard.dismiss(), + liveInput: liveInputRef.current + }) + }, []) + const handleTerminalTap = useCallback( (handle: string) => { if (handle !== activeHandleRef.current) { @@ -4253,13 +4297,14 @@ export default function SessionScreen() { void handleCreateTerminal() }, [client, creating, creatingBrowser, creatingMarkdown, showEmptyState, worktreeId]) - // Why: the reconnect loop parks at its give-up cap; without an in-session - // affordance the only recovery is leaving the screen or restarting the - // app (issue #5049). Surface tap-to-retry once the verdict escalates. + // Why: the reconnect loop slows to a 90s trickle at its give-up cap; + // surface tap-to-retry once the verdict escalates so recovery doesn't + // wait out the trickle timer (issue #5049). const connectionVerdict = classifyConnection({ state: connState, reconnectAttempts, - lastConnectedAt + lastConnectedAt, + endpoint: hostEndpoint }) const showConnectionRetry = connectionVerdict.kind === 'warning' || connectionVerdict.kind === 'unreachable' @@ -4272,7 +4317,7 @@ export default function SessionScreen() { ? '1 tab' : `${visibleTabs.length} tabs` : showConnectionRetry - ? `${connectionVerdict.label} — tap to retry` + ? `${verdictDisplayLabel(connectionVerdict)} — tap to retry` : MOBILE_SESSION_STATUS_LABELS[connState] // Why: keep safe-area padding in layout at all times, then visually translate @@ -4411,18 +4456,35 @@ export default function SessionScreen() { setActivePanel(action.next) return } + const descriptor = panelRouteDescriptor(action.panel) router.push({ - pathname: panelRouteDescriptor(action.panel).pathname, + pathname: descriptor.pathname, params: { hostId, worktreeId, name: worktreeName || '', - // Source control's post-diff-open dismissal keys off origin: 'session' (U2). - ...(action.panel === 'sourceControl' ? { origin: 'session' } : {}) + // SC + PR both land on the source-control hub; post-diff-open dismissal + // keys off origin: 'session' (U2). Files keeps its own route without origin. + ...(action.panel === 'sourceControl' || action.panel === 'pr' ? { origin: 'session' } : {}), + // The PR panel routes into the hub's Pull Request segment via descriptor params. + ...descriptor.params } }) } + const openAgentSessionHistory = () => { + const params = new URLSearchParams({ name: worktreeName || '' }) + router.push(`/h/${hostId}/agent-history/${encodeURIComponent(worktreeId)}?${params.toString()}`) + } + const showAgentSessionHistoryAction = + !isFolderWorkspaceRoute && agentSessionHistorySupported === true + const showChecksAction = shouldShowSessionHeaderChecksAction({ + isFolderWorkspaceRoute, + repoContextLoaded: prRepoContextLoaded, + hostedChecksSupported: prIsGithubRepo + }) + const showHeaderMoreButton = showAgentSessionHistoryAction || showChecksAction + return ( @@ -4458,45 +4520,27 @@ export default function SessionScreen() { - [ - styles.filesButton, - pressed && styles.filesButtonPressed, - activePanel === 'files' && styles.filesButtonActive - ]} - onPress={() => handlePanelTap('files')} - hitSlop={8} + - - + icon={Folder} + onPress={() => handlePanelTap('files')} + /> {!isFolderWorkspaceRoute && ( - [ - styles.filesButton, - pressed && styles.filesButtonPressed, - activePanel === 'sourceControl' && styles.filesButtonActive - ]} - onPress={() => handlePanelTap('sourceControl')} - hitSlop={8} + - - + icon={GitBranch} + onPress={() => handlePanelTap('sourceControl')} + /> )} - {prRepoContextLoaded && prIsGithubRepo ? ( - [ - styles.filesButton, - pressed && styles.filesButtonPressed, - activePanel === 'pr' && styles.filesButtonActive - ]} - onPress={() => handlePanelTap('pr')} - hitSlop={8} - accessibilityLabel="Open pull request" - > - - + {showHeaderMoreButton ? ( + setShowHeaderMoreActions(true)} + /> ) : null} @@ -4780,10 +4824,38 @@ export default function SessionScreen() { > {/* Accessory keys */} + {/* Why: a fixed, always-visible escape hatch from the open + keyboard. Kept outside the horizontal ScrollView so it does + not scroll away, and out of the terminal-byte shortcut path so + it cannot be hidden by user shortcut customization (#5106). */} + {keyboardLift > 0 && ( + [ + styles.keyboardDismissKey, + pressed && styles.accessoryKeyPressed + ]} + onPress={dismissSoftwareKeyboard} + hitSlop={8} + accessibilityRole="button" + accessibilityLabel="Dismiss keyboard" + accessibilityHint="Hides the software keyboard and keeps the current terminal session open." + > + + + + + + )} {/* Why: with default tap handling the first tap on any accessory key dismisses the open keyboard and is swallowed, so live input lost its keyboard on every Esc/Tab press (#5106). */} - setInput((previousText) => normalizeTerminalTextInput(text, previousText)) - } + // Why: iOS kills an active dictation/IME session when JS + // writes a value that differs from the native field text; + // store the raw field text and normalize at send time. + onChangeText={setInput} placeholder="Type a command…" placeholderTextColor={colors.textMuted} autoCapitalize="none" @@ -5074,13 +5148,6 @@ export default function SessionScreen() { hostId={hostId} worktreeId={worktreeId} name={worktreeName || ''} - client={client} - connState={connState} - branch={prBranch} - headSha={prHeadSha} - gitStatus={prStatus} - isGithubRepo={prIsGithubRepo} - branchContextLoaded={prContextLoaded && prRepoContextLoaded} availableWidth={sessionContentRowWidth} onRequestClose={() => setActivePanel(null)} onFileOpenStart={handleFileOpenStart} @@ -5090,6 +5157,15 @@ export default function SessionScreen() { + handlePanelTap('pr')} + onClose={() => setShowHeaderMoreActions(false)} + /> + () return ( ) diff --git a/mobile/app/h/[hostId]/tasks.tsx b/mobile/app/h/[hostId]/tasks.tsx index 08f69b4972f6..fea23f017642 100644 --- a/mobile/app/h/[hostId]/tasks.tsx +++ b/mobile/app/h/[hostId]/tasks.tsx @@ -29,7 +29,6 @@ import { Pencil, Plus, RefreshCw, - Search, Send, X } from 'lucide-react-native' @@ -48,6 +47,7 @@ import { ConfirmModal } from '../../../src/components/ConfirmModal' import { MobileMarkdown } from '../../../src/components/MobileMarkdown' import { MobileAgentIcon } from '../../../src/components/MobileAgentIcon' import { MobileWorkspaceNameInput } from '../../../src/components/MobileWorkspaceNameInput' +import { MobileSearchField } from '../../../src/components/MobileSearchField' import { MobileSyntaxSegments } from '../../../src/components/MobileSyntaxSegments' import { PickerModal, type PickerOption } from '../../../src/components/PickerModal' import { TaskProviderLogo } from '../../../src/components/TaskProviderLogo' @@ -8668,6 +8668,7 @@ export default function MobileTasksScreen() { : provider === 'gitlab' ? 'No GitLab tasks' : 'No Linear tasks' + const isGithubProjectSearch = provider === 'github' && githubMode === 'project' return ( @@ -9048,31 +9049,33 @@ export default function MobileTasksScreen() { {provider === 'gitlab' && gitlabView === 'todos' ? null : provider === 'linear' && !linearConnected ? null : ( - - 0 || + (appliedGithubProjectSearch !== undefined && + appliedGithubProjectSearch.length > 0) + : provider === 'github' + ? query.trim() !== getTaskPresetQuery(githubPreset).trim() + : undefined + } + editable={taskUiReady} onSubmitEditing={() => { if (!taskUiReady) { return } - if (provider === 'github' && githubMode === 'project') { + if (isGithubProjectSearch) { applyGitHubProjectSearch() return } @@ -9091,42 +9094,38 @@ export default function MobileTasksScreen() { } }} onBlur={() => { - if (provider === 'github' && githubMode === 'project') { + if (isGithubProjectSearch) { applyGitHubProjectSearch() } }} + // Why: Project clear means unfiltered results ('' override when the view + // has a default filter), not restore view default. GitHub items clear + // restores the preset query. Linear clears and persists empty resume. + onClear={() => { + if (isGithubProjectSearch) { + const viewFilter = githubProjectTable?.selectedView.filter ?? '' + setGithubProjectSearch('') + // Why: undefined = use view default; '' = explicit unfiltered override. + setAppliedGithubProjectSearch(viewFilter ? '' : undefined) + return + } + if (provider === 'github') { + const nextQuery = getTaskPresetQuery(githubPreset) + setQuery(nextQuery) + setAppliedQuery(nextQuery) + persistTaskResumeState({ + githubItemsPreset: githubPreset, + githubItemsQuery: nextQuery + }) + return + } + setQuery('') + setAppliedQuery('') + if (provider === 'linear') { + persistTaskResumeState({ linearQuery: '' }) + } + }} /> - {(provider === 'github' && githubMode === 'project' - ? githubProjectSearch.length > 0 || appliedGithubProjectSearch !== undefined - : query.length > 0) && ( - { - if (provider === 'github' && githubMode === 'project') { - const viewFilter = githubProjectTable?.selectedView.filter ?? '' - setGithubProjectSearch('') - setAppliedGithubProjectSearch(viewFilter ? '' : undefined) - return - } - if (provider === 'github') { - const nextQuery = getTaskPresetQuery(githubPreset) - setQuery(nextQuery) - setAppliedQuery(nextQuery) - persistTaskResumeState({ - githubItemsPreset: githubPreset, - githubItemsQuery: nextQuery - }) - return - } - setQuery('') - setAppliedQuery('') - if (provider === 'linear') { - persistTaskResumeState({ linearQuery: '' }) - } - }} - > - - - )} )} @@ -13818,20 +13817,11 @@ const styles = StyleSheet.create({ color: colors.textSecondary }, searchBar: { - flexDirection: 'row', - alignItems: 'center', paddingHorizontal: spacing.md, - paddingVertical: spacing.xs + 2, - gap: spacing.sm, - borderTopWidth: 1, + paddingVertical: spacing.sm, + borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: colors.borderSubtle }, - searchInput: { - flex: 1, - color: colors.textPrimary, - fontSize: 13, - paddingVertical: 2 - }, errorBanner: { paddingHorizontal: spacing.lg, paddingVertical: spacing.sm, diff --git a/mobile/app/h/_layout.tsx b/mobile/app/h/_layout.tsx index 7c7d1cc89708..55eade98e03c 100644 --- a/mobile/app/h/_layout.tsx +++ b/mobile/app/h/_layout.tsx @@ -46,6 +46,10 @@ function HostStack({ animation }: { animation: 'none' | 'default' }) { name="[hostId]/source-control/[worktreeId]" options={{ title: 'Source Control' }} /> + diff --git a/mobile/app/index.tsx b/mobile/app/index.tsx index acaf97b7646f..eaee0e5f9358 100644 --- a/mobile/app/index.tsx +++ b/mobile/app/index.tsx @@ -34,7 +34,7 @@ import { useForceReconnect, usePrimeHosts } from '../src/transport/client-context' -import { classifyConnection } from '../src/transport/connection-health' +import { classifyConnection, verdictDisplayLabel } from '../src/transport/connection-health' import { subscribeToDesktopNotifications } from '../src/notifications/mobile-notifications' import type { ConnectionState, HostProfile } from '../src/transport/types' import { triggerMediumImpact } from '../src/platform/haptics' @@ -827,7 +827,8 @@ export default function HomeScreen() { const verdict = classifyConnection({ state, reconnectAttempts: attempts, - lastConnectedAt + lastConnectedAt, + endpoint: item.endpoint }) const isError = verdict.kind === 'warning' || @@ -859,7 +860,7 @@ export default function HomeScreen() { - {verdict.label} + {verdictDisplayLabel(verdict)} {connected && info ? ` · ${info.totalWorktrees} worktree${info.totalWorktrees !== 1 ? 's' : ''}${info.activeCount > 0 ? ` · ${info.activeCount} active` : ''}` : ''} diff --git a/mobile/app/troubleshoot.tsx b/mobile/app/troubleshoot.tsx index 0a1a63b7c274..5ae53e0084c0 100644 --- a/mobile/app/troubleshoot.tsx +++ b/mobile/app/troubleshoot.tsx @@ -14,13 +14,9 @@ import { ChevronLeft, ChevronDown, ChevronUp, - WifiOff, - Shield, - Monitor, - Clock, - Globe, Activity, CheckCircle2, + ScrollText, XCircle, AlertTriangle } from 'lucide-react-native' @@ -30,7 +26,12 @@ import { startDiagnosticFetchTimeout, type DiagnosticFetchTimeout } from '../src/diagnostics/diagnostic-fetch-timeout' -import { formatEndpoint, testHostReachability } from '../src/diagnostics/host-reachability' +import { + formatEndpoint, + testHostReachability, + unreachableHostDetail +} from '../src/diagnostics/host-reachability' +import { troubleshootCommonIssues } from '../src/diagnostics/troubleshoot-common-issues' type DiagnosticStatus = 'idle' | 'running' | 'done' @@ -40,66 +41,6 @@ type CheckResult = { detail: string } -type TroubleshootSection = { - id: string - icon: React.ReactNode - title: string - steps: string[] -} - -const sections: TroubleshootSection[] = [ - { - id: 'wifi', - icon: , - title: 'Different WiFi Networks', - steps: [ - 'Both devices must be on the same local network.', - 'Ethernet and WiFi must share the same subnet.', - 'Try reconnecting WiFi on both devices.' - ] - }, - { - id: 'firewall', - icon: , - title: 'Firewall Blocking Port 6768', - steps: [ - 'macOS: System Settings → Network → Firewall — allow Orca.', - 'Windows: Defender Firewall → Allow app — enable Orca for Private networks.', - 'Linux: sudo ufw allow 6768', - 'Corporate/school networks may block P2P — try a personal hotspot.' - ] - }, - { - id: 'desktop', - icon: , - title: 'Desktop App Not Running', - steps: [ - 'Orca must be open on your desktop to accept connections.', - 'Try restarting Orca — the companion server starts on launch.', - 'After an update, you may need to re-pair via QR code.' - ] - }, - { - id: 'timeout', - icon: , - title: 'Connection Timeout', - steps: [ - 'Check WiFi signal strength on your phone.', - 'Go back to the host list and tap your host to retry.', - 'Restart both apps if timeouts persist.' - ] - }, - { - id: 'vpn', - icon: , - title: 'VPN Interference', - steps: [ - 'VPNs can route local traffic through a remote server.', - 'Disable the VPN or enable split tunneling / "Allow LAN".' - ] - } -] - function StatusIcon({ status }: { status: CheckResult['status'] }) { switch (status) { case 'pass': @@ -211,7 +152,7 @@ export default function TroubleshootScreen() { status: reachable ? 'pass' : 'fail', detail: reachable ? `Reachable at ${formatEndpoint(host.endpoint)}` - : `Cannot reach ${formatEndpoint(host.endpoint)}` + : unreachableHostDetail(host.endpoint) }) setChecks([...results]) } @@ -273,6 +214,17 @@ export default function TroubleshootScreen() { + [ + styles.diagnosticButton, + pressed && styles.diagnosticButtonPressed + ]} + onPress={() => router.push('/connection-log')} + > + + View connection log + + {checks.length > 0 && ( {checks.map((check, i) => ( @@ -295,7 +247,7 @@ export default function TroubleshootScreen() { Common issues - {sections.map((section, i) => ( + {troubleshootCommonIssues.map((section, i) => ( {i > 0 && } uuid": "11.1.1" + } } } diff --git a/mobile/pnpm-lock.yaml b/mobile/pnpm-lock.yaml index f3c4b72ed1c6..496855fc2666 100644 --- a/mobile/pnpm-lock.yaml +++ b/mobile/pnpm-lock.yaml @@ -4,13 +4,16 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +overrides: + xcode>uuid: 11.1.1 + importers: .: dependencies: '@orca/expo-two-way-audio': specifier: file:./packages/expo-two-way-audio - version: file:packages/expo-two-way-audio(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + version: file:packages/expo-two-way-audio(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) '@react-native-async-storage/async-storage': specifier: ^2.2.0 version: 2.2.0(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) @@ -27,62 +30,62 @@ importers: specifier: ^6.0.3 version: 6.0.3 expo: - specifier: ^55.0.23 - version: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + specifier: ^55.0.27 + version: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) expo-build-properties: specifier: ^55.0.13 - version: 55.0.13(expo@55.0.23) + version: 55.0.13(expo@55.0.27) expo-camera: specifier: ^55.0.18 - version: 55.0.18(@types/emscripten@1.41.5)(expo@55.0.23)(react-native-web@0.21.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + version: 55.0.18(@types/emscripten@1.41.5)(expo@55.0.27)(react-native-web@0.21.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) expo-clipboard: specifier: ^55.0.13 - version: 55.0.13(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + version: 55.0.13(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) expo-constants: specifier: ^55.0.16 - version: 55.0.16(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) + version: 55.0.16(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) expo-crypto: specifier: ^55.0.14 - version: 55.0.14(expo@55.0.23) + version: 55.0.14(expo@55.0.27) expo-dev-client: specifier: ~55.0.35 - version: 55.0.35(expo@55.0.23) + version: 55.0.35(expo@55.0.27) expo-document-picker: specifier: ^55.0.13 - version: 55.0.13(expo@55.0.23) + version: 55.0.13(expo@55.0.27) expo-file-system: specifier: 55.0.19 - version: 55.0.19(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) + version: 55.0.19(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) expo-haptics: specifier: ^55.0.14 - version: 55.0.14(expo@55.0.23) + version: 55.0.14(expo@55.0.27) expo-image-manipulator: specifier: ^55.0.17 - version: 55.0.17(expo@55.0.23) + version: 55.0.17(expo@55.0.27) expo-image-picker: specifier: ^55.0.20 - version: 55.0.20(expo@55.0.23) + version: 55.0.20(expo@55.0.27) expo-linking: specifier: ^55.0.15 - version: 55.0.15(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + version: 55.0.15(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) expo-modules-core: specifier: ~55.0.25 version: 55.0.25(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) expo-network: specifier: ~55.0.14 - version: 55.0.14(expo@55.0.23)(react@19.2.6) + version: 55.0.14(expo@55.0.27)(react@19.2.6) expo-notifications: specifier: ^55.0.22 - version: 55.0.22(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + version: 55.0.22(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) expo-router: specifier: ^55.0.14 - version: 55.0.14(e0a8113e3689d84edb7af23d00a72ffa) + version: 55.0.14(7ffd97bbc113b875771c40f21f44415d) expo-secure-store: specifier: ^55.0.13 - version: 55.0.13(expo@55.0.23) + version: 55.0.13(expo@55.0.27) expo-splash-screen: specifier: ^55.0.20 - version: 55.0.20(expo@55.0.23)(typescript@5.9.3) + version: 55.0.20(expo@55.0.27)(typescript@7.0.2) expo-status-bar: specifier: ^55.0.6 version: 55.0.6(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) @@ -158,7 +161,7 @@ importers: version: 0.25.4 expo-module-scripts: specifier: ^55.0.2 - version: 55.0.2(@babel/core@7.29.7)(@babel/runtime@7.29.2)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(eslint@9.39.4)(expo@55.0.23)(jest@29.7.0(@types/node@25.9.3))(prettier@2.8.8)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-refresh@0.14.2)(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6) + version: 55.0.2(@babel/core@7.29.7)(@babel/runtime@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(eslint@9.39.4)(expo@55.0.27)(jest@29.7.0(@types/node@26.1.1))(prettier@2.8.8)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-refresh@0.14.2)(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6) oxfmt: specifier: ^0.52.0 version: 0.52.0 @@ -172,14 +175,14 @@ importers: specifier: ^4.22.4 version: 4.22.4 typescript: - specifier: ^5.9.3 - version: 5.9.3 + specifier: ^7.0.2 + version: 7.0.2 vite: specifier: ^8.0.16 - version: 8.1.0(@types/node@25.9.3)(esbuild@0.25.4)(terser@5.48.0)(tsx@4.22.4)(yaml@2.9.0) + version: 8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0) vitest: specifier: ^4.1.9 - version: 4.1.9(@types/node@25.9.3)(jsdom@20.0.3)(vite@8.1.0(@types/node@25.9.3)(esbuild@0.25.4)(terser@5.48.0)(tsx@4.22.4)(yaml@2.9.0)) + version: 4.1.9(@types/node@26.1.1)(jsdom@20.0.3)(vite@8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0)) packages: @@ -190,6 +193,9 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/code-frame@7.10.4': + resolution: {integrity: sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==} + '@babel/code-frame@7.29.0': resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==} engines: {node: '>=6.9.0'} @@ -383,6 +389,10 @@ packages: resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==} engines: {node: '>=6.9.0'} + '@babel/highlight@7.25.9': + resolution: {integrity: sha512-llL88JShoCsth8fF8R4SJnIn+WLvR6ccFxu1H3FlMhDontdcmZWf2HgIZ7AIqV3Xcck1idlohrN4EUBQz6klbw==} + engines: {node: '>=6.9.0'} + '@babel/parser@7.29.3': resolution: {integrity: sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA==} engines: {node: '>=6.0.0'} @@ -1500,8 +1510,8 @@ packages: resolution: {integrity: sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@eslint/eslintrc@3.3.5': - resolution: {integrity: sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==} + '@eslint/eslintrc@3.3.6': + resolution: {integrity: sha512-l2Ul9PrHsPCKcEY/ac7VgFj9D80C7S68sOKc618SyHDPK36s1XcFebXY0iTzUVn4Yq+YbwvSnDmCz9yxjX+QrA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} '@eslint/js@9.39.4': @@ -1519,8 +1529,8 @@ packages: '@expo-google-fonts/material-symbols@0.4.34': resolution: {integrity: sha512-PdwETUhvu1gHF1e8eIyEHnBJLq/dRNoTrT5yhsGUfGyRxH5pbm54dF3+QPknxwMKj0M1trN7PSelYz+yzlt3lA==} - '@expo/cli@55.0.29': - resolution: {integrity: sha512-r2dXQ82e/3nwxS7faLRL6HBD8UWDo/IyptQ0Vg6Z5Bgyp2Kd24h8xPn3RHfY3LLJ3wfEXglf4E79/Dqkm1Z6WA==} + '@expo/cli@55.0.33': + resolution: {integrity: sha512-mCpv91YrgiQUCXEHbNOQNPeStO4NKvYaXgKuzzLjklrCUPf3f+u0oYcS5rl3KoFvTEifhOiuA0VkLDR8U0GGPg==} hasBin: true peerDependencies: expo: '*' @@ -1535,6 +1545,9 @@ packages: '@expo/code-signing-certificates@0.0.6': resolution: {integrity: sha512-iNe0puxwBNEcuua9gmTGzq+SuMDa0iATai1FlFTMHJ/vUmKvN/V//drXoLJkVb5i5H3iE/n/qIJxyoBnXouD0w==} + '@expo/config-plugins@55.0.10': + resolution: {integrity: sha512-1txnRnMLIO5lM/Of/VyvDkCwZap0YFvCyfSTIlUQamhwhx6Rh7r8TXfcIstaDYUQ7X6GTMkNxLXWbcYS6ZAFDw==} + '@expo/config-plugins@55.0.8': resolution: {integrity: sha512-8WfWTRntTCcowfOS+tHdB0z98gKetTwktg4G5TWkCkXVa8Jt1NUnvzaaU4UHk2vbR2U4N84RyZJFizSwfF6C9g==} @@ -1544,6 +1557,9 @@ packages: '@expo/config@55.0.16': resolution: {integrity: sha512-H5dpQv5TfyZDNheZAWO3SmP10diGWZwN5QOUsArkDJih0QKNtahQBOmrV2xbhgln/nrUGoy41U/ZIY/MEx63Ug==} + '@expo/config@55.0.18': + resolution: {integrity: sha512-yezuyUk1VvVuwVyvKQrMHGosoC0WTh7HFAycpISMyeinSUHDjEBGvHUSQxtQ/71MR4g9lPJkEhFKeRjGx7I/Yg==} + '@expo/devcert@1.2.1': resolution: {integrity: sha512-qC4eaxmKMTmJC2ahwyui6ud8f3W60Ss7pMkpBq40Hu3zyiAaugPXnZ24145U7K36qO9UHdZUVxsCvIpz2RYYCA==} @@ -1579,8 +1595,17 @@ packages: '@expo/json-file@10.0.14': resolution: {integrity: sha512-yWwBFywFv+SxkJp/pIzzA416JVYflNUh7pqQzgaA6nXDqRyK7KfrqVzk8PdUfDnqbBcaZZxpzNssfQZzp5KHrA==} - '@expo/local-build-cache-provider@55.0.12': - resolution: {integrity: sha512-Wqhe7ajt6lyIEQvqDC1zm0MQ1RqQLlM9awCepY9pz+tm9rvhuxGPZTSddWeD8k4kolinBlDbLDFnNi06XgaDWQ==} + '@expo/json-file@10.0.16': + resolution: {integrity: sha512-fcVkWEj+hLuP2yt5W0aw6LmDRqSPWDLUSxOMcmFeV+algmIF59sQVKCwB9btjQLd4V6x9N0pISkQEkBubUHrCw==} + + '@expo/json-file@10.2.0': + resolution: {integrity: sha512-S6XzKe3R9GQeHiUPXc3xJjOv2VJhOEwFYf7xdC2z2cUqt3kZJ9mSO877sNQloVdnW/SUCtPY3bexlM7nwq+CAQ==} + + '@expo/json-file@11.0.0': + resolution: {integrity: sha512-pHJCETqFL5x5BzNV6cEPwjwuECgGmnl0bNmfHIJ6LM1tlh2eVXi5HEdit3zby/JO/B8Otk5cgcqtJXgvvUat3A==} + + '@expo/local-build-cache-provider@55.0.14': + resolution: {integrity: sha512-Itv/Wm8wBuq2QoJeda7N0Ys2ciq3ZQW+JLL8XijWMYOO/llieKeZue95FsuaREp3Ijdo0pSw0/cu+EkrwmU0vA==} '@expo/log-box@55.0.11': resolution: {integrity: sha512-JQHFLWkskIbJi6cxYMjErx8lQqfFJilDQLKmdTO3m3YkdmN9GE/CrzjOfVlCG0DGEGZJ90br0pGKvGPdXNsHKw==} @@ -1598,8 +1623,8 @@ packages: react: '*' react-native: '*' - '@expo/metro-config@55.0.20': - resolution: {integrity: sha512-dUv0simEyPbN2wbOjI+BdEZyXdghgCZD0+3rrA1WxXZN1lRofUx6g2+Nik2Qg61v/BXFrCTh8reYEzQPzHOhdQ==} + '@expo/metro-config@55.0.24': + resolution: {integrity: sha512-GQ8vernAY3BClpntFj+DDm4rmTpuFZYKxZ/82Q0XTZAOHnum68WIgRbgG2aRpAyVVs1wRBToKlLiSFCkpSS41w==} peerDependencies: expo: '*' peerDependenciesMeta: @@ -1624,21 +1649,29 @@ packages: resolution: {integrity: sha512-yDyBlNIgg+rKoKCOVM9ZyAtgqRx6gHw+JtmZTrYYW4auAfwS6kE/iInmCpVXPqRy0OhJHgXj6q5PCgWELLVMeg==} hasBin: true - '@expo/osascript@2.4.3': - resolution: {integrity: sha512-wbuj3EebM7W9hN/Wp4xTzKd6rQ2zKJzAxkFxkOOwyysLp0HOAgQ4/5RINyoS241pZUX2rUHq7mAJ7pcCQ8U0Ow==} + '@expo/osascript@2.7.0': + resolution: {integrity: sha512-wKIXL8UtbuX4KwavPasIW3CUcgTbYfjzLcgUhjyKUAYDEqMaf6gmU1bqz3ffBPTokmX+G8/vFG1ZuI9etQWukA==} engines: {node: '>=12'} - '@expo/package-manager@1.10.5': - resolution: {integrity: sha512-nCP9Mebfl3jvOr0/P6VAuyah6PAtun+aihIL2zAtuE8uSe94JWkVZ7051i0MUVO+y3gFpBqnr8IIH5ch+VJjHA==} + '@expo/package-manager@1.13.0': + resolution: {integrity: sha512-s3W3eZafJDEyVL7W/jxj2Nz3eONKxSCU604S5xj8ijrVaRz83x0DnZznLf/UXQEI1w+FyibH68nHeQyk767b1A==} '@expo/plist@0.5.3': resolution: {integrity: sha512-jz5oPcPDd3fygwVxwSwmO6wodTwm0Qa14NUyPy0ka7H8sFmCtNZUI2+DzVe/EXjOhq1FbEjrwl89gdlWYOnVjQ==} + '@expo/plist@0.5.4': + resolution: {integrity: sha512-Jqppj0FULNq6Zp5JtQrFICl8TtpMjwwUbxEcEC2T3z7m+TOrTQEHZXz3D3Ay7vhbmvD+VMgfWJ4ARclJXeN8Eg==} + '@expo/prebuild-config@55.0.17': resolution: {integrity: sha512-Mcs+dg4Ripu0yCtzf66KZr18PehI1O8HxzJw+G5SUF8VWX+ic99aci1PltvmydWepLwTQL6ykmpXicAUA31IqA==} peerDependencies: expo: '*' + '@expo/prebuild-config@55.0.19': + resolution: {integrity: sha512-rLGjUXW0EUoxu/PJUOC0Lz5PEs27DmBA9Es3t2xV2ftI3kGZJK6oNt1vVq5D/Rn6MhZ5SFxqd3kziyP8ELoN6g==} + peerDependencies: + expo: '*' + '@expo/require-utils@55.0.5': resolution: {integrity: sha512-U4K/CQ2VpXuwfNGsN+daKmYOt15hCP8v/pXaYH6eut7kdYZo6SfJ1yr67BIcJ+1Gzzs+QzTxswAZChKpXmceyw==} peerDependencies: @@ -1647,15 +1680,15 @@ packages: typescript: optional: true - '@expo/router-server@55.0.16': - resolution: {integrity: sha512-LvAdrm039nQBG+95+ff5Rc4CsBuoc/giDhjQrgxB9lKJqC/ZTq1xbwfEZFNq6yokX6fOCs/vlxdhmSkOjMIrvg==} + '@expo/router-server@55.0.18': + resolution: {integrity: sha512-W0VsvIiR48OvdlAOUlag4qspGYT/DV4srfYowlbYxwZh5Qw0MjiZAID4Zt7F0qynGZZxx8OZPpFhIX7XsqtRmg==} peerDependencies: '@expo/metro-runtime': ^55.0.11 expo: '*' expo-constants: ^55.0.16 - expo-font: ^55.0.7 + expo-font: ^55.0.8 expo-router: '*' - expo-server: ^55.0.9 + expo-server: ^55.0.11 react: '*' react-dom: '*' react-server-dom-webpack: ~19.0.1 || ~19.1.2 || ~19.2.1 @@ -1679,6 +1712,10 @@ packages: resolution: {integrity: sha512-QdWi16+CHB9JYP7gma19OVVg0BFkvU8zNj9GjWorYI8Iv8FUxjOCcYRuAmX4s/h91e4e7BPsskc8cSrZYho9Ew==} engines: {node: '>=12'} + '@expo/spawn-async@1.8.0': + resolution: {integrity: sha512-eb9xxd/LbuEGSdua4NumCu/McVB9EM+F/JxB9pWgnERw4HQ9XyTNH1KapG6oqLWR8TuRK2LQfzJlmNi94CVobw==} + engines: {node: '>=12'} + '@expo/sudo-prompt@9.3.2': resolution: {integrity: sha512-HHQigo3rQWKMDzYDLkubN5WQOYXJJE2eNqIQC2axC2iO3mHdwnIR7FgZVvHWtBwAdzBgAP0ECp8KqS8TiMKvgw==} @@ -2666,8 +2703,8 @@ packages: '@types/node@25.6.0': resolution: {integrity: sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==} - '@types/node@25.9.3': - resolution: {integrity: sha512-603BddQMv3pUcr4U2dhujk83N2tTDVr/34wII2B6bJy6g+8WD6yUb11jszNs0gdi4PesVWl7ABt8nYMVpnLUcg==} + '@types/node@26.1.1': + resolution: {integrity: sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==} '@types/react-native@0.73.0': resolution: {integrity: sha512-6ZRPQrYM72qYKGWidEttRe6M5DZBEV5F+MHMHqd4TTYx0tfkcdrUFGdef6CCxY0jXU7wldvd/zA/b0A/kTeJmA==} @@ -2756,6 +2793,126 @@ packages: resolution: {integrity: sha512-NwjLUnGy8/Zfx23fl50tRC8rYaYnM52xNRYFAXvmiil9yh1+K6aRVQMnzW6gQB/1DLgWt977lYQn7C+wtgXZiA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + '@ungap/structured-clone@1.3.1': resolution: {integrity: sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==} @@ -2842,11 +2999,6 @@ packages: engines: {node: '>=0.4.0'} hasBin: true - acorn@8.17.0: - resolution: {integrity: sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==} - engines: {node: '>=0.4.0'} - hasBin: true - agent-base@6.0.2: resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} engines: {node: '>= 6.0.0'} @@ -3035,6 +3187,21 @@ packages: expo-widgets: optional: true + babel-preset-expo@55.0.23: + resolution: {integrity: sha512-oY+UFcXRLtidYp0JcttzxV5Qxx7KBjBJIShalb+hk4TQoLYafJr4ubpYajLwt7BBgAIVwBdxltKeYeNYXYf02A==} + peerDependencies: + '@babel/runtime': ^7.20.0 + expo: '*' + expo-widgets: ^55.0.20 + react-refresh: '>=0.14.0 <1.0.0' + peerDependenciesMeta: + '@babel/runtime': + optional: true + expo: + optional: true + expo-widgets: + optional: true + babel-preset-jest@29.6.3: resolution: {integrity: sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -3431,8 +3598,8 @@ packages: resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} - dnssd-advertise@1.1.4: - resolution: {integrity: sha512-AmGyK9WpNf06WeP5TjHZq/wNzP76OuEeaiTlKr9E/EEelYLczywUKoqRz+DPRq/ErssjT4lU+/W7wzJW+7K/ZA==} + dnssd-advertise@1.1.6: + resolution: {integrity: sha512-Ndrrf6BMPalkQPd/zubL+4YghH2J9NspapQ09uDXwYbvOPkP0oaqf5CkcwJ0b50kS2O3ul6yVu+jz+RY62Cejg==} doctrine@2.1.0: resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==} @@ -3836,8 +4003,14 @@ packages: expo: '*' react-native: '*' - expo-font@55.0.7: - resolution: {integrity: sha512-oH39Xb+3i6Y69b7YRP+P+5WLx7621t+ep/RAgLwJJYpTjs7CnSohUG+873rEtqsTAuQGi63ms7x9ZeHj1E9LYw==} + expo-file-system@55.0.23: + resolution: {integrity: sha512-XNV/NaPc7Tvd2JIsWkPW8s2vfJUI/Oe4UMX9TmOGpc6cn5BckDw/nn2Qre9lq4btT4FWHJw4SAOHmATShLC0og==} + peerDependencies: + expo: '*' + react-native: '*' + + expo-font@55.0.8: + resolution: {integrity: sha512-WyP75pnKqhLNktYwDn3xKAUNt5rLihRDv8XWGhhz6VEhVqypixpT86NA3uGtiDTlM3gGjhrYCY7o7ypXgCUOZg==} peerDependencies: expo: '*' react: '*' @@ -3905,8 +4078,8 @@ packages: resolution: {integrity: sha512-gtFQzs6wduZxYo4/1udcVLANDvQbVUVFjK1xJjgtZuUBlbJ+xFjQg5wOsQaffUDO3kqrG+DRXt1ihSxK72Wqkg==} hasBin: true - expo-modules-autolinking@55.0.21: - resolution: {integrity: sha512-P9KsJgOwI7JVwxmGfRvcXkXO4LNRvHRdWmb4ukLmX15G/vZ7b6SM17yiYkPceWq1F5KeeZ11KFjEcl0y17xy7w==} + expo-modules-autolinking@55.0.24: + resolution: {integrity: sha512-A0OyMbTPZqibYrwqj98HFYTNSvl4NSS4Zt+R5A8qiAx3nM0mc81e6Iqw7Wl4J8M/t36lJ+cT3WuVTz5Oszj6Hw==} hasBin: true expo-modules-core@55.0.25: @@ -3972,6 +4145,10 @@ packages: peerDependencies: expo: '*' + expo-server@55.0.11: + resolution: {integrity: sha512-AxRdHqcv0H1g4s923vu+5n1Nrhne23bjXbP+Vl7+Lwfpe7MG9PuU1IS95IJK6a+7BVV1mRN6QlZvs8Yv7EEXNQ==} + engines: {node: '>=20.16.0'} + expo-server@55.0.9: resolution: {integrity: sha512-N5Ipn1NwqaJzEm+G97o0Jbe4g/th3R/16N1DabnYryXKCiZwDkK13/w3VfGkQN9LOOaBP+JIRxGf4M8lQKPzyA==} engines: {node: '>=20.16.0'} @@ -4000,8 +4177,8 @@ packages: peerDependencies: expo: '*' - expo@55.0.23: - resolution: {integrity: sha512-b+lKwfzJzFiSm9G0wVGWw3c2YoZyubbl9gHOF1ZFuK8FqtxSge8pDDJMuEFmTi14dbKwh/tirB7MiORq54r7CQ==} + expo@55.0.27: + resolution: {integrity: sha512-uB8fbowkb/Xel2/x4b+cFfg76GGb2lhgaPVdm/ago+QL/852VJP+bUU6LzQVszQFmCTMHCJyrQ4l8enThCnfxw==} hasBin: true peerDependencies: '@expo/dom-webview': '*' @@ -4714,12 +4891,12 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} - js-yaml@3.14.2: - resolution: {integrity: sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==} + js-yaml@3.15.0: + resolution: {integrity: sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==} hasBin: true - js-yaml@4.2.0: - resolution: {integrity: sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==} + js-yaml@4.3.0: + resolution: {integrity: sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==} hasBin: true jsc-safe-url@0.2.4: @@ -5406,10 +5583,6 @@ packages: postcss-value-parser@4.2.0: resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==} - postcss@8.4.49: - resolution: {integrity: sha512-OCVPnIObs4N29kxTjzLfUryOkvZEq+pf8jTF0lg8E7uETuWHA+v7j3c/xJmiqpX450191LlmZfUKkXxkTry7nA==} - engines: {node: ^10 || ^12 || >=14} - postcss@8.5.15: resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==} engines: {node: ^10 || ^12 || >=14} @@ -5768,6 +5941,11 @@ packages: engines: {node: '>=10'} hasBin: true + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + send@0.19.2: resolution: {integrity: sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==} engines: {node: '>= 0.8.0'} @@ -6055,8 +6233,8 @@ packages: engines: {node: '>=10'} hasBin: true - terser@5.48.0: - resolution: {integrity: sha512-J/9An6vs9Us6wKRriSFXBWdRZapREHqFzdNUKk0pmu804EMR6dr6winwo7e5JDxN4xahxQsuysyYFwlwj4XN/Q==} + terser@5.49.0: + resolution: {integrity: sha512-SNiDnXyHSrxVcIOtVbULzcTmniUiwcV7Nwdyj1twVubeTmbjoa8p69KKDpfkdoOavuM4/GRm1+ykI8qqnavHoA==} engines: {node: '>=10'} hasBin: true @@ -6198,6 +6376,11 @@ packages: engines: {node: '>=14.17'} hasBin: true + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + ua-parser-js@1.0.41: resolution: {integrity: sha512-LbBDqdIC5s8iROCUjMbW1f5dJQTEFB1+KO9ogbvlb3nm9n4YHa5p4KTvFPWvh2Hs8gZMBuiB1/8+pdfe/tDPug==} hasBin: true @@ -6209,8 +6392,8 @@ packages: undici-types@7.19.2: resolution: {integrity: sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==} - undici-types@7.24.6: - resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} + undici-types@8.3.0: + resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==} unicode-canonical-property-names-ecmascript@2.0.1: resolution: {integrity: sha512-dA8WbNeb2a6oQzAQ55YlT5vQAWGV9WXOsi3SskE3bcCdM0P4SDd+24zS/OCacdRq5BkdsRj9q3Pg6YyQoxIGqg==} @@ -6282,9 +6465,8 @@ packages: resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==} engines: {node: '>= 0.4.0'} - uuid@7.0.3: - resolution: {integrity: sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==} - deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028). + uuid@11.1.1: + resolution: {integrity: sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==} hasBin: true v8-to-istanbul@9.3.0: @@ -6424,8 +6606,8 @@ packages: resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==} engines: {node: '>=12'} - whatwg-url-minimum@0.1.1: - resolution: {integrity: sha512-u2FNVjFVFZhdjb502KzXy1gKn1mEisQRJssmSJT8CPhZdZa0AP6VCbWlXERKyGu0l09t0k50FiDiralpGhBxgA==} + whatwg-url-minimum@0.1.2: + resolution: {integrity: sha512-XPEm0XFQWNVG292lII1PrRRJl3sItrs7CettZ4ncYxuDVpLyy+NwlGyut2hXI0JswcJUxeCH+CyOJK0ZzAXD6A==} whatwg-url@11.0.0: resolution: {integrity: sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==} @@ -6547,6 +6729,10 @@ packages: resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} engines: {node: '>=12'} + yargs@17.7.3: + resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==} + engines: {node: '>=12'} + yocto-queue@0.1.0: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} @@ -6596,6 +6782,10 @@ snapshots: '@nicolo-ribaudo/chokidar-2': 2.1.8-no-fsevents.3 chokidar: 3.6.0 + '@babel/code-frame@7.10.4': + dependencies: + '@babel/highlight': 7.25.9 + '@babel/code-frame@7.29.0': dependencies: '@babel/helper-validator-identifier': 7.28.5 @@ -6868,6 +7058,13 @@ snapshots: '@babel/template': 7.29.7 '@babel/types': 7.29.7 + '@babel/highlight@7.25.9': + dependencies: + '@babel/helper-validator-identifier': 7.29.7 + chalk: 2.4.2 + js-tokens: 4.0.0 + picocolors: 1.1.1 + '@babel/parser@7.29.3': dependencies: '@babel/types': 7.29.0 @@ -8008,7 +8205,7 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/eslintrc@3.3.5': + '@eslint/eslintrc@3.3.6': dependencies: ajv: 6.15.0 debug: 4.4.3 @@ -8016,7 +8213,7 @@ snapshots: globals: 14.0.0 ignore: 5.3.2 import-fresh: 3.3.1 - js-yaml: 4.2.0 + js-yaml: 4.3.0 minimatch: 3.1.5 strip-json-comments: 3.1.1 transitivePeerDependencies: @@ -8033,24 +8230,24 @@ snapshots: '@expo-google-fonts/material-symbols@0.4.34': {} - '@expo/cli@55.0.29(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-constants@55.0.16)(expo-font@55.0.7)(expo-router@55.0.14)(expo@55.0.23)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3)': + '@expo/cli@55.0.33(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-constants@55.0.16)(expo-font@55.0.8)(expo-router@55.0.14)(expo@55.0.27)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2)': dependencies: '@expo/code-signing-certificates': 0.0.6 - '@expo/config': 55.0.16(typescript@5.9.3) - '@expo/config-plugins': 55.0.8 + '@expo/config': 55.0.18(typescript@7.0.2) + '@expo/config-plugins': 55.0.10 '@expo/devcert': 1.2.1 '@expo/env': 2.1.2 - '@expo/image-utils': 0.8.14(typescript@5.9.3) - '@expo/json-file': 10.0.14 - '@expo/log-box': 55.0.12(@expo/dom-webview@55.0.5)(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + '@expo/image-utils': 0.8.14(typescript@7.0.2) + '@expo/json-file': 10.2.0 + '@expo/log-box': 55.0.12(@expo/dom-webview@55.0.5)(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) '@expo/metro': 55.1.1 - '@expo/metro-config': 55.0.20(expo@55.0.23)(typescript@5.9.3) - '@expo/osascript': 2.4.3 - '@expo/package-manager': 1.10.5 - '@expo/plist': 0.5.3 - '@expo/prebuild-config': 55.0.17(expo@55.0.23)(typescript@5.9.3) - '@expo/require-utils': 55.0.5(typescript@5.9.3) - '@expo/router-server': 55.0.16(@expo/metro-runtime@55.0.10)(expo-constants@55.0.16)(expo-font@55.0.7)(expo-router@55.0.14)(expo-server@55.0.9)(expo@55.0.23)(react-dom@19.2.6(react@19.2.6))(react@19.2.6) + '@expo/metro-config': 55.0.24(expo@55.0.27)(typescript@7.0.2) + '@expo/osascript': 2.7.0 + '@expo/package-manager': 1.13.0 + '@expo/plist': 0.5.4 + '@expo/prebuild-config': 55.0.19(expo@55.0.27)(typescript@7.0.2) + '@expo/require-utils': 55.0.5(typescript@7.0.2) + '@expo/router-server': 55.0.18(@expo/metro-runtime@55.0.10)(expo-constants@55.0.16)(expo-font@55.0.8)(expo-router@55.0.14)(expo-server@55.0.11)(expo@55.0.27)(react-dom@19.2.6(react@19.2.6))(react@19.2.6) '@expo/schema-utils': 55.0.4 '@expo/spawn-async': 1.7.2 '@expo/ws-tunnel': 1.0.6 @@ -8066,9 +8263,9 @@ snapshots: compression: 1.8.1 connect: 3.7.0 debug: 4.4.3 - dnssd-advertise: 1.1.4 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-server: 55.0.9 + dnssd-advertise: 1.1.6 + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-server: 55.0.11 fetch-nodeshim: 0.4.10 getenv: 2.0.0 glob: 13.0.6 @@ -8082,7 +8279,7 @@ snapshots: progress: 2.0.3 prompts: 2.4.2 resolve-from: 5.0.0 - semver: 7.7.4 + semver: 7.8.4 send: 0.19.2 slugify: 1.6.9 source-map-support: 0.5.21 @@ -8094,7 +8291,7 @@ snapshots: ws: 8.21.0 zod: 3.25.76 optionalDependencies: - expo-router: 55.0.14(e0a8113e3689d84edb7af23d00a72ffa) + expo-router: 55.0.14(7ffd97bbc113b875771c40f21f44415d) react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) transitivePeerDependencies: - '@expo/dom-webview' @@ -8113,6 +8310,24 @@ snapshots: dependencies: node-forge: 1.4.0 + '@expo/config-plugins@55.0.10': + dependencies: + '@expo/config-types': 55.0.5 + '@expo/json-file': 10.0.16 + '@expo/plist': 0.5.4 + '@expo/sdk-runtime-versions': 1.0.0 + chalk: 4.1.2 + debug: 4.4.3 + getenv: 2.0.0 + glob: 13.0.6 + resolve-from: 5.0.0 + semver: 7.8.4 + slugify: 1.6.9 + xcode: 3.0.1 + xml2js: 0.6.0 + transitivePeerDependencies: + - supports-color + '@expo/config-plugins@55.0.8': dependencies: '@expo/config-types': 55.0.5 @@ -8149,6 +8364,38 @@ snapshots: - supports-color - typescript + '@expo/config@55.0.16(typescript@7.0.2)': + dependencies: + '@expo/config-plugins': 55.0.8 + '@expo/config-types': 55.0.5 + '@expo/json-file': 10.0.14 + '@expo/require-utils': 55.0.5(typescript@7.0.2) + deepmerge: 4.3.1 + getenv: 2.0.0 + glob: 13.0.6 + resolve-workspace-root: 2.0.1 + semver: 7.7.4 + slugify: 1.6.9 + transitivePeerDependencies: + - supports-color + - typescript + + '@expo/config@55.0.18(typescript@7.0.2)': + dependencies: + '@expo/config-plugins': 55.0.10 + '@expo/config-types': 55.0.5 + '@expo/json-file': 10.2.0 + '@expo/require-utils': 55.0.5(typescript@7.0.2) + deepmerge: 4.3.1 + getenv: 2.0.0 + glob: 13.0.6 + resolve-workspace-root: 2.0.1 + semver: 7.8.4 + slugify: 1.6.9 + transitivePeerDependencies: + - supports-color + - typescript + '@expo/devcert@1.2.1': dependencies: '@expo/sudo-prompt': 9.3.2 @@ -8163,9 +8410,9 @@ snapshots: react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) - '@expo/dom-webview@55.0.5(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': + '@expo/dom-webview@55.0.5(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) @@ -8189,13 +8436,13 @@ snapshots: ignore: 5.3.2 minimatch: 10.2.5 resolve-from: 5.0.0 - semver: 7.7.4 + semver: 7.8.4 transitivePeerDependencies: - supports-color - '@expo/image-utils@0.8.14(typescript@5.9.3)': + '@expo/image-utils@0.8.14(typescript@7.0.2)': dependencies: - '@expo/require-utils': 55.0.5(typescript@5.9.3) + '@expo/require-utils': 55.0.5(typescript@7.0.2) '@expo/spawn-async': 1.7.2 chalk: 4.1.2 getenv: 2.0.0 @@ -8211,40 +8458,55 @@ snapshots: '@babel/code-frame': 7.29.0 json5: 2.2.3 - '@expo/local-build-cache-provider@55.0.12(typescript@5.9.3)': + '@expo/json-file@10.0.16': dependencies: - '@expo/config': 55.0.16(typescript@5.9.3) + '@babel/code-frame': 7.10.4 + json5: 2.2.3 + + '@expo/json-file@10.2.0': + dependencies: + '@babel/code-frame': 7.29.7 + json5: 2.2.3 + + '@expo/json-file@11.0.0': + dependencies: + '@babel/code-frame': 7.29.7 + json5: 2.2.3 + + '@expo/local-build-cache-provider@55.0.14(typescript@7.0.2)': + dependencies: + '@expo/config': 55.0.18(typescript@7.0.2) chalk: 4.1.2 transitivePeerDependencies: - supports-color - typescript - '@expo/log-box@55.0.11(@expo/dom-webview@55.0.5)(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': + '@expo/log-box@55.0.11(@expo/dom-webview@55.0.5)(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': dependencies: - '@expo/dom-webview': 55.0.5(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + '@expo/dom-webview': 55.0.5(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) anser: 1.4.10 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) stacktrace-parser: 0.1.11 - '@expo/log-box@55.0.12(@expo/dom-webview@55.0.5)(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': + '@expo/log-box@55.0.12(@expo/dom-webview@55.0.5)(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': dependencies: - '@expo/dom-webview': 55.0.5(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + '@expo/dom-webview': 55.0.5(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) anser: 1.4.10 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) stacktrace-parser: 0.1.11 - '@expo/metro-config@55.0.20(expo@55.0.23)(typescript@5.9.3)': + '@expo/metro-config@55.0.24(expo@55.0.27)(typescript@7.0.2)': dependencies: - '@babel/code-frame': 7.29.0 + '@babel/code-frame': 7.29.7 '@babel/core': 7.29.7 - '@babel/generator': 7.29.1 - '@expo/config': 55.0.16(typescript@5.9.3) + '@babel/generator': 7.29.7 + '@expo/config': 55.0.18(typescript@7.0.2) '@expo/env': 2.1.2 - '@expo/json-file': 10.0.14 + '@expo/json-file': 10.0.16 '@expo/metro': 55.1.1 '@expo/spawn-async': 1.7.2 browserslist: 4.28.2 @@ -8256,21 +8518,21 @@ snapshots: jsc-safe-url: 0.2.4 lightningcss: 1.32.0 picomatch: 4.0.4 - postcss: 8.4.49 + postcss: 8.5.15 resolve-from: 5.0.0 optionalDependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) transitivePeerDependencies: - bufferutil - supports-color - typescript - utf-8-validate - '@expo/metro-runtime@55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.23)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': + '@expo/metro-runtime@55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.27)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': dependencies: - '@expo/log-box': 55.0.11(@expo/dom-webview@55.0.5)(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + '@expo/log-box': 55.0.11(@expo/dom-webview@55.0.5)(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) anser: 1.4.10 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) pretty-format: 29.7.0 react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) @@ -8306,14 +8568,14 @@ snapshots: dependencies: semver: 5.7.2 - '@expo/osascript@2.4.3': + '@expo/osascript@2.7.0': dependencies: - '@expo/spawn-async': 1.7.2 + '@expo/spawn-async': 1.8.0 - '@expo/package-manager@1.10.5': + '@expo/package-manager@1.13.0': dependencies: - '@expo/json-file': 10.0.14 - '@expo/spawn-async': 1.7.2 + '@expo/json-file': 11.0.0 + '@expo/spawn-async': 1.8.0 chalk: 4.1.2 npm-package-arg: 11.0.3 ora: 3.4.0 @@ -8325,16 +8587,22 @@ snapshots: base64-js: 1.5.1 xmlbuilder: 15.1.1 - '@expo/prebuild-config@55.0.17(expo@55.0.23)(typescript@5.9.3)': + '@expo/plist@0.5.4': dependencies: - '@expo/config': 55.0.16(typescript@5.9.3) + '@xmldom/xmldom': 0.8.13 + base64-js: 1.5.1 + xmlbuilder: 15.1.1 + + '@expo/prebuild-config@55.0.17(expo@55.0.27)(typescript@7.0.2)': + dependencies: + '@expo/config': 55.0.16(typescript@7.0.2) '@expo/config-plugins': 55.0.8 '@expo/config-types': 55.0.5 - '@expo/image-utils': 0.8.14(typescript@5.9.3) + '@expo/image-utils': 0.8.14(typescript@7.0.2) '@expo/json-file': 10.0.14 '@react-native/normalize-colors': 0.83.6 debug: 4.4.3 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) resolve-from: 5.0.0 semver: 7.7.4 xml2js: 0.6.0 @@ -8342,6 +8610,23 @@ snapshots: - supports-color - typescript + '@expo/prebuild-config@55.0.19(expo@55.0.27)(typescript@7.0.2)': + dependencies: + '@expo/config': 55.0.18(typescript@7.0.2) + '@expo/config-plugins': 55.0.10 + '@expo/config-types': 55.0.5 + '@expo/image-utils': 0.8.14(typescript@7.0.2) + '@expo/json-file': 10.2.0 + '@react-native/normalize-colors': 0.83.6 + debug: 4.4.3 + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + resolve-from: 5.0.0 + semver: 7.8.4 + xml2js: 0.6.0 + transitivePeerDependencies: + - supports-color + - typescript + '@expo/require-utils@55.0.5(typescript@5.9.3)': dependencies: '@babel/code-frame': 7.29.0 @@ -8352,17 +8637,27 @@ snapshots: transitivePeerDependencies: - supports-color - '@expo/router-server@55.0.16(@expo/metro-runtime@55.0.10)(expo-constants@55.0.16)(expo-font@55.0.7)(expo-router@55.0.14)(expo-server@55.0.9)(expo@55.0.23)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': + '@expo/require-utils@55.0.5(typescript@7.0.2)': + dependencies: + '@babel/code-frame': 7.29.0 + '@babel/core': 7.29.7 + '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7) + optionalDependencies: + typescript: 7.0.2 + transitivePeerDependencies: + - supports-color + + '@expo/router-server@55.0.18(@expo/metro-runtime@55.0.10)(expo-constants@55.0.16)(expo-font@55.0.8)(expo-router@55.0.14)(expo-server@55.0.11)(expo@55.0.27)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)': dependencies: debug: 4.4.3 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-constants: 55.0.16(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) - expo-font: 55.0.7(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) - expo-server: 55.0.9 + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-constants: 55.0.16(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) + expo-font: 55.0.8(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + expo-server: 55.0.11 react: 19.2.6 optionalDependencies: - '@expo/metro-runtime': 55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.23)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) - expo-router: 55.0.14(e0a8113e3689d84edb7af23d00a72ffa) + '@expo/metro-runtime': 55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.27)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + expo-router: 55.0.14(7ffd97bbc113b875771c40f21f44415d) react-dom: 19.2.6(react@19.2.6) transitivePeerDependencies: - supports-color @@ -8375,11 +8670,15 @@ snapshots: dependencies: cross-spawn: 7.0.6 + '@expo/spawn-async@1.8.0': + dependencies: + cross-spawn: 7.0.6 + '@expo/sudo-prompt@9.3.2': {} - '@expo/vector-icons@15.1.1(expo-font@55.0.7)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': + '@expo/vector-icons@15.1.1(expo-font@55.0.8)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': dependencies: - expo-font: 55.0.7(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + expo-font: 55.0.8(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) @@ -8387,9 +8686,9 @@ snapshots: '@expo/xcpretty@4.4.4': dependencies: - '@babel/code-frame': 7.29.0 + '@babel/code-frame': 7.29.7 chalk: 4.1.2 - js-yaml: 4.2.0 + js-yaml: 4.3.0 '@humanfs/core@0.19.2': dependencies: @@ -8414,7 +8713,7 @@ snapshots: camelcase: 5.3.1 find-up: 4.1.0 get-package-type: 0.1.0 - js-yaml: 3.14.2 + js-yaml: 3.15.0 resolve-from: 5.0.0 '@istanbuljs/schema@0.1.6': {} @@ -8435,14 +8734,14 @@ snapshots: '@jest/test-result': 29.7.0 '@jest/transform': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 25.9.3 + '@types/node': 26.1.1 ansi-escapes: 4.3.2 chalk: 4.1.2 ci-info: 3.9.0 exit: 0.1.2 graceful-fs: 4.2.11 jest-changed-files: 29.7.0 - jest-config: 29.7.0(@types/node@25.9.3) + jest-config: 29.7.0(@types/node@26.1.1) jest-haste-map: 29.7.0 jest-message-util: 29.7.0 jest-regex-util: 29.6.3 @@ -8515,7 +8814,7 @@ snapshots: '@jest/transform': 29.7.0 '@jest/types': 29.6.3 '@jridgewell/trace-mapping': 0.3.31 - '@types/node': 25.9.3 + '@types/node': 26.1.1 chalk: 4.1.2 collect-v8-coverage: 1.0.3 exit: 0.1.2 @@ -8627,9 +8926,9 @@ snapshots: '@nicolo-ribaudo/chokidar-2@2.1.8-no-fsevents.3': optional: true - '@orca/expo-two-way-audio@file:packages/expo-two-way-audio(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': + '@orca/expo-two-way-audio@file:packages/expo-two-way-audio(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)': dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) @@ -9082,7 +9381,7 @@ snapshots: invariant: 2.2.4 nullthrows: 1.1.1 tinyglobby: 0.2.17 - yargs: 17.7.2 + yargs: 17.7.3 '@react-native/community-cli-plugin@0.83.9(@react-native/metro-config@0.85.2(@babel/core@7.29.7))': dependencies: @@ -9324,7 +9623,7 @@ snapshots: '@standard-schema/spec@1.1.0': {} - '@testing-library/react-native@13.3.3(jest@29.7.0(@types/node@25.9.3))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6)': + '@testing-library/react-native@13.3.3(jest@29.7.0(@types/node@26.1.1))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6)': dependencies: jest-matcher-utils: 30.3.0 picocolors: 1.1.1 @@ -9334,7 +9633,7 @@ snapshots: react-test-renderer: 19.2.6(react@19.2.6) redent: 3.0.0 optionalDependencies: - jest: 29.7.0(@types/node@25.9.3) + jest: 29.7.0(@types/node@26.1.1) '@tootallnate/once@2.0.1': {} @@ -9416,9 +9715,9 @@ snapshots: dependencies: undici-types: 7.19.2 - '@types/node@25.9.3': + '@types/node@26.1.1': dependencies: - undici-types: 7.24.6 + undici-types: 8.3.0 '@types/react-native@0.73.0(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)': dependencies: @@ -9460,7 +9759,7 @@ snapshots: '@typescript-eslint/eslint-plugin@8.59.2(@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4)(typescript@5.9.3)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@5.9.3) + '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@7.0.2) '@typescript-eslint/scope-manager': 8.59.2 '@typescript-eslint/type-utils': 8.59.2(eslint@9.39.4)(typescript@5.9.3) '@typescript-eslint/utils': 8.59.2(eslint@9.39.4)(typescript@5.9.3) @@ -9473,7 +9772,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@5.9.3)': + '@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@7.0.2)': dependencies: '@typescript-eslint/scope-manager': 8.59.2 '@typescript-eslint/types': 8.59.2 @@ -9481,7 +9780,7 @@ snapshots: '@typescript-eslint/visitor-keys': 8.59.2 debug: 4.4.3 eslint: 9.39.4 - typescript: 5.9.3 + typescript: 7.0.2 transitivePeerDependencies: - supports-color @@ -9548,6 +9847,66 @@ snapshots: '@typescript-eslint/types': 8.59.2 eslint-visitor-keys: 5.0.1 + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + '@ungap/structured-clone@1.3.1': {} '@vitest/expect@4.1.9': @@ -9559,13 +9918,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.9(vite@8.1.0(@types/node@25.9.3)(esbuild@0.25.4)(terser@5.48.0)(tsx@4.22.4)(yaml@2.9.0))': + '@vitest/mocker@4.1.9(vite@8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))': dependencies: '@vitest/spy': 4.1.9 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 8.1.0(@types/node@25.9.3)(esbuild@0.25.4)(terser@5.48.0)(tsx@4.22.4)(yaml@2.9.0) + vite: 8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0) '@vitest/pretty-format@4.1.9': dependencies: @@ -9626,9 +9985,9 @@ snapshots: acorn: 8.15.0 acorn-walk: 8.3.5 - acorn-jsx@5.3.2(acorn@8.17.0): + acorn-jsx@5.3.2(acorn@8.15.0): dependencies: - acorn: 8.17.0 + acorn: 8.15.0 acorn-walk@8.3.5: dependencies: @@ -9636,8 +9995,6 @@ snapshots: acorn@8.15.0: {} - acorn@8.17.0: {} - agent-base@6.0.2: dependencies: debug: 4.4.3 @@ -9882,7 +10239,7 @@ snapshots: '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/core@7.29.7) '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/core@7.29.7) - babel-preset-expo@55.0.21(@babel/core@7.29.7)(@babel/runtime@7.29.2)(expo@55.0.23)(react-refresh@0.14.2): + babel-preset-expo@55.0.21(@babel/core@7.29.7)(@babel/runtime@7.29.7)(expo@55.0.27)(react-refresh@0.14.2): dependencies: '@babel/generator': 7.29.1 '@babel/helper-module-imports': 7.28.6 @@ -9909,8 +10266,41 @@ snapshots: react-refresh: 0.14.2 resolve-from: 5.0.0 optionalDependencies: - '@babel/runtime': 7.29.2 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + '@babel/runtime': 7.29.7 + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + transitivePeerDependencies: + - '@babel/core' + - supports-color + + babel-preset-expo@55.0.23(@babel/core@7.29.7)(@babel/runtime@7.29.7)(expo@55.0.27)(react-refresh@0.14.2): + dependencies: + '@babel/generator': 7.29.7 + '@babel/helper-module-imports': 7.29.7 + '@babel/plugin-proposal-decorators': 7.29.0(@babel/core@7.29.7) + '@babel/plugin-proposal-export-default-from': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-syntax-export-default-from': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-class-static-block': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/core@7.29.7) + '@babel/plugin-transform-flow-strip-types': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7) + '@babel/plugin-transform-private-methods': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-private-property-in-object': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-runtime': 7.29.7(@babel/core@7.29.7) + '@babel/preset-react': 7.28.5(@babel/core@7.29.7) + '@babel/preset-typescript': 7.28.5(@babel/core@7.29.7) + '@react-native/babel-preset': 0.83.6(@babel/core@7.29.7) + babel-plugin-react-compiler: 1.0.0 + babel-plugin-react-native-web: 0.21.2 + babel-plugin-syntax-hermes-parser: 0.32.1 + babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7) + debug: 4.4.3 + react-refresh: 0.14.2 + resolve-from: 5.0.0 + optionalDependencies: + '@babel/runtime': 7.29.7 + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) transitivePeerDependencies: - '@babel/core' - supports-color @@ -10171,13 +10561,13 @@ snapshots: dependencies: browserslist: 4.28.2 - create-jest@29.7.0(@types/node@25.9.3): + create-jest@29.7.0(@types/node@26.1.1): dependencies: '@jest/types': 29.6.3 chalk: 4.1.2 exit: 0.1.2 graceful-fs: 4.2.11 - jest-config: 29.7.0(@types/node@25.9.3) + jest-config: 29.7.0(@types/node@26.1.1) jest-util: 29.7.0 prompts: 2.4.2 transitivePeerDependencies: @@ -10311,7 +10701,7 @@ snapshots: diff-sequences@29.6.3: {} - dnssd-advertise@1.1.4: {} + dnssd-advertise@1.1.6: {} doctrine@2.1.0: dependencies: @@ -10564,7 +10954,7 @@ snapshots: eslint-config-universe@15.0.4(eslint@9.39.4)(prettier@2.8.8)(typescript@5.9.3): dependencies: '@typescript-eslint/eslint-plugin': 8.59.2(@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4)(typescript@5.9.3) - '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@5.9.3) + '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@7.0.2) eslint: 9.39.4 eslint-config-prettier: 9.1.2(eslint@9.39.4) eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4) @@ -10595,7 +10985,7 @@ snapshots: dependencies: debug: 3.2.7 optionalDependencies: - '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@5.9.3) + '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@7.0.2) eslint: 9.39.4 eslint-import-resolver-node: 0.3.10 transitivePeerDependencies: @@ -10637,7 +11027,7 @@ snapshots: string.prototype.trimend: 1.0.9 tsconfig-paths: 3.15.0 optionalDependencies: - '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@5.9.3) + '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@7.0.2) transitivePeerDependencies: - eslint-import-resolver-typescript - eslint-import-resolver-webpack @@ -10727,7 +11117,7 @@ snapshots: '@eslint/config-array': 0.21.2 '@eslint/config-helpers': 0.4.2 '@eslint/core': 0.17.0 - '@eslint/eslintrc': 3.3.5 + '@eslint/eslintrc': 3.3.6 '@eslint/js': 9.39.4 '@eslint/plugin-kit': 0.4.1 '@humanfs/node': 0.16.8 @@ -10761,8 +11151,8 @@ snapshots: espree@10.4.0: dependencies: - acorn: 8.17.0 - acorn-jsx: 5.3.2(acorn@8.17.0) + acorn: 8.15.0 + acorn-jsx: 5.3.2(acorn@8.15.0) eslint-visitor-keys: 4.2.1 esprima@4.0.1: {} @@ -10811,32 +11201,32 @@ snapshots: jest-message-util: 29.7.0 jest-util: 29.7.0 - expo-application@55.0.14(expo@55.0.23): + expo-application@55.0.14(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) - expo-asset@55.0.17(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3): + expo-asset@55.0.17(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2): dependencies: - '@expo/image-utils': 0.8.14(typescript@5.9.3) - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-constants: 55.0.16(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) + '@expo/image-utils': 0.8.14(typescript@7.0.2) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-constants: 55.0.16(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) transitivePeerDependencies: - supports-color - typescript - expo-build-properties@55.0.13(expo@55.0.23): + expo-build-properties@55.0.13(expo@55.0.27): dependencies: '@expo/schema-utils': 55.0.4 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) resolve-from: 5.0.0 semver: 7.7.4 - expo-camera@55.0.18(@types/emscripten@1.41.5)(expo@55.0.23)(react-native-web@0.21.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): + expo-camera@55.0.18(@types/emscripten@1.41.5)(expo@55.0.27)(react-native-web@0.21.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): dependencies: barcode-detector: 3.1.3(@types/emscripten@1.41.5) - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) optionalDependencies: @@ -10844,92 +11234,97 @@ snapshots: transitivePeerDependencies: - '@types/emscripten' - expo-clipboard@55.0.13(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): + expo-clipboard@55.0.13(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) - expo-constants@55.0.16(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)): + expo-constants@55.0.16(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)): dependencies: '@expo/env': 2.1.2 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) transitivePeerDependencies: - supports-color - expo-crypto@55.0.14(expo@55.0.23): + expo-crypto@55.0.14(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) - expo-dev-client@55.0.35(expo@55.0.23): + expo-dev-client@55.0.35(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-dev-launcher: 55.0.36(expo@55.0.23) - expo-dev-menu: 55.0.30(expo@55.0.23) - expo-dev-menu-interface: 55.0.2(expo@55.0.23) - expo-manifests: 55.0.17(expo@55.0.23) - expo-updates-interface: 55.1.6(expo@55.0.23) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-dev-launcher: 55.0.36(expo@55.0.27) + expo-dev-menu: 55.0.30(expo@55.0.27) + expo-dev-menu-interface: 55.0.2(expo@55.0.27) + expo-manifests: 55.0.17(expo@55.0.27) + expo-updates-interface: 55.1.6(expo@55.0.27) - expo-dev-launcher@55.0.36(expo@55.0.23): + expo-dev-launcher@55.0.36(expo@55.0.27): dependencies: '@expo/schema-utils': 55.0.4 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-dev-menu: 55.0.30(expo@55.0.23) - expo-manifests: 55.0.17(expo@55.0.23) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-dev-menu: 55.0.30(expo@55.0.27) + expo-manifests: 55.0.17(expo@55.0.27) - expo-dev-menu-interface@55.0.2(expo@55.0.23): + expo-dev-menu-interface@55.0.2(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) - expo-dev-menu@55.0.30(expo@55.0.23): + expo-dev-menu@55.0.30(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-dev-menu-interface: 55.0.2(expo@55.0.23) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-dev-menu-interface: 55.0.2(expo@55.0.27) - expo-document-picker@55.0.13(expo@55.0.23): + expo-document-picker@55.0.13(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + + expo-file-system@55.0.19(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)): + dependencies: + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) - expo-file-system@55.0.19(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)): + expo-file-system@55.0.23(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) - expo-font@55.0.7(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): + expo-font@55.0.8(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) fontfaceobserver: 2.3.0 react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) - expo-glass-effect@55.0.11(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): + expo-glass-effect@55.0.11(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) - expo-haptics@55.0.14(expo@55.0.23): + expo-haptics@55.0.14(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) - expo-image-loader@55.0.1(expo@55.0.23): + expo-image-loader@55.0.1(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) - expo-image-manipulator@55.0.17(expo@55.0.23): + expo-image-manipulator@55.0.17(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-image-loader: 55.0.1(expo@55.0.23) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-image-loader: 55.0.1(expo@55.0.27) - expo-image-picker@55.0.20(expo@55.0.23): + expo-image-picker@55.0.20(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-image-loader: 55.0.1(expo@55.0.23) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-image-loader: 55.0.1(expo@55.0.27) - expo-image@55.0.10(expo@55.0.23)(react-native-web@0.21.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): + expo-image@55.0.10(expo@55.0.27)(react-native-web@0.21.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) sf-symbols-typescript: 2.2.0 @@ -10938,14 +11333,14 @@ snapshots: expo-json-utils@55.0.2: {} - expo-keep-awake@55.0.8(expo@55.0.23)(react@19.2.6): + expo-keep-awake@55.0.8(expo@55.0.27)(react@19.2.6): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react: 19.2.6 - expo-linking@55.0.15(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): + expo-linking@55.0.15(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): dependencies: - expo-constants: 55.0.16(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) + expo-constants: 55.0.16(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) invariant: 2.2.4 react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) @@ -10953,12 +11348,12 @@ snapshots: - expo - supports-color - expo-manifests@55.0.17(expo@55.0.23): + expo-manifests@55.0.17(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) expo-json-utils: 55.0.2 - expo-module-scripts@55.0.2(@babel/core@7.29.7)(@babel/runtime@7.29.2)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(eslint@9.39.4)(expo@55.0.23)(jest@29.7.0(@types/node@25.9.3))(prettier@2.8.8)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-refresh@0.14.2)(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6): + expo-module-scripts@55.0.2(@babel/core@7.29.7)(@babel/runtime@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(eslint@9.39.4)(expo@55.0.27)(jest@29.7.0(@types/node@26.1.1))(prettier@2.8.8)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-refresh@0.14.2)(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6): dependencies: '@babel/cli': 7.28.6(@babel/core@7.29.7) '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/core@7.29.7) @@ -10966,19 +11361,19 @@ snapshots: '@babel/preset-typescript': 7.28.5(@babel/core@7.29.7) '@expo/npm-proofread': 1.0.1 '@expo/spawn-async': 1.7.2 - '@testing-library/react-native': 13.3.3(jest@29.7.0(@types/node@25.9.3))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6) + '@testing-library/react-native': 13.3.3(jest@29.7.0(@types/node@26.1.1))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6) '@tsconfig/node18': 18.2.6 '@types/jest': 29.5.14 babel-plugin-dynamic-import-node: 2.3.3 - babel-preset-expo: 55.0.21(@babel/core@7.29.7)(@babel/runtime@7.29.2)(expo@55.0.23)(react-refresh@0.14.2) + babel-preset-expo: 55.0.21(@babel/core@7.29.7)(@babel/runtime@7.29.7)(expo@55.0.27)(react-refresh@0.14.2) commander: 12.1.0 eslint-config-universe: 15.0.4(eslint@9.39.4)(prettier@2.8.8)(typescript@5.9.3) glob: 13.0.6 - jest-expo: 55.0.17(@babel/core@7.29.7)(expo@55.0.23)(jest@29.7.0(@types/node@25.9.3))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + jest-expo: 55.0.17(@babel/core@7.29.7)(expo@55.0.27)(jest@29.7.0(@types/node@26.1.1))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) jest-snapshot-prettier: prettier@2.8.8 - jest-watch-typeahead: 2.2.1(jest@29.7.0(@types/node@25.9.3)) + jest-watch-typeahead: 2.2.1(jest@29.7.0(@types/node@26.1.1)) resolve-workspace-root: 2.0.1 - ts-jest: 29.0.5(@babel/core@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(jest@29.7.0(@types/node@25.9.3))(typescript@5.9.3) + ts-jest: 29.0.5(@babel/core@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(jest@29.7.0(@types/node@26.1.1))(typescript@5.9.3) typescript: 5.9.3 transitivePeerDependencies: - '@babel/core' @@ -11004,9 +11399,9 @@ snapshots: - supports-color - utf-8-validate - expo-modules-autolinking@55.0.21(typescript@5.9.3): + expo-modules-autolinking@55.0.24(typescript@7.0.2): dependencies: - '@expo/require-utils': 55.0.5(typescript@5.9.3) + '@expo/require-utils': 55.0.5(typescript@7.0.2) '@expo/spawn-async': 1.7.2 chalk: 4.1.2 commander: 7.2.0 @@ -11022,29 +11417,29 @@ snapshots: optionalDependencies: react-native-worklets: 0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) - expo-network@55.0.14(expo@55.0.23)(react@19.2.6): + expo-network@55.0.14(expo@55.0.27)(react@19.2.6): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) react: 19.2.6 - expo-notifications@55.0.22(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3): + expo-notifications@55.0.22(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2): dependencies: - '@expo/image-utils': 0.8.14(typescript@5.9.3) + '@expo/image-utils': 0.8.14(typescript@7.0.2) abort-controller: 3.0.0 badgin: 1.2.3 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-application: 55.0.14(expo@55.0.23) - expo-constants: 55.0.16(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-application: 55.0.14(expo@55.0.27) + expo-constants: 55.0.16(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) transitivePeerDependencies: - supports-color - typescript - expo-router@55.0.14(e0a8113e3689d84edb7af23d00a72ffa): + expo-router@55.0.14(7ffd97bbc113b875771c40f21f44415d): dependencies: - '@expo/log-box': 55.0.12(@expo/dom-webview@55.0.5)(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) - '@expo/metro-runtime': 55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.23)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + '@expo/log-box': 55.0.12(@expo/dom-webview@55.0.5)(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + '@expo/metro-runtime': 55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.27)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) '@expo/schema-utils': 55.0.4 '@radix-ui/react-slot': 1.2.4(@types/react@19.2.14)(react@19.2.6) '@radix-ui/react-tabs': 1.1.13(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6) @@ -11054,13 +11449,13 @@ snapshots: client-only: 0.0.1 debug: 4.4.3 escape-string-regexp: 4.0.0 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-constants: 55.0.16(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) - expo-glass-effect: 55.0.11(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) - expo-image: 55.0.10(expo@55.0.23)(react-native-web@0.21.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) - expo-linking: 55.0.15(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-constants: 55.0.16(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) + expo-glass-effect: 55.0.11(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + expo-image: 55.0.10(expo@55.0.27)(react-native-web@0.21.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + expo-linking: 55.0.15(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) expo-server: 55.0.9 - expo-symbols: 55.0.8(expo-font@55.0.7)(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + expo-symbols: 55.0.8(expo-font@55.0.8)(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) fast-deep-equal: 3.1.3 invariant: 2.2.4 nanoid: 3.3.12 @@ -11078,7 +11473,7 @@ snapshots: use-latest-callback: 0.2.6(react@19.2.6) vaul: 1.1.2(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6) optionalDependencies: - '@testing-library/react-native': 13.3.3(jest@29.7.0(@types/node@25.9.3))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6) + '@testing-library/react-native': 13.3.3(jest@29.7.0(@types/node@26.1.1))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6) react-dom: 19.2.6(react@19.2.6) react-native-gesture-handler: 2.31.2(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) react-native-reanimated: 4.3.0(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) @@ -11090,16 +11485,18 @@ snapshots: - expo-font - supports-color - expo-secure-store@55.0.13(expo@55.0.23): + expo-secure-store@55.0.13(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + + expo-server@55.0.11: {} expo-server@55.0.9: {} - expo-splash-screen@55.0.20(expo@55.0.23)(typescript@5.9.3): + expo-splash-screen@55.0.20(expo@55.0.27)(typescript@7.0.2): dependencies: - '@expo/prebuild-config': 55.0.17(expo@55.0.23)(typescript@5.9.3) - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + '@expo/prebuild-config': 55.0.17(expo@55.0.27)(typescript@7.0.2) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) transitivePeerDependencies: - supports-color - typescript @@ -11110,49 +11507,49 @@ snapshots: react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) react-native-is-edge-to-edge: 1.3.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) - expo-symbols@55.0.8(expo-font@55.0.7)(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): + expo-symbols@55.0.8(expo-font@55.0.8)(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): dependencies: '@expo-google-fonts/material-symbols': 0.4.34 - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-font: 55.0.7(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-font: 55.0.8(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) sf-symbols-typescript: 2.2.0 - expo-updates-interface@55.1.6(expo@55.0.23): + expo-updates-interface@55.1.6(expo@55.0.27): dependencies: - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) - expo@55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3): + expo@55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2): dependencies: - '@babel/runtime': 7.29.2 - '@expo/cli': 55.0.29(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-constants@55.0.16)(expo-font@55.0.7)(expo-router@55.0.14)(expo@55.0.23)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - '@expo/config': 55.0.16(typescript@5.9.3) - '@expo/config-plugins': 55.0.8 + '@babel/runtime': 7.29.7 + '@expo/cli': 55.0.33(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-constants@55.0.16)(expo-font@55.0.8)(expo-router@55.0.14)(expo@55.0.27)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + '@expo/config': 55.0.18(typescript@7.0.2) + '@expo/config-plugins': 55.0.10 '@expo/devtools': 55.0.3(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) '@expo/fingerprint': 0.16.7 - '@expo/local-build-cache-provider': 55.0.12(typescript@5.9.3) - '@expo/log-box': 55.0.12(@expo/dom-webview@55.0.5)(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + '@expo/local-build-cache-provider': 55.0.14(typescript@7.0.2) + '@expo/log-box': 55.0.12(@expo/dom-webview@55.0.5)(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) '@expo/metro': 55.1.1 - '@expo/metro-config': 55.0.20(expo@55.0.23)(typescript@5.9.3) - '@expo/vector-icons': 15.1.1(expo-font@55.0.7)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + '@expo/metro-config': 55.0.24(expo@55.0.27)(typescript@7.0.2) + '@expo/vector-icons': 15.1.1(expo-font@55.0.8)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) '@ungap/structured-clone': 1.3.1 - babel-preset-expo: 55.0.21(@babel/core@7.29.7)(@babel/runtime@7.29.2)(expo@55.0.23)(react-refresh@0.14.2) - expo-asset: 55.0.17(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) - expo-constants: 55.0.16(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) - expo-file-system: 55.0.19(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) - expo-font: 55.0.7(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) - expo-keep-awake: 55.0.8(expo@55.0.23)(react@19.2.6) - expo-modules-autolinking: 55.0.21(typescript@5.9.3) + babel-preset-expo: 55.0.23(@babel/core@7.29.7)(@babel/runtime@7.29.7)(expo@55.0.27)(react-refresh@0.14.2) + expo-asset: 55.0.17(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) + expo-constants: 55.0.16(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) + expo-file-system: 55.0.23(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6)) + expo-font: 55.0.8(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + expo-keep-awake: 55.0.8(expo@55.0.27)(react@19.2.6) + expo-modules-autolinking: 55.0.24(typescript@7.0.2) expo-modules-core: 55.0.25(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) pretty-format: 29.7.0 react: 19.2.6 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) react-refresh: 0.14.2 - whatwg-url-minimum: 0.1.1 + whatwg-url-minimum: 0.1.2 optionalDependencies: - '@expo/dom-webview': 55.0.5(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) - '@expo/metro-runtime': 55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.23)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + '@expo/dom-webview': 55.0.5(expo@55.0.27)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) + '@expo/metro-runtime': 55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.27)(react-dom@19.2.6(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) react-native-webview: 13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) transitivePeerDependencies: - '@babel/core' @@ -11670,7 +12067,7 @@ snapshots: '@babel/parser': 7.29.7 '@istanbuljs/schema': 0.1.6 istanbul-lib-coverage: 3.2.2 - semver: 7.8.4 + semver: 7.8.5 transitivePeerDependencies: - supports-color @@ -11714,7 +12111,7 @@ snapshots: '@jest/expect': 29.7.0 '@jest/test-result': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 25.9.3 + '@types/node': 26.1.1 chalk: 4.1.2 co: 4.6.0 dedent: 1.7.2 @@ -11734,26 +12131,26 @@ snapshots: - babel-plugin-macros - supports-color - jest-cli@29.7.0(@types/node@25.9.3): + jest-cli@29.7.0(@types/node@26.1.1): dependencies: '@jest/core': 29.7.0 '@jest/test-result': 29.7.0 '@jest/types': 29.6.3 chalk: 4.1.2 - create-jest: 29.7.0(@types/node@25.9.3) + create-jest: 29.7.0(@types/node@26.1.1) exit: 0.1.2 import-local: 3.2.0 - jest-config: 29.7.0(@types/node@25.9.3) + jest-config: 29.7.0(@types/node@26.1.1) jest-util: 29.7.0 jest-validate: 29.7.0 - yargs: 17.7.2 + yargs: 17.7.3 transitivePeerDependencies: - '@types/node' - babel-plugin-macros - supports-color - ts-node - jest-config@29.7.0(@types/node@25.9.3): + jest-config@29.7.0(@types/node@26.1.1): dependencies: '@babel/core': 7.29.7 '@jest/test-sequencer': 29.7.0 @@ -11778,7 +12175,7 @@ snapshots: slash: 3.0.0 strip-json-comments: 3.1.1 optionalDependencies: - '@types/node': 25.9.3 + '@types/node': 26.1.1 transitivePeerDependencies: - babel-plugin-macros - supports-color @@ -11833,18 +12230,18 @@ snapshots: jest-mock: 29.7.0 jest-util: 29.7.0 - jest-expo@55.0.17(@babel/core@7.29.7)(expo@55.0.23)(jest@29.7.0(@types/node@25.9.3))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3): + jest-expo@55.0.17(@babel/core@7.29.7)(expo@55.0.27)(jest@29.7.0(@types/node@26.1.1))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3): dependencies: '@expo/config': 55.0.16(typescript@5.9.3) '@expo/json-file': 10.0.14 '@jest/create-cache-key-function': 29.7.0 '@jest/globals': 29.7.0 babel-jest: 29.7.0(@babel/core@7.29.7) - expo: 55.0.23(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo: 55.0.27(@babel/core@7.29.7)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@7.0.2) jest-environment-jsdom: 29.7.0 jest-snapshot: 29.7.0 jest-watch-select-projects: 2.0.0 - jest-watch-typeahead: 2.2.1(jest@29.7.0(@types/node@25.9.3)) + jest-watch-typeahead: 2.2.1(jest@29.7.0(@types/node@26.1.1)) json5: 2.2.3 lodash: 4.18.1 react-native: 0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6) @@ -11948,7 +12345,7 @@ snapshots: '@jest/test-result': 29.7.0 '@jest/transform': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 25.9.3 + '@types/node': 26.1.1 chalk: 4.1.2 emittery: 0.13.1 graceful-fs: 4.2.11 @@ -11976,7 +12373,7 @@ snapshots: '@jest/test-result': 29.7.0 '@jest/transform': 29.7.0 '@jest/types': 29.6.3 - '@types/node': 25.9.3 + '@types/node': 26.1.1 chalk: 4.1.2 cjs-module-lexer: 1.4.3 collect-v8-coverage: 1.0.3 @@ -12043,11 +12440,11 @@ snapshots: chalk: 3.0.0 prompts: 2.4.2 - jest-watch-typeahead@2.2.1(jest@29.7.0(@types/node@25.9.3)): + jest-watch-typeahead@2.2.1(jest@29.7.0(@types/node@26.1.1)): dependencies: ansi-escapes: 6.2.1 chalk: 4.1.2 - jest: 29.7.0(@types/node@25.9.3) + jest: 29.7.0(@types/node@26.1.1) jest-regex-util: 29.6.3 jest-watcher: 29.7.0 slash: 5.1.0 @@ -12072,12 +12469,12 @@ snapshots: merge-stream: 2.0.0 supports-color: 8.1.1 - jest@29.7.0(@types/node@25.9.3): + jest@29.7.0(@types/node@26.1.1): dependencies: '@jest/core': 29.7.0 '@jest/types': 29.6.3 import-local: 3.2.0 - jest-cli: 29.7.0(@types/node@25.9.3) + jest-cli: 29.7.0(@types/node@26.1.1) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -12088,12 +12485,12 @@ snapshots: js-tokens@4.0.0: {} - js-yaml@3.14.2: + js-yaml@3.15.0: dependencies: argparse: 1.0.10 esprima: 4.0.1 - js-yaml@4.2.0: + js-yaml@4.3.0: dependencies: argparse: 2.0.1 @@ -12285,7 +12682,7 @@ snapshots: make-dir@4.0.0: dependencies: - semver: 7.8.4 + semver: 7.8.5 make-error@1.3.6: {} @@ -12433,7 +12830,7 @@ snapshots: metro-minify-terser@0.84.4: dependencies: flow-enums-runtime: 0.0.6 - terser: 5.48.0 + terser: 5.49.0 metro-resolver@0.83.7: dependencies: @@ -12651,7 +13048,7 @@ snapshots: source-map: 0.5.7 throat: 5.0.0 ws: 7.5.11 - yargs: 17.7.2 + yargs: 17.7.3 transitivePeerDependencies: - bufferutil - supports-color @@ -12735,7 +13132,7 @@ snapshots: dependencies: hosted-git-info: 7.0.2 proc-log: 4.2.0 - semver: 7.7.4 + semver: 7.8.4 validate-npm-package-name: 5.0.1 npm-run-path@4.0.1: @@ -12985,12 +13382,6 @@ snapshots: postcss-value-parser@4.2.0: {} - postcss@8.4.49: - dependencies: - nanoid: 3.3.12 - picocolors: 1.1.1 - source-map-js: 1.2.1 - postcss@8.5.15: dependencies: nanoid: 3.3.12 @@ -13423,6 +13814,8 @@ snapshots: semver@7.8.4: {} + semver@7.8.5: {} + send@0.19.2: dependencies: debug: 2.6.9 @@ -13737,10 +14130,10 @@ snapshots: commander: 2.20.3 source-map-support: 0.5.21 - terser@5.48.0: + terser@5.49.0: dependencies: '@jridgewell/source-map': 0.3.11 - acorn: 8.17.0 + acorn: 8.15.0 commander: 2.20.3 source-map-support: 0.5.21 @@ -13797,11 +14190,11 @@ snapshots: picomatch: 4.0.4 typescript: 5.9.3 - ts-jest@29.0.5(@babel/core@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(jest@29.7.0(@types/node@25.9.3))(typescript@5.9.3): + ts-jest@29.0.5(@babel/core@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(jest@29.7.0(@types/node@26.1.1))(typescript@5.9.3): dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 - jest: 29.7.0(@types/node@25.9.3) + jest: 29.7.0(@types/node@26.1.1) jest-util: 29.7.0 json5: 2.2.3 lodash.memoize: 4.1.2 @@ -13881,6 +14274,29 @@ snapshots: typescript@5.9.3: {} + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + ua-parser-js@1.0.41: {} unbox-primitive@1.1.0: @@ -13892,7 +14308,7 @@ snapshots: undici-types@7.19.2: {} - undici-types@7.24.6: {} + undici-types@8.3.0: {} unicode-canonical-property-names-ecmascript@2.0.1: {} @@ -13949,7 +14365,7 @@ snapshots: utils-merge@1.0.1: {} - uuid@7.0.3: {} + uuid@11.1.1: {} v8-to-istanbul@9.3.0: dependencies: @@ -13970,7 +14386,7 @@ snapshots: - '@types/react' - '@types/react-dom' - vite@8.1.0(@types/node@25.9.3)(esbuild@0.25.4)(terser@5.48.0)(tsx@4.22.4)(yaml@2.9.0): + vite@8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0): dependencies: lightningcss: 1.32.0 picomatch: 4.0.4 @@ -13978,17 +14394,17 @@ snapshots: rolldown: 1.1.3 tinyglobby: 0.2.17 optionalDependencies: - '@types/node': 25.9.3 + '@types/node': 26.1.1 esbuild: 0.25.4 fsevents: 2.3.3 - terser: 5.48.0 + terser: 5.49.0 tsx: 4.22.4 yaml: 2.9.0 - vitest@4.1.9(@types/node@25.9.3)(jsdom@20.0.3)(vite@8.1.0(@types/node@25.9.3)(esbuild@0.25.4)(terser@5.48.0)(tsx@4.22.4)(yaml@2.9.0)): + vitest@4.1.9(@types/node@26.1.1)(jsdom@20.0.3)(vite@8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0)): dependencies: '@vitest/expect': 4.1.9 - '@vitest/mocker': 4.1.9(vite@8.1.0(@types/node@25.9.3)(esbuild@0.25.4)(terser@5.48.0)(tsx@4.22.4)(yaml@2.9.0)) + '@vitest/mocker': 4.1.9(vite@8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0)) '@vitest/pretty-format': 4.1.9 '@vitest/runner': 4.1.9 '@vitest/snapshot': 4.1.9 @@ -14005,10 +14421,10 @@ snapshots: tinyexec: 1.1.2 tinyglobby: 0.2.17 tinyrainbow: 3.1.0 - vite: 8.1.0(@types/node@25.9.3)(esbuild@0.25.4)(terser@5.48.0)(tsx@4.22.4)(yaml@2.9.0) + vite: 8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: - '@types/node': 25.9.3 + '@types/node': 26.1.1 jsdom: 20.0.3 transitivePeerDependencies: - msw @@ -14041,7 +14457,7 @@ snapshots: whatwg-mimetype@3.0.0: {} - whatwg-url-minimum@0.1.1: {} + whatwg-url-minimum@0.1.2: {} whatwg-url@11.0.0: dependencies: @@ -14125,7 +14541,7 @@ snapshots: xcode@3.0.1: dependencies: simple-plist: 1.3.1 - uuid: 7.0.3 + uuid: 11.1.1 xml-name-validator@4.0.0: {} @@ -14160,6 +14576,16 @@ snapshots: y18n: 5.0.8 yargs-parser: 21.1.1 + yargs@17.7.3: + dependencies: + cliui: 8.0.1 + escalade: 3.2.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 21.1.1 + yocto-queue@0.1.0: {} zod@3.25.76: {} diff --git a/mobile/src/agent-history/MobileAgentSessionHistoryIcon.tsx b/mobile/src/agent-history/MobileAgentSessionHistoryIcon.tsx new file mode 100644 index 000000000000..75a4409d5a0e --- /dev/null +++ b/mobile/src/agent-history/MobileAgentSessionHistoryIcon.tsx @@ -0,0 +1,48 @@ +import Svg, { Path } from 'react-native-svg' + +type MobileAgentSessionHistoryIconProps = { + size?: number + color?: string + strokeWidth?: number +} + +export function MobileAgentSessionHistoryIcon({ + size = 18, + color = '#000000', + strokeWidth = 2 +}: MobileAgentSessionHistoryIconProps) { + return ( + + {/* Why: desktop uses Tabler's category glyph for Agent Session History. */} + + + + + + + ) +} diff --git a/mobile/src/agent-history/MobileAgentSessionHistoryList.tsx b/mobile/src/agent-history/MobileAgentSessionHistoryList.tsx new file mode 100644 index 000000000000..9bc7ceedd911 --- /dev/null +++ b/mobile/src/agent-history/MobileAgentSessionHistoryList.tsx @@ -0,0 +1,177 @@ +import { useCallback, useMemo, useState } from 'react' +import { ActivityIndicator, Pressable, RefreshControl, SectionList, Text, View } from 'react-native' +import { Play } from 'lucide-react-native' +import { colors } from '../theme/mobile-theme' +import { MobileAgentIcon } from '../components/MobileAgentIcon' +import { recentSessionConversationTurns } from '../../../src/shared/ai-vault-session-display' +import type { AiVaultSession } from '../../../src/shared/ai-vault-types' +import type { MobileAgentHistorySection } from './agent-history-sections' +import type { MobileAgentHistoryCard } from './agent-history-session-card' +import { styles } from './agent-history-styles' + +// Lazy-render at most this many preview turns when a card is tapped — the +// scanner already bounds preview text, but rendering them only on tap keeps the +// list cheap. +const PREVIEW_TURN_LIMIT = 5 + +type Props = { + sections: MobileAgentHistorySection[] + sessionsById: ReadonlyMap + refreshing: boolean + showCurrentWorktreeBadges: boolean + resumeActionStateBySessionId?: ReadonlyMap + onResume?: (session: AiVaultSession) => void | Promise + onRefresh: () => void +} + +export function MobileAgentSessionHistoryList({ + sections, + sessionsById, + refreshing, + showCurrentWorktreeBadges, + resumeActionStateBySessionId, + onResume, + onRefresh +}: Props) { + const [expandedId, setExpandedId] = useState(null) + + const toggleExpanded = useCallback((id: string) => { + setExpandedId((prev) => (prev === id ? null : id)) + }, []) + + const renderItem = useCallback( + ({ item }: { item: MobileAgentHistoryCard }) => ( + toggleExpanded(item.id)} + /> + ), + [ + expandedId, + onResume, + resumeActionStateBySessionId, + sessionsById, + showCurrentWorktreeBadges, + toggleExpanded + ] + ) + + return ( + card.id} + stickySectionHeadersEnabled={false} + contentContainerStyle={styles.list} + refreshControl={ + + } + renderSectionHeader={({ section }) => ( + + + {section.label} + + {section.data.length} + + )} + renderItem={renderItem} + /> + ) +} + +function AgentHistoryCardRow({ + card, + expanded, + session, + showCurrentWorktreeBadge, + resumeActionState, + onResume, + onPress +}: { + card: MobileAgentHistoryCard + expanded: boolean + session: AiVaultSession | null + showCurrentWorktreeBadge: boolean + resumeActionState?: { disabled: boolean; loading: boolean } + onResume?: (session: AiVaultSession) => void | Promise + onPress: () => void +}) { + const previewTurns = useMemo( + () => (expanded && session ? recentSessionConversationTurns(session, PREVIEW_TURN_LIMIT) : []), + [expanded, session] + ) + + return ( + [styles.card, pressed && styles.cardPressed]} + onPress={onPress} + > + + + + {card.title} + + {card.timeAgo ? {card.timeAgo} : null} + + {card.lastMessage ? ( + + {card.lastMessage} + + ) : null} + + {card.agentLabel} + + {card.messageCount} {card.messageCount === 1 ? 'message' : 'messages'} + + {showCurrentWorktreeBadge && card.isCurrentWorktree ? ( + + current worktree + + ) : null} + {session && onResume ? ( + [ + styles.resumeButton, + resumeActionState?.disabled && styles.resumeButtonDisabled, + pressed && !resumeActionState?.disabled && styles.resumeButtonPressed + ]} + onPress={(event) => { + event.stopPropagation() + if (!resumeActionState?.disabled) { + void onResume(session) + } + }} + disabled={resumeActionState?.disabled} + hitSlop={8} + accessibilityRole="button" + accessibilityLabel="Resume agent session" + > + {resumeActionState?.loading ? ( + + ) : ( + + )} + + ) : null} + + {expanded && previewTurns.length > 0 ? ( + + {previewTurns.map((turn, index) => ( + + {turn.role} + {turn.text} + + ))} + + ) : null} + + ) +} diff --git a/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx b/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx new file mode 100644 index 000000000000..8879b7836875 --- /dev/null +++ b/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx @@ -0,0 +1,421 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { ActivityIndicator, Pressable, Text, TextInput, View } from 'react-native' +import { SafeAreaView } from 'react-native-safe-area-context' +import { useRouter } from 'expo-router' +import { ChevronLeft, RefreshCw } from 'lucide-react-native' +import { colors } from '../theme/mobile-theme' +import { useHostClient } from '../transport/client-context' +import type { RpcSuccess } from '../transport/types' +import type { RpcClient } from '../transport/rpc-client' +import { getWorktreeLabel } from '../session/worktree-label' +import { + buildMobileAiVaultResumeLaunch, + createMobileAiVaultResumeMutationRegistry, + readMobileRuntimeHostPlatform, + readMobileRuntimeTerminalWindowsShell, + resolveMobileAiVaultResumePlatform, + resumeAiVaultSessionInTerminal, + RESUME_RPC_TIMEOUT_MS, + type MobileAiVaultResumeSettings +} from '../session/ai-vault-resume-launch' +import { triggerError, triggerSuccess } from '../platform/haptics' +import type { AiVaultScope, AiVaultSession } from '../../../src/shared/ai-vault-types' +import type { Worktree } from '../worktree/workspace-list-types' +import { useMobileAgentHistoryState } from './use-mobile-agent-history-state' +import { buildMobileAgentHistorySections } from './agent-history-sections' +import { shouldShowMobileCurrentWorktreeBadge } from './agent-history-current-worktree-badge' +import { MobileAgentSessionHistoryList } from './MobileAgentSessionHistoryList' +import { + resolveMobileAiVaultSessionResumeTarget, + type MobileAiVaultResumeFolderWorkspace, + type MobileAiVaultResumeProjectGroup, + type MobileAiVaultResumeRepo +} from './agent-history-resume-target' +import { buildMobileAgentHistoryResumeActionState } from './agent-history-session-card' +import { styles } from './agent-history-styles' + +export type MobileAgentSessionHistoryPanelProps = { + hostId: string + worktreeId: string + name?: string +} + +const SCOPE_TABS: { scope: AiVaultScope; label: string }[] = [ + { scope: 'workspace', label: 'Workspace' }, + { scope: 'project', label: 'Project' }, + { scope: 'all', label: 'All' } +] + +export function MobileAgentSessionHistoryPanel({ + hostId, + worktreeId, + name = '' +}: MobileAgentSessionHistoryPanelProps) { + const router = useRouter() + const { client, state: connState } = useHostClient(hostId) + const [worktrees, setWorktrees] = useState([]) + const [worktreesLoaded, setWorktreesLoaded] = useState(false) + const [query, setQuery] = useState('') + const [resumingSessionId, setResumingSessionId] = useState(null) + const [resumeMessage, setResumeMessage] = useState(null) + const resumeLaunchInFlightRef = useRef(false) + const resumeMutationRegistryRef = useRef( + createMobileAiVaultResumeMutationRegistry(createMobileAiVaultResumeMutationId) + ) + const worktreeLabel = getWorktreeLabel(name, worktreeId) + + // Why: the worktree list seeds the host-local scopePaths derivation and the + // active-worktree path for the "current worktree" badge. + useEffect(() => { + if (!client || connState !== 'connected') { + return + } + let cancelled = false + void (async () => { + try { + const worktreeResponse = await client.sendRequest('worktree.ps', { limit: 10000 }) + if (cancelled) { + return + } + if (worktreeResponse.ok) { + const result = (worktreeResponse as RpcSuccess).result as { worktrees: Worktree[] } + setWorktrees(result.worktrees) + } + } catch { + // Why: worktree list is best-effort context; the session scan still runs + // (without it, scoped tabs can't narrow and fall back to the full list). + } finally { + // Why: mark loaded even on failure so a scoped tab proceeds with an + // unscoped fetch instead of holding a spinner forever. + if (!cancelled) { + setWorktreesLoaded(true) + } + } + })() + return () => { + cancelled = true + } + }, [client, connState]) + + const { + scope, + screenState, + refreshing, + hostStatusResult, + activeWorktreePath, + scopeFilterPaths, + onSelectScope, + onRefresh, + retry + } = useMobileAgentHistoryState({ hostId, worktreeId, worktrees, worktreesLoaded }) + + const sessions = screenState.kind === 'ready' ? screenState.sessions : EMPTY_SESSIONS + const issues = screenState.kind === 'ready' ? screenState.issues : EMPTY_ISSUES + const sessionsById = useMemo( + () => new Map(sessions.map((session) => [session.id, session])), + [sessions] + ) + const sections = useMemo( + () => + buildMobileAgentHistorySections(sessions, { + query, + scope, + scopeFilterPaths, + activeWorktreePath, + now: Date.now() + }), + [sessions, query, scope, scopeFilterPaths, activeWorktreePath] + ) + + const hostPlatform = useMemo( + () => readMobileRuntimeHostPlatform(hostStatusResult), + [hostStatusResult] + ) + const hostTerminalWindowsShell = useMemo( + () => readMobileRuntimeTerminalWindowsShell(hostStatusResult), + [hostStatusResult] + ) + + const resumeActionStateBySessionId = useMemo( + () => buildMobileAgentHistoryResumeActionState(sessions, resumingSessionId), + [resumingSessionId, sessions] + ) + + const onResumeSession = useCallback( + async (session: AiVaultSession): Promise => { + if (resumeLaunchInFlightRef.current) { + return + } + if (!client || connState !== 'connected') { + setResumeMessage('Waiting for host...') + triggerError() + return + } + if (!session.sessionId) { + setResumeMessage('This session is missing a resume id.') + triggerError() + return + } + + resumeLaunchInFlightRef.current = true + setResumingSessionId(session.id) + setResumeMessage(null) + try { + const { + repos, + folderWorkspaces, + projectGroups, + settings, + worktrees: freshWorktrees + } = await loadMobileResumeMetadata(client) + const target = resolveMobileAiVaultSessionResumeTarget({ + session, + activeWorktreeId: worktreeId, + // Why: resolve against live worktrees so a workspace deleted or + // archived since panel mount can't be picked; the mount-time list is + // only a fallback when the fresh fetch fails. + worktrees: freshWorktrees ?? worktrees, + repos, + folderWorkspaces, + projectGroups + }) + if (target.status !== 'ready') { + setResumeMessage(target.message) + triggerError() + return + } + + const platform = resolveMobileAiVaultResumePlatform( + target.targetStatus, + hostPlatform, + target.workspacePath, + target.terminalPlatform + ) + if (!platform) { + setResumeMessage('Unable to determine host platform.') + triggerError() + return + } + + const launch = buildMobileAiVaultResumeLaunch({ + session, + hostPlatform: platform, + hostTerminalWindowsShell, + settings + }) + await resumeAiVaultSessionInTerminal(client, target.worktreeId, { + ...launch, + clientMutationId: resumeMutationRegistryRef.current.claim(session.id) + }) + resumeMutationRegistryRef.current.releaseOnSuccess(session.id) + triggerSuccess() + setResumeMessage('Agent session queued.') + router.push( + `/h/${encodeURIComponent(hostId)}/session/${encodeURIComponent(target.worktreeId)}` as Parameters< + typeof router.push + >[0] + ) + } catch (err) { + triggerError() + setResumeMessage(err instanceof Error ? err.message : 'Failed to resume session.') + } finally { + resumeLaunchInFlightRef.current = false + setResumingSessionId(null) + } + }, + [ + client, + connState, + hostId, + hostPlatform, + hostTerminalWindowsShell, + router, + worktreeId, + worktrees + ] + ) + + return ( + + + + [styles.backButton, pressed && styles.backButtonPressed]} + onPress={() => router.back()} + hitSlop={8} + accessibilityLabel="Back" + > + + + + + Agent Session History + + + {worktreeLabel} + + + [styles.refreshButton, pressed && styles.refreshButtonPressed]} + onPress={() => void onRefresh()} + hitSlop={8} + accessibilityLabel="Refresh agent sessions" + > + + + + + + {screenState.kind === 'loading' ? ( + + + + ) : screenState.kind === 'unsupported' ? ( + + Agent Session History Unavailable + + Update Orca on this host to browse agent session history. + + + ) : screenState.kind === 'error' ? ( + + Unable to Load + {screenState.message} + + Retry + + + ) : ( + <> + + {SCOPE_TABS.map((tab) => { + const active = scope === tab.scope + return ( + onSelectScope(tab.scope)} + > + + {tab.label} + + + ) + })} + + + + + {issues.length > 0 ? ( + + + {issues.length} {issues.length === 1 ? 'transcript' : 'transcripts'} skipped + + + ) : null} + {resumeMessage ? ( + + {resumeMessage} + + ) : null} + {sections.length === 0 ? ( + + No agent sessions + + {query ? 'No sessions match your search.' : 'No past agent sessions in this scope.'} + + + ) : ( + void onRefresh()} + /> + )} + + )} + + ) +} + +const EMPTY_SESSIONS: AiVaultSession[] = [] +const EMPTY_ISSUES: { agent: AiVaultSession['agent']; path: string; message: string }[] = [] + +async function loadMobileResumeMetadata(client: Pick): Promise<{ + repos: MobileAiVaultResumeRepo[] + folderWorkspaces: MobileAiVaultResumeFolderWorkspace[] + projectGroups: MobileAiVaultResumeProjectGroup[] + settings: MobileAiVaultResumeSettings | null + worktrees: Worktree[] | null +}> { + // Why: repo.list can enrich repo remote identities, so fetch resume-only + // metadata after explicit user intent instead of delaying history browsing. + // timeoutMs: without it a socket drop parks these on the reconnect waiter + // for minutes, pinning the resume spinner (see RESUME_RPC_TIMEOUT_MS). + const [ + repoResponse, + folderWorkspaceResponse, + projectGroupResponse, + settingsResponse, + worktreeResponse + ] = await Promise.all([ + client.sendRequest('repo.list', undefined, { timeoutMs: RESUME_RPC_TIMEOUT_MS }), + client + .sendRequest('folderWorkspace.list', undefined, { timeoutMs: RESUME_RPC_TIMEOUT_MS }) + .catch(() => null), + client + .sendRequest('projectGroup.list', undefined, { timeoutMs: RESUME_RPC_TIMEOUT_MS }) + .catch(() => null), + client + .sendRequest('settings.get', undefined, { timeoutMs: RESUME_RPC_TIMEOUT_MS }) + .catch(() => null), + client + .sendRequest('worktree.ps', { limit: 10000 }, { timeoutMs: RESUME_RPC_TIMEOUT_MS }) + .catch(() => null) + ]) + if (!repoResponse.ok) { + throw new Error(repoResponse.error?.message || 'Unable to load workspace metadata.') + } + const repoResult = repoResponse.result as { repos?: MobileAiVaultResumeRepo[] } + const folderWorkspaceResult = + folderWorkspaceResponse?.ok === true + ? (folderWorkspaceResponse.result as { + folderWorkspaces?: MobileAiVaultResumeFolderWorkspace[] + }) + : null + const projectGroupResult = + projectGroupResponse?.ok === true + ? (projectGroupResponse.result as { groups?: MobileAiVaultResumeProjectGroup[] }) + : null + const settingsResult = + settingsResponse?.ok === true + ? (settingsResponse.result as { settings?: MobileAiVaultResumeSettings }) + : null + const worktreeResult = + worktreeResponse?.ok === true ? (worktreeResponse.result as { worktrees?: Worktree[] }) : null + return { + repos: repoResult.repos ?? [], + folderWorkspaces: folderWorkspaceResult?.folderWorkspaces ?? [], + projectGroups: projectGroupResult?.groups ?? [], + settings: settingsResult?.settings ?? null, + worktrees: worktreeResult?.worktrees ?? null + } +} + +function createMobileAiVaultResumeMutationId(sessionId: string): string { + const sessionPart = sessionId.replace(/[^a-zA-Z0-9_.:-]/g, '_').slice(0, 64) || 'session' + const randomPart = Math.random().toString(36).slice(2, 10) + return `ai-vault-resume:${sessionPart}:${Date.now().toString(36)}:${randomPart}` +} diff --git a/mobile/src/agent-history/agent-history-capability.ts b/mobile/src/agent-history/agent-history-capability.ts new file mode 100644 index 000000000000..28db8f48e2ed --- /dev/null +++ b/mobile/src/agent-history/agent-history-capability.ts @@ -0,0 +1,4 @@ +// Why: mobile's protocol-version.ts is a separate copy without the capability +// constants (mirrors MOBILE_TASKS_CAPABILITY in tasks.tsx). Keep this string in +// lockstep with src/shared/protocol-version.ts AI_VAULT_RUNTIME_CAPABILITY. +export const MOBILE_AI_VAULT_CAPABILITY = 'aiVault.v1' diff --git a/mobile/src/agent-history/agent-history-current-worktree-badge.ts b/mobile/src/agent-history/agent-history-current-worktree-badge.ts new file mode 100644 index 000000000000..4dbcae4d6db1 --- /dev/null +++ b/mobile/src/agent-history/agent-history-current-worktree-badge.ts @@ -0,0 +1,7 @@ +import type { AiVaultScope } from '../../../src/shared/ai-vault-types' + +export function shouldShowMobileCurrentWorktreeBadge(scope: AiVaultScope): boolean { + // Why: Workspace is already the current-worktree-only view; Project and All + // still mix in sibling/other worktrees, so the badge remains useful there. + return scope !== 'workspace' +} diff --git a/mobile/src/agent-history/agent-history-resume-target.test.ts b/mobile/src/agent-history/agent-history-resume-target.test.ts new file mode 100644 index 000000000000..d59feb98e15a --- /dev/null +++ b/mobile/src/agent-history/agent-history-resume-target.test.ts @@ -0,0 +1,372 @@ +import { describe, expect, it } from 'vitest' +import { + getMobileAiVaultResumeRepoTargetStatus, + getMobileAiVaultResumeWorktreeTargetStatus, + isSupportedMobileAiVaultResumeTargetStatus, + mobileAiVaultResumeTargetBlockMessage, + resolveMobileAiVaultSessionResumeTarget +} from './agent-history-resume-target' +import type { AiVaultSession } from '../../../src/shared/ai-vault-types' +import type { Worktree } from '../worktree/workspace-list-types' + +function session(overrides: Partial = {}): AiVaultSession { + return { + id: 'claude:1', + executionHostId: 'local', + agent: 'claude', + sessionId: 'session-1', + title: 'Resume target', + cwd: '/Users/ada/repo/app', + branch: null, + model: null, + filePath: '/Users/ada/.claude/session.jsonl', + codexHome: null, + createdAt: null, + updatedAt: null, + modifiedAt: '2026-06-29T00:00:00.000Z', + messageCount: 2, + totalTokens: 10, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: '', + subagent: null, + ...overrides + } +} + +function worktree(overrides: Partial & { worktreeId: string; path: string }): Worktree { + return { + repoId: 'local-repo', + repo: 'orca', + branch: 'main', + displayName: overrides.worktreeId, + liveTerminalCount: 0, + hasAttachedPty: false, + preview: '', + unread: false, + isPinned: false, + linkedPR: null, + ...overrides + } +} + +describe('mobile AI Vault resume target guards', () => { + const worktrees = [ + { worktreeId: 'local-wt', repoId: 'local-repo' }, + { worktreeId: 'ssh-wt', repoId: 'ssh-repo' }, + { worktreeId: 'runtime-wt', repoId: 'runtime-repo' }, + { worktreeId: 'host-owned-wt', repoId: 'local-repo', hostId: 'ssh:builder' as const }, + { + worktreeId: 'folder:folder-local', + repoId: 'folder-workspace:group-local', + workspaceKind: 'folder-workspace' as const + }, + { + worktreeId: 'folder:folder-ssh', + repoId: 'folder-workspace:group-local', + workspaceKind: 'folder-workspace' as const + }, + { + worktreeId: 'folder:folder-runtime', + repoId: 'folder-workspace:group-runtime', + workspaceKind: 'folder-workspace' as const + } + ] + const repos = [ + { id: 'local-repo', path: '/Users/ada/repo', connectionId: null }, + { id: 'ssh-repo', path: '/home/ada/ssh-repo', connectionId: 'builder' }, + { + id: 'runtime-repo', + path: '/workspace/runtime', + connectionId: null, + executionHostId: 'runtime:devbox' as const + } + ] + const folderWorkspaces = [ + { id: 'folder-local', projectGroupId: 'group-local', folderPath: '/Users/ada/folder' }, + { + id: 'folder-ssh', + projectGroupId: 'group-local', + folderPath: '/home/ada/folder', + connectionId: 'folder-builder' + }, + { id: 'folder-runtime', projectGroupId: 'group-runtime', folderPath: '/workspace/folder' } + ] + const projectGroups = [ + { id: 'group-local', connectionId: null }, + { id: 'group-runtime', executionHostId: 'runtime:devbox' as const } + ] + + it('classifies local, SSH, runtime, and unknown repos', () => { + expect(getMobileAiVaultResumeRepoTargetStatus(repos[0])).toBe('local') + expect(getMobileAiVaultResumeRepoTargetStatus(repos[1])).toBe('ssh') + expect(getMobileAiVaultResumeRepoTargetStatus(repos[2])).toBe('runtime') + expect(getMobileAiVaultResumeRepoTargetStatus(null)).toBe('unknown') + }) + + it('classifies worktrees from their repo, with worktree host taking precedence', () => { + expect( + getMobileAiVaultResumeWorktreeTargetStatus({ worktreeId: 'local-wt', worktrees, repos }) + ).toBe('local') + expect( + getMobileAiVaultResumeWorktreeTargetStatus({ worktreeId: 'ssh-wt', worktrees, repos }) + ).toBe('ssh') + expect( + getMobileAiVaultResumeWorktreeTargetStatus({ worktreeId: 'runtime-wt', worktrees, repos }) + ).toBe('runtime') + expect( + getMobileAiVaultResumeWorktreeTargetStatus({ worktreeId: 'host-owned-wt', worktrees, repos }) + ).toBe('ssh') + expect( + getMobileAiVaultResumeWorktreeTargetStatus({ + worktreeId: 'folder:folder-local', + worktrees, + repos, + folderWorkspaces, + projectGroups + }) + ).toBe('local') + expect( + getMobileAiVaultResumeWorktreeTargetStatus({ + worktreeId: 'folder:folder-ssh', + worktrees, + repos, + folderWorkspaces, + projectGroups + }) + ).toBe('ssh') + expect( + getMobileAiVaultResumeWorktreeTargetStatus({ + worktreeId: 'folder:folder-runtime', + worktrees, + repos, + folderWorkspaces, + projectGroups + }) + ).toBe('runtime') + expect( + getMobileAiVaultResumeWorktreeTargetStatus({ worktreeId: 'missing', worktrees, repos }) + ).toBe('unknown') + }) + + it('supports local targets only; SSH hosts cannot see host-local transcripts', () => { + expect(isSupportedMobileAiVaultResumeTargetStatus('local')).toBe(true) + expect(isSupportedMobileAiVaultResumeTargetStatus('ssh')).toBe(false) + expect(isSupportedMobileAiVaultResumeTargetStatus('runtime')).toBe(false) + expect(mobileAiVaultResumeTargetBlockMessage('runtime')).toContain('runtime-hosted') + expect(mobileAiVaultResumeTargetBlockMessage('ssh')).toContain('SSH workspace') + expect(mobileAiVaultResumeTargetBlockMessage('ssh')).toContain('local workspace') + expect(mobileAiVaultResumeTargetBlockMessage('unknown')).toContain('local workspace') + }) + + it('resolves project-scope rows to the matched session worktree before the route worktree', () => { + const target = resolveMobileAiVaultSessionResumeTarget({ + session: session({ cwd: '/Users/ada/repo/feature/src' }), + activeWorktreeId: 'route-wt', + worktrees: [ + worktree({ worktreeId: 'route-wt', path: '/Users/ada/repo/main' }), + worktree({ worktreeId: 'session-wt', path: '/Users/ada/repo/feature' }) + ], + repos + }) + expect(target).toEqual({ + status: 'ready', + worktreeId: 'session-wt', + targetStatus: 'local', + workspacePath: '/Users/ada/repo/feature', + terminalPlatform: null + }) + }) + + it('falls back to the active route worktree when the session worktree is archived', () => { + const target = resolveMobileAiVaultSessionResumeTarget({ + session: session({ cwd: '/Users/ada/repo/archive/src' }), + activeWorktreeId: 'route-wt', + worktrees: [ + worktree({ worktreeId: 'route-wt', path: '/Users/ada/repo/main' }), + worktree({ + worktreeId: 'archived-wt', + path: '/Users/ada/repo/archive', + isArchived: true + }) + ], + repos + }) + expect(target).toEqual({ + status: 'ready', + worktreeId: 'route-wt', + targetStatus: 'local', + workspacePath: '/Users/ada/repo/main', + terminalPlatform: null + }) + }) + + it('blocks runtime targets when no supported fallback is available', () => { + const target = resolveMobileAiVaultSessionResumeTarget({ + session: session({ cwd: '/Users/ada/runtime/app' }), + activeWorktreeId: 'runtime-wt', + worktrees: [ + worktree({ worktreeId: 'runtime-wt', repoId: 'runtime-repo', path: '/Users/ada/runtime' }) + ], + repos + }) + expect(target.status).toBe('blocked') + expect(target.status === 'blocked' ? target.message : '').toContain('runtime-hosted') + }) + + it('blocks SSH folder workspace targets because transcripts are host-local', () => { + const target = resolveMobileAiVaultSessionResumeTarget({ + session: session({ cwd: '/home/ada/folder/src' }), + activeWorktreeId: 'folder:folder-ssh', + worktrees: [ + worktree({ + worktreeId: 'folder:folder-ssh', + repoId: 'folder-workspace:group-local', + workspaceKind: 'folder-workspace', + path: '/home/ada/folder' + }) + ], + repos, + folderWorkspaces, + projectGroups + }) + expect(target.status).toBe('blocked') + expect(target.status === 'blocked' ? target.message : '').toContain('SSH workspace') + }) + + it('skips an SSH session-worktree candidate in favor of a local active-worktree fallback', () => { + const target = resolveMobileAiVaultSessionResumeTarget({ + session: session({ cwd: '/home/ada/ssh-repo/feature/src' }), + activeWorktreeId: 'route-wt', + worktrees: [ + worktree({ worktreeId: 'route-wt', path: '/Users/ada/repo/main' }), + worktree({ + worktreeId: 'ssh-session-wt', + repoId: 'ssh-repo', + path: '/home/ada/ssh-repo/feature' + }) + ], + repos + }) + expect(target).toEqual({ + status: 'ready', + worktreeId: 'route-wt', + targetStatus: 'local', + workspacePath: '/Users/ada/repo/main', + terminalPlatform: null + }) + }) + + it('blocks SSH session worktrees with the SSH message when no local fallback exists', () => { + const target = resolveMobileAiVaultSessionResumeTarget({ + session: session({ cwd: '/home/ada/ssh-repo/feature/src' }), + activeWorktreeId: 'ssh-session-wt', + worktrees: [ + worktree({ + worktreeId: 'ssh-session-wt', + repoId: 'ssh-repo', + path: '/home/ada/ssh-repo/feature' + }) + ], + repos + }) + expect(target.status).toBe('blocked') + expect(target.status === 'blocked' ? target.message : '').toContain('SSH workspace') + }) + + it('blocks folder workspaces whose candidate repos include a runtime owner', () => { + const target = resolveMobileAiVaultSessionResumeTarget({ + session: session({ cwd: '/workspace/folder/src' }), + activeWorktreeId: 'folder:folder-runtime-candidate', + worktrees: [ + worktree({ + worktreeId: 'folder:folder-runtime-candidate', + repoId: 'folder-workspace:group-local', + workspaceKind: 'folder-workspace', + path: '/workspace/folder' + }) + ], + repos: [ + ...repos, + { + id: 'runtime-in-folder', + path: '/workspace/folder/repo', + connectionId: null, + executionHostId: 'runtime:devbox' as const + } + ], + folderWorkspaces: [ + { + id: 'folder-runtime-candidate', + projectGroupId: 'group-local', + folderPath: '/workspace/folder' + } + ], + projectGroups + }) + expect(target.status).toBe('blocked') + expect(target.status === 'blocked' ? target.message : '').toContain('runtime-hosted') + }) + + it('blocks folder workspaces when folder metadata is unavailable', () => { + const target = resolveMobileAiVaultSessionResumeTarget({ + session: session({ cwd: '/Users/ada/folder/src' }), + activeWorktreeId: 'folder:missing-folder', + worktrees: [ + worktree({ + worktreeId: 'folder:missing-folder', + repoId: 'folder-workspace:group-local', + workspaceKind: 'folder-workspace', + path: '/Users/ada/folder' + }) + ], + repos, + folderWorkspaces: [], + projectGroups + }) + expect(target).toEqual({ + status: 'blocked', + message: 'Open a local workspace before resuming a session.' + }) + }) + + it('blocks folder workspaces with mixed candidate repo hosts as unknown', () => { + const target = resolveMobileAiVaultSessionResumeTarget({ + session: session({ cwd: '/Users/ada/mixed/src' }), + activeWorktreeId: 'folder:folder-mixed', + worktrees: [ + worktree({ + worktreeId: 'folder:folder-mixed', + repoId: 'folder-workspace:group-local', + workspaceKind: 'folder-workspace', + path: '/Users/ada/mixed' + }) + ], + repos: [ + { + id: 'local-in-folder', + path: '/Users/ada/mixed/local', + connectionId: null + }, + { + id: 'ssh-in-folder', + path: '/Users/ada/mixed/ssh', + connectionId: 'builder' + } + ], + folderWorkspaces: [ + { + id: 'folder-mixed', + projectGroupId: 'group-local', + folderPath: '/Users/ada/mixed' + } + ], + projectGroups + }) + expect(target).toEqual({ + status: 'blocked', + message: 'Open a local workspace before resuming a session.' + }) + }) +}) diff --git a/mobile/src/agent-history/agent-history-resume-target.ts b/mobile/src/agent-history/agent-history-resume-target.ts new file mode 100644 index 000000000000..a63a7ca92c76 --- /dev/null +++ b/mobile/src/agent-history/agent-history-resume-target.ts @@ -0,0 +1,304 @@ +import { + getRepoExecutionHostId, + normalizeExecutionHostId, + parseExecutionHostId, + toSshExecutionHostId, + type ExecutionHostId +} from '../../../src/shared/execution-host' +import type { AiVaultSession } from '../../../src/shared/ai-vault-types' +import { isPathInsideOrEqual } from '../../../src/shared/cross-platform-path' +import type { Worktree } from '../worktree/workspace-list-types' +import { + canResumeInMobileSessionWorktree, + resolveMobileAgentHistorySessionWorktree +} from './agent-history-session-worktree' + +export type MobileAiVaultResumeTargetStatus = 'local' | 'ssh' | 'runtime' | 'unknown' + +export type MobileAiVaultResumeRepo = { + id: string + path?: string | null + projectGroupId?: string | null + connectionId?: string | null + executionHostId?: ExecutionHostId | null +} + +type MobileAiVaultResumeWorktree = Pick & { + path?: string | null + workspaceKind?: Worktree['workspaceKind'] + hostId?: ExecutionHostId | null +} + +export type MobileAiVaultResumeFolderWorkspace = { + id: string + projectGroupId: string + folderPath: string + connectionId?: string | null +} + +export type MobileAiVaultResumeProjectGroup = { + id: string + parentGroupId?: string | null + connectionId?: string | null + executionHostId?: ExecutionHostId | string | null +} + +export type MobileAiVaultSessionResumeTarget = + | { + status: 'ready' + worktreeId: string + targetStatus: 'local' + workspacePath: string | null + terminalPlatform: NodeJS.Platform | null + } + | { status: 'blocked'; message: string } + +export function getMobileAiVaultResumeRepoTargetStatus( + repo: MobileAiVaultResumeRepo | null | undefined +): MobileAiVaultResumeTargetStatus { + if (!repo) { + return 'unknown' + } + return getMobileAiVaultResumeExecutionHostTargetStatus(getRepoExecutionHostId(repo)) +} + +export function getMobileAiVaultResumeWorktreeTargetStatus(args: { + worktreeId: string | null + worktrees: readonly MobileAiVaultResumeWorktree[] + repos: readonly MobileAiVaultResumeRepo[] + folderWorkspaces?: readonly MobileAiVaultResumeFolderWorkspace[] + projectGroups?: readonly MobileAiVaultResumeProjectGroup[] +}): MobileAiVaultResumeTargetStatus { + if (!args.worktreeId) { + return 'unknown' + } + const worktree = args.worktrees.find((candidate) => candidate.worktreeId === args.worktreeId) + if (!worktree) { + return 'unknown' + } + if (worktree.workspaceKind === 'folder-workspace') { + return getMobileAiVaultResumeFolderTargetStatus({ + worktreeId: args.worktreeId, + worktree, + repos: args.repos, + folderWorkspaces: args.folderWorkspaces ?? [], + projectGroups: args.projectGroups ?? [] + }) + } + const worktreeHost = getMobileAiVaultResumeExecutionHostTargetStatus(worktree.hostId) + if (worktreeHost !== 'unknown') { + return worktreeHost + } + return getMobileAiVaultResumeRepoTargetStatus( + args.repos.find((candidate) => candidate.id === worktree.repoId) + ) +} + +export function isSupportedMobileAiVaultResumeTargetStatus( + status: MobileAiVaultResumeTargetStatus +): status is 'local' { + // Why: mobile sessions come from the host-local transcript scan, so an SSH + // workspace cannot see the transcript file (mirror of desktop #6270). + return status === 'local' +} + +export function mobileAiVaultResumeTargetBlockMessage( + status: MobileAiVaultResumeTargetStatus +): string { + if (status === 'runtime') { + return 'Resume from history is not available in runtime-hosted workspaces.' + } + if (status === 'ssh') { + return 'This session is stored on the host machine, so it cannot be resumed in an SSH workspace. Open a local workspace for this project.' + } + return 'Open a local workspace before resuming a session.' +} + +export function resolveMobileAiVaultSessionResumeTarget(args: { + session: AiVaultSession + activeWorktreeId: string | null + worktrees: readonly Worktree[] + repos: readonly MobileAiVaultResumeRepo[] + folderWorkspaces?: readonly MobileAiVaultResumeFolderWorkspace[] + projectGroups?: readonly MobileAiVaultResumeProjectGroup[] +}): MobileAiVaultSessionResumeTarget { + const sessionWorktree = resolveMobileAgentHistorySessionWorktree({ + session: args.session, + worktrees: args.worktrees, + activeWorktreeId: args.activeWorktreeId + }) + const sessionWorktreeId = canResumeInMobileSessionWorktree(sessionWorktree) + ? sessionWorktree?.worktreeId + : null + const candidateWorktreeIds = [ + sessionWorktreeId, + args.activeWorktreeId && args.activeWorktreeId !== sessionWorktreeId + ? args.activeWorktreeId + : null + ].filter((candidate): candidate is string => Boolean(candidate)) + + for (const candidateWorktreeId of candidateWorktreeIds) { + const targetStatus = getMobileAiVaultResumeWorktreeTargetStatus({ + worktreeId: candidateWorktreeId, + worktrees: args.worktrees, + repos: args.repos, + folderWorkspaces: args.folderWorkspaces, + projectGroups: args.projectGroups + }) + if (!isSupportedMobileAiVaultResumeTargetStatus(targetStatus)) { + continue + } + return { + status: 'ready', + worktreeId: candidateWorktreeId, + targetStatus, + workspacePath: + args.worktrees.find((worktree) => worktree.worktreeId === candidateWorktreeId)?.path ?? + null, + terminalPlatform: + args.worktrees.find((worktree) => worktree.worktreeId === candidateWorktreeId) + ?.terminalPlatform ?? null + } + } + + const blockedStatus = getMobileAiVaultResumeWorktreeTargetStatus({ + worktreeId: candidateWorktreeIds[0] ?? args.activeWorktreeId, + worktrees: args.worktrees, + repos: args.repos, + folderWorkspaces: args.folderWorkspaces, + projectGroups: args.projectGroups + }) + return { status: 'blocked', message: mobileAiVaultResumeTargetBlockMessage(blockedStatus) } +} + +function getMobileAiVaultResumeFolderTargetStatus(args: { + worktreeId: string + worktree: MobileAiVaultResumeWorktree + repos: readonly MobileAiVaultResumeRepo[] + folderWorkspaces: readonly MobileAiVaultResumeFolderWorkspace[] + projectGroups: readonly MobileAiVaultResumeProjectGroup[] +}): MobileAiVaultResumeTargetStatus { + const folderWorkspaceId = args.worktreeId.startsWith('folder:') + ? args.worktreeId.slice('folder:'.length) + : null + const folderWorkspace = folderWorkspaceId + ? args.folderWorkspaces.find((workspace) => workspace.id === folderWorkspaceId) + : null + if (!folderWorkspace) { + return 'unknown' + } + const projectGroupId = + folderWorkspace.projectGroupId ?? parseFolderWorkspaceRepoId(args.worktree.repoId) + const projectGroup = projectGroupId + ? args.projectGroups.find((group) => group.id === projectGroupId) + : null + + const groupHostId = normalizeExecutionHostId(projectGroup?.executionHostId) + if (groupHostId) { + return getMobileAiVaultResumeExecutionHostTargetStatus(groupHostId) + } + + const explicitConnectionId = ( + folderWorkspace?.connectionId ?? + projectGroup?.connectionId ?? + '' + ).trim() + if (explicitConnectionId) { + return getMobileAiVaultResumeExecutionHostTargetStatus( + toSshExecutionHostId(explicitConnectionId) + ) + } + + return mergeMobileAiVaultResumeExecutionHostTargetStatuses( + getMobileFolderWorkspaceCandidateRepos({ + folderWorkspace, + projectGroupId, + projectGroups: args.projectGroups, + repos: args.repos + }).map(getRepoExecutionHostId) + ) +} + +function getMobileAiVaultResumeExecutionHostTargetStatus( + hostId: ExecutionHostId | null | undefined +): MobileAiVaultResumeTargetStatus { + const parsed = parseExecutionHostId(hostId) + if (!parsed) { + return 'unknown' + } + return parsed.kind +} + +function parseFolderWorkspaceRepoId(repoId: string): string | null { + const prefix = 'folder-workspace:' + return repoId.startsWith(prefix) ? repoId.slice(prefix.length) || null : null +} + +function getMobileFolderWorkspaceCandidateRepos(args: { + folderWorkspace: MobileAiVaultResumeFolderWorkspace | null | undefined + projectGroupId: string | null + projectGroups: readonly MobileAiVaultResumeProjectGroup[] + repos: readonly MobileAiVaultResumeRepo[] +}): MobileAiVaultResumeRepo[] { + if (!args.folderWorkspace || !args.projectGroupId) { + return [] + } + const folderWorkspace = args.folderWorkspace + const groupIds = getMobileProjectGroupSubtreeIds(args.projectGroups, args.projectGroupId) + const groupRepos = args.repos.filter( + (repo) => typeof repo.projectGroupId === 'string' && groupIds.has(repo.projectGroupId) + ) + const pathRepos = args.repos.filter( + (repo) => + !(typeof repo.projectGroupId === 'string' && groupIds.has(repo.projectGroupId)) && + typeof repo.path === 'string' && + repo.path.trim().length > 0 && + isPathInsideOrEqual(folderWorkspace.folderPath, repo.path) + ) + if (folderWorkspace.connectionId) { + return [ + ...groupRepos, + ...pathRepos.filter((repo) => (repo.connectionId ?? null) === folderWorkspace.connectionId) + ] + } + if (groupRepos.length === 0) { + return pathRepos + } + const groupConnectionIds = new Set(groupRepos.map((repo) => repo.connectionId ?? null)) + return [ + ...groupRepos, + ...pathRepos.filter((repo) => groupConnectionIds.has(repo.connectionId ?? null)) + ] +} + +function getMobileProjectGroupSubtreeIds( + projectGroups: readonly MobileAiVaultResumeProjectGroup[], + projectGroupId: string +): Set { + const ids = new Set([projectGroupId]) + let changed = true + while (changed) { + changed = false + for (const group of projectGroups) { + if (group.parentGroupId && ids.has(group.parentGroupId) && !ids.has(group.id)) { + ids.add(group.id) + changed = true + } + } + } + return ids +} + +function mergeMobileAiVaultResumeExecutionHostTargetStatuses( + hostIds: readonly ExecutionHostId[] +): MobileAiVaultResumeTargetStatus { + if (hostIds.length === 0) { + return 'local' + } + const statuses = hostIds.map(getMobileAiVaultResumeExecutionHostTargetStatus) + const uniqueStatuses = new Set(statuses) + if (uniqueStatuses.has('runtime')) { + return 'runtime' + } + return new Set(hostIds).size === 1 ? (statuses[0] ?? 'unknown') : 'unknown' +} diff --git a/mobile/src/agent-history/agent-history-scope-paths.test.ts b/mobile/src/agent-history/agent-history-scope-paths.test.ts new file mode 100644 index 000000000000..59f16ec9ef80 --- /dev/null +++ b/mobile/src/agent-history/agent-history-scope-paths.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest' +import type { Worktree } from '../worktree/workspace-list-types' +import { deriveMobileAiVaultScopePaths } from './agent-history-scope-paths' + +function worktree(overrides: Partial): Pick { + return { + worktreeId: overrides.worktreeId ?? 'w1', + path: overrides.path ?? '/Users/ada/repo/app', + repoId: overrides.repoId ?? 'repo-1' + } +} + +const active = worktree({ worktreeId: 'w1', path: '/Users/ada/repo/app', repoId: 'repo-1' }) +const sibling = worktree({ worktreeId: 'w2', path: '/Users/ada/repo/app-2', repoId: 'repo-1' }) +const otherRepo = worktree({ worktreeId: 'w3', path: '/Users/ada/other/ui', repoId: 'repo-2' }) + +describe('deriveMobileAiVaultScopePaths', () => { + it('workspace scope returns only the active worktree path', () => { + expect( + deriveMobileAiVaultScopePaths('workspace', active, [active, sibling, otherRepo]) + ).toEqual(['/Users/ada/repo/app']) + }) + + it('project scope adds same-repo siblings but not other-repo worktrees', () => { + expect(deriveMobileAiVaultScopePaths('project', active, [active, sibling, otherRepo])).toEqual([ + '/Users/ada/repo/app', + '/Users/ada/repo/app-2' + ]) + }) + + it('all scope returns no scope hints (global recency list)', () => { + expect(deriveMobileAiVaultScopePaths('all', active, [active, sibling])).toEqual([]) + }) + + it('returns no paths when there is no active worktree', () => { + expect(deriveMobileAiVaultScopePaths('workspace', null, [sibling])).toEqual([]) + }) + + it('caps project scope at 64 paths so the host RPC bound does not reject the request', () => { + const siblings = Array.from({ length: 200 }, (_, index) => + worktree({ + worktreeId: `w-sib-${index}`, + path: `/Users/ada/repo/app-${index}`, + repoId: 'repo-1' + }) + ) + const result = deriveMobileAiVaultScopePaths('project', active, [active, ...siblings]) + expect(result.length).toBe(64) + // Active worktree is seeded first, so it survives truncation. + expect(result[0]).toBe('/Users/ada/repo/app') + }) + + it('dedupes and skips non-absolute paths', () => { + const dupe = worktree({ worktreeId: 'w4', path: '/Users/ada/repo/app', repoId: 'repo-1' }) + const relative = worktree({ worktreeId: 'w5', path: 'relative/path', repoId: 'repo-1' }) + expect(deriveMobileAiVaultScopePaths('project', active, [active, dupe, relative])).toEqual([ + '/Users/ada/repo/app' + ]) + }) +}) diff --git a/mobile/src/agent-history/agent-history-scope-paths.ts b/mobile/src/agent-history/agent-history-scope-paths.ts new file mode 100644 index 000000000000..da3b98457d26 --- /dev/null +++ b/mobile/src/agent-history/agent-history-scope-paths.ts @@ -0,0 +1,60 @@ +import { + isRuntimePathAbsolute, + normalizeRuntimePathForComparison +} from '../../../src/shared/cross-platform-path' +import type { Worktree } from '../worktree/workspace-list-types' +import { + AI_VAULT_SCOPE_PATHS_MAX_COUNT, + type AiVaultScope +} from '../../../src/shared/ai-vault-types' + +// Why: the renderer's deriveAiVault* helpers are renderer-located and +// Metro-unresolvable, so mobile does its own minimal derivation seeded by the +// active worktree's path plus same-repo sibling worktrees (mobile already loads +// the full worktree list via worktree.ps). scopePaths only widen the host scan's +// discovery breadth; they are host-local match prefixes, never device paths. +export function deriveMobileAiVaultScopePaths( + scope: AiVaultScope, + activeWorktree: Pick | null, + liveWorktrees: readonly Pick[] +): string[] { + // 'all' scope scans without scope hints — the host returns the global recency + // list, so no scopePaths are needed (and would only narrow discovery). + if (scope === 'all' || !activeWorktree) { + return [] + } + + const paths: string[] = [] + addScopePath(paths, activeWorktree.path) + + // Workspace scope = the active worktree only. Project scope additionally + // covers same-repo sibling worktrees so the project view stays complete. + if (scope === 'project') { + for (const worktree of liveWorktrees) { + // Why: the RPC rejects (does not truncate) oversized scopePaths, and the + // list only widens discovery — dropping tail siblings beats hard-failing. + if (paths.length >= AI_VAULT_SCOPE_PATHS_MAX_COUNT) { + break + } + if (worktree.repoId === activeWorktree.repoId) { + addScopePath(paths, worktree.path) + } + } + } + + return paths +} + +function addScopePath(paths: string[], pathValue: string | undefined): void { + const trimmedPath = pathValue?.trim() + if (!trimmedPath || !isRuntimePathAbsolute(trimmedPath)) { + return + } + const comparisonPath = normalizeRuntimePathForComparison(trimmedPath) + if ( + paths.some((existingPath) => normalizeRuntimePathForComparison(existingPath) === comparisonPath) + ) { + return + } + paths.push(trimmedPath) +} diff --git a/mobile/src/agent-history/agent-history-sections.ts b/mobile/src/agent-history/agent-history-sections.ts new file mode 100644 index 000000000000..52f76b202d03 --- /dev/null +++ b/mobile/src/agent-history/agent-history-sections.ts @@ -0,0 +1,59 @@ +import { + filterAiVaultSessions, + groupAiVaultSessions +} from '../../../src/shared/ai-vault-session-filters' +import { AI_VAULT_AGENTS } from '../../../src/shared/ai-vault-types' +import type { AiVaultScope, AiVaultSession } from '../../../src/shared/ai-vault-types' +import { + buildMobileAgentHistoryCard, + type MobileAgentHistoryCard +} from './agent-history-session-card' + +// Why: `data` (not `cards`) is the field name React Native's SectionList reads +// for each section's rows — naming it anything else renders empty sections. +export type MobileAgentHistorySection = { + key: string + label: string + data: MobileAgentHistoryCard[] +} + +// Why: the host treats scopePaths as a WIDENING union (it adds in-scope sessions +// beyond the recency cap, never restricts), so the Workspace/Project tabs must +// narrow on the client like the desktop panel does. Mobile has no project-key +// metadata, so both scoped tabs narrow by cwd path-prefix: Workspace = the active +// worktree path, Project = the active worktree + same-repo siblings (the same set +// deriveMobileAiVaultScopePaths produces). 'all' applies no path narrowing. +// hideEmptySessions matches the desktop default. +export function buildMobileAgentHistorySections( + sessions: readonly AiVaultSession[], + options: { + query: string + scope: AiVaultScope + scopeFilterPaths: readonly string[] + activeWorktreePath: string | null + now: number + } +): MobileAgentHistorySection[] { + // Why: narrow scoped tabs by cwd path-prefix. When the worktree list hasn't + // loaded yet, scopeFilterPaths is empty — fall back to unnarrowed rather than + // filtering everything out (which would flash an empty list); the memo re-runs + // with real paths once worktree.ps resolves. + const narrowByPath = options.scope !== 'all' && options.scopeFilterPaths.length > 0 + const filtered = filterAiVaultSessions(sessions, { + query: options.query, + agents: AI_VAULT_AGENTS, + scope: narrowByPath ? 'workspace' : 'all', + sort: 'updated', + activeWorktreePaths: narrowByPath ? options.scopeFilterPaths : [], + hideEmptySessions: true + }) + + const groups = groupAiVaultSessions(filtered, 'folder') + return groups.map((group) => ({ + key: group.key, + label: group.label, + data: group.sessions.map((session) => + buildMobileAgentHistoryCard(session, options.activeWorktreePath, options.now) + ) + })) +} diff --git a/mobile/src/agent-history/agent-history-session-card.test.ts b/mobile/src/agent-history/agent-history-session-card.test.ts new file mode 100644 index 000000000000..d38285aee14e --- /dev/null +++ b/mobile/src/agent-history/agent-history-session-card.test.ts @@ -0,0 +1,221 @@ +import { describe, expect, it } from 'vitest' +import type { AiVaultSession } from '../../../src/shared/ai-vault-types' +import { + buildMobileAgentHistoryResumeActionState, + buildMobileAgentHistoryCard, + isSessionInActiveWorktree +} from './agent-history-session-card' +import { buildMobileAgentHistorySections } from './agent-history-sections' +import { MOBILE_AI_VAULT_CAPABILITY } from './agent-history-capability' +import { shouldShowMobileCurrentWorktreeBadge } from './agent-history-current-worktree-badge' + +const NOW = Date.parse('2026-06-29T00:00:00.000Z') + +function session(overrides: Partial = {}): AiVaultSession { + return { + id: 'claude:1', + executionHostId: 'local', + agent: 'claude', + sessionId: 'session-1', + title: 'Implement vault filters', + cwd: '/Users/ada/repo/app', + branch: 'feature/vault', + model: 'claude-sonnet-4-5', + filePath: '/Users/ada/.claude/projects/session-1.jsonl', + codexHome: null, + createdAt: '2026-06-28T23:00:00.000Z', + updatedAt: '2026-06-28T23:55:00.000Z', + modifiedAt: '2026-06-28T23:55:00.000Z', + messageCount: 4, + totalTokens: 1200, + previewMessages: [ + { role: 'user', text: 'add the scope tabs', timestamp: null }, + { role: 'assistant', text: 'done — tabs added', timestamp: null } + ], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: '', + subagent: null, + ...overrides + } +} + +describe('buildMobileAgentHistoryCard', () => { + it('maps the card view-model with time-ago, label, and last message', () => { + const card = buildMobileAgentHistoryCard(session(), '/Users/ada/repo/app', NOW) + expect(card.agentLabel).toBe('Claude') + expect(card.timeAgo).toBe('5m') + expect(card.lastMessage).toBe('done — tabs added') + expect(card.messageCount).toBe(4) + expect(card.isCurrentWorktree).toBe(true) + }) + + it('omits the current-worktree badge when cwd is outside the active worktree', () => { + const card = buildMobileAgentHistoryCard(session(), '/Users/ada/other', NOW) + expect(card.isCurrentWorktree).toBe(false) + }) + + it('falls back to a title for empty session titles', () => { + const card = buildMobileAgentHistoryCard(session({ title: '' }), null, NOW) + expect(card.title).toBe('Untitled session') + expect(card.isCurrentWorktree).toBe(false) + }) +}) + +describe('buildMobileAgentHistoryResumeActionState', () => { + it('disables all resume buttons while one session is launching', () => { + const state = buildMobileAgentHistoryResumeActionState( + [session({ id: 'claude:1' }), session({ id: 'codex:2', agent: 'codex' })], + 'codex:2' + ) + expect(state.get('claude:1')).toEqual({ disabled: true, loading: false }) + expect(state.get('codex:2')).toEqual({ disabled: true, loading: true }) + }) + + it('keeps resume buttons enabled when no launch is in flight', () => { + const state = buildMobileAgentHistoryResumeActionState([session({ id: 'claude:1' })], null) + expect(state.get('claude:1')).toEqual({ disabled: false, loading: false }) + }) +}) + +describe('isSessionInActiveWorktree', () => { + it('matches a nested cwd inside the worktree path', () => { + expect( + isSessionInActiveWorktree({ cwd: '/Users/ada/repo/app/src' }, '/Users/ada/repo/app') + ).toBe(true) + }) + + it('is false without a cwd or active path', () => { + expect(isSessionInActiveWorktree({ cwd: null }, '/Users/ada/repo/app')).toBe(false) + expect(isSessionInActiveWorktree({ cwd: '/Users/ada/repo/app' }, null)).toBe(false) + }) +}) + +describe('buildMobileAgentHistorySections', () => { + it('hides empty sessions by default and groups remaining by folder', () => { + const sections = buildMobileAgentHistorySections( + [ + session(), + // Truly empty: no turns, no preview turns, no recoverable signals — + // preview turns alone now count as resumable content and stay visible. + session({ id: 'claude:empty', messageCount: 0, previewMessages: [] }) + ], + { + query: '', + scope: 'all', + scopeFilterPaths: [], + activeWorktreePath: '/Users/ada/repo/app', + now: NOW + } + ) + const allCards = sections.flatMap((s) => s.data) + expect(allCards.map((card) => card.id)).toEqual(['claude:1']) + }) + + it('applies the search query across sections', () => { + const sections = buildMobileAgentHistorySections( + [session(), session({ id: 'claude:2', title: 'Repair terminal tabs' })], + { query: 'repair', scope: 'all', scopeFilterPaths: [], activeWorktreePath: null, now: NOW } + ) + expect(sections.flatMap((s) => s.data).map((card) => card.id)).toEqual(['claude:2']) + }) + + // Why: the host union widens, so the screen must narrow scoped tabs by cwd + // path-prefix on the client — otherwise Workspace/Project show the same set as All. + it('narrows Workspace scope to sessions whose cwd is inside the active worktree path', () => { + const sessions = [ + session({ id: 'claude:in', cwd: '/Users/ada/repo/app/src' }), + session({ id: 'claude:out', cwd: '/Users/ada/other-repo' }) + ] + const sections = buildMobileAgentHistorySections(sessions, { + query: '', + scope: 'workspace', + scopeFilterPaths: ['/Users/ada/repo/app'], + activeWorktreePath: '/Users/ada/repo/app', + now: NOW + }) + expect(sections.flatMap((s) => s.data).map((card) => card.id)).toEqual(['claude:in']) + }) + + it('narrows Project scope to the active worktree plus same-repo sibling paths', () => { + const sessions = [ + session({ id: 'claude:active', cwd: '/Users/ada/repo/app' }), + session({ id: 'claude:sibling', cwd: '/Users/ada/repo/app-feature/lib' }), + session({ id: 'claude:foreign', cwd: '/Users/ada/unrelated' }) + ] + const sections = buildMobileAgentHistorySections(sessions, { + query: '', + scope: 'project', + scopeFilterPaths: ['/Users/ada/repo/app', '/Users/ada/repo/app-feature'], + activeWorktreePath: '/Users/ada/repo/app', + now: NOW + }) + expect( + sections + .flatMap((s) => s.data) + .map((card) => card.id) + .sort() + ).toEqual(['claude:active', 'claude:sibling']) + }) + + // Why: before worktree.ps resolves, scopeFilterPaths is empty on a scoped tab; + // the builder must fall back to unnarrowed rather than filter to an empty list. + it('falls back to unnarrowed when a scoped tab has no scopeFilterPaths yet', () => { + const sessions = [ + session({ id: 'claude:a', cwd: '/Users/ada/repo/app' }), + session({ id: 'claude:b', cwd: '/Users/ada/elsewhere' }) + ] + const sections = buildMobileAgentHistorySections(sessions, { + query: '', + scope: 'workspace', + scopeFilterPaths: [], + activeWorktreePath: null, + now: NOW + }) + expect( + sections + .flatMap((s) => s.data) + .map((card) => card.id) + .sort() + ).toEqual(['claude:a', 'claude:b']) + }) + + it('shows all sessions under All scope regardless of path', () => { + const sessions = [ + session({ id: 'claude:a', cwd: '/Users/ada/repo/app' }), + session({ id: 'claude:b', cwd: '/Users/ada/elsewhere' }) + ] + const sections = buildMobileAgentHistorySections(sessions, { + query: '', + scope: 'all', + scopeFilterPaths: [], + activeWorktreePath: '/Users/ada/repo/app', + now: NOW + }) + expect( + sections + .flatMap((s) => s.data) + .map((card) => card.id) + .sort() + ).toEqual(['claude:a', 'claude:b']) + }) +}) + +describe('MOBILE_AI_VAULT_CAPABILITY', () => { + it('stays in lockstep with the host AI_VAULT_RUNTIME_CAPABILITY string', () => { + // Why: mobile's protocol-version copy lacks the host constant; this literal + // must match src/shared/protocol-version.ts AI_VAULT_RUNTIME_CAPABILITY. + expect(MOBILE_AI_VAULT_CAPABILITY).toBe('aiVault.v1') + }) +}) + +describe('shouldShowMobileCurrentWorktreeBadge', () => { + it('hides the repeated current-worktree badge in Workspace scope', () => { + expect(shouldShowMobileCurrentWorktreeBadge('workspace')).toBe(false) + }) + + it('keeps the badge in mixed Project and All scopes', () => { + expect(shouldShowMobileCurrentWorktreeBadge('project')).toBe(true) + expect(shouldShowMobileCurrentWorktreeBadge('all')).toBe(true) + }) +}) diff --git a/mobile/src/agent-history/agent-history-session-card.ts b/mobile/src/agent-history/agent-history-session-card.ts new file mode 100644 index 000000000000..e18ac3f5410e --- /dev/null +++ b/mobile/src/agent-history/agent-history-session-card.ts @@ -0,0 +1,68 @@ +import { isPathInsideOrEqual } from '../../../src/shared/cross-platform-path' +import { latestSessionConversationTurn } from '../../../src/shared/ai-vault-session-display' +import { aiVaultAgentLabel } from '../../../src/shared/ai-vault-types' +import type { AiVaultSession } from '../../../src/shared/ai-vault-types' +import { formatTimeAgo } from '../worktree/agent-row-display' + +export type MobileAgentHistoryCard = { + id: string + agent: AiVaultSession['agent'] + agentLabel: string + title: string + lastMessage: string + messageCount: number + timeAgo: string + isCurrentWorktree: boolean +} + +export type MobileAgentHistoryResumeActionState = { + disabled: boolean + loading: boolean +} + +// Why: a session belongs to the active worktree when its recorded cwd is inside +// (or equal to) the worktree path; session rows carry no host id, so this is a +// path-prefix check (same logic the desktop badge uses). +export function isSessionInActiveWorktree( + session: Pick, + activeWorktreePath: string | null +): boolean { + if (!activeWorktreePath || !session.cwd) { + return false + } + return isPathInsideOrEqual(activeWorktreePath, session.cwd) +} + +export function buildMobileAgentHistoryCard( + session: AiVaultSession, + activeWorktreePath: string | null, + now: number +): MobileAgentHistoryCard { + const latestTurn = latestSessionConversationTurn(session) + const updatedAtMs = Date.parse(session.updatedAt ?? session.modifiedAt) + return { + id: session.id, + agent: session.agent, + agentLabel: aiVaultAgentLabel(session.agent), + title: session.title || 'Untitled session', + lastMessage: latestTurn?.text.trim() ?? '', + messageCount: session.messageCount, + timeAgo: Number.isFinite(updatedAtMs) ? formatTimeAgo(updatedAtMs, now) : '', + isCurrentWorktree: isSessionInActiveWorktree(session, activeWorktreePath) + } +} + +export function buildMobileAgentHistoryResumeActionState( + sessions: readonly Pick[], + resumingSessionId: string | null +): ReadonlyMap { + return new Map( + sessions.map((session) => [ + session.id, + { + disabled: resumingSessionId !== null, + loading: resumingSessionId === session.id + } + ]) + ) +} diff --git a/mobile/src/agent-history/agent-history-session-worktree.test.ts b/mobile/src/agent-history/agent-history-session-worktree.test.ts new file mode 100644 index 000000000000..9a7ad0d3981e --- /dev/null +++ b/mobile/src/agent-history/agent-history-session-worktree.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest' +import type { AiVaultSession } from '../../../src/shared/ai-vault-types' +import type { Worktree } from '../worktree/workspace-list-types' +import { + canResumeInMobileSessionWorktree, + resolveMobileAgentHistorySessionWorktree +} from './agent-history-session-worktree' + +function session(cwd: string | null): Pick { + return { cwd } +} + +function worktree(overrides: Partial & { worktreeId: string; path: string }): Worktree { + return { + repoId: 'repo-1', + repo: 'orca', + branch: 'main', + displayName: overrides.worktreeId, + liveTerminalCount: 0, + hasAttachedPty: false, + preview: '', + unread: false, + isPinned: false, + linkedPR: null, + ...overrides + } +} + +describe('resolveMobileAgentHistorySessionWorktree', () => { + it('matches the active worktree when session cwd is inside it', () => { + const resolved = resolveMobileAgentHistorySessionWorktree({ + session: session('/Users/ada/repo/app/src'), + worktrees: [worktree({ worktreeId: 'wt-1', path: '/Users/ada/repo/app' })], + activeWorktreeId: 'wt-1' + }) + expect(resolved).toMatchObject({ status: 'current', worktreeId: 'wt-1' }) + }) + + it('prefers the longest active path match', () => { + const resolved = resolveMobileAgentHistorySessionWorktree({ + session: session('/Users/ada/repo/app/packages/mobile'), + worktrees: [ + worktree({ worktreeId: 'root', path: '/Users/ada/repo' }), + worktree({ worktreeId: 'app', path: '/Users/ada/repo/app' }) + ], + activeWorktreeId: 'root' + }) + expect(resolved).toMatchObject({ status: 'active', worktreeId: 'app' }) + }) + + it('marks archived worktrees as unavailable for resume', () => { + const resolved = resolveMobileAgentHistorySessionWorktree({ + session: session('/Users/ada/repo/app'), + worktrees: [ + worktree({ worktreeId: 'archived', path: '/Users/ada/repo/app', isArchived: true }) + ], + activeWorktreeId: 'other' + }) + expect(resolved).toMatchObject({ status: 'archived', worktreeId: 'archived' }) + expect(canResumeInMobileSessionWorktree(resolved)).toBe(false) + }) + + it('returns null when the session cwd has no active worktree match', () => { + expect( + resolveMobileAgentHistorySessionWorktree({ + session: session('/Users/ada/missing'), + worktrees: [worktree({ worktreeId: 'wt-1', path: '/Users/ada/repo/app' })], + activeWorktreeId: 'wt-1' + }) + ).toBeNull() + }) + + it('matches WSL UNC worktree paths against Linux transcript paths', () => { + const resolved = resolveMobileAgentHistorySessionWorktree({ + session: session('/home/ada/repo/app'), + worktrees: [ + worktree({ + worktreeId: 'wsl', + path: '\\\\wsl.localhost\\Ubuntu\\home\\ada\\repo' + }) + ], + activeWorktreeId: 'wsl' + }) + expect(resolved).toMatchObject({ status: 'current', worktreeId: 'wsl' }) + }) +}) diff --git a/mobile/src/agent-history/agent-history-session-worktree.ts b/mobile/src/agent-history/agent-history-session-worktree.ts new file mode 100644 index 000000000000..0e859bbf5ee1 --- /dev/null +++ b/mobile/src/agent-history/agent-history-session-worktree.ts @@ -0,0 +1,103 @@ +import { isPathInsideOrEqual, isRuntimePathAbsolute } from '../../../src/shared/cross-platform-path' +import { parseWslUncPath } from '../../../src/shared/wsl-paths' +import { splitWorktreeIdForFilesystem } from '../../../src/shared/worktree-id' +import type { AiVaultSession } from '../../../src/shared/ai-vault-types' +import type { Worktree } from '../worktree/workspace-list-types' + +export type MobileAgentHistorySessionWorktreeStatus = 'current' | 'active' | 'archived' + +export type MobileAgentHistorySessionWorktreeInfo = { + status: MobileAgentHistorySessionWorktreeStatus + worktreeId: string + path: string +} + +type WorktreeCandidate = { + worktree: WorktreeWithPriorIds + path: string + source: 'current-path' | 'prior-path' +} + +type WorktreeWithPriorIds = Worktree & { + priorWorktreeIds?: readonly string[] +} + +export function resolveMobileAgentHistorySessionWorktree(args: { + session: Pick + worktrees: readonly Worktree[] + activeWorktreeId: string | null +}): MobileAgentHistorySessionWorktreeInfo | null { + if (!args.session.cwd) { + return null + } + const sessionCwd = args.session.cwd + + const candidates = buildMobileWorktreeCandidates(args.worktrees) + .filter((candidate) => isSessionInWorktreePath(candidate.path, sessionCwd)) + .sort(compareWorktreeCandidates) + const best = candidates[0] + if (!best) { + return null + } + + return { + status: + best.worktree.worktreeId === args.activeWorktreeId + ? 'current' + : best.worktree.isArchived + ? 'archived' + : 'active', + worktreeId: best.worktree.worktreeId, + path: best.path + } +} + +export function canResumeInMobileSessionWorktree( + worktreeInfo: MobileAgentHistorySessionWorktreeInfo | null +): boolean { + return Boolean(worktreeInfo && worktreeInfo.status !== 'archived') +} + +function buildMobileWorktreeCandidates(worktrees: readonly Worktree[]): WorktreeCandidate[] { + const candidates: WorktreeCandidate[] = [] + for (const worktree of worktrees as readonly WorktreeWithPriorIds[]) { + if (hasUsablePath(worktree.path)) { + candidates.push({ worktree, path: worktree.path, source: 'current-path' }) + } + for (const priorWorktreeId of worktree.priorWorktreeIds ?? []) { + const parsed = splitWorktreeIdForFilesystem(priorWorktreeId) + if (!parsed || parsed.repoId !== worktree.repoId || !hasUsablePath(parsed.worktreePath)) { + continue + } + candidates.push({ worktree, path: parsed.worktreePath, source: 'prior-path' }) + } + } + return candidates +} + +function hasUsablePath(pathValue: string): boolean { + return Boolean(pathValue.trim() && isRuntimePathAbsolute(pathValue)) +} + +function isSessionInWorktreePath(worktreePath: string, sessionCwd: string): boolean { + if (isPathInsideOrEqual(worktreePath, sessionCwd)) { + return true + } + const wslPath = parseWslUncPath(worktreePath) + return wslPath ? isPathInsideOrEqual(wslPath.linuxPath, sessionCwd) : false +} + +function compareWorktreeCandidates(left: WorktreeCandidate, right: WorktreeCandidate): number { + const lengthDifference = normalizedPathLength(right.path) - normalizedPathLength(left.path) + if (lengthDifference !== 0) { + return lengthDifference + } + if (left.source === right.source) { + return 0 + } + return left.source === 'current-path' ? -1 : 1 +} + +function normalizedPathLength(pathValue: string): number { + return pathValue.replace(/\\/g, '/').replace(/\/+$/g, '').toLowerCase().length +} diff --git a/mobile/src/agent-history/agent-history-styles.ts b/mobile/src/agent-history/agent-history-styles.ts new file mode 100644 index 000000000000..c3174623bf40 --- /dev/null +++ b/mobile/src/agent-history/agent-history-styles.ts @@ -0,0 +1,242 @@ +import { StyleSheet } from 'react-native' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' + +export const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: colors.bgBase + }, + header: { + backgroundColor: colors.bgBase + }, + topBar: { + flexDirection: 'row', + alignItems: 'center', + paddingHorizontal: spacing.sm, + paddingVertical: spacing.sm, + borderBottomWidth: 1, + borderBottomColor: colors.borderSubtle + }, + backButton: { + padding: spacing.xs, + borderRadius: radii.button + }, + backButtonPressed: { + backgroundColor: colors.bgRaised + }, + titleBlock: { + flex: 1, + marginHorizontal: spacing.sm + }, + title: { + color: colors.textPrimary, + fontSize: typography.titleSize, + fontWeight: '600' + }, + meta: { + color: colors.textSecondary, + fontSize: typography.metaSize + }, + refreshButton: { + padding: spacing.xs, + borderRadius: radii.button + }, + refreshButtonPressed: { + backgroundColor: colors.bgRaised + }, + scopeTabs: { + flexDirection: 'row', + paddingHorizontal: spacing.md, + paddingTop: spacing.sm, + gap: spacing.xs + }, + scopeTab: { + flex: 1, + alignItems: 'center', + paddingVertical: spacing.sm, + borderRadius: radii.button, + backgroundColor: colors.bgPanel + }, + scopeTabActive: { + backgroundColor: colors.bgRaised + }, + scopeTabText: { + color: colors.textSecondary, + fontSize: typography.bodySize + }, + scopeTabTextActive: { + color: colors.textPrimary, + fontWeight: '600' + }, + searchRow: { + paddingHorizontal: spacing.md, + paddingTop: spacing.sm + }, + searchInput: { + backgroundColor: colors.bgPanel, + borderRadius: radii.input, + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm, + color: colors.textPrimary, + fontSize: typography.bodySize + }, + list: { + paddingHorizontal: spacing.md, + paddingTop: spacing.sm, + paddingBottom: spacing.xl + }, + groupHeader: { + flexDirection: 'row', + alignItems: 'center', + paddingVertical: spacing.sm, + gap: spacing.sm + }, + groupHeaderText: { + color: colors.textSecondary, + fontSize: typography.metaSize, + fontWeight: '600', + textTransform: 'uppercase' + }, + groupHeaderCount: { + color: colors.textMuted, + fontSize: typography.metaSize + }, + card: { + backgroundColor: colors.bgPanel, + borderRadius: radii.card, + padding: spacing.md, + marginBottom: spacing.sm + }, + cardPressed: { + backgroundColor: colors.bgRaised + }, + cardTopRow: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm + }, + cardTitle: { + flex: 1, + color: colors.textPrimary, + fontSize: typography.bodySize, + fontWeight: '600' + }, + cardTimeAgo: { + color: colors.textMuted, + fontSize: typography.metaSize + }, + cardLastMessage: { + color: colors.textSecondary, + fontSize: typography.metaSize, + marginTop: spacing.xs + }, + cardMetaRow: { + flexDirection: 'row', + alignItems: 'center', + flexWrap: 'wrap', + gap: spacing.sm, + marginTop: spacing.xs + }, + cardMetaText: { + color: colors.textMuted, + fontSize: typography.metaSize + }, + currentBadge: { + backgroundColor: colors.bgRaised, + borderRadius: radii.button, + paddingHorizontal: spacing.sm, + paddingVertical: 2 + }, + currentBadgeText: { + color: colors.accentBlue, + fontSize: typography.metaSize, + fontWeight: '600' + }, + resumeButton: { + minHeight: 28, + minWidth: 28, + alignItems: 'center', + justifyContent: 'center', + marginLeft: 'auto', + paddingHorizontal: spacing.xs, + paddingVertical: spacing.xs, + borderRadius: radii.button + }, + resumeButtonPressed: { + opacity: 0.78 + }, + resumeButtonDisabled: { + opacity: 0.45 + }, + preview: { + marginTop: spacing.sm, + paddingTop: spacing.sm, + borderTopWidth: 1, + borderTopColor: colors.borderSubtle, + gap: spacing.sm + }, + previewTurn: { + gap: 2 + }, + previewRole: { + color: colors.textMuted, + fontSize: typography.metaSize, + fontWeight: '600', + textTransform: 'uppercase' + }, + previewText: { + color: colors.textSecondary, + fontSize: typography.metaSize + }, + noticeBanner: { + marginHorizontal: spacing.md, + marginTop: spacing.sm, + padding: spacing.sm, + borderRadius: radii.input, + backgroundColor: colors.bgPanel + }, + noticeText: { + color: colors.statusAmber, + fontSize: typography.metaSize + }, + resumeBanner: { + marginHorizontal: spacing.md, + marginTop: spacing.sm, + padding: spacing.sm, + borderRadius: radii.input, + backgroundColor: colors.bgPanel + }, + resumeBannerText: { + color: colors.textSecondary, + fontSize: typography.metaSize + }, + state: { + flex: 1, + alignItems: 'center', + justifyContent: 'center', + padding: spacing.xl, + gap: spacing.sm + }, + stateTitle: { + color: colors.textPrimary, + fontSize: typography.bodySize, + fontWeight: '600' + }, + stateText: { + color: colors.textSecondary, + fontSize: typography.metaSize, + textAlign: 'center' + }, + retryButton: { + marginTop: spacing.sm, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.sm, + borderRadius: radii.button, + backgroundColor: colors.bgRaised + }, + retryText: { + color: colors.textPrimary, + fontSize: typography.bodySize, + fontWeight: '600' + } +}) diff --git a/mobile/src/agent-history/use-mobile-agent-history-state.ts b/mobile/src/agent-history/use-mobile-agent-history-state.ts new file mode 100644 index 000000000000..a0a82bee019a --- /dev/null +++ b/mobile/src/agent-history/use-mobile-agent-history-state.ts @@ -0,0 +1,192 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useHostClient, useForceReconnect } from '../transport/client-context' +import type { RpcSuccess } from '../transport/types' +import type { + AiVaultListResult, + AiVaultScanIssue, + AiVaultScope, + AiVaultSession +} from '../../../src/shared/ai-vault-types' +import type { Worktree } from '../worktree/workspace-list-types' +import { deriveMobileAiVaultScopePaths } from './agent-history-scope-paths' +import { MOBILE_AI_VAULT_CAPABILITY } from './agent-history-capability' + +export { MOBILE_AI_VAULT_CAPABILITY } + +// Why: mirror the desktop renderer's SESSION_LIMIT=500. limit caps only the +// global recency list; the in-scope Claude union is capped separately host-side, +// so the response can still be large — hence virtualization + lazy preview. +const MOBILE_AI_VAULT_SESSION_LIMIT = 500 + +export type AgentHistoryScreenState = + | { kind: 'loading' } + | { kind: 'unsupported' } + | { kind: 'error'; message: string } + | { kind: 'ready'; sessions: AiVaultSession[]; issues: AiVaultScanIssue[] } + +type StatusWithCapabilities = { capabilities?: string[] } + +export type MobileAgentHistoryStateParams = { + hostId: string + worktreeId: string + worktrees: readonly Worktree[] + // Why: distinguishes "worktree list not fetched yet" from "fetched, but this + // worktree isn't in it" so a scoped tab holds loading only for the former. + worktreesLoaded: boolean +} + +export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams) { + const { hostId, worktreeId, worktrees, worktreesLoaded } = params + const { client, state: connState } = useHostClient(hostId) + const forceReconnect = useForceReconnect() + const [scope, setScope] = useState('workspace') + const [screenState, setScreenState] = useState({ kind: 'loading' }) + const [hostStatusResult, setHostStatusResult] = useState(null) + const [refreshing, setRefreshing] = useState(false) + const generationRef = useRef(0) + const mountedRef = useRef(true) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + } + }, []) + + const activeWorktree = useMemo( + () => worktrees.find((worktree) => worktree.worktreeId === worktreeId) ?? null, + [worktrees, worktreeId] + ) + const activeWorktreePath = activeWorktree?.path ?? null + // Why: the host union only widens, so the screen narrows by these cwd + // path-prefixes for the current scope (empty for 'all'). Same derivation the + // RPC scopePaths use, reused client-side for the actual narrowing. + const scopeFilterPaths = useMemo( + () => deriveMobileAiVaultScopePaths(scope, activeWorktree, worktrees), + [scope, activeWorktree, worktrees] + ) + + const loadSessions = useCallback( + async (options: { scope: AiVaultScope; force: boolean }): Promise => { + const generation = generationRef.current + 1 + generationRef.current = generation + const isCurrent = () => mountedRef.current && generationRef.current === generation + + if (!client || connState !== 'connected') { + if (isCurrent()) { + // Why: keep the stale list visible through transient reconnects + // (connState flips re-run the load effect) instead of tearing it + // down to a full-screen error, matching the host list screen. + setScreenState((prev) => + prev.kind === 'ready' ? prev : { kind: 'error', message: 'Waiting for host…' } + ) + } + return + } + + setScreenState((prev) => (prev.kind === 'ready' ? prev : { kind: 'loading' })) + try { + // Gate on the capability so older hosts lacking the method are detected + // and we never call a missing RPC. + const statusResponse = await client.sendRequest('status.get') + if (!isCurrent()) { + return + } + if (!statusResponse.ok) { + throw new Error(statusResponse.error?.message || 'Unable to reach host') + } + const status = (statusResponse as RpcSuccess).result as StatusWithCapabilities + setHostStatusResult(status) + if (!status.capabilities?.includes(MOBILE_AI_VAULT_CAPABILITY)) { + setScreenState({ kind: 'unsupported' }) + return + } + + // Why: a scoped tab needs the active worktree's path to narrow. Until the + // worktree list has loaded, hold loading rather than firing an unscoped + // fetch that would briefly show unrelated host history. Once loaded we + // proceed even if the worktree isn't found, to avoid a stuck spinner. + if (options.scope !== 'all' && !activeWorktree && !worktreesLoaded) { + if (isCurrent()) { + setScreenState((prev) => (prev.kind === 'ready' ? prev : { kind: 'loading' })) + } + return + } + + const scopePaths = deriveMobileAiVaultScopePaths(options.scope, activeWorktree, worktrees) + const response = await client.sendRequest('aiVault.listSessions', { + limit: MOBILE_AI_VAULT_SESSION_LIMIT, + force: options.force, + scopePaths + }) + if (!isCurrent()) { + return + } + if (!response.ok) { + throw new Error(response.error?.message || 'Unable to load agent sessions') + } + const result = (response as RpcSuccess).result as AiVaultListResult + setScreenState({ kind: 'ready', sessions: result.sessions, issues: result.issues }) + } catch (err) { + if (!isCurrent()) { + return + } + const message = err instanceof Error ? err.message : 'Unable to load agent sessions' + setHostStatusResult(null) + setScreenState({ kind: 'error', message }) + } + }, + [activeWorktree, client, connState, worktrees, worktreesLoaded] + ) + + // Initial + reconnect load. Why: scope switches reuse the host's 15s cache + // (force:false) so a tab tap is cheap; only an explicit refresh bypasses it. + useEffect(() => { + void loadSessions({ scope, force: false }) + // eslint-disable-next-line react-hooks/exhaustive-deps -- scope handled by onSelectScope + }, [loadSessions]) + + const onSelectScope = useCallback( + (nextScope: AiVaultScope) => { + setScope(nextScope) + void loadSessions({ scope: nextScope, force: false }) + }, + [loadSessions] + ) + + const onRefresh = useCallback(async () => { + setRefreshing(true) + try { + // Why: pull-to-refresh bypasses the host TTL (force:true) and joins any + // active inflight scan; otherwise a refresh within 15s shows no change. + await loadSessions({ scope, force: true }) + } finally { + if (mountedRef.current) { + setRefreshing(false) + } + } + }, [loadSessions, scope]) + + const retry = useCallback(() => { + if (connState !== 'connected' && hostId) { + void forceReconnect(hostId) + return + } + void loadSessions({ scope, force: false }) + }, [connState, forceReconnect, hostId, loadSessions, scope]) + + return { + connState, + scope, + screenState, + refreshing, + hostStatusResult, + activeWorktreePath, + scopeFilterPaths, + onSelectScope, + onRefresh, + retry + } +} + +export type MobileAgentHistoryState = ReturnType diff --git a/mobile/src/agent-history/worktree-navigation-actions.ts b/mobile/src/agent-history/worktree-navigation-actions.ts new file mode 100644 index 000000000000..8359c8ee0207 --- /dev/null +++ b/mobile/src/agent-history/worktree-navigation-actions.ts @@ -0,0 +1,50 @@ +import { GitBranch } from 'lucide-react-native' +import type { ActionSheetAction } from '../components/ActionSheetModal' +import { colors } from '../theme/mobile-theme' +import { MOBILE_AI_VAULT_CAPABILITY } from './agent-history-capability' +import { MobileAgentSessionHistoryIcon } from './MobileAgentSessionHistoryIcon' + +type Args = { + hostId: string + worktreeId: string + worktreeName: string + hostCapabilities: readonly string[] + navigate: (target: string) => void + onDone: () => void +} + +// Why: builds the per-worktree "navigate to a screen" action-sheet actions +// (Source Control + Agent Session History). The Agent Session History action is +// included only on hosts advertising the aiVault.v1 capability, so we never +// navigate to a screen that would call a missing RPC method. Extracted from the +// host index action sheet to keep that file under its max-lines budget. +export function buildWorktreeNavigationActions(args: Args): ActionSheetAction[] { + const actions: ActionSheetAction[] = [ + { + label: 'Source Control', + icon: GitBranch, + onPress: () => { + const params = new URLSearchParams({ name: args.worktreeName, origin: 'host' }) + args.navigate( + `/h/${args.hostId}/source-control/${encodeURIComponent(args.worktreeId)}?${params.toString()}` + ) + args.onDone() + } + } + ] + if (args.hostCapabilities.includes(MOBILE_AI_VAULT_CAPABILITY)) { + actions.push({ + label: 'Agent Session History', + renderIcon: () => + MobileAgentSessionHistoryIcon({ size: 16, color: colors.textSecondary, strokeWidth: 2 }), + onPress: () => { + const params = new URLSearchParams({ name: args.worktreeName }) + args.navigate( + `/h/${args.hostId}/agent-history/${encodeURIComponent(args.worktreeId)}?${params.toString()}` + ) + args.onDone() + } + }) + } + return actions +} diff --git a/mobile/src/components/AccountUsage.tsx b/mobile/src/components/AccountUsage.tsx index 9d85bf434b70..00b3e6074876 100644 --- a/mobile/src/components/AccountUsage.tsx +++ b/mobile/src/components/AccountUsage.tsx @@ -21,9 +21,9 @@ export { hasRenderableUsage } from './account-usage-state' -// Why: matches desktop StatusBar convention — bars show percent remaining -// (so a fresh account renders full, a depleted one renders empty), not -// percent used. Color thresholds invert accordingly. +// Why: matches desktop StatusBar — bars show percent used (consumption), same +// as Claude/Codex harness meters. Fresh account is empty/green; depleted is +// full/red. export function UsageBar({ label, usedPercent, @@ -35,13 +35,15 @@ export function UsageBar({ unavailable: boolean loading?: boolean }) { - const remaining = usedPercent == null ? null : Math.max(0, Math.min(100, 100 - usedPercent)) + // Why: round then clamp so bar width, color, and label share one value (desktop parity). + const used = usedPercent == null ? null : Math.max(0, Math.min(100, Math.round(usedPercent))) + // Why: same consumption bands as desktop barColor (green <60, amber <80, red ≥80). const barColor = - remaining == null + used == null ? colors.textMuted - : remaining <= 10 + : used >= 80 ? colors.statusRed - : remaining <= 30 + : used >= 60 ? colors.statusAmber : colors.statusGreen return ( @@ -52,7 +54,7 @@ export function UsageBar({ style={[ styles.usageFill, { - width: `${remaining ?? 0}%`, + width: `${used ?? 0}%`, backgroundColor: unavailable ? colors.textMuted : barColor } ]} @@ -61,9 +63,7 @@ export function UsageBar({ {loading ? ( ) : ( - - {unavailable || remaining == null ? '—' : `${Math.round(remaining)}%`} - + {unavailable || used == null ? '—' : `${used}%`} )} ) diff --git a/mobile/src/components/MobileMarkdown.tsx b/mobile/src/components/MobileMarkdown.tsx index 5ee7ca6b4e75..3200dcc5d71f 100644 --- a/mobile/src/components/MobileMarkdown.tsx +++ b/mobile/src/components/MobileMarkdown.tsx @@ -15,7 +15,7 @@ const MAX_TABLE_COLUMNS = 8 function openMarkdownUrl(url: string): void { const trimmed = url.trim() if (/^(https?:|mailto:)/i.test(trimmed)) { - void Linking.openURL(trimmed) + void Linking.openURL(trimmed).catch(() => {}) } } diff --git a/mobile/src/components/MobilePRSidebar.tsx b/mobile/src/components/MobilePRSidebar.tsx index 932f72e262ab..42829df03102 100644 --- a/mobile/src/components/MobilePRSidebar.tsx +++ b/mobile/src/components/MobilePRSidebar.tsx @@ -39,6 +39,8 @@ type Props = { gitStatus: MobileGitStatusResult | null headSha: string | null bottomInset?: number + // Hub chrome already shows open-on-web; hide the in-body icon there. + showOpenOnWeb?: boolean } // Mutation hooks run unconditionally here and gate internally until a PR is ready. @@ -52,17 +54,15 @@ export function MobilePRSidebar({ gitBranch, gitStatus, headSha, - bottomInset = 0 + bottomInset = 0, + showOpenOnWeb = true }: Props) { const branch = prSidebarRenderBranch(state) // prNumber is 0 until ready; the hook gates on `ready` so it never fires early. const prNumber = state.kind === 'ready' ? state.data.pr.number : 0 - const prRepo = - state.kind === 'ready' - ? state.data.pr.prRepo - ? { owner: state.data.pr.prRepo.owner, repo: state.data.pr.prRepo.repo } - : null - : null + // Prefer the stable PRInfo.prRepo reference — cloning owner/repo each render + // reallocates and thrash-updates the mutation/comment/title hooks. + const prRepo = state.kind === 'ready' ? (state.data.pr.prRepo ?? null) : null const actions = useMobilePrActions({ client, connState, @@ -95,6 +95,9 @@ export function MobilePRSidebar({ style={{ flex: 1 }} contentContainerStyle={[styles.scrollContent, { paddingBottom: bottomInset }]} keyboardShouldPersistTaps="handled" + // Why: root-comment / reply composers sit at the bottom of this scroll + // area; without keyboard insets the focused field stays under the keyboard. + automaticallyAdjustKeyboardInsets showsVerticalScrollIndicator={false} > ) @@ -129,7 +133,8 @@ function PrSidebarContent({ actions, commentActions, titleAction, - triage + triage, + showOpenOnWeb }: { branch: ReturnType state: PrSidebarState @@ -144,6 +149,7 @@ function PrSidebarContent({ commentActions: MobilePrCommentActions titleAction: MobilePrTitleAction triage: MobilePrAiTriage + showOpenOnWeb: boolean }) { if (branch === 'loading') { return ( @@ -209,6 +215,7 @@ function PrSidebarContent({ titleAction={titleAction} triage={triage} refetch={refetch} + showOpenOnWeb={showOpenOnWeb} /> ) } @@ -223,7 +230,8 @@ function PrSidebarSections({ commentActions, titleAction, triage, - refetch + refetch, + showOpenOnWeb }: { data: Extract['data'] client: RpcClient | null @@ -233,6 +241,7 @@ function PrSidebarSections({ titleAction: MobilePrTitleAction triage: MobilePrAiTriage refetch: () => void + showOpenOnWeb: boolean }) { const pr = data.pr // Bind the triage launchers to this PR's data; the prompt builders are pure so @@ -262,19 +271,30 @@ function PrSidebarSections({ isBusy: triage.isBusy('resolve-conflicts'), error: triage.error } + // One card for identity + actions so the ready PR isn't a stack of thin + // duplicate blocks (badge row, title, branches, then another action band). return ( <> - - {/* Conflicting-files section mirrors desktop order: directly below the header, - before actions/checks. Renders only when the PR has merge conflicts. */} + + + + + + + {/* Own titled section when present; null otherwise (no empty chrome). */} - {}) } diff --git a/mobile/src/components/MobileSearchField.tsx b/mobile/src/components/MobileSearchField.tsx new file mode 100644 index 000000000000..2dfd6bf26e4d --- /dev/null +++ b/mobile/src/components/MobileSearchField.tsx @@ -0,0 +1,201 @@ +import { useEffect, useRef, useState } from 'react' +import { + InteractionManager, + Platform, + Pressable, + StyleSheet, + TextInput, + View, + type TextInputProps +} from 'react-native' +import { Search, X } from 'lucide-react-native' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' + +// Why: toolbar/list chrome paints and settles after the open tap; native +// autoFocus alone often fails to raise the soft keyboard on iOS/Android. +const SEARCH_AUTO_FOCUS_DELAY_MS = 120 + +type MobileSearchFieldProps = { + value: string + onChangeText: (text: string) => void + placeholder: string + onClear?: () => void + /** Override clear-button visibility (default: value is non-empty). */ + showClear?: boolean + clearAccessibilityLabel?: string + autoFocus?: boolean + /** Re-run delayed focus when this identity changes (e.g. each time search opens). */ + focusKey?: unknown + returnKeyType?: TextInputProps['returnKeyType'] + onSubmitEditing?: TextInputProps['onSubmitEditing'] + onBlur?: TextInputProps['onBlur'] + editable?: boolean + accessibilityLabel?: string +} + +/** + * Raised search field used on list screens. Sits above the base/panel canvas + * so it reads as a tappable control instead of chrome that blends into the list. + */ +export function MobileSearchField({ + value, + onChangeText, + placeholder, + onClear, + showClear, + clearAccessibilityLabel = 'Clear search', + autoFocus = false, + focusKey, + returnKeyType = 'search', + onSubmitEditing, + onBlur, + editable = true, + accessibilityLabel +}: MobileSearchFieldProps) { + const inputRef = useRef(null) + const [focused, setFocused] = useState(false) + const clearVisible = showClear ?? value.length > 0 + + useEffect(() => { + if (!autoFocus || !editable) { + return + } + + let timeout: ReturnType | undefined + // Why: wait for the open-press interaction + layout to finish, then focus + // so the soft keyboard actually appears (not just a caret with no IME). + const task = InteractionManager.runAfterInteractions(() => { + timeout = setTimeout(() => { + inputRef.current?.focus() + }, SEARCH_AUTO_FOCUS_DELAY_MS) + }) + + return () => { + task.cancel() + if (timeout) { + clearTimeout(timeout) + } + } + }, [autoFocus, editable, focusKey]) + + function handleClear() { + if (onClear) { + onClear() + } else { + onChangeText('') + } + // Why: pressing the clear chip steals focus and drops the keyboard; + // re-focus so the user can keep typing without tapping the field again. + requestAnimationFrame(() => { + inputRef.current?.focus() + }) + } + + return ( + + + setFocused(true)} + onBlur={(event) => { + setFocused(false) + onBlur?.(event) + }} + clearButtonMode="never" + accessibilityLabel={accessibilityLabel ?? placeholder} + selectionColor={colors.accentBlue} + /> + {clearVisible ? ( + [styles.clearButton, pressed && styles.clearButtonPressed]} + > + {/* Why: chip + larger hit target — a bare 14px X was hard to tap and + read as decoration rather than a clear control. */} + + + + + ) : null} + + ) +} + +const styles = StyleSheet.create({ + shell: { + minHeight: 42, + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + // Why: bgRaised lifts the field off bgBase/bgPanel so search is an obvious + // control, matching TextInputModal / MobilePrBasePicker input shells. + backgroundColor: colors.bgRaised, + borderWidth: 1, + borderColor: colors.borderSubtle, + borderRadius: radii.input, + paddingLeft: spacing.md, + paddingRight: spacing.xs, + paddingVertical: Platform.OS === 'ios' ? spacing.sm : spacing.xs + 2 + }, + shellFocused: { + // Why: monochrome focus cue without burning the blue accent token + // (reserved for state/selection). textMuted reads clearly on bgRaised. + borderColor: colors.textMuted + }, + shellDisabled: { + opacity: 0.55 + }, + input: { + flex: 1, + minWidth: 0, + padding: 0, + margin: 0, + color: colors.textPrimary, + fontSize: typography.bodySize, + // Why: Android TextInput draws extra vertical padding that misaligns the + // icon/clear chip unless we zero it out. + includeFontPadding: false, + textAlignVertical: 'center' + }, + clearButton: { + minWidth: 36, + minHeight: 36, + alignItems: 'center', + justifyContent: 'center' + }, + clearButtonPressed: { + opacity: 0.7 + }, + clearChip: { + width: 24, + height: 24, + borderRadius: 12, + alignItems: 'center', + justifyContent: 'center', + // Why: textMuted reads as a solid chip on bgRaised; borderSubtle was nearly + // invisible and made the clear control feel like decorative chrome. + backgroundColor: colors.textMuted + } +}) diff --git a/mobile/src/components/pr-sidebar/MobilePrViewPanel.tsx b/mobile/src/components/pr-sidebar/MobilePrViewPanel.tsx index e1b19263f540..f587074e12ee 100644 --- a/mobile/src/components/pr-sidebar/MobilePrViewPanel.tsx +++ b/mobile/src/components/pr-sidebar/MobilePrViewPanel.tsx @@ -1,13 +1,10 @@ -import { useEffect } from 'react' -import { Pressable, StyleSheet, Text, View } from 'react-native' -import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' -import { useRouter } from 'expo-router' -import { ChevronLeft, X } from 'lucide-react-native' -import { colors, radii, spacing, typography } from '../../theme/mobile-theme' +import { StyleSheet, View } from 'react-native' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import { colors } from '../../theme/mobile-theme' import type { ConnectionState } from '../../transport/types' import type { RpcClient } from '../../transport/rpc-client' import type { MobileGitStatusResult } from '../../source-control/mobile-git-status' -import { useMobilePrSidebarController } from '../../session/use-mobile-pr-sidebar-controller' +import type { MobilePrSidebarController } from '../../session/use-mobile-pr-sidebar-controller' import { MobilePRSidebar } from '../MobilePRSidebar' type Props = { @@ -19,13 +16,13 @@ type Props = { gitStatus: MobileGitStatusResult | null isGithubRepo?: boolean branchContextLoaded?: boolean - // Embedded (docked) drops the full-screen SafeAreaView chrome and shows a close - // affordance; the dock column owns the safe-area insets. Full-screen otherwise. - embedded?: boolean - onRequestClose?: () => void + controller: MobilePrSidebarController } -export function MobilePrViewPanel({ +// Chromeless PR sidebar body for the source-control hub's Pull Request segment. +// The hub owns the header, segmented control, load triggers, and the shared +// controller (one fetch feeds both the branch-card chip and this body). +export function MobilePrViewPanelBody({ client, connState, worktreeId, @@ -34,32 +31,10 @@ export function MobilePrViewPanel({ gitStatus, isGithubRepo = true, branchContextLoaded = true, - embedded = false, - onRequestClose + controller }: Props) { - const router = useRouter() const insets = useSafeAreaInsets() - const controller = useMobilePrSidebarController({ - client, - connState, - worktreeId, - branch, - headSha - }) - // A docked/full-screen PR panel is always visible — there is no drawer to open, - // so trigger the load directly once context is ready rather than gating on the - // showPRSidebar overlay flag (KTD4). - const prSidebarKind = controller.prSidebarState.kind - const refetch = controller.refetchPRSidebar - useEffect(() => { - if (branch && isGithubRepo && prSidebarKind === 'hidden') { - refetch() - } - }, [branch, isGithubRepo, prSidebarKind, refetch]) - - // Embedded: the dock column applies the bottom inset; full-screen relies on its own - // SafeAreaView (edges top only), so content must clear the home indicator itself. const sidebarState = !branchContextLoaded ? ({ kind: 'loading' } as const) : !isGithubRepo @@ -73,63 +48,24 @@ export function MobilePrViewPanel({ message: 'Current branch unavailable.' } as const) : controller.prSidebarState - const sidebar = ( - - ) - - if (embedded) { - return ( - - - - [styles.iconButton, pressed && styles.iconButtonPressed]} - onPress={onRequestClose} - hitSlop={8} - accessibilityLabel="Close pull request panel" - > - - - - Pull Request - - - - {sidebar} - - ) - } return ( - - - - [styles.iconButton, pressed && styles.iconButtonPressed]} - onPress={() => router.back()} - hitSlop={8} - accessibilityLabel="Back to session" - > - - - - Pull Request - - - - {sidebar} - + + + ) } @@ -137,34 +73,5 @@ const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: colors.bgBase - }, - header: { - backgroundColor: colors.bgPanel, - borderBottomWidth: StyleSheet.hairlineWidth, - borderBottomColor: colors.borderSubtle - }, - topBar: { - minHeight: 58, - flexDirection: 'row', - alignItems: 'center', - gap: spacing.md, - paddingHorizontal: spacing.md - }, - iconButton: { - width: 36, - height: 36, - alignItems: 'center', - justifyContent: 'center', - borderRadius: radii.button - }, - iconButtonPressed: { - backgroundColor: colors.bgRaised - }, - title: { - flex: 1, - minWidth: 0, - color: colors.textPrimary, - fontSize: typography.titleSize, - fontWeight: '600' } }) diff --git a/mobile/src/components/pr-sidebar/PRActionsSection.tsx b/mobile/src/components/pr-sidebar/PRActionsSection.tsx index 86b910a08cac..5fae6803889d 100644 --- a/mobile/src/components/pr-sidebar/PRActionsSection.tsx +++ b/mobile/src/components/pr-sidebar/PRActionsSection.tsx @@ -7,7 +7,6 @@ import type { RpcClient } from '../../transport/rpc-client' import type { MobilePrActions } from '../../session/use-mobile-pr-actions' import { unlinkMobilePr } from '../../source-control/mobile-pr-link' import { ConfirmModal } from '../ConfirmModal' -import { PRSection } from './PRSection' import { canShowMobilePRAutoMergeControl } from './pr-auto-merge-availability' import { resolveMobilePrMergeMethod, resolvePrActionAvailability } from './pr-actions-state' import { prActionsStyles as styles } from './pr-actions-styles' @@ -25,12 +24,13 @@ type Confirm = | { kind: 'merge'; method: GitHubPRMergeMethod } | { kind: 'state'; state: 'open' | 'closed' } -// Merge, auto-merge toggle, and close/reopen. Destructive actions route through -// ConfirmModal first (R5). The firing row shows a spinner in place of its icon -// and disables; other rows stay interactive (uniform visual). +// Merge primary; Close/Reopen + Unlink share one secondary row. No section title — +// button labels are self-explanatory and a header wasted a full row on mobile. export function PRActionsSection({ pr, actions, client, worktreeId, onUnlinked }: Props) { const [confirm, setConfirm] = useState(null) const [unlinking, setUnlinking] = useState(false) + // Local unlink errors — unlink is not routed through the actions engine. + const [unlinkError, setUnlinkError] = useState(null) // Mobile keeps merge one-tap: use the repo default instead of surfacing a // desktop-style method picker in the narrow PR action stack. @@ -41,23 +41,31 @@ export function PRActionsSection({ pr, actions, client, worktreeId, onUnlinked } const mergeBusy = actions.isBusy({ kind: 'merge' }) const autoMergeBusy = actions.isBusy({ kind: 'autoMerge' }) const stateBusy = actions.isBusy({ kind: 'state' }) + const unlinkBusy = unlinking || mergeBusy || autoMergeBusy || stateBusy const showAutoMerge = avail.canAutoMerge && canShowMobilePRAutoMergeControl({ ...pr, autoMergeEnabled: autoMerge || pr.autoMergeEnabled === true }) + const showSecondary = avail.canClose || avail.canReopen || avail.canUnlink + const actionError = unlinkError ?? actions.error const unlink = useCallback(async (): Promise => { if (!client || unlinking) { return } setUnlinking(true) + setUnlinkError(null) try { const outcome = await unlinkMobilePr(client, worktreeId) if (outcome.ok) { onUnlinked() + } else { + setUnlinkError(outcome.error) } + } catch (err) { + setUnlinkError(err instanceof Error ? err.message : 'Failed to unlink pull request.') } finally { setUnlinking(false) } @@ -89,6 +97,8 @@ export function PRActionsSection({ pr, actions, client, worktreeId, onUnlinked } if (!confirm) { return } + // Engine errors take over the shared error line after this; drop unlink text. + setUnlinkError(null) if (confirm.kind === 'merge') { actions.merge(confirm.method) } else { @@ -99,8 +109,7 @@ export function PRActionsSection({ pr, actions, client, worktreeId, onUnlinked } const copy = confirmCopy() return ( - - {/* Merge controls only while the PR can still be merged (open/draft). */} + {avail.canMerge ? ( setConfirm({ kind: 'merge', method: effectiveMethod })} + onPress={() => { + setUnlinkError(null) + setConfirm({ kind: 'merge', method: effectiveMethod }) + }} disabled={mergeBusy} accessibilityRole="button" accessibilityLabel="Merge pull request" @@ -124,13 +136,15 @@ export function PRActionsSection({ pr, actions, client, worktreeId, onUnlinked } ) : null} - {/* Auto-merge toggle — optimistic, reverts on transient failure. */} {showAutoMerge ? ( Auto-merge when ready actions.setAutoMerge(!autoMerge, effectiveMethod)} + onPress={() => { + setUnlinkError(null) + actions.setAutoMerge(!autoMerge, effectiveMethod) + }} disabled={autoMergeBusy} accessibilityRole="switch" accessibilityState={{ checked: autoMerge }} @@ -147,49 +161,59 @@ export function PRActionsSection({ pr, actions, client, worktreeId, onUnlinked } ) : null} - {/* Close (open PRs) / Reopen (closed PRs) — confirmed before firing (R5). */} - {avail.canClose || avail.canReopen ? ( - setConfirm({ kind: 'state', state: avail.canClose ? 'closed' : 'open' })} - disabled={stateBusy} - accessibilityRole="button" - accessibilityLabel={avail.canClose ? 'Close pull request' : 'Reopen pull request'} - > - {stateBusy ? : null} - - {avail.canClose ? 'Close' : 'Reopen'} - - - ) : null} - - {/* Unlink the PR from this worktree. Disabled while another PR mutation is in - flight so clearing the link can't race a merge/close refetch. */} - {avail.canUnlink ? ( - void unlink()} - disabled={unlinking || mergeBusy || autoMergeBusy || stateBusy} - accessibilityRole="button" - accessibilityLabel="Unlink pull request" - > - {unlinking ? ( - - ) : ( - - )} - Unlink - + {showSecondary ? ( + + {avail.canClose || avail.canReopen ? ( + { + setUnlinkError(null) + setConfirm({ kind: 'state', state: avail.canClose ? 'closed' : 'open' }) + }} + disabled={stateBusy} + accessibilityRole="button" + accessibilityLabel={avail.canClose ? 'Close pull request' : 'Reopen pull request'} + > + {stateBusy ? : null} + + {avail.canClose ? 'Close' : 'Reopen'} + + + ) : null} + {avail.canUnlink ? ( + void unlink()} + disabled={unlinkBusy} + accessibilityRole="button" + accessibilityLabel="Unlink pull request" + > + {unlinking ? ( + + ) : ( + + )} + Unlink + + ) : null} + ) : null} - {actions.error ? {actions.error} : null} + {actionError ? {actionError} : null} - {/* A Modal is taken out of the flex flow, so it adds no body gap here. */} setConfirm(null)} /> - + ) } diff --git a/mobile/src/components/pr-sidebar/PRCommentsSection.tsx b/mobile/src/components/pr-sidebar/PRCommentsSection.tsx index 051f1392e9d2..b6c0a1009d69 100644 --- a/mobile/src/components/pr-sidebar/PRCommentsSection.tsx +++ b/mobile/src/components/pr-sidebar/PRCommentsSection.tsx @@ -5,6 +5,7 @@ import type { GitHubWorkItemDetails, PRState } from '../../../../src/shared/type import type { GitHubPrRepoSlug } from '../../session/github-pr-rpc' import { colors } from '../../theme/mobile-theme' import { canAddRootComment } from '../../session/pr-comment-actions' +import { isPrSidebarDetailsPlaceholder } from '../../session/mobile-pr-sidebar-state' import type { MobilePrCommentActions } from '../../session/use-mobile-pr-comment-actions' import { PRSection } from './PRSection' import { CommentMarkdown } from './CommentMarkdown' @@ -50,10 +51,15 @@ const COMMENT_PAGE = 12 // review comments, reactions, and collapsible resolved threads. export function PRCommentsSection({ details, prState, prRepo, actions }: Props) { // details is null while phase 2 (the heavy comments/body payload) is still loading. + // A synthetic placeholder means phase 2 failed — do not paint that as empty success. const loadingDetails = details === null + const detailsFailed = details != null && isPrSidebarDetailsPlaceholder(details) const body = details?.body ?? '' - const comments = useMemo(() => details?.comments ?? [], [details]) - const isPr = details?.item.type === 'pr' + const comments = useMemo( + () => (details && !isPrSidebarDetailsPlaceholder(details) ? details.comments : []), + [details] + ) + const isPr = details != null && !detailsFailed && details.item.type === 'pr' // Per-card action bundle (stable callbacks from the hook) — built once so the // memo'd cards don't re-render on unrelated timeline changes. @@ -94,6 +100,10 @@ export function PRCommentsSection({ details, prState, prRepo, actions }: Props) {loadingDetails ? ( + ) : detailsFailed ? ( + + Could not load description. Tap refresh to try again. + ) : body.trim() ? ( ) : ( @@ -113,6 +123,8 @@ export function PRCommentsSection({ details, prState, prRepo, actions }: Props) > {loadingDetails ? ( + ) : detailsFailed ? ( + Could not load comments. Tap refresh to try again. ) : ( {comments.length === 0 ? ( diff --git a/mobile/src/components/pr-sidebar/PRReviewersSection.tsx b/mobile/src/components/pr-sidebar/PRReviewersSection.tsx index ad16241c2064..bc09ecd3502c 100644 --- a/mobile/src/components/pr-sidebar/PRReviewersSection.tsx +++ b/mobile/src/components/pr-sidebar/PRReviewersSection.tsx @@ -5,6 +5,7 @@ import { colors } from '../../theme/mobile-theme' import type { GitHubWorkItemDetails } from '../../../../src/shared/types' import type { RpcClient } from '../../transport/rpc-client' import type { MobilePrActions } from '../../session/use-mobile-pr-actions' +import { isPrSidebarDetailsPlaceholder } from '../../session/mobile-pr-sidebar-state' import { getPRReviewerRows } from './pr-checks-presentation' import { ReviewerPickerDrawer } from './ReviewerPickerDrawer' import { PRSection } from './PRSection' @@ -20,8 +21,17 @@ type Props = { // Requested reviewers + their latest review status, with a picker to request / // remove (optimistic add/remove via the actions hook). export function PRReviewersSection({ details, actions, client, worktreeId }: Props) { + // details === null means phase 2 (work-item payload) is still in flight — same + // signal Comments uses. Do not treat that as "no reviewers" or the section goes + // blank while checks (phase 1) already paint. A synthetic placeholder means + // phase 2 failed (no body/comments/reviews landed). + const loadingDetails = details === null + const detailsFailed = details != null && isPrSidebarDetailsPlaceholder(details) const authoritativeRows = useMemo( - () => (details?.item ? getPRReviewerRows(details.item) : []), + () => + details?.item && !isPrSidebarDetailsPlaceholder(details) + ? getPRReviewerRows(details.item) + : [], [details] ) const [pickerOpen, setPickerOpen] = useState(false) @@ -46,21 +56,27 @@ export function PRReviewersSection({ details, actions, client, worktreeId }: Pro return author ? [author, ...logins] : logins }, [authoritativeRows, details]) - return ( - setPickerOpen(true)} - accessibilityRole="button" - accessibilityLabel="Add or remove reviewers" - > - - - } + const addButton = ( + setPickerOpen(true)} + accessibilityRole="button" + accessibilityLabel="Add or remove reviewers" > - {rows.length === 0 ? ( + + + ) + + return ( + + {loadingDetails ? ( + + + Loading reviewers… + + ) : detailsFailed ? ( + Could not load reviewers. Tap refresh to try again. + ) : rows.length === 0 ? ( No reviewers requested ) : ( rows.map((row) => { diff --git a/mobile/src/components/pr-sidebar/PRSection.tsx b/mobile/src/components/pr-sidebar/PRSection.tsx index a573258d41a4..0ed5ce904163 100644 --- a/mobile/src/components/pr-sidebar/PRSection.tsx +++ b/mobile/src/components/pr-sidebar/PRSection.tsx @@ -3,22 +3,28 @@ import { Text, View } from 'react-native' import { mobilePrSidebarStyles as styles } from './mobile-pr-sidebar-styles' type Props = { - title: string + // Optional: omit for self-explanatory sections (e.g. action buttons) so the + // header row doesn't waste vertical space on mobile. + title?: string // Optional trailing control(s) in the header row (e.g. add-reviewer, checks // summary + rerun). Rendered right-aligned opposite the title. trailing?: ReactNode children: ReactNode } -// Shared card shell for the titled PR sections (Actions/Reviewers/Checks). Mirrors -// the desktop PR page's card-with-header-divider so the sections read consistently. +// Shared card shell for PR sections (Actions/Reviewers/Checks). Mirrors the +// desktop PR page's card-with-header-divider so the sections read consistently. +// Header is omitted when neither title nor trailing is provided. export function PRSection({ title, trailing, children }: Props) { + const showHeader = Boolean(title) || trailing != null return ( - - {title} - {trailing ? {trailing} : null} - + {showHeader ? ( + + {title ? {title} : null} + {trailing ? {trailing} : null} + + ) : null} {children} ) diff --git a/mobile/src/components/pr-sidebar/PRSidebarHeader.tsx b/mobile/src/components/pr-sidebar/PRSidebarHeader.tsx index e2f31f3cc412..8a399babe78f 100644 --- a/mobile/src/components/pr-sidebar/PRSidebarHeader.tsx +++ b/mobile/src/components/pr-sidebar/PRSidebarHeader.tsx @@ -1,6 +1,6 @@ import { useState } from 'react' import { ActivityIndicator, Pressable, Text, TextInput, View } from 'react-native' -import { ArrowRight, Pencil } from 'lucide-react-native' +import { ArrowRight, ExternalLink, Pencil } from 'lucide-react-native' import { colors } from '../../theme/mobile-theme' import type { GitHubWorkItemDetails, PRInfo } from '../../../../src/shared/types' import type { MobilePrTitleAction } from '../../session/use-mobile-pr-title-action' @@ -16,11 +16,21 @@ type Props = { details: GitHubWorkItemDetails | null // Inline title-edit action; the pencil affordance only shows when the PR is editable. titleAction: MobilePrTitleAction + // Hub chrome already surfaces open-on-web; hide the duplicate icon in that case. + showOpenOnWeb?: boolean + // When true, render without section chrome so identity can share a card with actions. + bare?: boolean } -// Header: state badge (incl. draft — display-only), title, author, head->base. -// The title is inline-editable on an open/draft PR (desktop parity). -export function PRSidebarHeader({ pr, details, titleAction }: Props) { +// Compact identity: state + # + author on one meta row, title, head→base. +// # lives only in the meta row (not also after the title) to avoid repetition. +export function PRSidebarHeader({ + pr, + details, + titleAction, + showOpenOnWeb = true, + bare = false +}: Props) { const item = details?.item const badge = prStateBadge(pr.state) const badgeColor = statusColor(badge.token) @@ -29,58 +39,79 @@ export function PRSidebarHeader({ pr, details, titleAction }: Props) { const baseRef = item?.baseRefName ?? null const headRef = item?.branchName ?? null const editable = canEditPRTitle(pr.state) - // Tapping the state badge or the #number opens the PR on its host (GitHub/etc.) - // in the phone browser — pr.url is the canonical web URL. const openPr = pr.url ? () => openMobilePrUrl(pr.url) : undefined - return ( - - - [ - styles.badge, - { borderColor: badgeColor }, - pressed && { opacity: 0.6 } - ]} - > - {badge.label} - - - {author ? by {author} : null} - {baseRef && headRef ? ( - // head -> base reads in merge direction (desktop ChecksPanel parity). - - {headRef} - - {baseRef} - + const body = ( + <> + + + [ + styles.badge, + { borderColor: badgeColor }, + pressed && { opacity: 0.6 } + ]} + > + {badge.label} + + + #{pr.number} + + {author ? · {author} : null} + + {showOpenOnWeb && openPr ? ( + [styles.iconButton, pressed && { opacity: 0.6 }]} + > + + ) : null} + + {baseRef && headRef ? ( + + + {headRef} + + + + {baseRef} + + + ) : null} + + ) + + if (bare) { + return {body} + } + return ( + + {body} ) } function PRTitle({ title, - number, editable, - openPr, titleAction }: { title: string - number: number editable: boolean - openPr: (() => void) | undefined titleAction: MobilePrTitleAction }) { const [editing, setEditing] = useState(false) @@ -106,7 +137,7 @@ function PRTitle({ if (editing) { return ( - + - - {title}{' '} - - #{number} - - + {title} {editable ? ( diff --git a/mobile/src/components/pr-sidebar/ReviewerPickerDrawer.tsx b/mobile/src/components/pr-sidebar/ReviewerPickerDrawer.tsx index 97d89a34b3e6..8a3a161f3582 100644 --- a/mobile/src/components/pr-sidebar/ReviewerPickerDrawer.tsx +++ b/mobile/src/components/pr-sidebar/ReviewerPickerDrawer.tsx @@ -1,5 +1,5 @@ import { useEffect, useMemo, useState } from 'react' -import { ActivityIndicator, FlatList, Pressable, Text, TextInput, View } from 'react-native' +import { ActivityIndicator, Pressable, Text, TextInput, View } from 'react-native' import { Check } from 'lucide-react-native' import { colors } from '../../theme/mobile-theme' import type { GitHubAssignableUser } from '../../../../src/shared/types' @@ -26,9 +26,10 @@ type LoadState = | { status: 'error'; message: string } | { status: 'loaded'; users: GitHubAssignableUser[] } -// A search + FlatList of github.listAssignableUsers in a BottomDrawer (not a new -// primitive). Seeded with already-requested/latest reviewers + author at the top. -// Optimistic add/remove via onToggle. +// Searchable assignable-user list in a BottomDrawer. Mapped rows (not FlatList): +// this drawer is opened from the PR ScrollView, and a VirtualizedList nested in +// that ScrollView throws and can leave the Reviewers section blank. +// Seeded reviewers + author sort first for quick un-request. export function ReviewerPickerDrawer({ visible, onClose, @@ -47,16 +48,22 @@ export function ReviewerPickerDrawer({ } let cancelled = false setLoad({ status: 'loading' }) - void fetchAssignableUsers(client, worktreeId).then((outcome) => { - if (cancelled) { - return - } - setLoad( - outcome.ok - ? { status: 'loaded', users: outcome.result } - : { status: 'error', message: outcome.error } - ) - }) + void fetchAssignableUsers(client, worktreeId) + .then((outcome) => { + if (cancelled) { + return + } + setLoad( + outcome.ok + ? { status: 'loaded', users: outcome.result } + : { status: 'error', message: outcome.error } + ) + }) + .catch(() => { + if (!cancelled) { + setLoad({ status: 'error', message: 'Failed to load people' }) + } + }) return () => { cancelled = true } @@ -107,15 +114,12 @@ export function ReviewerPickerDrawer({ No matching people ) : ( - u.login} - keyboardShouldPersistTaps="handled" - renderItem={({ item }) => { + + {ordered.map((item) => { const requested = isRequested(item.login) return ( onToggle(item.login)} accessibilityRole="button" @@ -134,8 +138,8 @@ export function ReviewerPickerDrawer({ ) - }} - /> + })} + )} ) diff --git a/mobile/src/components/pr-sidebar/mobile-pr-sidebar-styles.ts b/mobile/src/components/pr-sidebar/mobile-pr-sidebar-styles.ts index c3f0ad685818..edf308350e42 100644 --- a/mobile/src/components/pr-sidebar/mobile-pr-sidebar-styles.ts +++ b/mobile/src/components/pr-sidebar/mobile-pr-sidebar-styles.ts @@ -25,8 +25,7 @@ export const mobilePrSidebarStyles = StyleSheet.create({ section: { backgroundColor: colors.bgPanel, borderBottomWidth: StyleSheet.hairlineWidth, - borderBottomColor: colors.borderSubtle, - overflow: 'hidden' + borderBottomColor: colors.borderSubtle }, // Section header row: title + optional trailing control, divided from the body // by a hairline border (desktop `h-10 border-b px-3`). @@ -55,7 +54,25 @@ export const mobilePrSidebarStyles = StyleSheet.create({ fontSize: 13, fontWeight: '600' }, - // Header section: state badge, title, author, base<-head branches. + // Identity + actions share one section card (hub redesign): no per-block chrome. + identityBlock: { + gap: spacing.sm + }, + // State badge + #number + author on one row; open-on-web flush right when shown. + metaRow: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + gap: spacing.sm + }, + metaLeft: { + flex: 1, + minWidth: 0, + flexDirection: 'row', + alignItems: 'center', + flexWrap: 'wrap', + gap: spacing.xs + }, badge: { alignSelf: 'flex-start', paddingHorizontal: spacing.sm, @@ -69,6 +86,7 @@ export const mobilePrSidebarStyles = StyleSheet.create({ fontWeight: '700' }, prTitle: { + flex: 1, color: colors.textPrimary, fontSize: typography.titleSize, fontWeight: '700', @@ -78,6 +96,12 @@ export const mobilePrSidebarStyles = StyleSheet.create({ color: colors.textSecondary, fontSize: typography.metaSize }, + // #number in the meta row — stronger than author so the identity scans first. + prMetaStrong: { + color: colors.textPrimary, + fontSize: typography.metaSize, + fontWeight: '600' + }, // Title row: tappable area pairing the title with a trailing edit affordance. titleRow: { flexDirection: 'row', @@ -97,10 +121,11 @@ export const mobilePrSidebarStyles = StyleSheet.create({ gap: spacing.xs }, branchPill: { + flexShrink: 1, color: colors.textPrimary, fontSize: typography.metaSize, fontFamily: typography.monoFamily, - backgroundColor: colors.bgPanel, + backgroundColor: colors.bgRaised, paddingHorizontal: spacing.xs, paddingVertical: 2, borderRadius: radii.button @@ -139,6 +164,13 @@ export const mobilePrSidebarStyles = StyleSheet.create({ color: colors.textSecondary, fontSize: typography.metaSize }, + // Loading / empty status row inside Reviewers (and similar) section bodies. + reviewersStatus: { + minHeight: 44, + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm + }, summaryLabel: { fontSize: typography.bodySize, fontWeight: '700' @@ -267,8 +299,10 @@ export const mobilePrSidebarStyles = StyleSheet.create({ fontSize: typography.bodySize, marginBottom: spacing.sm }, + // No maxHeight / FlatList: the parent BottomDrawer scrolls this block so we + // never nest a VirtualizedList inside the PR page ScrollView. pickerList: { - maxHeight: 320 + gap: 0 }, pickerRow: { minHeight: 44, diff --git a/mobile/src/components/pr-sidebar/pr-actions-styles.ts b/mobile/src/components/pr-sidebar/pr-actions-styles.ts index 865516e34686..6d89e75bf988 100644 --- a/mobile/src/components/pr-sidebar/pr-actions-styles.ts +++ b/mobile/src/components/pr-sidebar/pr-actions-styles.ts @@ -5,6 +5,19 @@ import { colors, radii, spacing, typography } from '../../theme/mobile-theme' // line). Split out of mobile-pr-sidebar-styles to keep that file under the // 300-line cap. export const prActionsStyles = StyleSheet.create({ + // Bare block when identity + actions share one section card. + actionsBlock: { + gap: spacing.sm + }, + // Close/Reopen + Unlink share a row so secondary actions don't stack full-width. + secondaryRow: { + flexDirection: 'row', + alignItems: 'stretch', + gap: spacing.sm + }, + secondaryButton: { + flex: 1 + }, // Primary CTA (merge) and secondary action buttons (close/reopen/rerun/add). actionButton: { minHeight: 44, diff --git a/mobile/src/components/pr-sidebar/pr-comment-composer-styles.ts b/mobile/src/components/pr-sidebar/pr-comment-composer-styles.ts index 3d44a9e0cc2d..e6cb4966ca21 100644 --- a/mobile/src/components/pr-sidebar/pr-comment-composer-styles.ts +++ b/mobile/src/components/pr-sidebar/pr-comment-composer-styles.ts @@ -5,7 +5,8 @@ import { colors, radii, spacing, typography } from '../../theme/mobile-theme' // match the PR comment timeline; split out to keep PRCommentComposer focused. export const prCommentComposerStyles = StyleSheet.create({ container: { - gap: spacing.sm + // Input → Cancel/Save needs clear separation (title edit was flush without this). + gap: spacing.md }, input: { minHeight: 64, diff --git a/mobile/src/diagnostics/connection-diagnostics-report.test.ts b/mobile/src/diagnostics/connection-diagnostics-report.test.ts new file mode 100644 index 000000000000..d2326ffa0227 --- /dev/null +++ b/mobile/src/diagnostics/connection-diagnostics-report.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest' +import { buildConnectionDiagnosticsReport } from './connection-diagnostics-report' + +const NOW = Date.UTC(2026, 6, 9, 22, 0, 0) + +describe('buildConnectionDiagnosticsReport', () => { + it('summarizes a failing Tailscale host with its log', () => { + const report = buildConnectionDiagnosticsReport({ + hostName: 'Host 1', + endpoint: 'ws://100.65.9.106:6768', + state: 'reconnecting', + reconnectAttempts: 12, + lastConnectedAt: NOW - 5 * 60_000, + platform: 'ios 26.5.1', + appVersion: '0.0.29', + entries: [ + { + id: 'log-1', + ts: NOW - 60_000, + level: 'error', + message: 'WebSocket connect timeout', + detail: 'No TCP/WS handshake within 12s — endpoint unreachable?' + } + ], + nowMs: NOW + }) + + expect(report).toContain('App: Orca Mobile 0.0.29 · ios 26.5.1') + expect(report).toContain('Endpoint: 100.65.9.106:6768 (Tailscale)') + expect(report).toContain('State: reconnecting (reconnect attempts: 12)') + expect(report).toContain('(5m 0s ago)') + expect(report).toContain( + '[error] WebSocket connect timeout — No TCP/WS handshake within 12s — endpoint unreachable?' + ) + }) + + it('marks never-connected sessions and empty logs', () => { + const report = buildConnectionDiagnosticsReport({ + hostName: 'Host 2', + endpoint: 'ws://192.168.1.50:6768', + state: 'connecting', + reconnectAttempts: 0, + lastConnectedAt: null, + platform: 'android 15', + appVersion: '0.0.29', + entries: [], + nowMs: NOW + }) + + expect(report).toContain('Endpoint: 192.168.1.50:6768') + expect(report).not.toContain('(Tailscale)') + expect(report).toContain('Last connected: never this session') + expect(report).toContain('No connection events recorded this session.') + }) +}) diff --git a/mobile/src/diagnostics/connection-diagnostics-report.ts b/mobile/src/diagnostics/connection-diagnostics-report.ts new file mode 100644 index 000000000000..c762c69799eb --- /dev/null +++ b/mobile/src/diagnostics/connection-diagnostics-report.ts @@ -0,0 +1,58 @@ +import { isTailscaleEndpoint } from '../../../src/shared/remote-runtime-tailscale-hint' +import type { ConnectionLogEntry, ConnectionState } from '../transport/types' +import { formatEndpoint } from './host-reachability' + +// Why: one shareable text blob answering everything we historically had to +// ask reporters one message at a time (endpoint type, state, attempt count, +// last-connected, versions, and the reconnect lifecycle log). +export function buildConnectionDiagnosticsReport(args: { + hostName: string + endpoint: string + state: ConnectionState + reconnectAttempts: number + lastConnectedAt: number | null + platform: string + appVersion: string + entries: readonly ConnectionLogEntry[] + nowMs?: number +}): string { + const now = args.nowMs ?? Date.now() + const lines: string[] = [] + lines.push('Orca Mobile connection diagnostics') + lines.push(`Generated: ${new Date(now).toISOString()}`) + lines.push(`App: Orca Mobile ${args.appVersion} · ${args.platform}`) + lines.push(`Host: ${args.hostName}`) + lines.push( + `Endpoint: ${formatEndpoint(args.endpoint)}${isTailscaleEndpoint(args.endpoint) ? ' (Tailscale)' : ''}` + ) + lines.push(`State: ${args.state} (reconnect attempts: ${args.reconnectAttempts})`) + lines.push( + args.lastConnectedAt == null + ? 'Last connected: never this session' + : `Last connected: ${new Date(args.lastConnectedAt).toISOString()} (${formatAgo(now - args.lastConnectedAt)} ago)` + ) + lines.push('') + if (args.entries.length === 0) { + lines.push('No connection events recorded this session.') + } else { + lines.push(`Connection log (${args.entries.length} events, oldest first):`) + for (const entry of args.entries) { + const detail = entry.detail ? ` — ${entry.detail}` : '' + lines.push(`${new Date(entry.ts).toISOString()} [${entry.level}] ${entry.message}${detail}`) + } + } + return lines.join('\n') +} + +function formatAgo(ms: number): string { + const seconds = Math.max(0, Math.round(ms / 1000)) + if (seconds < 60) { + return `${seconds}s` + } + const minutes = Math.floor(seconds / 60) + if (minutes < 60) { + return `${minutes}m ${seconds % 60}s` + } + const hours = Math.floor(minutes / 60) + return `${hours}h ${minutes % 60}m` +} diff --git a/mobile/src/diagnostics/host-reachability.test.ts b/mobile/src/diagnostics/host-reachability.test.ts index 9b2933a4e0f0..d20bc8c28cf7 100644 --- a/mobile/src/diagnostics/host-reachability.test.ts +++ b/mobile/src/diagnostics/host-reachability.test.ts @@ -1,5 +1,27 @@ import { describe, expect, it, vi } from 'vitest' -import { testHostReachability } from './host-reachability' +import { testHostReachability, unreachableHostDetail } from './host-reachability' + +describe('unreachableHostDetail', () => { + it('points at Tailscale for tailnet CGNAT endpoints', () => { + expect(unreachableHostDetail('ws://100.65.9.106:6768')).toBe( + 'Cannot reach 100.65.9.106:6768 — check Tailscale' + ) + }) + + it('points at Tailscale for MagicDNS endpoints', () => { + expect(unreachableHostDetail('ws://my-desktop.tailnet-1234.ts.net:6768')).toBe( + 'Cannot reach my-desktop.tailnet-1234.ts.net:6768 — check Tailscale' + ) + }) + + it('stays generic for LAN endpoints', () => { + expect(unreachableHostDetail('ws://192.168.1.50:6768')).toBe('Cannot reach 192.168.1.50:6768') + }) + + it('does not treat non-CGNAT 100.x addresses as Tailscale', () => { + expect(unreachableHostDetail('ws://100.20.1.5:6768')).toBe('Cannot reach 100.20.1.5:6768') + }) +}) describe('testHostReachability', () => { it('returns false without leaving timers when WebSocket rejects a malformed endpoint', async () => { diff --git a/mobile/src/diagnostics/host-reachability.ts b/mobile/src/diagnostics/host-reachability.ts index 7ae292126e89..495d65a97643 100644 --- a/mobile/src/diagnostics/host-reachability.ts +++ b/mobile/src/diagnostics/host-reachability.ts @@ -1,3 +1,5 @@ +import { isTailscaleEndpoint } from '../../../src/shared/remote-runtime-tailscale-hint' + const HOST_REACHABILITY_TIMEOUT_MS = 4000 // Why: troubleshooting needs a cheap endpoint probe without completing the @@ -56,3 +58,13 @@ export function formatEndpoint(endpoint: string): string { return endpoint } } + +// Why: an unreachable 100.x/*.ts.net host almost always means the phone's +// Tailscale tunnel is down or wedged (known iOS failure mode, fixed by +// toggling the VPN) — point at that instead of a bare "Cannot reach". +export function unreachableHostDetail(endpoint: string): string { + if (isTailscaleEndpoint(endpoint)) { + return `Cannot reach ${formatEndpoint(endpoint)} — check Tailscale` + } + return `Cannot reach ${formatEndpoint(endpoint)}` +} diff --git a/mobile/src/diagnostics/troubleshoot-common-issues.tsx b/mobile/src/diagnostics/troubleshoot-common-issues.tsx new file mode 100644 index 000000000000..5dc91eb65fc2 --- /dev/null +++ b/mobile/src/diagnostics/troubleshoot-common-issues.tsx @@ -0,0 +1,73 @@ +import { WifiOff, Shield, Monitor, Clock, Globe } from 'lucide-react-native' +import { colors } from '../theme/mobile-theme' + +export type TroubleshootSection = { + id: string + icon: React.ReactNode + title: string + steps: string[] +} + +export const troubleshootCommonIssues: TroubleshootSection[] = [ + { + id: 'wifi', + icon: , + title: 'Different WiFi Networks', + steps: [ + 'Both devices must be on the same local network (unless connected through Tailscale).', + 'Ethernet and WiFi must share the same subnet.', + 'Try reconnecting WiFi on both devices.' + ] + }, + { + id: 'firewall', + icon: , + title: 'Firewall Blocking Port 6768', + steps: [ + 'macOS: System Settings → Network → Firewall — allow Orca.', + 'Windows: Defender Firewall → Allow app — enable Orca for Private networks.', + 'Linux: sudo ufw allow 6768', + 'Corporate/school networks may block P2P — try a personal hotspot.' + ] + }, + { + id: 'desktop', + icon: , + title: 'Desktop App Not Running', + steps: [ + 'Orca must be open on your desktop to accept connections.', + 'Try restarting Orca — the companion server starts on launch.', + 'After an update, you may need to re-pair via QR code.' + ] + }, + { + id: 'timeout', + icon: , + title: 'Connection Timeout', + steps: [ + 'Check WiFi signal strength on your phone.', + 'Go back to the host list and tap your host to retry.', + 'Restart both apps if timeouts persist.' + ] + }, + { + id: 'tailscale', + icon: , + title: 'Tailscale Host Unreachable', + steps: [ + 'Host addresses like 100.x.x.x or *.ts.net connect through Tailscale — keep it ON.', + 'iOS/Android can silently wedge the tunnel: toggle Tailscale off and back on in the Tailscale app.', + 'Check the desktop is awake and shows as connected in your tailnet.', + 'Update the Tailscale app — recent releases fix reconnect bugs.' + ] + }, + { + id: 'vpn', + icon: , + title: 'Other VPN Interference', + steps: [ + 'Non-Tailscale VPNs can route local traffic through a remote server.', + 'Disable that VPN or enable split tunneling / "Allow LAN".' + ] + } +] diff --git a/mobile/src/notifications/mobile-notifications.test.ts b/mobile/src/notifications/mobile-notifications.test.ts index 46eab52ec920..7ae4315086b0 100644 --- a/mobile/src/notifications/mobile-notifications.test.ts +++ b/mobile/src/notifications/mobile-notifications.test.ts @@ -1,6 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import * as Notifications from 'expo-notifications' -import { subscribeToDesktopNotifications } from './mobile-notifications' +import { + setScheduledNotificationsMaxForTests, + subscribeToDesktopNotifications +} from './mobile-notifications' import type { RpcClient } from '../transport/rpc-client' import { loadPushNotificationsEnabled } from '../storage/preferences' @@ -268,4 +271,48 @@ describe('subscribeToDesktopNotifications', () => { expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalled() }) + + // Why: notificationId is unique per completion, so the map grew unbounded when + // the desktop never sent a dismiss (the remote-mobile case). It is now capped. + it('evicts the oldest scheduled entry once the cap is exceeded', async () => { + setScheduledNotificationsMaxForTests(1) + try { + vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) + vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ + status: 'granted', + canAskAgain: true + } as never) + vi.mocked(Notifications.scheduleNotificationAsync) + .mockResolvedValueOnce('scheduled-old') + .mockResolvedValueOnce('scheduled-new') + vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) + let onEvent: ((data: unknown) => void) | null = null + const client = { + subscribe: vi.fn((_method, _params, callback: (data: unknown) => void) => { + onEvent = callback + return vi.fn() + }), + getState: vi.fn(() => 'connected'), + sendRequest: vi.fn() + } as unknown as RpcClient + + subscribeToDesktopNotifications(client, 'host-1') + onEvent?.({ type: 'notification', title: 't', body: 'b', notificationId: 'agent:old' }) + await flushAsync() + onEvent?.({ type: 'notification', title: 't', body: 'b', notificationId: 'agent:new' }) + await flushAsync() + + // The older entry was evicted by the cap: dismissing it is a no-op... + onEvent?.({ type: 'dismiss', notificationId: 'agent:old' }) + await flushAsync() + expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalledWith('scheduled-old') + + // ...while the most-recent entry is retained and still dismissable. + onEvent?.({ type: 'dismiss', notificationId: 'agent:new' }) + await flushAsync() + expect(Notifications.dismissNotificationAsync).toHaveBeenCalledWith('scheduled-new') + } finally { + setScheduledNotificationsMaxForTests() + } + }) }) diff --git a/mobile/src/notifications/mobile-notifications.ts b/mobile/src/notifications/mobile-notifications.ts index 83abea6fb8a5..9ab936f75c64 100644 --- a/mobile/src/notifications/mobile-notifications.ts +++ b/mobile/src/notifications/mobile-notifications.ts @@ -31,10 +31,42 @@ type ScheduledNotificationState = { const scheduledNotificationsByHostAndNotificationId = new Map() +// Why: notificationId embeds a per-completion timestamp (buildAgentNotificationId), +// so every agent-task-complete inserts a new, never-reused key. Entries are only +// removed when the desktop sends a matching dismiss — which a remote mobile user +// (not at the desktop) frequently never gets — so the map grew for the app's whole +// life. Bound it; a settled entry only retains a small identifier used for later +// programmatic dismissal, unnecessary for long-past completions. +const MAX_SCHEDULED_NOTIFICATIONS = 256 +let maxScheduledNotifications = MAX_SCHEDULED_NOTIFICATIONS + function getStoredNotificationKey(hostId: string, notificationId: string): string { return `${encodeURIComponent(hostId)}:${encodeURIComponent(notificationId)}` } +// Evict the oldest SETTLED entries (never one mid-schedule) until within the cap. +// Map iteration is insertion order, so the first match is the oldest. +function boundScheduledNotifications(): void { + while (scheduledNotificationsByHostAndNotificationId.size > maxScheduledNotifications) { + let evicted = false + for (const [key, state] of scheduledNotificationsByHostAndNotificationId) { + if (!state.pending) { + scheduledNotificationsByHostAndNotificationId.delete(key) + evicted = true + break + } + } + if (!evicted) { + break + } + } +} + +/** Test-only: override the cap (pass no arg to restore the default). */ +export function setScheduledNotificationsMaxForTests(max?: number): void { + maxScheduledNotifications = max ?? MAX_SCHEDULED_NOTIFICATIONS +} + export type NotificationPermissionState = { granted: boolean status: string @@ -155,6 +187,7 @@ async function showLocalNotification(event: NotificationEvent, hostId: string): return } notificationState.identifier = scheduledIdentifier + boundScheduledNotifications() } finally { if (notificationState.pending === pending) { notificationState.pending = undefined diff --git a/mobile/src/session/MobileSessionHeaderIconButton.tsx b/mobile/src/session/MobileSessionHeaderIconButton.tsx new file mode 100644 index 000000000000..68e1a1173a45 --- /dev/null +++ b/mobile/src/session/MobileSessionHeaderIconButton.tsx @@ -0,0 +1,39 @@ +import type { ComponentType } from 'react' +import { Pressable } from 'react-native' +import { colors } from '../theme/mobile-theme' +import { styles } from '../../app/h/[hostId]/session/mobile-session-styles' + +type HeaderIconProps = { + size?: number + color?: string + strokeWidth?: number +} + +type MobileSessionHeaderIconButtonProps = { + active?: boolean + accessibilityLabel: string + icon: ComponentType + onPress: () => void +} + +export function MobileSessionHeaderIconButton({ + active = false, + accessibilityLabel, + icon: Icon, + onPress +}: MobileSessionHeaderIconButtonProps) { + return ( + [ + styles.filesButton, + pressed && styles.filesButtonPressed, + active && styles.filesButtonActive + ]} + onPress={onPress} + hitSlop={8} + accessibilityLabel={accessibilityLabel} + > + + + ) +} diff --git a/mobile/src/session/MobileSessionHeaderMoreActionsSheet.tsx b/mobile/src/session/MobileSessionHeaderMoreActionsSheet.tsx new file mode 100644 index 000000000000..d6f6ebb45184 --- /dev/null +++ b/mobile/src/session/MobileSessionHeaderMoreActionsSheet.tsx @@ -0,0 +1,57 @@ +import { ListChecks } from 'lucide-react-native' +import { MobileAgentSessionHistoryIcon } from '../agent-history/MobileAgentSessionHistoryIcon' +import { ActionSheetModal } from '../components/ActionSheetModal' +import { colors } from '../theme/mobile-theme' + +type Props = { + visible: boolean + showAgentSessionHistory: boolean + showChecks: boolean + onOpenAgentSessionHistory: () => void + onOpenChecks: () => void + onClose: () => void +} + +export function MobileSessionHeaderMoreActionsSheet({ + visible, + showAgentSessionHistory, + showChecks, + onOpenAgentSessionHistory, + onOpenChecks, + onClose +}: Props) { + return ( + ( + + ), + onPress: onOpenAgentSessionHistory + } + ] + : []), + ...(showChecks + ? [ + { + label: 'Checks', + hint: 'Open pull request checks', + icon: ListChecks, + onPress: onOpenChecks + } + ] + : []) + ]} + onClose={onClose} + /> + ) +} diff --git a/mobile/src/session/SessionDockColumn.tsx b/mobile/src/session/SessionDockColumn.tsx index f02e89f7329a..2f7ae6b5ca3f 100644 --- a/mobile/src/session/SessionDockColumn.tsx +++ b/mobile/src/session/SessionDockColumn.tsx @@ -1,27 +1,16 @@ import { memo } from 'react' import { View, StyleSheet } from 'react-native' -import type { ConnectionState } from '../transport/types' -import type { RpcClient } from '../transport/rpc-client' import { MobileSourceControlPanel } from '../source-control/MobileSourceControlPanel' import { MobileFileExplorerPanel } from '../files/MobileFileExplorerPanel' -import { MobilePrViewPanel } from '../components/pr-sidebar/MobilePrViewPanel' import { mobilePrSidebarStyles } from '../components/pr-sidebar/mobile-pr-sidebar-styles' import { useMobileDockResize } from './use-mobile-dock-resize' import type { ActivePanel } from './session-panel-host' -import type { MobileGitStatusResult } from '../source-control/mobile-git-status' type Props = { activePanel: Exclude hostId: string worktreeId: string name: string - client: RpcClient | null - connState: ConnectionState - branch: string | null - headSha: string | null - gitStatus: MobileGitStatusResult | null - isGithubRepo: boolean - branchContextLoaded: boolean availableWidth: number onRequestClose: () => void onFileOpenStart?: () => void @@ -40,13 +29,6 @@ export function SessionDockColumn({ hostId, worktreeId, name, - client, - connState, - branch, - headSha, - gitStatus, - isGithubRepo, - branchContextLoaded, availableWidth, onRequestClose, onFileOpenStart, @@ -63,13 +45,6 @@ export function SessionDockColumn({ hostId={hostId} worktreeId={worktreeId} name={name} - client={client} - connState={connState} - branch={branch} - headSha={headSha} - gitStatus={gitStatus} - isGithubRepo={isGithubRepo} - branchContextLoaded={branchContextLoaded} onRequestClose={onRequestClose} onFileOpenStart={onFileOpenStart} onOpenedFileDiff={onOpenedFileDiff} @@ -85,18 +60,14 @@ const DockPanelContent = memo(function DockPanelContent({ hostId, worktreeId, name, - client, - connState, - branch, - headSha, - gitStatus, - isGithubRepo, - branchContextLoaded, onRequestClose, onFileOpenStart, onOpenedFileDiff }: DockPanelContentProps) { - if (activePanel === 'sourceControl') { + // Source Control and Pull Request share one hub instance so swapping dock icons + // keeps commit draft / visited-tab / scroll state and lands on the right segment + // (design: PR dock maps to hub + tab=pr). + if (activePanel === 'sourceControl' || activePanel === 'pr') { return ( ) } - if (activePanel === 'files') { - return ( - - ) - } return ( - diff --git a/mobile/src/session/TerminalPaneView.tsx b/mobile/src/session/TerminalPaneView.tsx index da34ed870c1a..beb8118dabfd 100644 --- a/mobile/src/session/TerminalPaneView.tsx +++ b/mobile/src/session/TerminalPaneView.tsx @@ -1,12 +1,12 @@ import { useCallback } from 'react' import { StyleSheet, View } from 'react-native' -import { - TerminalWebView, - type MobileTerminalTheme, - type TerminalKeyboardAvoidanceMetrics, - type TerminalModes, - type TerminalWebViewHandle -} from '../terminal/TerminalWebView' +import { TerminalWebView } from '../terminal/TerminalWebView' +import type { + MobileTerminalTheme, + TerminalKeyboardAvoidanceMetrics, + TerminalModes, + TerminalWebViewHandle +} from '../terminal/terminal-webview-contract' type TerminalPaneViewProps = { handle: string diff --git a/mobile/src/session/ai-vault-resume-launch.test.ts b/mobile/src/session/ai-vault-resume-launch.test.ts new file mode 100644 index 000000000000..c97849298fb3 --- /dev/null +++ b/mobile/src/session/ai-vault-resume-launch.test.ts @@ -0,0 +1,300 @@ +import { describe, expect, it, vi } from 'vitest' +import type { AiVaultSession } from '../../../src/shared/ai-vault-types' +import { + buildMobileAiVaultResumeLaunch, + buildMobileAiVaultResumeCommand, + createMobileAiVaultResumeMutationRegistry, + readMobileRuntimeHostPlatform, + readMobileRuntimeTerminalWindowsShell, + resolveMobileAiVaultResumePlatform, + resumeAiVaultSessionInTerminal, + RESUME_RPC_TIMEOUT_MS +} from './ai-vault-resume-launch' + +function session(overrides: Partial = {}): AiVaultSession { + return { + id: 'claude:1', + executionHostId: 'local', + agent: 'claude', + sessionId: 'session 1', + title: 'Resume me', + cwd: '/Users/ada/repo', + branch: 'main', + model: null, + filePath: '/Users/ada/.claude/session.jsonl', + codexHome: null, + createdAt: null, + updatedAt: null, + modifiedAt: '2026-06-29T00:00:00.000Z', + messageCount: 2, + totalTokens: 10, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: '', + subagent: null, + ...overrides + } +} + +describe('buildMobileAiVaultResumeCommand', () => { + it('delegates POSIX command construction to the shared AI Vault builder', () => { + expect(buildMobileAiVaultResumeCommand({ session: session(), hostPlatform: 'darwin' })).toBe( + "cd '/Users/ada/repo' && claude --resume 'session 1'" + ) + }) + + it('uses PowerShell-safe queued command construction for default local Windows terminals', () => { + expect( + buildMobileAiVaultResumeCommand({ + session: session({ + agent: 'codex', + sessionId: 'codex-1', + cwd: 'C:\\repo app', + codexHome: 'C:\\Users\\Ada\\.codex' + }), + hostPlatform: 'win32' + }) + ).toBe( + "Set-Location -LiteralPath 'C:\\repo app'; $env:CODEX_HOME='C:\\Users\\Ada\\.codex'; codex resume 'codex-1'" + ) + }) + + it('resumes OMP sessions by absolute transcript path like desktop', () => { + // Regression: custom OMP_CODING_AGENT_DIR / WSL-store sessions miss on an + // id lookup, so the forwarded filePath must win over the session id. + expect( + buildMobileAiVaultResumeCommand({ + session: session({ + agent: 'omp', + sessionId: '019f27cd-4268-7000-96e7-62f42a55c144', + filePath: '/Users/ada/.omp/agent/sessions/repo/sess.jsonl', + cwd: '/Users/ada/repo' + }), + hostPlatform: 'darwin' + }) + ).toBe("cd '/Users/ada/repo' && omp --resume '/Users/ada/.omp/agent/sessions/repo/sess.jsonl'") + }) + + it('uses cmd wrapping when the host Windows terminal is configured as cmd', () => { + const command = buildMobileAiVaultResumeCommand({ + session: session({ + agent: 'codex', + sessionId: 'codex-1', + cwd: 'C:\\repo app', + codexHome: 'C:\\Users\\Ada\\.codex' + }), + hostPlatform: 'win32', + hostTerminalWindowsShell: 'cmd.exe' + }) + expect(command).toContain('cmd /d /s /c') + expect(command).toContain('cd /d ""C:\\repo app""') + expect(command).toContain('set ""CODEX_HOME=C:\\Users\\Ada\\.codex""') + expect(command).toContain('codex resume ""codex-1""') + }) + + it('uses POSIX command construction and converts Codex home for WSL targets', () => { + expect( + buildMobileAiVaultResumeCommand({ + session: session({ + agent: 'codex', + sessionId: 'codex-1', + cwd: '/home/ada/repo', + codexHome: '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.codex' + }), + hostPlatform: 'linux' + }) + ).toBe("cd '/home/ada/repo' && CODEX_HOME='/home/ada/.codex' codex resume 'codex-1'") + }) + + it('passes command overrides through to the shared builder', () => { + expect( + buildMobileAiVaultResumeCommand({ + session: session({ sessionId: 'abc' }), + hostPlatform: 'linux', + commandOverride: 'claude-dev' + }) + ).toBe("cd '/Users/ada/repo' && claude-dev --resume 'abc'") + }) +}) + +describe('buildMobileAiVaultResumeLaunch', () => { + it('uses shared TUI startup planning for default args, env, and launch config', () => { + const launch = buildMobileAiVaultResumeLaunch({ + session: session({ + agent: 'claude', + sessionId: 'abc 123', + cwd: '/Users/ada/repo' + }), + hostPlatform: 'darwin', + settings: { + agentCmdOverrides: { claude: 'claude-dev' }, + agentDefaultArgs: { claude: '--model opus' }, + agentDefaultEnv: { claude: { ANTHROPIC_BASE_URL: 'http://localhost:3000' } } + } + }) + expect(launch.command).toBe( + "cd '/Users/ada/repo' && claude-dev '--model' 'opus' '--resume' 'abc 123'" + ) + expect(launch.env).toEqual({ ANTHROPIC_BASE_URL: 'http://localhost:3000' }) + expect(launch.launchAgent).toBe('claude') + expect(launch.launchConfig).toEqual({ + agentCommand: "claude-dev '--model' 'opus'", + agentArgs: '--model opus', + agentEnv: { ANTHROPIC_BASE_URL: 'http://localhost:3000' } + }) + }) +}) + +describe('resumeAiVaultSessionInTerminal', () => { + it('creates a fresh terminal and sends the command with Enter', async () => { + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ + ok: true, + result: { tab: { type: 'terminal', id: 'tab-1', terminal: 'pty-1', title: 'Terminal' } } + }) + .mockResolvedValueOnce({ ok: true, result: { send: { accepted: true } } }) + + await expect( + resumeAiVaultSessionInTerminal({ sendRequest }, 'worktree-1', { + command: 'claude --resume abc', + env: { ANTHROPIC_BASE_URL: 'http://localhost:3000' }, + launchConfig: { + agentCommand: 'claude', + agentArgs: '', + agentEnv: { ANTHROPIC_BASE_URL: 'http://localhost:3000' } + }, + launchAgent: 'claude', + clientMutationId: 'resume-1' + }) + ).resolves.toMatchObject({ id: 'tab-1', terminal: 'pty-1' }) + expect(sendRequest).toHaveBeenNthCalledWith( + 1, + 'session.tabs.createTerminal', + { + worktree: 'id:worktree-1', + env: { ANTHROPIC_BASE_URL: 'http://localhost:3000' }, + launchConfig: { + agentCommand: 'claude', + agentArgs: '', + agentEnv: { ANTHROPIC_BASE_URL: 'http://localhost:3000' } + }, + launchAgent: 'claude', + clientMutationId: 'resume-1' + }, + // Why: a socket drop mid-resume must reject within the request timeout + // instead of parking on the reconnect waiter with the spinner pinned. + { timeoutMs: RESUME_RPC_TIMEOUT_MS } + ) + expect(sendRequest).toHaveBeenNthCalledWith( + 2, + 'terminal.send', + { + terminal: 'pty-1', + text: 'claude --resume abc', + enter: true + }, + { timeoutMs: RESUME_RPC_TIMEOUT_MS } + ) + }) + + it('throws when terminal creation fails', async () => { + const sendRequest = vi.fn().mockResolvedValueOnce({ + ok: false, + error: { message: 'no terminal' } + }) + await expect( + resumeAiVaultSessionInTerminal({ sendRequest }, 'worktree-1', { command: 'command' }) + ).rejects.toThrow('no terminal') + }) + + it('throws when the created terminal response is malformed', async () => { + const sendRequest = vi.fn().mockResolvedValueOnce({ ok: true, result: { tab: { id: 'x' } } }) + await expect( + resumeAiVaultSessionInTerminal({ sendRequest }, 'worktree-1', { command: 'command' }) + ).rejects.toThrow('Created terminal response was invalid') + }) + + it('throws when terminal send fails or is locked', async () => { + const failedSend = vi + .fn() + .mockResolvedValueOnce({ + ok: true, + result: { tab: { type: 'terminal', id: 'tab-1', terminal: 'pty-1' } } + }) + .mockResolvedValueOnce({ ok: false, error: { message: 'send failed' } }) + await expect( + resumeAiVaultSessionInTerminal({ sendRequest: failedSend }, 'worktree-1', { + command: 'command' + }) + ).rejects.toThrow('send failed') + + const lockedSend = vi + .fn() + .mockResolvedValueOnce({ + ok: true, + result: { tab: { type: 'terminal', id: 'tab-1', terminal: 'pty-1' } } + }) + .mockResolvedValueOnce({ ok: true, result: { send: { accepted: false } } }) + await expect( + resumeAiVaultSessionInTerminal({ sendRequest: lockedSend }, 'worktree-1', { + command: 'command' + }) + ).rejects.toThrow('Terminal input is locked') + }) +}) + +describe('createMobileAiVaultResumeMutationRegistry', () => { + it('reuses the claimed id across retries until a success releases it', () => { + let mints = 0 + const registry = createMobileAiVaultResumeMutationRegistry((sessionId) => { + mints += 1 + return `${sessionId}:mutation-${mints}` + }) + + expect(registry.claim('session-a')).toBe('session-a:mutation-1') + // A failed attempt keeps the key so the host can dedup the retry. + expect(registry.claim('session-a')).toBe('session-a:mutation-1') + + registry.releaseOnSuccess('session-a') + // A resume after success mints fresh so the user can fork intentionally. + expect(registry.claim('session-a')).toBe('session-a:mutation-2') + }) + + it('tracks sessions independently', () => { + const registry = createMobileAiVaultResumeMutationRegistry((sessionId) => `${sessionId}:id`) + expect(registry.claim('session-a')).toBe('session-a:id') + expect(registry.claim('session-b')).toBe('session-b:id') + registry.releaseOnSuccess('session-b') + expect(registry.claim('session-a')).toBe('session-a:id') + }) +}) + +describe('resume platform helpers', () => { + it('reads a valid host platform from status.get', () => { + expect(readMobileRuntimeHostPlatform({ hostPlatform: 'win32' })).toBe('win32') + expect(readMobileRuntimeHostPlatform({ hostPlatform: 'not-a-platform' })).toBeNull() + }) + + it('reads the host Windows terminal shell from status.get', () => { + expect(readMobileRuntimeTerminalWindowsShell({ terminalWindowsShell: 'wsl.exe' })).toBe( + 'wsl.exe' + ) + expect(readMobileRuntimeTerminalWindowsShell({ terminalWindowsShell: '' })).toBeNull() + }) + + it('uses Linux/POSIX construction for SSH targets and host platform for local targets', () => { + expect(resolveMobileAiVaultResumePlatform('ssh', 'win32')).toBe('linux') + expect(resolveMobileAiVaultResumePlatform('local', 'darwin')).toBe('darwin') + expect( + resolveMobileAiVaultResumePlatform( + 'local', + 'win32', + '\\\\wsl.localhost\\Ubuntu\\home\\ada\\repo' + ) + ).toBe('linux') + expect(resolveMobileAiVaultResumePlatform('local', 'win32', 'C:\\repo', 'linux')).toBe('linux') + expect(resolveMobileAiVaultResumePlatform('runtime', 'linux')).toBeNull() + }) +}) diff --git a/mobile/src/session/ai-vault-resume-launch.ts b/mobile/src/session/ai-vault-resume-launch.ts new file mode 100644 index 000000000000..61144c0de2ba --- /dev/null +++ b/mobile/src/session/ai-vault-resume-launch.ts @@ -0,0 +1,269 @@ +import type { AiVaultSession } from '../../../src/shared/ai-vault-types' +import { + buildAiVaultResumeCommand, + buildAiVaultResumeShellCommand +} from '../../../src/shared/ai-vault-types' +import { isResumableTuiAgent } from '../../../src/shared/agent-session-resume' +import type { SleepingAgentLaunchConfig } from '../../../src/shared/agent-session-resume' +import { buildAgentResumeStartupPlan } from '../../../src/shared/tui-agent-startup' +import { + resolveTuiAgentLaunchArgs, + resolveTuiAgentLaunchEnv +} from '../../../src/shared/tui-agent-launch-defaults' +import type { TuiAgent } from '../../../src/shared/types' +import { parseWslUncPath } from '../../../src/shared/wsl-paths' +import { resolveWindowsShellStartupFamily } from '../../../src/shared/windows-terminal-shell' +import type { RpcClient } from '../transport/rpc-client' +import { + readMobileReviewCreatedTerminal, + readMobileReviewTerminalSendAccepted, + type MobileReviewTerminalTab +} from './mobile-diff-review-rpc' +import type { MobileAiVaultResumeTargetStatus } from '../agent-history/agent-history-resume-target' + +const NODE_PLATFORMS = new Set([ + 'aix', + 'android', + 'darwin', + 'freebsd', + 'haiku', + 'linux', + 'openbsd', + 'sunos', + 'win32', + 'cygwin', + 'netbsd' +]) + +export function buildMobileAiVaultResumeCommand(args: { + session: Pick & + Partial> + hostPlatform: NodeJS.Platform + hostTerminalWindowsShell?: string | null + commandOverride?: string | null +}): string { + // Why: this command is typed into the freshly created host terminal, so on + // Windows it must match the host's live shell instead of the phone platform. + const shell = + args.hostPlatform === 'win32' + ? resolveWindowsShellStartupFamily(args.hostTerminalWindowsShell) + : undefined + return buildAiVaultResumeCommand({ + agent: args.session.agent, + sessionId: args.session.sessionId, + // Why: OMP resumes by absolute transcript path (custom OMP dir / WSL-store + // sessions miss on an id lookup), so mobile forwards it like desktop does. + resumeFilePath: args.session.filePath, + cwd: args.session.cwd, + platform: args.hostPlatform, + commandOverride: args.commandOverride, + codexHome: getMobileAiVaultResumeCodexHome(args.session.codexHome, args.hostPlatform), + shell + }) +} + +export type MobileAiVaultResumeSettings = { + agentCmdOverrides?: Partial> + agentDefaultArgs?: Partial> + agentDefaultEnv?: Partial>> +} + +export type MobileAiVaultResumeLaunch = { + command: string + env?: Record + launchConfig?: SleepingAgentLaunchConfig + launchAgent?: TuiAgent +} + +export function buildMobileAiVaultResumeLaunch(args: { + session: Pick & + Partial> + hostPlatform: NodeJS.Platform + hostTerminalWindowsShell?: string | null + settings?: MobileAiVaultResumeSettings | null +}): MobileAiVaultResumeLaunch { + const shell = + args.hostPlatform === 'win32' + ? resolveWindowsShellStartupFamily(args.hostTerminalWindowsShell) + : undefined + const codexHome = getMobileAiVaultResumeCodexHome(args.session.codexHome, args.hostPlatform) + const cmdOverrides = normalizeMobileAiVaultResumeCommandOverrides( + args.settings?.agentCmdOverrides + ) + const commandOverride = cmdOverrides[args.session.agent] ?? null + if (isResumableTuiAgent(args.session.agent)) { + const startupPlan = buildAgentResumeStartupPlan({ + agent: args.session.agent, + providerSession: { key: 'session_id', id: args.session.sessionId }, + cmdOverrides, + platform: args.hostPlatform, + shell, + agentArgs: resolveTuiAgentLaunchArgs(args.session.agent, args.settings?.agentDefaultArgs), + agentEnv: resolveTuiAgentLaunchEnv(args.session.agent, args.settings?.agentDefaultEnv) + }) + if (startupPlan) { + return { + command: buildAiVaultResumeShellCommand({ + resumeCommand: startupPlan.launchCommand, + cwd: args.session.cwd, + platform: args.hostPlatform, + codexHome, + shell + }), + ...(startupPlan.env ? { env: startupPlan.env } : {}), + launchConfig: startupPlan.launchConfig, + launchAgent: startupPlan.agent + } + } + } + return { + command: buildMobileAiVaultResumeCommand({ + session: args.session, + hostPlatform: args.hostPlatform, + hostTerminalWindowsShell: args.hostTerminalWindowsShell, + commandOverride + }) + } +} + +function normalizeMobileAiVaultResumeCommandOverrides( + overrides: Partial> | null | undefined +): Partial> { + const normalized: Partial> = {} + if (!overrides) { + return normalized + } + for (const [agent, command] of Object.entries(overrides) as [TuiAgent, string | null][]) { + if (typeof command === 'string' && command.trim()) { + normalized[agent] = command + } + } + return normalized +} + +// Why: without an explicit timeout, a socket drop mid-resume parks the request +// on the reconnect waiter for the full reconnect budget, pinning the spinner. +export const RESUME_RPC_TIMEOUT_MS = 30_000 + +export async function resumeAiVaultSessionInTerminal( + client: Pick, + worktreeId: string, + launch: MobileAiVaultResumeLaunch & { clientMutationId?: string } +): Promise { + const created = await client.sendRequest( + 'session.tabs.createTerminal', + { + worktree: `id:${worktreeId}`, + ...(launch.env ? { env: launch.env } : {}), + ...(launch.launchConfig ? { launchConfig: launch.launchConfig } : {}), + ...(launch.launchAgent ? { launchAgent: launch.launchAgent } : {}), + ...(launch.clientMutationId ? { clientMutationId: launch.clientMutationId } : {}) + }, + { timeoutMs: RESUME_RPC_TIMEOUT_MS } + ) + if (!created.ok) { + throw new Error(created.error?.message || 'Failed to create terminal') + } + const terminalTab = readMobileReviewCreatedTerminal(created.result) + if (!terminalTab) { + throw new Error('Created terminal response was invalid') + } + const sent = await client.sendRequest( + 'terminal.send', + { + terminal: terminalTab.terminal, + text: launch.command, + enter: true + }, + { timeoutMs: RESUME_RPC_TIMEOUT_MS } + ) + if (!sent.ok) { + throw new Error(sent.error?.message || 'Failed to send resume command') + } + if (!readMobileReviewTerminalSendAccepted(sent.result)) { + throw new Error('Terminal input is locked') + } + return terminalTab +} + +export type MobileAiVaultResumeMutationRegistry = { + claim(sessionId: string): string + releaseOnSuccess(sessionId: string): void +} + +// Why: a retry after a failed/interrupted resume must reuse the same +// idempotency key so the host dedups the create, while a resume after success +// mints a fresh key so the user can intentionally fork the session. +export function createMobileAiVaultResumeMutationRegistry( + mintId: (sessionId: string) => string +): MobileAiVaultResumeMutationRegistry { + const bySessionId = new Map() + return { + claim(sessionId: string): string { + const existing = bySessionId.get(sessionId) + if (existing) { + return existing + } + const minted = mintId(sessionId) + bySessionId.set(sessionId, minted) + return minted + }, + releaseOnSuccess(sessionId: string): void { + bySessionId.delete(sessionId) + } + } +} + +export function readMobileRuntimeHostPlatform(statusResult: unknown): NodeJS.Platform | null { + if (!statusResult || typeof statusResult !== 'object') { + return null + } + const hostPlatform = (statusResult as { hostPlatform?: unknown }).hostPlatform + return typeof hostPlatform === 'string' && NODE_PLATFORMS.has(hostPlatform as NodeJS.Platform) + ? (hostPlatform as NodeJS.Platform) + : null +} + +export function readMobileRuntimeTerminalWindowsShell(statusResult: unknown): string | null { + if (!statusResult || typeof statusResult !== 'object') { + return null + } + const shell = (statusResult as { terminalWindowsShell?: unknown }).terminalWindowsShell + return typeof shell === 'string' && shell.trim().length > 0 ? shell : null +} + +export function resolveMobileAiVaultResumePlatform( + targetStatus: MobileAiVaultResumeTargetStatus, + hostPlatform: NodeJS.Platform | null, + workspacePath?: string | null, + terminalPlatform?: NodeJS.Platform | null +): NodeJS.Platform | null { + if (targetStatus === 'ssh') { + // Why: desktop builds SSH resume commands for the remote POSIX execution + // host instead of the phone or local desktop platform. + return 'linux' + } + if (targetStatus === 'local') { + if (terminalPlatform === 'linux' && hostPlatform === 'win32') { + // Why: Windows-hosted WSL project terminals run a POSIX shell even when + // the visible workspace path is a normal Windows path. + return 'linux' + } + if (workspacePath && parseWslUncPath(workspacePath)) { + // Why: a WSL UNC workspace on a Windows host runs in a Linux shell. + return 'linux' + } + return hostPlatform + } + return null +} + +function getMobileAiVaultResumeCodexHome( + codexHome: string | null, + platform: NodeJS.Platform +): string | null { + if (!codexHome || platform !== 'linux') { + return codexHome + } + return parseWslUncPath(codexHome)?.linuxPath ?? codexHome +} diff --git a/mobile/src/session/github-pr-rpc.test.ts b/mobile/src/session/github-pr-rpc.test.ts index 1adb72ec8b85..56904e482cd3 100644 --- a/mobile/src/session/github-pr-rpc.test.ts +++ b/mobile/src/session/github-pr-rpc.test.ts @@ -172,6 +172,23 @@ describe('readWorkItemDetails', () => { expect(parsed?.item.latestReviews).toEqual([{ login: 'ok', state: null, avatarUrl: null }]) }) + it('accepts raw gh latestReviews author.login nesting', () => { + const parsed = readWorkItemDetails({ + item: { + id: 'n', + type: 'pr', + number: 1, + state: 'open', + latestReviews: [ + { author: { login: 'coderabbitai', avatarUrl: 'https://a' }, state: 'COMMENTED' } + ] + } + }) + expect(parsed?.item.latestReviews).toEqual([ + { login: 'coderabbitai', state: 'COMMENTED', avatarUrl: 'https://a' } + ]) + }) + it('returns null when item is unparseable', () => { expect(readWorkItemDetails({ item: { number: 1 } })).toBeNull() expect(readWorkItemDetails(null)).toBeNull() diff --git a/mobile/src/session/github-pr-value-readers.ts b/mobile/src/session/github-pr-value-readers.ts index e7dcf9313ba0..6ba8ccd69540 100644 --- a/mobile/src/session/github-pr-value-readers.ts +++ b/mobile/src/session/github-pr-value-readers.ts @@ -123,14 +123,23 @@ export function readReviewSummary(value: unknown): GitHubPRReviewSummary | null if (!isRecord(value)) { return null } - const login = readString(value.login) + // Desktop maps latestReviews to top-level `login`. Raw `gh pr view --json` + // keeps nested `author.login` — accept both so mobile never drops reviewers. + const nestedAuthor = isRecord(value.author) ? value.author : null + const login = + readString(value.login) ?? (nestedAuthor ? readString(nestedAuthor.login) : undefined) if (login === undefined) { return null } + const avatarUrl = + readString(value.avatarUrl) ?? + (nestedAuthor + ? (readString(nestedAuthor.avatarUrl) ?? readString(nestedAuthor.avatar_url) ?? null) + : null) return { login, state: readString(value.state) ?? null, - avatarUrl: readString(value.avatarUrl) ?? null + avatarUrl } } diff --git a/mobile/src/session/mobile-pr-sidebar-state.ts b/mobile/src/session/mobile-pr-sidebar-state.ts index 5f5b679b210b..1b4d9a1b50bc 100644 --- a/mobile/src/session/mobile-pr-sidebar-state.ts +++ b/mobile/src/session/mobile-pr-sidebar-state.ts @@ -140,6 +140,62 @@ export async function loadPrSidebarDetails( } } +// UI treats details===null as "still loading". After phase 2 finishes (success or +// non-fatal failure), never leave null — use prior comments if any, else empty body. +export function resolvePrSidebarDetailsAfterPhase2(args: { + fetched: GitHubWorkItemDetails | null + prior: GitHubWorkItemDetails | null + pr: PRInfo +}): GitHubWorkItemDetails { + if (args.fetched != null) { + return args.fetched + } + if (args.prior != null) { + return args.prior + } + return emptyPrSidebarDetails(args.pr) +} + +// Placeholder details so Description/Comments leave the spinner after a failed phase 2. +// The synthetic id is the only id shape we mint — real GitHub node ids never match. +export function emptyPrSidebarDetails(pr: PRInfo): GitHubWorkItemDetails { + return { + item: { + id: `pr-${pr.number}`, + type: 'pr', + number: pr.number, + title: pr.title, + state: pr.state, + url: pr.url, + labels: [], + updatedAt: pr.updatedAt, + author: null + }, + body: '', + comments: [] + } +} + +// True when phase 2 failed and we synthesized a stand-in (no body/comments/reviews). +export function isPrSidebarDetailsPlaceholder(details: GitHubWorkItemDetails): boolean { + return details.item.id === `pr-${details.item.number}` +} + +// Phase-2 still needs a real payload: null (in flight / not started) or a +// synthetic placeholder from a failed fetch. Real details (including empty body) +// do not qualify — ensure/retry must not re-pull those. +export function prSidebarDetailsNeedFetch( + details: GitHubWorkItemDetails | null | undefined +): boolean { + return details == null || isPrSidebarDetailsPlaceholder(details) +} + +// Soft head refresh may restart an in-flight phase-1 load; only skip when there is +// no visible/in-flight sidebar work (hidden or terminal error states). +export function shouldSoftRefreshPrSidebarOnHeadChange(kind: PrSidebarState['kind']): boolean { + return kind === 'ready' || kind === 'none' || kind === 'loading' +} + // Stale-response guard (KTD6): a load tagged with an older sequence must not // overwrite a newer one. The hook bumps a monotonic counter per load. export function shouldApplyResult(resultSeq: number, latestSeq: number): boolean { diff --git a/mobile/src/session/mobile-session-route-helpers.ts b/mobile/src/session/mobile-session-route-helpers.ts index e5a8d4329b74..18434e21f5af 100644 --- a/mobile/src/session/mobile-session-route-helpers.ts +++ b/mobile/src/session/mobile-session-route-helpers.ts @@ -1,4 +1,4 @@ -import type { TerminalModes } from '../terminal/TerminalWebView' +import type { TerminalModes } from '../terminal/terminal-webview-contract' import type { ConnectionState } from '../transport/types' export const MOBILE_SESSION_STATUS_LABELS: Record = { diff --git a/mobile/src/session/mobile-session-startup-source.test.ts b/mobile/src/session/mobile-session-startup-source.test.ts index be295594f81a..aca17cfb5096 100644 --- a/mobile/src/session/mobile-session-startup-source.test.ts +++ b/mobile/src/session/mobile-session-startup-source.test.ts @@ -41,6 +41,8 @@ describe('mobile session startup', () => { expect(startupEffect.indexOf("sendRequest('worktree.activate'")).toBeLessThan( startupEffect.indexOf('await fetchSessionTabs()') ) + expect(startupEffect).toContain('headlessActivationNeedsHostRenderer(response.result)') + expect(startupEffect).toContain("showToast('Open Orca on the host to wake sleeping agents.'") }) it('activates an already-selected pending terminal tab after hydration', () => { diff --git a/mobile/src/session/mobile-terminal-records.test.ts b/mobile/src/session/mobile-terminal-records.test.ts index 4ebf74766823..0ebd2c556318 100644 --- a/mobile/src/session/mobile-terminal-records.test.ts +++ b/mobile/src/session/mobile-terminal-records.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest' import { getTerminalRecordsFromSessionTabs, mergeTerminalListWithKnownRecords, + mergeTerminalRecordsByCurrentOrder, mobileSessionTabsEqual, type MobileTerminalSessionTab, type TerminalRecord @@ -24,6 +25,17 @@ const darkTheme = { } describe('mobile terminal records', () => { + it('keeps the known theme when a session-tab snapshot omits it', () => { + const known: TerminalRecord[] = [ + { handle: 'pty-1', title: 'Old title', terminalTheme: darkTheme, isActive: false } + ] + const snapshot: TerminalRecord[] = [{ handle: 'pty-1', title: 'Current title', isActive: true }] + + expect(mergeTerminalRecordsByCurrentOrder(snapshot, known)).toEqual([ + { handle: 'pty-1', title: 'Current title', terminalTheme: darkTheme, isActive: true } + ]) + }) + it('keeps session-tab terminal themes when terminal.list omits them', () => { const terminalList: TerminalRecord[] = [ { handle: 'pty-1', title: 'Terminal', isActive: true }, diff --git a/mobile/src/session/mobile-terminal-records.ts b/mobile/src/session/mobile-terminal-records.ts index 0f97af2529ef..ffe93ac29dda 100644 --- a/mobile/src/session/mobile-terminal-records.ts +++ b/mobile/src/session/mobile-terminal-records.ts @@ -1,4 +1,4 @@ -import type { MobileTerminalTheme } from '../terminal/TerminalWebView' +import type { MobileTerminalTheme } from '../terminal/terminal-webview-contract' import type { AgentStatusEntry } from '../../../src/shared/agent-status-types' export type TerminalRecord = { @@ -116,6 +116,20 @@ function mobileSessionTabEqual( } } +// Reconcile a partial session snapshot against the last known record for the +// same terminal. The snapshot owns live fields (title, activity); the known +// theme only survives when the snapshot omits it, since lightweight snapshots +// can drop it. +function mergeTerminalSnapshotWithKnownRecord( + snapshot: TerminalRecord, + known: TerminalRecord +): TerminalRecord { + return { + ...snapshot, + terminalTheme: snapshot.terminalTheme ?? known.terminalTheme + } +} + export function mergeTerminalRecordsByCurrentOrder( terminalTabs: TerminalRecord[], currentTerminals: TerminalRecord[] @@ -126,7 +140,12 @@ export function mergeTerminalRecordsByCurrentOrder( const terminalTabsByHandle = new Map(terminalTabs.map((tab) => [tab.handle, tab])) const currentHandles = new Set(currentTerminals.map((terminal) => terminal.handle)) return [ - ...currentTerminals.map((terminal) => terminalTabsByHandle.get(terminal.handle) ?? terminal), + ...currentTerminals.map((terminal) => { + const snapshotTerminal = terminalTabsByHandle.get(terminal.handle) + return snapshotTerminal + ? mergeTerminalSnapshotWithKnownRecord(snapshotTerminal, terminal) + : terminal + }), ...terminalTabs.filter((terminal) => !currentHandles.has(terminal.handle)) ] } diff --git a/mobile/src/session/pr-actions-engine.test.ts b/mobile/src/session/pr-actions-engine.test.ts index 72bde8724098..d879454c50c1 100644 --- a/mobile/src/session/pr-actions-engine.test.ts +++ b/mobile/src/session/pr-actions-engine.test.ts @@ -80,6 +80,51 @@ describe('PrActionsEngine — transport-rejection-normalized outcomes settle cle expect(engine.error).toBe('socket hung up') expect(engine.busy).toBeNull() }) + + it('surfaces a refetch throw as error without rejecting the action promise', async () => { + const engine = new PrActionsEngine({ + mutations: { + mergePR: async () => ({ ok: true }), + setPRAutoMerge: async () => ({ ok: true }), + updatePRState: async () => ({ ok: true }), + requestReviewers: async () => ({ ok: true }), + removeReviewers: async () => ({ ok: true }), + rerunChecks: async () => ({ ok: true }) + }, + prNumber: 1, + refetch: async () => { + throw new Error('refresh failed') + }, + onChange: () => {} + }) + await expect(engine.merge()).resolves.toBeUndefined() + expect(engine.error).toBe('refresh failed') + expect(engine.busy).toBeNull() + }) + + it('does not notify on no-op setError(null) at action start', async () => { + const onChange = vi.fn() + const engine = new PrActionsEngine({ + mutations: { + mergePR: async () => ({ ok: true }), + setPRAutoMerge: async () => ({ ok: true }), + updatePRState: async () => ({ ok: true }), + requestReviewers: async () => ({ ok: true }), + removeReviewers: async () => ({ ok: true }), + rerunChecks: async () => ({ ok: true }) + }, + prNumber: 1, + refetch: () => {}, + onChange + }) + // Idle: error is already null. Action start must only notify for busy, not a + // redundant clearError path. + onChange.mockClear() + const p = engine.merge() + // First notify is setBusy only (setError(null) no-ops). + expect(onChange).toHaveBeenCalledTimes(1) + await p + }) }) describe('PrActionsEngine — PR identity changes', () => { diff --git a/mobile/src/session/pr-actions-engine.ts b/mobile/src/session/pr-actions-engine.ts index a647b62dfe96..7c34954534dc 100644 --- a/mobile/src/session/pr-actions-engine.ts +++ b/mobile/src/session/pr-actions-engine.ts @@ -129,7 +129,12 @@ export class PrActionsEngine { return f } + // Why: action start pairs setBusy + setError(null); skip notify when unchanged + // so we don't force a full PR panel re-render for free. private setBusy(key: PrActionBusyKey | null): void { + if (key === null ? this.busy === null : busyKeyEquals(this.busy, key)) { + return + } this.busy = key this.cfg.onChange() } @@ -143,6 +148,9 @@ export class PrActionsEngine { } private setError(message: string | null): void { + if (this.error === message) { + return + } this.error = message this.cfg.onChange() } @@ -180,7 +188,14 @@ export class PrActionsEngine { } if (outcome.ok) { handlers.onSuccess() - await this.cfg.refetch() + // Why: void engine.merge() callers are fire-and-forget; refetch must not LogBox. + try { + await this.cfg.refetch() + } catch (err) { + if (this.identity === identity) { + this.setError(err instanceof Error ? err.message : 'Failed to refresh pull request.') + } + } return } // Both failure classes clear optimism to authoritative; only the message @@ -205,6 +220,10 @@ export class PrActionsEngine { prRepo: cfg.prRepo }) await this.settle(identity, outcome, { onSuccess: () => {}, onRevert: () => {} }) + } catch (err) { + if (this.identity === identity) { + this.setError(err instanceof Error ? err.message : 'Failed to merge pull request.') + } } finally { this.clearBusyIfOwned(identity, { kind: 'merge' }) } diff --git a/mobile/src/session/session-panel-host.test.ts b/mobile/src/session/session-panel-host.test.ts index 1028e489821a..1b17fa4f1e1a 100644 --- a/mobile/src/session/session-panel-host.test.ts +++ b/mobile/src/session/session-panel-host.test.ts @@ -4,6 +4,7 @@ import { nextActivePanel, resolvePanelAction, panelRouteDescriptor, + shouldShowSessionHeaderChecksAction, type ActivePanel } from './session-panel-host' @@ -77,6 +78,48 @@ describe('canDockSessionPanel', () => { }) }) +describe('shouldShowSessionHeaderChecksAction', () => { + it('shows Checks on git worktree routes once a checks-capable provider is confirmed', () => { + expect( + shouldShowSessionHeaderChecksAction({ + isFolderWorkspaceRoute: false, + repoContextLoaded: true, + hostedChecksSupported: true + }) + ).toBe(true) + }) + + it('hides Checks for providers without hosted checks (pr-panel guard would no-op it)', () => { + expect( + shouldShowSessionHeaderChecksAction({ + isFolderWorkspaceRoute: false, + repoContextLoaded: true, + hostedChecksSupported: false + }) + ).toBe(false) + }) + + it('hides Checks until the provider probe resolves', () => { + expect( + shouldShowSessionHeaderChecksAction({ + isFolderWorkspaceRoute: false, + repoContextLoaded: false, + hostedChecksSupported: false + }) + ).toBe(false) + }) + + it('hides Checks on folder workspace session routes', () => { + expect( + shouldShowSessionHeaderChecksAction({ + isFolderWorkspaceRoute: true, + repoContextLoaded: true, + hostedChecksSupported: true + }) + ).toBe(false) + }) +}) + describe('panelRouteDescriptor', () => { it('maps each panel to its expo-router pathname', () => { expect(panelRouteDescriptor('sourceControl')).toEqual({ @@ -86,7 +129,8 @@ describe('panelRouteDescriptor', () => { pathname: '/h/[hostId]/files/[worktreeId]' }) expect(panelRouteDescriptor('pr')).toEqual({ - pathname: '/h/[hostId]/pr/[worktreeId]' + pathname: '/h/[hostId]/source-control/[worktreeId]', + params: { tab: 'pr' } }) }) }) diff --git a/mobile/src/session/session-panel-host.ts b/mobile/src/session/session-panel-host.ts index 280c368c543a..5e1e4793e257 100644 --- a/mobile/src/session/session-panel-host.ts +++ b/mobile/src/session/session-panel-host.ts @@ -19,6 +19,17 @@ export type PanelAction = export const SESSION_DOCK_MIN_MAIN_WIDTH = 360 +export function shouldShowSessionHeaderChecksAction(args: { + isFolderWorkspaceRoute: boolean + repoContextLoaded: boolean + hostedChecksSupported: boolean +}): boolean { + // Why: the hosted checks panel is provider-gated and the pr-panel guard + // force-closes it for unsupported providers, so offering the action there + // (or before the provider probe resolves) would be a silent no-op. + return !args.isFolderWorkspaceRoute && args.repoContextLoaded && args.hostedChecksSupported +} + export function canDockSessionPanel(args: { isWideLayout: boolean availableWidth: number @@ -47,13 +58,18 @@ export function resolvePanelAction(args: { // Single source of truth for each panel's expo-router pathname pattern so narrow-push // and any deep-linking agree; the caller supplies the [hostId]/[worktreeId] params. -export function panelRouteDescriptor(panel: Exclude): { pathname: string } { +// The Pull Request panel is a segment of the source-control hub, so its narrow-push +// targets that route with `tab: 'pr'` rather than the standalone (redirecting) route. +export function panelRouteDescriptor(panel: Exclude): { + pathname: string + params?: Record +} { switch (panel) { case 'sourceControl': return { pathname: '/h/[hostId]/source-control/[worktreeId]' } case 'files': return { pathname: '/h/[hostId]/files/[worktreeId]' } case 'pr': - return { pathname: '/h/[hostId]/pr/[worktreeId]' } + return { pathname: '/h/[hostId]/source-control/[worktreeId]', params: { tab: 'pr' } } } } diff --git a/mobile/src/session/use-mobile-pr-branch-context.ts b/mobile/src/session/use-mobile-pr-branch-context.ts index ef2cf1a48d54..d0816b02f71c 100644 --- a/mobile/src/session/use-mobile-pr-branch-context.ts +++ b/mobile/src/session/use-mobile-pr-branch-context.ts @@ -34,12 +34,16 @@ export function deriveMobilePrBranchContext( // Loads repo eligibility independently from branch/SHA. The header PR icon only // needs the cheap GitHub probe; the panel can keep loading branch context after // the entry point is already stable in the top bar. +// +// `includeBranchIdentity: false` skips git.status + branchCompare — use when the +// caller only gates a PR entry on hosted-repo eligibility (session dock icon). export function useMobilePrBranchContext(input: { client: RpcClient | null connState: ConnectionState worktreeId: string + includeBranchIdentity?: boolean }): MobilePrBranchContext { - const { client, connState, worktreeId } = input + const { client, connState, worktreeId, includeBranchIdentity = true } = input const [context, setContext] = useState({ branch: null, headSha: null, @@ -60,7 +64,7 @@ export function useMobilePrBranchContext(input: { status: null, isGithubRepo: false, repoLoaded: false, - loaded: false + loaded: !includeBranchIdentity }) return } @@ -70,7 +74,8 @@ export function useMobilePrBranchContext(input: { status: null, isGithubRepo: false, repoLoaded: false, - loaded: false + // Repo-only mode is "loaded" for branch fields immediately (they stay null). + loaded: !includeBranchIdentity }) void loadMobilePrRepoContext(client, worktreeId) @@ -95,6 +100,12 @@ export function useMobilePrBranchContext(input: { } }) + if (!includeBranchIdentity) { + return () => { + cancelled = true + } + } + void loadMobilePrBranchIdentity(client, worktreeId) .then((next) => { if (!cancelled) { @@ -121,7 +132,7 @@ export function useMobilePrBranchContext(input: { return () => { cancelled = true } - }, [ready, client, worktreeId]) + }, [ready, client, worktreeId, includeBranchIdentity]) return context } diff --git a/mobile/src/session/use-mobile-pr-sidebar-controller-probe.test.ts b/mobile/src/session/use-mobile-pr-sidebar-controller-probe.test.ts new file mode 100644 index 000000000000..0645b6659c43 --- /dev/null +++ b/mobile/src/session/use-mobile-pr-sidebar-controller-probe.test.ts @@ -0,0 +1,100 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' + +const fetchGithubRepoSlugMock = vi.fn() + +// Only the repo probe matters here; the load path never runs without a branch. +vi.mock('./github-pr-rpc', () => ({ + fetchGithubRepoSlug: (...args: unknown[]) => fetchGithubRepoSlugMock(...args), + fetchHostedReviewForBranch: vi.fn(), + fetchPRChecks: vi.fn(), + fetchPRForBranch: vi.fn(), + fetchWorkItemDetails: vi.fn() +})) +vi.mock('../source-control/mobile-pr-link', () => ({ + fetchWorktreeLinkedPR: vi.fn(async () => null) +})) + +import { + useMobilePrSidebarController, + type MobilePrSidebarController +} from './use-mobile-pr-sidebar-controller' + +let captured: MobilePrSidebarController | null = null + +function Harness(props: Parameters[0]) { + captured = useMobilePrSidebarController(props) + return null +} + +async function flush(): Promise { + // Two ticks: the probe's resolved promise (.then) plus its setState commit. + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) +} + +describe('useMobilePrSidebarController repo probe', () => { + const client = { sendRequest: vi.fn() } as unknown as RpcClient + let renderer: ReactTestRenderer | null = null + + beforeEach(() => { + captured = null + fetchGithubRepoSlugMock.mockReset() + }) + + afterEach(() => { + act(() => { + renderer?.unmount() + }) + renderer = null + }) + + // Regression: repo eligibility must not be gated on a branch. A detached HEAD / + // mid-rebase worktree (branch === null) still has to resolve the probe, or the + // Pull Request segment gets stranded on a forever spinner instead of the + // "Current branch unavailable" state. + it('resolves the probe when connected without a branch (detached HEAD)', async () => { + fetchGithubRepoSlugMock.mockResolvedValue({ ok: true, result: { owner: 'o', repo: 'r' } }) + await act(async () => { + renderer = create( + createElement(Harness, { + client, + connState: 'connected', + worktreeId: 'w', + branch: null, + headSha: 'sha' + }) + ) + }) + await flush() + + expect(fetchGithubRepoSlugMock).toHaveBeenCalledWith(client, 'w') + expect(captured?.prSidebarRepoProbeLoaded).toBe(true) + expect(captured?.prSidebarIsGithubRepo).toBe(true) + // No branch means no PR load ran — state stays hidden, never a spinner. + expect(captured?.prSidebarState.kind).toBe('hidden') + }) + + it('does not probe until the client is connected', async () => { + fetchGithubRepoSlugMock.mockResolvedValue({ ok: true, result: { owner: 'o', repo: 'r' } }) + await act(async () => { + renderer = create( + createElement(Harness, { + client, + connState: 'connecting', + worktreeId: 'w', + branch: null, + headSha: 'sha' + }) + ) + }) + await flush() + + expect(fetchGithubRepoSlugMock).not.toHaveBeenCalled() + expect(captured?.prSidebarRepoProbeLoaded).toBe(false) + }) +}) diff --git a/mobile/src/session/use-mobile-pr-sidebar-controller.test.ts b/mobile/src/session/use-mobile-pr-sidebar-controller.test.ts index 005c4dc0e5b4..f402f7b58ad3 100644 --- a/mobile/src/session/use-mobile-pr-sidebar-controller.test.ts +++ b/mobile/src/session/use-mobile-pr-sidebar-controller.test.ts @@ -4,11 +4,17 @@ import type { HostedReviewInfo } from '../../../src/shared/hosted-review' import type { GitHubPrReadOutcome } from './github-pr-rpc' import { classifyPrSidebarFailure, + emptyPrSidebarDetails, + isPrSidebarDetailsPlaceholder, + prSidebarDetailsNeedFetch, loadPrSidebarData, loadPrSidebarDetails, + resolvePrSidebarDetailsAfterPhase2, shouldApplyResult, + shouldSoftRefreshPrSidebarOnHeadChange, type PrSidebarLoadDeps } from './mobile-pr-sidebar-state' +import { buildMobilePrSidebarIdentity } from './use-mobile-pr-sidebar-controller' function ok(result: T): GitHubPrReadOutcome { return { ok: true, result } @@ -200,3 +206,84 @@ describe('shouldApplyResult', () => { expect(shouldApplyResult(2, 3)).toBe(false) }) }) + +describe('shouldSoftRefreshPrSidebarOnHeadChange', () => { + it('restarts ready/none/loading so mid-flight head advances are not stuck', () => { + expect(shouldSoftRefreshPrSidebarOnHeadChange('ready')).toBe(true) + expect(shouldSoftRefreshPrSidebarOnHeadChange('none')).toBe(true) + expect(shouldSoftRefreshPrSidebarOnHeadChange('loading')).toBe(true) + }) + + it('skips hidden and terminal failures (chip bootstrap / retry own those)', () => { + expect(shouldSoftRefreshPrSidebarOnHeadChange('hidden')).toBe(false) + expect(shouldSoftRefreshPrSidebarOnHeadChange('error')).toBe(false) + expect(shouldSoftRefreshPrSidebarOnHeadChange('blocked')).toBe(false) + }) +}) + +describe('resolvePrSidebarDetailsAfterPhase2', () => { + it('prefers a successful fetch over prior details', () => { + const prior = emptyPrSidebarDetails(PR) + expect(resolvePrSidebarDetailsAfterPhase2({ fetched: DETAILS, prior, pr: PR })).toBe(DETAILS) + }) + + it('keeps prior details when the fetch is non-fatal null', () => { + const prior = emptyPrSidebarDetails(PR) + expect(resolvePrSidebarDetailsAfterPhase2({ fetched: null, prior, pr: PR })).toBe(prior) + }) + + it('uses empty details when phase 2 fails with nothing prior (no forever spinner)', () => { + const empty = resolvePrSidebarDetailsAfterPhase2({ + fetched: null, + prior: null, + pr: PR + }) + expect(empty.body).toBe('') + expect(empty.comments).toEqual([]) + expect(empty.item.number).toBe(7) + expect(empty.item.type).toBe('pr') + expect(isPrSidebarDetailsPlaceholder(empty)).toBe(true) + }) +}) + +describe('isPrSidebarDetailsPlaceholder / prSidebarDetailsNeedFetch', () => { + it('detects the synthetic hyphen id, not the host pr:n shape', () => { + const placeholder = emptyPrSidebarDetails(PR) + expect(isPrSidebarDetailsPlaceholder(placeholder)).toBe(true) + expect(isPrSidebarDetailsPlaceholder(DETAILS)).toBe(false) + // Host work-item ids use a colon (`pr:7`); placeholders use a hyphen (`pr-7`). + expect( + isPrSidebarDetailsPlaceholder({ + ...DETAILS, + item: { ...DETAILS.item, id: `pr:${PR.number}` } + }) + ).toBe(false) + }) + + it('needs fetch for null and placeholders, not real details', () => { + expect(prSidebarDetailsNeedFetch(null)).toBe(true) + expect(prSidebarDetailsNeedFetch(undefined)).toBe(true) + expect(prSidebarDetailsNeedFetch(emptyPrSidebarDetails(PR))).toBe(true) + expect(prSidebarDetailsNeedFetch(DETAILS)).toBe(false) + }) +}) + +describe('buildMobilePrSidebarIdentity', () => { + it('keys identity on worktree + branch, not head SHA', () => { + expect(buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: 'feat' })).toBe('w1\u0000feat') + // Head advances on commit must not form a new identity — soft refresh keeps ready UI. + expect(buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: 'feat' })).toBe( + buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: 'feat' }) + ) + }) + + it('is null without a branch and changes when branch or worktree changes', () => { + expect(buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: null })).toBeNull() + expect(buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: 'a' })).not.toBe( + buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: 'b' }) + ) + expect(buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: 'a' })).not.toBe( + buildMobilePrSidebarIdentity({ worktreeId: 'w2', branch: 'a' }) + ) + }) +}) diff --git a/mobile/src/session/use-mobile-pr-sidebar-controller.ts b/mobile/src/session/use-mobile-pr-sidebar-controller.ts index b14f0dec783a..752b2ecb3b88 100644 --- a/mobile/src/session/use-mobile-pr-sidebar-controller.ts +++ b/mobile/src/session/use-mobile-pr-sidebar-controller.ts @@ -11,7 +11,10 @@ import { import { loadPrSidebarData, loadPrSidebarDetails, + prSidebarDetailsNeedFetch, + resolvePrSidebarDetailsAfterPhase2, shouldApplyResult, + shouldSoftRefreshPrSidebarOnHeadChange, type PrSidebarLoadDeps, type PrSidebarState } from './mobile-pr-sidebar-state' @@ -27,12 +30,20 @@ type PrSidebarControllerInput = { headSha: string | null } -function buildPrSidebarIdentity(args: { +// Load options for the shared PR controller. The Source Control hub chip only needs +// phase 1 (PR + checks); phase 2 (comments/body) is heavy and should wait until the +// Pull Request segment is actually open. +export type PrSidebarLoadOptions = { + includeDetails?: boolean +} + +// Identity is worktree + branch only. Head SHA advances on every commit and must not +// wipe a ready chip/sidebar to "loading" — soft-refresh uses the new head instead. +export function buildMobilePrSidebarIdentity(args: { worktreeId: string branch: string | null - headSha: string | null }): string | null { - return args.branch ? `${args.worktreeId}\u0000${args.branch}\u0000${args.headSha ?? ''}` : null + return args.branch ? `${args.worktreeId}\u0000${args.branch}` : null } export function useMobilePrSidebarController(input: PrSidebarControllerInput) { @@ -41,13 +52,31 @@ export function useMobilePrSidebarController(input: PrSidebarControllerInput) { // independent of whether the branch has an open PR (a no-PR branch shows an // empty state rather than hiding the icon). const [isGithubRepo, setIsGithubRepo] = useState(false) + // False until the probe resolves for this worktree. Consumers gate "unavailable + // for this provider" copy on it — isGithubRepo=false is meaningless mid-probe. + const [repoProbeLoaded, setRepoProbeLoaded] = useState(false) const [state, setState] = useState({ kind: 'hidden' }) const [showPRSidebar, setShowPRSidebar] = useState(false) const loadSeqRef = useRef(0) + // Phase-2-only fetches use a separate sequence so they cannot cancel a concurrent + // phase-1 soft refresh (and vice versa) when chip bootstrap left details null. + const detailsSeqRef = useRef(0) + // The (seq, prNumber) of the phase-2 fetch currently in flight. The hub's + // fill-in effect fires as soon as phase 1 renders ready with null details — + // exactly when load()'s own phase 2 just started. Without this claim, every + // cold PR-segment open fetched the heavy details payload twice. + const detailsInFlightRef = useRef<{ seq: number; prNumber: number } | null>(null) const stateIdentityRef = useRef(null) + const stateRef = useRef(state) + stateRef.current = state + const headShaRef = useRef(headSha) - const ready = client !== null && connState === 'connected' && !!branch - const identity = buildPrSidebarIdentity({ worktreeId, branch, headSha }) + // Repo eligibility (a GitHub remote) is independent of the branch, so the probe + // must not require one: a detached HEAD / mid-rebase worktree (branch === null) + // would otherwise never set repoProbeLoaded, stranding the PR segment on a + // forever spinner instead of the "Current branch unavailable" state. + const probeReady = client !== null && connState === 'connected' + const identity = buildMobilePrSidebarIdentity({ worktreeId, branch }) const buildDeps = useCallback((): PrSidebarLoadDeps | null => { if (!client) { @@ -63,66 +92,221 @@ export function useMobilePrSidebarController(input: PrSidebarControllerInput) { }, [client]) // Probe whether this is a GitHub repo to decide icon availability (GitHub-only). + // Worktree change must reset eligibility; a brief disconnect must not — otherwise + // the hub shows "unavailable for this provider" and hides the chip mid-session. + useEffect(() => { + setIsGithubRepo(false) + setRepoProbeLoaded(false) + }, [worktreeId]) + useEffect(() => { let cancelled = false - if (!ready || !client) { - setIsGithubRepo(false) + if (!probeReady || !client) { return } - void fetchGithubRepoSlug(client, worktreeId).then((outcome) => { - if (!cancelled) { - setIsGithubRepo(outcome.ok && outcome.result !== null) - } - }) + void fetchGithubRepoSlug(client, worktreeId) + .then((outcome) => { + if (!cancelled) { + setIsGithubRepo(outcome.ok && outcome.result !== null) + setRepoProbeLoaded(true) + } + }) + .catch(() => { + // Why: sendGithubPrRead already normalizes throws, but a cancelled + // unmount + any unexpected rejection must not surface as LogBox. + if (!cancelled) { + setIsGithubRepo(false) + setRepoProbeLoaded(true) + } + }) return () => { cancelled = true } - }, [ready, client, worktreeId]) + }, [probeReady, client, worktreeId]) useEffect(() => { if (!identity) { loadSeqRef.current += 1 + detailsSeqRef.current += 1 stateIdentityRef.current = null setState({ kind: 'hidden' }) return } if (stateIdentityRef.current !== null && stateIdentityRef.current !== identity) { - // Why: ready/loading data is scoped to branch+head. A branch switch must - // not let the open panel keep rendering the previous PR as "fresh." + // Why: ready/loading data is scoped to branch. A branch switch must not let + // the open panel keep rendering the previous PR as "fresh." loadSeqRef.current += 1 + detailsSeqRef.current += 1 stateIdentityRef.current = null setState({ kind: 'hidden' }) } }, [identity]) - const load = useCallback(async () => { + const load = useCallback( + async (options?: PrSidebarLoadOptions) => { + const includeDetails = options?.includeDetails ?? true + const deps = buildDeps() + const loadIdentity = identity + if (!deps || !branch || !loadIdentity) { + return + } + const seq = loadSeqRef.current + 1 + loadSeqRef.current = seq + // In-flight phase-2 work is NOT invalidated here: this load only takes phase-2 + // ownership when its own phase 2 actually starts (the bump below), so a load + // superseded at the phase-1 guard can never orphan a detailsSeq and silently + // discard the only details fetch. A stale ensure applying mid-phase-1 is safe — + // its identity/number/kind guards only let matching details through. + const previousIdentity = stateIdentityRef.current + stateIdentityRef.current = loadIdentity + // Soft refresh: same branch already showing ready/none stays visible while + // checks re-fetch (head advanced after commit). Hard loading only on first load + // or after a real identity wipe. + const keepVisible = + previousIdentity === loadIdentity && + (stateRef.current.kind === 'ready' || + stateRef.current.kind === 'none' || + stateRef.current.kind === 'loading') + if (!keepVisible) { + setState({ kind: 'loading' }) + } + // Phase 1: PR + checks (fast) — the worktree linkedPR read is parallelized with + // forBranch inside loadPrSidebarData so a closed/merged linked PR still resolves. + const next = await loadPrSidebarData(deps, { worktreeId, branch, headSha }) + if ( + !shouldApplyResult(seq, loadSeqRef.current) || + stateIdentityRef.current !== loadIdentity + ) { + return + } + stateIdentityRef.current = loadIdentity + + // Keep prior comments/body visible across phase 1 when the same PR is still open. + // loadPrSidebarData always returns details:null; without this, soft refresh and + // PR-tab refresh blank the comment tree until phase 2 finishes. + const priorDetails = + next.kind === 'ready' && + stateRef.current.kind === 'ready' && + stateRef.current.data.details != null && + stateRef.current.data.pr.number === next.data.pr.number + ? stateRef.current.data.details + : null + + if (next.kind === 'ready' && priorDetails != null) { + setState({ kind: 'ready', data: { ...next.data, details: priorDetails } }) + if (!includeDetails) { + return + } + } else { + setState(next) + if (next.kind !== 'ready' || !includeDetails) { + return + } + } + + // Phase 2: refresh (or first-load) the heavy comments/body payload. + const detailsSeq = detailsSeqRef.current + 1 + detailsSeqRef.current = detailsSeq + detailsInFlightRef.current = { seq: detailsSeq, prNumber: next.data.pr.number } + const fetchedDetails = await loadPrSidebarDetails(deps, worktreeId, next.data.pr.number) + // Release the claim unless a newer phase-2 superseded it (never clear theirs). + if (detailsInFlightRef.current?.seq === detailsSeq) { + detailsInFlightRef.current = null + } + // Phase-2 ownership is encoded by detailsSeq + identity + PR number alone — + // deliberately NOT by loadSeq: a chip-only soft refresh bumps loadSeq without + // bumping detailsSeq, and must not discard the in-flight details it preserved + // (ensure dedupes against this claim, so nothing would re-fetch them). + if ( + detailsSeq !== detailsSeqRef.current || + stateIdentityRef.current !== loadIdentity || + stateRef.current.kind !== 'ready' || + stateRef.current.data.pr.number !== next.data.pr.number + ) { + return + } + // Non-fatal null must not leave details===null (UI treats that as forever-loading). + const details = resolvePrSidebarDetailsAfterPhase2({ + fetched: fetchedDetails, + prior: stateRef.current.data.details, + pr: stateRef.current.data.pr + }) + setState({ kind: 'ready', data: { ...stateRef.current.data, details } }) + }, + [buildDeps, branch, headSha, identity, worktreeId] + ) + + // Phase-2 only — used when the hub opens the PR segment after a chip-only load. + // Uses detailsSeqRef (not loadSeqRef) so it cannot cancel a concurrent soft phase-1. + // Retries synthetic placeholders too: a failed phase-2 installs non-null empty + // details so Description/Comments leave the spinner, and without this ensure + // would never re-fetch on tab re-open. + const ensurePrSidebarDetails = useCallback(async () => { + const current = stateRef.current + if (current.kind !== 'ready' || !prSidebarDetailsNeedFetch(current.data.details)) { + return + } const deps = buildDeps() const loadIdentity = identity - if (!deps || !branch || !loadIdentity) { + if (!deps || !loadIdentity || stateIdentityRef.current !== loadIdentity) { return } - const seq = loadSeqRef.current + 1 - loadSeqRef.current = seq - stateIdentityRef.current = loadIdentity - setState({ kind: 'loading' }) - // Phase 1: PR + checks (fast) — the worktree linkedPR read is parallelized with - // forBranch inside loadPrSidebarData so a closed/merged linked PR still resolves. - const next = await loadPrSidebarData(deps, { worktreeId, branch, headSha }) - if (!shouldApplyResult(seq, loadSeqRef.current) || stateIdentityRef.current !== loadIdentity) { + const prNumber = current.data.pr.number + // A live phase-2 fetch for this PR is already in flight (its claim still owns + // the latest details seq) — do not start a duplicate. + const inFlight = detailsInFlightRef.current + if (inFlight && inFlight.prNumber === prNumber && inFlight.seq === detailsSeqRef.current) { return } - stateIdentityRef.current = loadIdentity - setState(next) - if (next.kind !== 'ready') { + const detailsSeq = detailsSeqRef.current + 1 + detailsSeqRef.current = detailsSeq + detailsInFlightRef.current = { seq: detailsSeq, prNumber } + const fetchedDetails = await loadPrSidebarDetails(deps, worktreeId, prNumber) + if (detailsInFlightRef.current?.seq === detailsSeq) { + detailsInFlightRef.current = null + } + if ( + detailsSeq !== detailsSeqRef.current || + stateIdentityRef.current !== loadIdentity || + stateRef.current.kind !== 'ready' || + stateRef.current.data.pr.number !== prNumber + ) { return } - // Phase 2: lazy-load the heavy comments/body payload and merge it in, so it never - // blocks the actionable PR UI. Re-check the seq so a newer load isn't clobbered. - const details = await loadPrSidebarDetails(deps, worktreeId, next.data.pr.number) - if (shouldApplyResult(seq, loadSeqRef.current) && stateIdentityRef.current === loadIdentity) { - setState({ kind: 'ready', data: { ...next.data, details } }) + const details = resolvePrSidebarDetailsAfterPhase2({ + fetched: fetchedDetails, + prior: stateRef.current.data.details, + pr: stateRef.current.data.pr + }) + setState({ + kind: 'ready', + data: { ...stateRef.current.data, details } + }) + }, [buildDeps, identity, worktreeId]) + + // Soft-refresh checks when HEAD advances on the same branch (post-commit). + // Also restarts an in-flight phase-1 load so a mid-flight head advance is not + // applied with a stale SHA (headShaRef would otherwise advance with no reload). + useEffect(() => { + if (headShaRef.current === headSha) { + return + } + headShaRef.current = headSha + // Identity was just wiped (branch/worktree switch): stateRef still holds the + // pre-wipe state in this effect flush, which would start a load flavored for + // the OLD surface (e.g. heavy details on the Changes tab). Let the owning + // surface's hidden-state effects drive the first load for the new identity. + if (stateIdentityRef.current === null) { + return + } + const current = stateRef.current + if (!shouldSoftRefreshPrSidebarOnHeadChange(current.kind)) { + return } - }, [buildDeps, branch, headSha, identity, worktreeId]) + void load({ + includeDetails: current.kind === 'ready' && current.data.details != null + }) + }, [headSha, load]) const openPRSidebar = useCallback(() => { setShowPRSidebar(true) @@ -131,17 +315,28 @@ export function useMobilePrSidebarController(input: PrSidebarControllerInput) { stateIdentityRef.current !== identity || (state.kind !== 'ready' && state.kind !== 'loading') ) { - void load() + void load({ includeDetails: true }) + } else if (state.kind === 'ready' && prSidebarDetailsNeedFetch(state.data.details)) { + // Retries phase-2 placeholders too (failed details load, not only null). + void ensurePrSidebarDetails() } - }, [identity, state.kind, load]) + }, [identity, state, load, ensurePrSidebarDetails]) + + const retry = useCallback(() => { + void load({ includeDetails: true }) + }, [load]) return { prSidebarState: state, prSidebarIsGithubRepo: isGithubRepo, + prSidebarRepoProbeLoaded: repoProbeLoaded, showPRSidebar, setShowPRSidebar, openPRSidebar, - retryPRSidebar: load, - refetchPRSidebar: load + retryPRSidebar: retry, + refetchPRSidebar: load, + ensurePrSidebarDetails } } + +export type MobilePrSidebarController = ReturnType diff --git a/mobile/src/session/use-mobile-terminal-paste.ts b/mobile/src/session/use-mobile-terminal-paste.ts index e3148be67f05..57ea720c4c89 100644 --- a/mobile/src/session/use-mobile-terminal-paste.ts +++ b/mobile/src/session/use-mobile-terminal-paste.ts @@ -2,7 +2,7 @@ import { useCallback, type RefObject } from 'react' import * as Clipboard from 'expo-clipboard' import { File as FsFile, Paths } from 'expo-file-system' import { ImageManipulator, SaveFormat } from 'expo-image-manipulator' -import type { TerminalModes } from '../terminal/TerminalWebView' +import type { TerminalModes } from '../terminal/terminal-webview-contract' import type { RpcClient } from '../transport/rpc-client' import type { ConnectionState } from '../transport/types' import { diff --git a/mobile/src/source-control/MobileGitHistoryList.tsx b/mobile/src/source-control/MobileGitHistoryList.tsx new file mode 100644 index 000000000000..d88fae540d83 --- /dev/null +++ b/mobile/src/source-control/MobileGitHistoryList.tsx @@ -0,0 +1,271 @@ +import { memo, useCallback, useEffect, useState } from 'react' +import { ActivityIndicator, FlatList, Pressable, StyleSheet, Text, View } from 'react-native' +import { ChevronDown, ChevronRight } from 'lucide-react-native' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' +import type { ConnectionState, RpcSuccess } from '../transport/types' +import type { RpcClient } from '../transport/rpc-client' +import { useForceReconnect } from '../transport/client-context' +import { + fetchMobileGitHistory, + mapMobileCommitRows, + type MobileCommitRow +} from './mobile-git-history' +import { resolveMobileHistoryScreenView } from './mobile-history-screen-state' +import type { GitBranchChangeEntry } from '../../../src/shared/types' + +type Props = { + client: RpcClient | null + connState: ConnectionState + worktreeId: string + // Needed so Retry can revive a parked reconnect loop (STA-1511 / #5049). + hostId: string + bottomInset: number + // Bumped by the hub header refresh so History reloads without remounting. + refreshNonce?: number +} + +// Headerless commit-history list. Extracted from the /history route so the hub's +// History segment and the standalone route render the same body over one code path. +// Memoized: it stays mounted (hidden) while the Changes segment is active, and must +// not re-reconcile its FlatList on every commit-message keystroke re-render. +export const MobileGitHistoryList = memo(function MobileGitHistoryList({ + client, + connState, + worktreeId, + hostId, + bottomInset, + refreshNonce = 0 +}: Props) { + const forceReconnect = useForceReconnect() + const [rows, setRows] = useState(null) + const [error, setError] = useState(null) + const [reloadNonce, setReloadNonce] = useState(0) + const [expanded, setExpanded] = useState(null) + const [filesById, setFilesById] = useState>({}) + + // Worktree identity change must wipe history immediately — even while + // disconnected — so a kept-mounted hub segment never shows another tree's commits. + useEffect(() => { + setRows(null) + setError(null) + setExpanded(null) + setFilesById({}) + }, [worktreeId]) + + useEffect(() => { + let active = true + if (!client || connState !== 'connected' || !worktreeId) { + // Why: leave already-loaded rows (and expand state) alone across a drop — + // resolveMobileHistoryScreenView keeps them visible (STA-1511). + return + } + // Reset prior error/rows so a successful retry doesn't stay stuck behind a + // stale error (error wins render precedence). + setError(null) + setRows(null) + setExpanded(null) + setFilesById({}) + void (async () => { + try { + const result = await fetchMobileGitHistory(client, worktreeId) + if (active) { + setRows(mapMobileCommitRows(result, Date.now())) + } + } catch (err) { + if (active) { + setError(err instanceof Error ? err.message : 'Failed to load history') + } + } + })() + return () => { + active = false + } + }, [client, connState, reloadNonce, refreshNonce, worktreeId]) + + const retry = useCallback(() => { + setError(null) + // Why: retrying the fetch is useless while the transport's reconnect loop + // is parked at its backoff cap — revive the connection instead (mirrors + // MobileSourceControlPanel / issue #5049). The load effect re-runs via + // connState once the fresh client connects. + if (connState !== 'connected' && hostId) { + void forceReconnect(hostId) + return + } + setReloadNonce((n) => n + 1) + }, [connState, forceReconnect, hostId]) + + const toggleCommit = useCallback( + (row: MobileCommitRow) => { + const next = expanded === row.id ? null : row.id + setExpanded(next) + if (next && !filesById[row.id]) { + // No client (disconnected while cached rows stay visible): resolve to an + // empty file list so the row shows "No file changes" instead of a spinner + // that never completes — no request can be made. + if (!client) { + setFilesById((prev) => ({ ...prev, [row.id]: [] })) + return + } + setFilesById((prev) => ({ ...prev, [row.id]: 'loading' })) + void client + .sendRequest('git.commitCompare', { worktree: `id:${worktreeId}`, commitId: row.id }) + .then((response) => { + const entries = response.ok + ? ((response as RpcSuccess).result as { entries: GitBranchChangeEntry[] }).entries + : [] + setFilesById((prev) => { + // Drop stale responses if the row is no longer loading (collapsed + re-opened). + if (prev[row.id] !== 'loading') { + return prev + } + return { ...prev, [row.id]: entries } + }) + }) + .catch(() => + setFilesById((prev) => { + if (prev[row.id] !== 'loading') { + return prev + } + return { ...prev, [row.id]: [] } + }) + ) + } + }, + [client, expanded, filesById, worktreeId] + ) + + const renderCommit = useCallback( + ({ item }: { item: MobileCommitRow }) => { + const files = filesById[item.id] + const isOpen = expanded === item.id + return ( + + [styles.commitHeader, pressed && styles.commitHeaderPressed]} + onPress={() => toggleCommit(item)} + > + {isOpen ? ( + + ) : ( + + )} + + + {item.subject} + + + {item.shortId} · {item.author} · {item.relativeTime} + + + + {isOpen ? ( + + {files === 'loading' || files === undefined ? ( + + ) : files.length === 0 ? ( + No file changes + ) : ( + files.map((file) => ( + + + {file.path} + + + {file.added ? +{file.added} : null} + {file.removed ? -{file.removed} : null} + + + )) + )} + + ) : null} + + ) + }, + [expanded, filesById, toggleCommit] + ) + + const view = resolveMobileHistoryScreenView({ + connected: client !== null && connState === 'connected', + rows, + error + }) + + if (view.kind === 'error' || view.kind === 'waiting') { + return ( + + + {view.kind === 'waiting' ? 'Waiting for desktop...' : view.message} + + + Retry + + + ) + } + if (view.kind === 'loading') { + return ( + + + + ) + } + if (view.kind === 'empty') { + return ( + + No commits. + + ) + } + return ( + row.id} + contentContainerStyle={{ paddingBottom: spacing.lg + bottomInset }} + /> + ) +}) + +const styles = StyleSheet.create({ + state: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: spacing.lg }, + stateText: { color: colors.textMuted, fontSize: typography.bodySize }, + retryButton: { + marginTop: spacing.md, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.sm, + borderRadius: radii.button, + backgroundColor: colors.bgRaised + }, + retryText: { color: colors.textPrimary, fontSize: typography.bodySize, fontWeight: '600' }, + commit: { borderBottomWidth: 1, borderBottomColor: colors.borderSubtle }, + commitHeader: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm + 2 + }, + commitHeaderPressed: { backgroundColor: colors.bgRaised }, + commitMain: { flex: 1, minWidth: 0 }, + commitSubject: { color: colors.textPrimary, fontSize: typography.bodySize }, + commitMeta: { + color: colors.textMuted, + fontSize: typography.metaSize, + fontFamily: typography.monoFamily, + marginTop: 2 + }, + files: { paddingHorizontal: spacing.lg, paddingBottom: spacing.sm, gap: 4 }, + fileRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm }, + filePath: { + flex: 1, + color: colors.textSecondary, + fontSize: typography.metaSize, + fontFamily: typography.monoFamily + }, + fileStat: { fontSize: typography.metaSize, fontFamily: typography.monoFamily }, + add: { color: colors.gitDecorationAdded }, + del: { color: colors.gitDecorationDeleted }, + empty: { color: colors.textMuted, fontSize: typography.metaSize } +}) diff --git a/mobile/src/source-control/MobileSourceControlBranchCard.tsx b/mobile/src/source-control/MobileSourceControlBranchCard.tsx new file mode 100644 index 000000000000..04aae01b0bc9 --- /dev/null +++ b/mobile/src/source-control/MobileSourceControlBranchCard.tsx @@ -0,0 +1,78 @@ +import { Pressable, Text, View } from 'react-native' +import { GitBranch } from 'lucide-react-native' +import { colors } from '../theme/mobile-theme' +import { styles } from './mobile-source-control-styles' +import { MobileSourceControlPrChip } from './MobileSourceControlPrChip' +import type { MobilePrChipSummary } from './mobile-pr-chip-summary' +import { mobileConflictAbortLabel } from './mobile-source-control-conflict-abort' + +type Props = { + branchLabel: string + syncLabel: string | null + unstagedCount: number + stagedCount: number + branchCount: number + conflictOperation: string | null + // True while any serial git IO is in flight — disables Abort so ops don't race. + conflictBusy: boolean + // True only while abort-merge / abort-rebase itself is running (label accuracy). + conflictAborting: boolean + onAbortConflict: (operation: string) => void + // The PR chip is shown only on repos with a hosted-review remote; null hides it. + prChip: MobilePrChipSummary | null + onOpenPr: () => void +} + +// Persistent card at the top of every hub segment: branch identity, sync/counts, +// conflict state, and the PR chip. Shared so PR/History see the same status the +// Changes lens does without re-deriving it. +export function MobileSourceControlBranchCard({ + branchLabel, + syncLabel, + unstagedCount, + stagedCount, + branchCount, + conflictOperation, + conflictBusy, + conflictAborting, + onAbortConflict, + prChip, + onOpenPr +}: Props) { + const showConflict = conflictOperation !== null && conflictOperation !== 'unknown' + return ( + + + + + + {branchLabel} + + + {syncLabel ? {syncLabel} : null} + + + {unstagedCount} changed + {stagedCount} staged + {branchCount > 0 ? {branchCount} on branch : null} + {showConflict ? ( + + {conflictOperation} + {conflictOperation === 'merge' || conflictOperation === 'rebase' ? ( + [styles.abortButton, pressed && styles.abortPressed]} + disabled={conflictBusy} + onPress={() => onAbortConflict(conflictOperation)} + > + + {mobileConflictAbortLabel(conflictOperation, conflictAborting)} + + + ) : null} + + ) : null} + + {prChip ? : null} + + ) +} diff --git a/mobile/src/source-control/MobileSourceControlContent.tsx b/mobile/src/source-control/MobileSourceControlContent.tsx index 1b50db62479e..a28504a5c53c 100644 --- a/mobile/src/source-control/MobileSourceControlContent.tsx +++ b/mobile/src/source-control/MobileSourceControlContent.tsx @@ -1,5 +1,5 @@ import { ActivityIndicator, Pressable, SectionList, Text, TextInput, View } from 'react-native' -import { GitBranch, Minus, MoreHorizontal, Plus, Sparkles } from 'lucide-react-native' +import { Minus, MoreHorizontal, Plus, Sparkles } from 'lucide-react-native' import { colors, spacing } from '../theme/mobile-theme' import { MobileSourceControlCreatePrEntry } from './MobileSourceControlCreatePrEntry' import { MobileCommitFailurePanel } from './MobileCommitFailurePanel' @@ -7,15 +7,17 @@ import { KEYBOARD_COMMIT_BAR_CLEARANCE } from './mobile-source-control-screen-st import { makeRenderFileRow, BranchCompareFooter } from './MobileSourceControlFileRows' import type { MobileSourceControlState } from './use-mobile-source-control-state' import { styles } from './mobile-source-control-styles' +import { hubStyles } from './mobile-source-control-hub-styles' type Props = { state: MobileSourceControlState } -// The ready-state body: summary card, changed-files list, and commit bar. +// The ready-state Changes segment body: quick actions, changed-files list, and commit bar. export function MobileSourceControlContent({ state }: Props) { const { insets, + connState, busyAction, commitMessage, setCommitMessage, @@ -28,23 +30,17 @@ export function MobileSourceControlContent({ state }: Props) { keyboardLift, openingPath, openingBranchPath, - status, sections, - branchEntries, hasVisibleChanges, stageablePaths, unstageablePaths, stagedCount, - unstagedCount, - branchLabel, - syncLabel, primaryAction, createPrAction, stageAll, unstageAll, generateCommitMessage, cancelGenerateCommitMessage, - abortConflictOperation, openFile, openBranchDiff, runGitAction @@ -56,41 +52,16 @@ export function MobileSourceControlContent({ state }: Props) { return ( <> - - - - - - {branchLabel} - - - {syncLabel ? {syncLabel} : null} - - - {unstagedCount} changed - {stagedCount} staged - {branchEntries.length > 0 ? ( - {branchEntries.length} on branch - ) : null} - {status && status.conflictOperation !== 'unknown' ? ( - - {status.conflictOperation} - {(status.conflictOperation === 'merge' || status.conflictOperation === 'rebase') && ( - [styles.abortButton, pressed && styles.abortPressed]} - disabled={busyAction !== null} - onPress={() => void abortConflictOperation(status.conflictOperation)} - > - - {busyAction === `abort-${status.conflictOperation}` - ? 'Aborting…' - : `Abort ${status.conflictOperation}`} - - - )} - - ) : null} + {connState !== 'connected' ? ( + // Why: once data has loaded the screen looks alive even when the + // desktop link is down, so taps appear to do nothing (STA-1511). + // Surface the reconnect state where the user is looking. + + + Reconnecting to desktop... + ) : null} + {commitFailureRecovery ? ( ) : ( void onRefresh: () => void + // When set (PR segment ready with a host URL), show open-on-web flush-right of + // the title so the control stays visible while the PR body scrolls. + onOpenPrWeb?: () => void + prNumber?: number | null } export function MobileSourceControlHeader({ @@ -16,7 +20,9 @@ export function MobileSourceControlHeader({ worktreeLabel, ioBusy, onBack, - onRefresh + onRefresh, + onOpenPrWeb, + prNumber = null }: Props) { return ( @@ -40,6 +46,21 @@ export function MobileSourceControlHeader({ {worktreeLabel} + {onOpenPrWeb ? ( + [styles.refreshButton, pressed && styles.refreshButtonPressed]} + onPress={onOpenPrWeb} + hitSlop={8} + accessibilityRole="link" + accessibilityLabel={ + prNumber != null + ? `Open pull request #${prNumber} on the web` + : 'Open pull request on the web' + } + > + + + ) : null} [ styles.refreshButton, diff --git a/mobile/src/source-control/MobileSourceControlPanel.tsx b/mobile/src/source-control/MobileSourceControlPanel.tsx index 256cb9c0ab6a..25656aae2bd5 100644 --- a/mobile/src/source-control/MobileSourceControlPanel.tsx +++ b/mobile/src/source-control/MobileSourceControlPanel.tsx @@ -1,3 +1,4 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ActivityIndicator, Pressable, Text, View } from 'react-native' import { SafeAreaView } from 'react-native-safe-area-context' import { colors } from '../theme/mobile-theme' @@ -6,7 +7,18 @@ import { useMobileSourceControlActionSheet } from './use-mobile-source-control-a import { MobileSourceControlHeader } from './MobileSourceControlHeader' import { MobileSourceControlContent } from './MobileSourceControlContent' import { MobileSourceControlModals } from './MobileSourceControlModals' +import { MobileSourceControlSegments } from './MobileSourceControlSegments' +import { MobileSourceControlBranchCard } from './MobileSourceControlBranchCard' +import { MobileGitHistoryList } from './MobileGitHistoryList' import { styles } from './mobile-source-control-styles' +import { hubStyles } from './mobile-source-control-hub-styles' +import type { SourceControlHubTab } from './mobile-source-control-hub-tab' +import { buildMobilePrChipSummary, countUnresolvedReviewThreads } from './mobile-pr-chip-summary' +import { isMobileConflictAborting } from './mobile-source-control-conflict-abort' +import { useMobilePrSidebarController } from '../session/use-mobile-pr-sidebar-controller' +import { prSidebarDetailsNeedFetch } from '../session/mobile-pr-sidebar-state' +import { MobilePrViewPanelBody } from '../components/pr-sidebar/MobilePrViewPanel' +import { openMobilePrUrl } from '../components/MobilePrComposeSheet' export type MobileSourceControlPanelProps = { hostId: string @@ -15,6 +27,8 @@ export type MobileSourceControlPanelProps = { /** Where the panel was launched from; drives the file-open dismissal path. */ origin?: string embedded?: boolean + /** Initial hub segment (from the route's `tab` deep-link param). */ + initialTab?: SourceControlHubTab onRequestClose?: () => void onFileOpenStart?: () => void onOpenedFileDiff?: (relativePath: string) => void @@ -26,10 +40,48 @@ export function MobileSourceControlPanel({ name = '', origin = '', embedded = false, + initialTab = 'changes', onRequestClose, onFileOpenStart, onOpenedFileDiff }: MobileSourceControlPanelProps) { + const [activeTab, setActiveTab] = useState(initialTab) + // Track first visit so Changes/History keep scroll state across segment switches + // without paying the mount cost until the user actually opens them. PR unmounts + // when inactive (WebViews / comment tree) but its controller state stays for the chip. + const [visitedTabs, setVisitedTabs] = useState>( + () => new Set([initialTab]) + ) + const [historyRefreshNonce, setHistoryRefreshNonce] = useState(0) + + // Deep-link / push with a different `tab` param should adopt the new segment + // (expo-router can reuse the screen instance when only query params change). + useEffect(() => { + setActiveTab(initialTab) + setVisitedTabs((prev) => { + if (prev.has(initialTab)) { + return prev + } + const next = new Set(prev) + next.add(initialTab) + return next + }) + }, [initialTab]) + + const selectTab = useCallback((tab: SourceControlHubTab) => { + setActiveTab(tab) + setVisitedTabs((prev) => { + if (prev.has(tab)) { + return prev + } + const next = new Set(prev) + next.add(tab) + return next + }) + }, []) + const openHistoryTab = useCallback(() => selectTab('history'), [selectTab]) + const openPrTab = useCallback(() => selectTab('pr'), [selectTab]) + const state = useMobileSourceControlState({ hostId, worktreeId, @@ -38,12 +90,15 @@ export function MobileSourceControlPanel({ embedded, onRequestClose, onFileOpenStart, - onOpenedFileDiff + onOpenedFileDiff, + onOpenHistory: openHistoryTab }) const actionSheetActions = useMobileSourceControlActionSheet(state) const { + client, connState, forceReconnect, + insets, router, setRootRef, worktreeLabel, @@ -51,25 +106,207 @@ export function MobileSourceControlPanel({ busyAction, openingPath, openingBranchPath, - loadStatus + loadStatus, + status, + branchCompareResult, + branchLabel, + syncLabel, + unstagedCount, + stagedCount, + branchEntries, + abortConflictOperation } = state const ioBusy = busyAction !== null || openingPath !== null || openingBranchPath !== null + const ready = screenState.kind === 'ready' + + // One PR controller feeds both the branch-card chip and the Pull Request + // segment, so the chip's rollup can never disagree with the checks list it + // links to. Branch + head come from the already-loaded git.status — no second + // status read. The chip loads independently, so it never blocks the file list. + // Keep last-known identity across a transient status unload (disconnect / + // failed refresh) so the controller does not wipe ready → hidden → cold start. + // Head SHA matches the review path: status.head ?? branchCompare headOid. + const lastPrBranchRef = useRef(null) + const lastPrHeadRef = useRef(null) + useEffect(() => { + lastPrBranchRef.current = null + lastPrHeadRef.current = null + }, [worktreeId]) + const statusBranch = status?.branch ?? null + const statusHead = status?.head ?? branchCompareResult?.summary.headOid ?? null + // Write last-known identity in an effect, not the render body: a discarded + // concurrent render must not leave the fallback holding a never-committed value. + useEffect(() => { + if (statusBranch) { + lastPrBranchRef.current = statusBranch + } + if (statusHead) { + lastPrHeadRef.current = statusHead + } + }, [statusBranch, statusHead]) + const prBranch = statusBranch ?? lastPrBranchRef.current + const prHeadSha = statusHead ?? lastPrHeadRef.current + const prController = useMobilePrSidebarController({ + client, + connState, + worktreeId, + branch: prBranch, + headSha: prHeadSha + }) + const isHostedRepo = prController.prSidebarIsGithubRepo + const prSidebarKind = prController.prSidebarState.kind + const refetchPr = prController.refetchPRSidebar + const ensurePrDetails = prController.ensurePrSidebarDetails + // Refs so tab effects do not re-fire when headSha recreates load() (soft refresh). + const refetchPrRef = useRef(refetchPr) + refetchPrRef.current = refetchPr + const ensurePrDetailsRef = useRef(ensurePrDetails) + ensurePrDetailsRef.current = ensurePrDetails + + // Chip bootstrap: phase-1 only (PR + checks). Full comment payload waits until + // the Pull Request segment is open — opening SC to stage must not pull details. + useEffect(() => { + if (activeTab === 'pr') { + return + } + if (prBranch && isHostedRepo && prSidebarKind === 'hidden') { + void refetchPrRef.current({ includeDetails: false }) + } + }, [activeTab, prBranch, isHostedRepo, prSidebarKind]) + + // Number of the ready PR whose phase-2 details are still missing (null when + // none). Keyed by PR number — not a boolean — so a same-branch PR swap during a + // chip-only soft refresh re-arms phase 2 for the new PR instead of leaving its + // comments on a forever-spinner (a stale ensure bails on the number mismatch). + // Placeholder details (failed phase 2) also count as missing so reopening the + // PR tab retries instead of leaving empty Description/Comments forever. + const prDetailsMissingFor = + prController.prSidebarState.kind === 'ready' && + prSidebarDetailsNeedFetch(prController.prSidebarState.data.details) + ? prController.prSidebarState.data.pr.number + : null + + // PR segment: full load or phase-2 fill-in. Body only mounts while active. + // Guarded (and keyed) on prBranch so a branch that arrives while the segment is + // already open — e.g. mounted on a detached HEAD, then checkout — still loads; + // kind stays 'hidden' through that transition, so kind alone can't re-fire this. + useEffect(() => { + if (activeTab !== 'pr' || !isHostedRepo || !prBranch) { + return + } + if (prSidebarKind === 'hidden') { + void refetchPrRef.current({ includeDetails: true }) + return + } + if (prDetailsMissingFor != null) { + void ensurePrDetailsRef.current() + } + }, [activeTab, isHostedRepo, prBranch, prSidebarKind, prDetailsMissingFor]) + + const prChip = useMemo(() => { + // No branch (detached HEAD / mid-rebase) never runs a PR load, so the shared + // state stays 'hidden' — which the chip would render as a forever spinner. + // Hide the chip instead; the Pull Request segment shows "branch unavailable". + if (!isHostedRepo || !prBranch) { + return null + } + const commentCount = + prController.prSidebarState.kind === 'ready' + ? countUnresolvedReviewThreads(prController.prSidebarState.data.details?.comments) + : null + return buildMobilePrChipSummary(prController.prSidebarState, commentCount) + }, [isHostedRepo, prBranch, prController.prSidebarState]) + + // Design: refresh the active segment's body work, plus git.status for the shared + // branch card (counts/sync stay honest even while on History). Preserve ready + // status on a failed refresh so PR chip identity is not wiped to hidden. + const onRefresh = useCallback(() => { + void loadStatus({ preserveReadyOnFailure: true }) + if (activeTab === 'history') { + setHistoryRefreshNonce((n) => n + 1) + return + } + if (!isHostedRepo) { + return + } + if (activeTab === 'pr') { + void refetchPr({ includeDetails: true }) + return + } + // Changes: light chip refresh so the branch card stays current without comments. + void refetchPr({ includeDetails: false }) + }, [activeTab, isHostedRepo, loadStatus, refetchPr]) // Embedded mode docks beside the terminal: close the dock instead of popping // a route, and skip the full-screen safe-area chrome (the dock column owns it). - // Fall back to router.back() when embedded without a close handler so the button - // never silently no-ops. const onBack = embedded ? (onRequestClose ?? (() => router.back())) : () => router.back() + // Chromeless PR body has no panel header — surface open-on-web on the hub chrome + // while the Pull Request segment is active (same affordance as the old /pr route). + const prWebUrl = + activeTab === 'pr' && + prController.prSidebarState.kind === 'ready' && + prController.prSidebarState.data.pr.url + ? prController.prSidebarState.data.pr.url + : null + const prWebNumber = + prController.prSidebarState.kind === 'ready' ? prController.prSidebarState.data.pr.number : null const header = ( void loadStatus()} + onRefresh={onRefresh} + onOpenPrWeb={prWebUrl ? () => openMobilePrUrl(prWebUrl) : undefined} + prNumber={prWebNumber} /> ) + const statusGate = + screenState.kind === 'loading' ? ( + + + + ) : screenState.kind === 'error' || screenState.kind === 'unavailable' ? ( + + + {screenState.kind === 'unavailable' ? 'Source Control Unavailable' : 'Unable to Load'} + + {screenState.message} + {screenState.kind === 'error' ? ( + { + // Why: retrying the request is useless while the transport's + // reconnect loop is parked at its give-up cap — revive the + // connection instead (issue #5049). loadStatus re-runs via + // its connState effect once the new client connects. + if (connState !== 'connected' && hostId) { + void forceReconnect(hostId) + return + } + void loadStatus() + }} + > + Retry + + ) : null} + + ) : null + + // History only needs the RPC client — do not block it behind git.status. + // Changes/PR need status (branch, file list, head SHA), so they stay gated. + const showChanges = ready && (activeTab === 'changes' || visitedTabs.has('changes')) + const showHistory = activeTab === 'history' || visitedTabs.has('history') + // Why: only mount the PR body while its segment is active. Keep-mounting retained + // Mermaid WebViews and re-rendered the comment tree on every commit keystroke. + // Controller + chip state still live for instant re-open without a full cold start. + const showPrBody = ready && activeTab === 'pr' + const conflictOperation = status?.conflictOperation ?? null + // Git status always reports a conflictOperation enum; 'unknown' means none. + const hasActiveConflict = conflictOperation != null && conflictOperation !== 'unknown' + const conflictAborting = isMobileConflictAborting(busyAction, conflictOperation) + return ( {embedded ? ( @@ -80,38 +317,68 @@ export function MobileSourceControlPanel({ )} - {screenState.kind === 'loading' ? ( - - + + + {/* Branch card + PR chip are the Changes/Commits glance layer. On the PR + tab they duplicate the ready PR body (#, state, checks rollup, branch + trajectory), so hide the whole card there and let the PR panel own it — + unless a merge/rebase conflict is active, which only this card can abort. */} + {ready && (activeTab !== 'pr' || hasActiveConflict) ? ( + void abortConflictOperation(operation)} + prChip={prChip} + onOpenPr={openPrTab} + /> + ) : null} + + {showChanges ? ( + + - ) : screenState.kind === 'error' || screenState.kind === 'unavailable' ? ( - - - {screenState.kind === 'unavailable' ? 'Source Control Unavailable' : 'Unable to Load'} - - {screenState.message} - {screenState.kind === 'error' ? ( - { - // Why: retrying the request is useless while the transport's - // reconnect loop is parked at its give-up cap — revive the - // connection instead (issue #5049). loadStatus re-runs via - // its connState effect once the new client connects. - if (connState !== 'connected' && hostId) { - void forceReconnect(hostId) - return - } - void loadStatus() - }} - > - Retry - - ) : null} + ) : activeTab === 'changes' ? ( + statusGate + ) : null} + + {showPrBody ? ( + + - ) : ( - - )} + ) : activeTab === 'pr' ? ( + statusGate + ) : null} + + {showHistory ? ( + + + + ) : null} diff --git a/mobile/src/source-control/MobileSourceControlPrChip.tsx b/mobile/src/source-control/MobileSourceControlPrChip.tsx new file mode 100644 index 000000000000..1165aae8b9b8 --- /dev/null +++ b/mobile/src/source-control/MobileSourceControlPrChip.tsx @@ -0,0 +1,121 @@ +import { ActivityIndicator, Pressable, Text, View } from 'react-native' +import { + AlertTriangle, + Check, + ChevronRight, + CircleDot, + GitPullRequest, + MessageSquare, + X +} from 'lucide-react-native' +import { colors } from '../theme/mobile-theme' +import { statusColor } from '../components/pr-sidebar/pr-sidebar-status-color' +import { hubStyles } from './mobile-source-control-hub-styles' +import type { MobilePrChipRollup, MobilePrChipSummary } from './mobile-pr-chip-summary' + +type Props = { + summary: MobilePrChipSummary + onPress: () => void +} + +// The glanceable PR status line on the branch card. Tapping it switches to the +// Pull Request segment. Rendered only when the repo supports hosted review — the +// parent gates on that, so this component always has something meaningful to show. +export function MobileSourceControlPrChip({ summary, onPress }: Props) { + return ( + [hubStyles.chip, pressed && hubStyles.chipPressed]} + onPress={onPress} + accessibilityRole="button" + accessibilityLabel={chipAccessibilityLabel(summary)} + > + + + + {summary.kind === 'loading' ? ( + <> + + + Loading pull request… + + + ) : summary.kind === 'none' ? ( + <> + Create pull request + + + + ) : summary.kind === 'unavailable' ? ( + <> + + {summary.message} + + + + ) : ( + <> + #{summary.number} + + + {summary.stateLabel} + + + + {summary.commentCount != null && summary.commentCount > 0 ? ( + + + {summary.commentCount} + + ) : null} + + + + )} + + ) +} + +function ChipRollup({ rollup }: { rollup: MobilePrChipRollup }) { + const color = statusColor(rollup.token) + return ( + + + {rollup.text} + + ) +} + +function RollupIcon({ kind, color }: { kind: MobilePrChipRollup['kind']; color: string }) { + const size = 13 + const strokeWidth = 2.3 + switch (kind) { + case 'conflict': + return + case 'failing': + return + case 'running': + return + case 'passed': + return + case 'none': + return null + } +} + +function chipAccessibilityLabel(summary: MobilePrChipSummary): string { + switch (summary.kind) { + case 'loading': + return 'Loading pull request' + case 'none': + return 'Create pull request' + case 'unavailable': + return `Pull request unavailable: ${summary.message}` + case 'ready': { + const comments = + summary.commentCount != null && summary.commentCount > 0 + ? `, ${summary.commentCount} unresolved comments` + : '' + return `Pull request #${summary.number}, ${summary.stateLabel}, ${summary.rollup.text}${comments}. Open pull request.` + } + } +} diff --git a/mobile/src/source-control/MobileSourceControlSegments.tsx b/mobile/src/source-control/MobileSourceControlSegments.tsx new file mode 100644 index 000000000000..89564aca4175 --- /dev/null +++ b/mobile/src/source-control/MobileSourceControlSegments.tsx @@ -0,0 +1,45 @@ +import { Pressable, Text, View } from 'react-native' +import { + SOURCE_CONTROL_HUB_TABS, + SOURCE_CONTROL_HUB_TAB_LABELS, + type SourceControlHubTab +} from './mobile-source-control-hub-tab' +import { hubStyles } from './mobile-source-control-hub-styles' + +type Props = { + active: SourceControlHubTab + onSelect: (tab: SourceControlHubTab) => void +} + +// The hub's top-level lens switcher. Switching is local state (no route push) so +// scroll position and the shared branch card persist across Changes/PR/History. +export function MobileSourceControlSegments({ active, onSelect }: Props) { + return ( + + {SOURCE_CONTROL_HUB_TABS.map((tab) => { + const isActive = tab === active + return ( + [ + hubStyles.segment, + isActive && hubStyles.segmentActive, + pressed && !isActive && hubStyles.segmentPressed + ]} + onPress={() => onSelect(tab)} + accessibilityRole="tab" + accessibilityState={{ selected: isActive }} + accessibilityLabel={SOURCE_CONTROL_HUB_TAB_LABELS[tab]} + > + + {SOURCE_CONTROL_HUB_TAB_LABELS[tab]} + + + ) + })} + + ) +} diff --git a/mobile/src/source-control/mobile-history-screen-state.test.ts b/mobile/src/source-control/mobile-history-screen-state.test.ts new file mode 100644 index 000000000000..1279f9a940f6 --- /dev/null +++ b/mobile/src/source-control/mobile-history-screen-state.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' +import { resolveMobileHistoryScreenView } from './mobile-history-screen-state' +import type { MobileCommitRow } from './mobile-git-history' + +const row: MobileCommitRow = { + id: 'abc123', + shortId: 'abc123', + subject: 'commit', + author: 'author', + parentId: null, + relativeTime: '1m' +} + +describe('resolveMobileHistoryScreenView', () => { + it('shows waiting (not an endless spinner) when disconnected with nothing loaded', () => { + // Regression (STA-1511): the load effect no-ops while disconnected, so + // rows stay null forever — the screen must offer a retry, not a spinner. + expect(resolveMobileHistoryScreenView({ connected: false, rows: null, error: null })).toEqual({ + kind: 'waiting' + }) + }) + + it('spins only while connected and loading', () => { + expect(resolveMobileHistoryScreenView({ connected: true, rows: null, error: null })).toEqual({ + kind: 'loading' + }) + }) + + it('keeps already-loaded rows visible across a connection drop', () => { + expect(resolveMobileHistoryScreenView({ connected: false, rows: [row], error: null })).toEqual({ + kind: 'rows', + rows: [row] + }) + }) + + it('prefers the error state over waiting so failures stay actionable', () => { + expect(resolveMobileHistoryScreenView({ connected: false, rows: null, error: 'boom' })).toEqual( + { kind: 'error', message: 'boom' } + ) + }) + + it('distinguishes an empty history from a pending load', () => { + expect(resolveMobileHistoryScreenView({ connected: true, rows: [], error: null })).toEqual({ + kind: 'empty' + }) + }) +}) diff --git a/mobile/src/source-control/mobile-history-screen-state.ts b/mobile/src/source-control/mobile-history-screen-state.ts new file mode 100644 index 000000000000..8d03f33f0284 --- /dev/null +++ b/mobile/src/source-control/mobile-history-screen-state.ts @@ -0,0 +1,30 @@ +import type { MobileCommitRow } from './mobile-git-history' + +export type MobileHistoryScreenView = + | { kind: 'error'; message: string } + | { kind: 'waiting' } + | { kind: 'loading' } + | { kind: 'empty' } + | { kind: 'rows'; rows: MobileCommitRow[] } + +// Why: the history load effect no-ops while the client isn't connected, so +// without an explicit 'waiting' view the screen showed an infinite spinner +// with no retry when opened during a reconnect window (STA-1511). Rows loaded +// before a drop stay visible — stale history beats a blank screen. +export function resolveMobileHistoryScreenView(input: { + connected: boolean + rows: MobileCommitRow[] | null + error: string | null +}): MobileHistoryScreenView { + const { connected, rows, error } = input + if (error) { + return { kind: 'error', message: error } + } + if (rows !== null) { + return rows.length === 0 ? { kind: 'empty' } : { kind: 'rows', rows } + } + if (!connected) { + return { kind: 'waiting' } + } + return { kind: 'loading' } +} diff --git a/mobile/src/source-control/mobile-pr-chip-summary.test.ts b/mobile/src/source-control/mobile-pr-chip-summary.test.ts new file mode 100644 index 000000000000..88186a06ea0f --- /dev/null +++ b/mobile/src/source-control/mobile-pr-chip-summary.test.ts @@ -0,0 +1,138 @@ +import { describe, it, expect } from 'vitest' +import type { PRCheckDetail, PRComment, PRInfo } from '../../../src/shared/types' +import type { PrSidebarState } from '../session/mobile-pr-sidebar-state' +import { buildMobilePrChipSummary, countUnresolvedReviewThreads } from './mobile-pr-chip-summary' + +function pr(overrides: Partial = {}): PRInfo { + return { + number: 7701, + title: 'Make center split more visible', + state: 'open', + url: 'https://example.test/pr/7701', + checksStatus: 'success', + updatedAt: '2026-07-07T00:00:00Z', + mergeable: 'MERGEABLE', + ...overrides + } +} + +function check( + conclusion: PRCheckDetail['conclusion'], + status: PRCheckDetail['status'] = 'completed' +): PRCheckDetail { + return { name: `check-${conclusion}-${status}`, status, conclusion, url: null } +} + +function ready(prInfo: PRInfo, checks: PRCheckDetail[]): PrSidebarState { + return { kind: 'ready', data: { pr: prInfo, checks, details: null } } +} + +describe('buildMobilePrChipSummary', () => { + it('maps non-ready states', () => { + expect(buildMobilePrChipSummary({ kind: 'hidden' })).toEqual({ kind: 'loading' }) + expect(buildMobilePrChipSummary({ kind: 'loading' })).toEqual({ kind: 'loading' }) + expect(buildMobilePrChipSummary({ kind: 'none' })).toEqual({ kind: 'none' }) + expect(buildMobilePrChipSummary({ kind: 'error', message: 'net' })).toEqual({ + kind: 'unavailable', + message: 'net' + }) + expect(buildMobilePrChipSummary({ kind: 'blocked', message: 'auth' })).toEqual({ + kind: 'unavailable', + message: 'auth' + }) + }) + + it('surfaces the PR number and state badge', () => { + const summary = buildMobilePrChipSummary(ready(pr({ state: 'draft' }), [check('success')])) + expect(summary.kind).toBe('ready') + if (summary.kind !== 'ready') { + return + } + expect(summary.number).toBe(7701) + expect(summary.stateLabel).toBe('Draft') + }) + + it('rolls up passed checks as passed/total', () => { + const summary = buildMobilePrChipSummary( + ready(pr(), [check('success'), check('success'), check('skipped')]) + ) + if (summary.kind !== 'ready') { + throw new Error('expected ready') + } + expect(summary.rollup).toEqual({ kind: 'passed', text: '2/3', token: 'statusGreen' }) + }) + + it('prefers failing over running and passing', () => { + const summary = buildMobilePrChipSummary( + ready(pr(), [check('success'), check('failure'), check(null, 'in_progress')]) + ) + if (summary.kind !== 'ready') { + throw new Error('expected ready') + } + expect(summary.rollup).toEqual({ kind: 'failing', text: '1 failing', token: 'statusRed' }) + }) + + it('shows running when nothing has failed yet', () => { + const summary = buildMobilePrChipSummary(ready(pr(), [check('success'), check(null, 'queued')])) + if (summary.kind !== 'ready') { + throw new Error('expected ready') + } + expect(summary.rollup).toEqual({ kind: 'running', text: '1 running', token: 'statusAmber' }) + }) + + it('lets a merge conflict win over green checks', () => { + const summary = buildMobilePrChipSummary( + ready(pr({ mergeable: 'CONFLICTING' }), [check('success')]) + ) + if (summary.kind !== 'ready') { + throw new Error('expected ready') + } + expect(summary.rollup.kind).toBe('conflict') + }) + + it('reports no checks when the list is empty', () => { + const summary = buildMobilePrChipSummary(ready(pr(), [])) + if (summary.kind !== 'ready') { + throw new Error('expected ready') + } + expect(summary.rollup).toEqual({ kind: 'none', text: 'No checks', token: 'textSecondary' }) + }) + + it('passes through the unresolved comment count', () => { + const summary = buildMobilePrChipSummary(ready(pr(), [check('success')]), 3) + if (summary.kind !== 'ready') { + throw new Error('expected ready') + } + expect(summary.commentCount).toBe(3) + }) +}) + +describe('countUnresolvedReviewThreads', () => { + function comment(overrides: Partial): PRComment { + return { + id: 1, + author: 'octocat', + authorAvatarUrl: '', + body: 'x', + createdAt: '2026-07-07T00:00:00Z', + url: '', + ...overrides + } + } + + it('returns null when details have not loaded', () => { + expect(countUnresolvedReviewThreads(null)).toBeNull() + expect(countUnresolvedReviewThreads(undefined)).toBeNull() + }) + + it('counts each unresolved thread once and ignores resolved threads', () => { + const comments = [ + comment({ id: 1, threadId: 't1', isResolved: false }), + comment({ id: 2, threadId: 't1', isResolved: false }), + comment({ id: 3, threadId: 't2', isResolved: true }), + comment({ id: 4, threadId: 't3' }), + comment({ id: 5 }) + ] + expect(countUnresolvedReviewThreads(comments)).toBe(2) + }) +}) diff --git a/mobile/src/source-control/mobile-pr-chip-summary.ts b/mobile/src/source-control/mobile-pr-chip-summary.ts new file mode 100644 index 000000000000..87f54d434724 --- /dev/null +++ b/mobile/src/source-control/mobile-pr-chip-summary.ts @@ -0,0 +1,104 @@ +import type { PRComment } from '../../../src/shared/types' +import type { PrSidebarState } from '../session/mobile-pr-sidebar-state' +import { + prStateBadge, + summarizePRChecks, + type MobileStatusToken +} from '../components/pr-sidebar/pr-checks-presentation' + +// Pure derivation of the branch-card PR chip from the shared PR sidebar state. +// No React/native imports so the rollup precedence is unit-testable (KTD5). The +// chip and the Pull Request segment read the SAME PrSidebarState, so the chip's +// check rollup can never disagree with the checks list it links to. + +// The single check-rollup token the chip shows. Exactly one wins, by precedence: +// merge conflict > failing > running > passed > no checks. Worst-actionable-first +// so a red/amber signal is never hidden behind a green count. +export type MobilePrChipRollup = + | { kind: 'conflict'; text: string; token: MobileStatusToken } + | { kind: 'failing'; text: string; token: MobileStatusToken } + | { kind: 'running'; text: string; token: MobileStatusToken } + | { kind: 'passed'; text: string; token: MobileStatusToken } + | { kind: 'none'; text: string; token: MobileStatusToken } + +export type MobilePrChipSummary = + | { kind: 'loading' } + // GitHub repo, but this branch has no open/linked PR — the chip becomes a + // "create pull request" affordance that routes to the PR segment's composer. + | { kind: 'none' } + // A permanent (auth/permission) or transient failure loading PR data. The chip + // degrades to a muted, tappable line rather than vanishing. + | { kind: 'unavailable'; message: string } + | { + kind: 'ready' + number: number + stateLabel: string + stateToken: MobileStatusToken + rollup: MobilePrChipRollup + // Unresolved review-comment count, when the deferred details payload has + // loaded; null while it is still loading or unavailable. + commentCount: number | null + } + +// Unresolved review threads (the "💬 n" count). Counts each inline thread once by +// threadId when it is not resolved; top-level conversation comments (no threadId) +// are not review threads and don't count. Returns null when details haven't loaded. +export function countUnresolvedReviewThreads( + comments: PRComment[] | null | undefined +): number | null { + if (!comments) { + return null + } + const unresolved = new Set() + for (const comment of comments) { + if (comment.threadId && comment.isResolved !== true) { + unresolved.add(comment.threadId) + } + } + return unresolved.size +} + +export function buildMobilePrChipSummary( + state: PrSidebarState, + commentCount: number | null = null +): MobilePrChipSummary { + switch (state.kind) { + case 'hidden': + case 'loading': + return { kind: 'loading' } + case 'none': + return { kind: 'none' } + case 'error': + case 'blocked': + return { kind: 'unavailable', message: state.message } + case 'ready': { + const badge = prStateBadge(state.data.pr.state) + return { + kind: 'ready', + number: state.data.pr.number, + stateLabel: badge.label, + stateToken: badge.token, + rollup: buildChipRollup(state), + commentCount + } + } + } +} + +function buildChipRollup(state: Extract): MobilePrChipRollup { + // Conflicts win: the checks may be green, but the PR still can't merge. + if (state.data.pr.mergeable === 'CONFLICTING') { + return { kind: 'conflict', text: 'Conflicts', token: 'statusAmber' } + } + const checks = summarizePRChecks(state.data.checks) + if (checks.failed > 0) { + return { kind: 'failing', text: `${checks.failed} failing`, token: 'statusRed' } + } + if (checks.pending > 0) { + return { kind: 'running', text: `${checks.pending} running`, token: 'statusAmber' } + } + if (checks.passed > 0) { + return { kind: 'passed', text: `${checks.passed}/${checks.total}`, token: 'statusGreen' } + } + return { kind: 'none', text: 'No checks', token: 'textSecondary' } +} diff --git a/mobile/src/source-control/mobile-source-control-actions.test.ts b/mobile/src/source-control/mobile-source-control-actions.test.ts index 5ed3deb23702..8dc281a40193 100644 --- a/mobile/src/source-control/mobile-source-control-actions.test.ts +++ b/mobile/src/source-control/mobile-source-control-actions.test.ts @@ -52,7 +52,7 @@ describe('buildMobileSourceControlActions', () => { expect(labels.some((l) => l.startsWith('Fast-forward'))).toBe(true) expect(labels).toContain('Rebase onto base') expect(labels).toContain('Switch branch') - expect(labels).toContain('History') + expect(labels).toContain('Commits') expect(labels).toContain('Create PR') }) @@ -90,7 +90,7 @@ describe('buildMobileSourceControlActions', () => { const handlers = noopHandlers() const actions = buildMobileSourceControlActions(args({ handlers })) action(actions, 'Switch branch')?.onPress() - action(actions, 'History')?.onPress() + action(actions, 'Commits')?.onPress() expect(handlers.checkout).toHaveBeenCalled() expect(handlers.history).toHaveBeenCalled() }) diff --git a/mobile/src/source-control/mobile-source-control-actions.ts b/mobile/src/source-control/mobile-source-control-actions.ts index 0e504c5a2b15..b06af8a6aaba 100644 --- a/mobile/src/source-control/mobile-source-control-actions.ts +++ b/mobile/src/source-control/mobile-source-control-actions.ts @@ -217,7 +217,7 @@ export function buildMobileSourceControlActions( onPress: handlers.checkout }, { - label: 'History', + label: 'Commits', iconKey: 'history', disabled: busy, onPress: handlers.history diff --git a/mobile/src/source-control/mobile-source-control-conflict-abort.test.ts b/mobile/src/source-control/mobile-source-control-conflict-abort.test.ts new file mode 100644 index 000000000000..fa9e40a47464 --- /dev/null +++ b/mobile/src/source-control/mobile-source-control-conflict-abort.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { + isMobileConflictAborting, + mobileConflictAbortLabel +} from './mobile-source-control-conflict-abort' + +describe('isMobileConflictAborting', () => { + it('is true only for the matching abort action', () => { + expect(isMobileConflictAborting('abort-merge', 'merge')).toBe(true) + expect(isMobileConflictAborting('abort-rebase', 'rebase')).toBe(true) + }) + + it('is false for other busy actions (stage/commit must not look like abort)', () => { + expect(isMobileConflictAborting('stage-all', 'merge')).toBe(false) + expect(isMobileConflictAborting('commit', 'rebase')).toBe(false) + expect(isMobileConflictAborting(null, 'merge')).toBe(false) + expect(isMobileConflictAborting('abort-merge', 'rebase')).toBe(false) + expect(isMobileConflictAborting('abort-merge', 'unknown')).toBe(false) + }) +}) + +describe('mobileConflictAbortLabel', () => { + it('shows Aborting only while abort is in flight', () => { + expect(mobileConflictAbortLabel('merge', true)).toBe('Aborting…') + expect(mobileConflictAbortLabel('merge', false)).toBe('Abort merge') + expect(mobileConflictAbortLabel('rebase', false)).toBe('Abort rebase') + }) +}) diff --git a/mobile/src/source-control/mobile-source-control-conflict-abort.ts b/mobile/src/source-control/mobile-source-control-conflict-abort.ts new file mode 100644 index 000000000000..ac71bcbf9edf --- /dev/null +++ b/mobile/src/source-control/mobile-source-control-conflict-abort.ts @@ -0,0 +1,18 @@ +// Pure helpers for the branch-card conflict Abort control. Kept free of React so +// the busy-label rule (abort-in-flight only) is unit-testable. + +/** True while git.abortMerge / git.abortRebase is the active serial action. */ +export function isMobileConflictAborting( + busyAction: string | null, + conflictOperation: string | null +): boolean { + if (conflictOperation !== 'merge' && conflictOperation !== 'rebase') { + return false + } + return busyAction === `abort-${conflictOperation}` +} + +/** Label for the Abort control — never says "Aborting…" for unrelated busy work. */ +export function mobileConflictAbortLabel(conflictOperation: string, aborting: boolean): string { + return aborting ? 'Aborting…' : `Abort ${conflictOperation}` +} diff --git a/mobile/src/source-control/mobile-source-control-hub-styles.ts b/mobile/src/source-control/mobile-source-control-hub-styles.ts new file mode 100644 index 000000000000..10d126177e86 --- /dev/null +++ b/mobile/src/source-control/mobile-source-control-hub-styles.ts @@ -0,0 +1,126 @@ +import { StyleSheet } from 'react-native' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' + +// Styles for the hub's segmented control and the branch-card PR chip. Split from +// mobile-source-control-styles.ts so neither file crosses the line limit. +export const hubStyles = StyleSheet.create({ + // Full-width tab bar under the hub header. Edge-to-edge, no inset track and no + // inner padding — segments share height evenly so the control doesn't float in a + // pill frame with gaps above/below the active cell. + segments: { + flexDirection: 'row', + alignItems: 'stretch', + width: '100%', + backgroundColor: colors.bgPanel, + borderBottomWidth: StyleSheet.hairlineWidth, + borderBottomColor: colors.borderSubtle + }, + segment: { + flex: 1, + minHeight: 40, + alignItems: 'center', + justifyContent: 'center', + paddingHorizontal: spacing.xs, + // Reserved so active underline doesn't change layout height. + borderBottomWidth: 2, + borderBottomColor: 'transparent' + }, + segmentActive: { + borderBottomColor: colors.textPrimary + }, + segmentPressed: { + opacity: 0.7 + }, + segmentText: { + color: colors.textSecondary, + fontSize: typography.bodySize, + fontWeight: '600' + }, + segmentTextActive: { + color: colors.textPrimary + }, + // The PR chip sits below the count row inside the branch card, separated by a + // hairline so it reads as a distinct, tappable status line. + chip: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + marginTop: spacing.md, + paddingTop: spacing.md, + borderTopWidth: StyleSheet.hairlineWidth, + borderTopColor: colors.borderSubtle + }, + chipPressed: { + opacity: 0.7 + }, + chipIcon: { + width: 18, + alignItems: 'center' + }, + chipNumber: { + color: colors.textPrimary, + fontSize: typography.bodySize, + fontWeight: '700' + }, + statePill: { + paddingHorizontal: spacing.sm, + paddingVertical: 1, + borderRadius: radii.button, + borderWidth: StyleSheet.hairlineWidth + }, + statePillText: { + fontSize: typography.metaSize, + fontWeight: '700' + }, + rollup: { + flexDirection: 'row', + alignItems: 'center', + gap: 4 + }, + rollupText: { + fontSize: typography.metaSize, + fontWeight: '600' + }, + comment: { + flexDirection: 'row', + alignItems: 'center', + gap: 4 + }, + commentText: { + color: colors.textSecondary, + fontSize: typography.metaSize, + fontWeight: '600' + }, + // Pushes the chevron to the trailing edge without a fixed-width spacer. + chipSpacer: { + flex: 1, + minWidth: spacing.sm + }, + chipCreateText: { + color: colors.accentBlue, + fontSize: typography.bodySize, + fontWeight: '600' + }, + chipMutedText: { + flex: 1, + color: colors.textMuted, + fontSize: typography.metaSize + }, + // Wraps the Changes-only controls (commit-failure/error notice, create-PR entry, + // bulk Stage/Unstage row) that used to live inside the summary card, now that the + // card is shared across segments and holds only branch status. + changesControls: { + paddingHorizontal: spacing.lg, + marginTop: spacing.xs + }, + // Fills the remaining space below the header/segments/card so each segment's + // scroll view (SectionList / PR sidebar / history list) expands and scrolls. + tabBody: { + flex: 1 + }, + // Keep a previously-visited segment mounted (scroll + fetch state) without + // participating in layout while another segment is active. + tabBodyHidden: { + display: 'none' + } +}) diff --git a/mobile/src/source-control/mobile-source-control-hub-tab.test.ts b/mobile/src/source-control/mobile-source-control-hub-tab.test.ts new file mode 100644 index 000000000000..4caf135cf13e --- /dev/null +++ b/mobile/src/source-control/mobile-source-control-hub-tab.test.ts @@ -0,0 +1,22 @@ +import { describe, it, expect } from 'vitest' +import { parseSourceControlHubTab, SOURCE_CONTROL_HUB_TABS } from './mobile-source-control-hub-tab' + +describe('parseSourceControlHubTab', () => { + it('accepts each known tab', () => { + for (const tab of SOURCE_CONTROL_HUB_TABS) { + expect(parseSourceControlHubTab(tab)).toBe(tab) + } + }) + + it('reads the first element of an array param', () => { + expect(parseSourceControlHubTab(['pr', 'history'])).toBe('pr') + }) + + it('falls back to changes for unknown, empty, or missing values', () => { + expect(parseSourceControlHubTab('nope')).toBe('changes') + expect(parseSourceControlHubTab('')).toBe('changes') + expect(parseSourceControlHubTab(undefined)).toBe('changes') + expect(parseSourceControlHubTab(null)).toBe('changes') + expect(parseSourceControlHubTab([])).toBe('changes') + }) +}) diff --git a/mobile/src/source-control/mobile-source-control-hub-tab.ts b/mobile/src/source-control/mobile-source-control-hub-tab.ts new file mode 100644 index 000000000000..3a0a48406cef --- /dev/null +++ b/mobile/src/source-control/mobile-source-control-hub-tab.ts @@ -0,0 +1,29 @@ +// The three lenses of the mobile Source Control hub. Kept as a pure module (no +// React/native imports) so tab parsing is unit-testable and the deep-link `tab` +// query param and the segmented control share one source of truth. + +export type SourceControlHubTab = 'changes' | 'pr' | 'history' + +export const SOURCE_CONTROL_HUB_TABS: readonly SourceControlHubTab[] = [ + 'changes', + 'pr', + 'history' +] as const + +export const SOURCE_CONTROL_HUB_TAB_LABELS: Record = { + changes: 'Changes', + pr: 'Pull Request', + history: 'Commits' +} + +// Normalize a route param (possibly an array from expo-router, possibly unknown) +// to a valid tab, defaulting to 'changes'. Deep links that name a stale/invalid +// tab fall back rather than render a blank body. +export function parseSourceControlHubTab( + value: string | string[] | undefined | null +): SourceControlHubTab { + const first = Array.isArray(value) ? value[0] : value + return SOURCE_CONTROL_HUB_TABS.includes(first as SourceControlHubTab) + ? (first as SourceControlHubTab) + : 'changes' +} diff --git a/mobile/src/source-control/mobile-source-control-styles.ts b/mobile/src/source-control/mobile-source-control-styles.ts index 3d22020651f5..ea766731840f 100644 --- a/mobile/src/source-control/mobile-source-control-styles.ts +++ b/mobile/src/source-control/mobile-source-control-styles.ts @@ -125,6 +125,24 @@ const baseStyles = StyleSheet.create({ fontWeight: '600', textTransform: 'capitalize' }, + reconnectBanner: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + marginHorizontal: spacing.lg, + marginTop: spacing.lg, + marginBottom: -spacing.sm, + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm, + borderRadius: radii.button, + backgroundColor: colors.bgRaised, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.statusAmber + }, + reconnectBannerText: { + color: colors.textPrimary, + fontSize: typography.metaSize + }, actionError: { marginTop: spacing.sm, paddingHorizontal: spacing.md, diff --git a/mobile/src/source-control/use-mobile-source-control-runners.ts b/mobile/src/source-control/use-mobile-source-control-runners.ts index 298923447796..026a706a5f96 100644 --- a/mobile/src/source-control/use-mobile-source-control-runners.ts +++ b/mobile/src/source-control/use-mobile-source-control-runners.ts @@ -45,6 +45,8 @@ type Params = { setCreatedPrUrl: (next: string | null) => void setCreatedPrWarning: (next: string | null) => void recordCommitFailure: RecordMobileCommitFailure + // Hub override: switch to the History segment instead of pushing the route. + onOpenHistory?: () => void } // All git workflow + action-sheet runners for the source-control panel. Split @@ -78,7 +80,8 @@ export function useMobileSourceControlRunners(params: Params) { setShowBranchPicker, setCreatedPrUrl, setCreatedPrWarning, - recordCommitFailure + recordCommitFailure, + onOpenHistory } = params const runGitWorkflow = useCallback( @@ -248,14 +251,24 @@ export function useMobileSourceControlRunners(params: Params) { const openHistory = useCallback(() => { setShowActionSheet(false) + // Inside the hub, History is a segment — switch to it rather than pushing a + // route. Fallback pushes the hub with `tab=history` (not the redirecting + // /history route) so deep links land in one hop. + if (onOpenHistory) { + onOpenHistory() + return + } if (hostId && worktreeId) { - router.push( - `/h/${hostId}/history/${encodeURIComponent(worktreeId)}` as Parameters< - typeof router.push - >[0] - ) + router.push({ + pathname: '/h/[hostId]/source-control/[worktreeId]', + params: { + hostId, + worktreeId, + tab: 'history' + } + } as Parameters[0]) } - }, [hostId, router, setShowActionSheet, worktreeId]) + }, [hostId, onOpenHistory, router, setShowActionSheet, worktreeId]) // Switch to a local branch, then reload status. const checkoutBranch = useCallback( diff --git a/mobile/src/source-control/use-mobile-source-control-state.ts b/mobile/src/source-control/use-mobile-source-control-state.ts index cc69b89059c9..c9a8ca406b08 100644 --- a/mobile/src/source-control/use-mobile-source-control-state.ts +++ b/mobile/src/source-control/use-mobile-source-control-state.ts @@ -42,6 +42,9 @@ export type MobileSourceControlStateParams = { onRequestClose?: () => void onFileOpenStart?: () => void onOpenedFileDiff?: (relativePath: string) => void + // When the panel runs inside the hub, "History" switches the segment instead of + // pushing the standalone route. Absent for the standalone/dock usage. + onOpenHistory?: () => void } export function useMobileSourceControlState(params: MobileSourceControlStateParams) { @@ -53,7 +56,8 @@ export function useMobileSourceControlState(params: MobileSourceControlStatePara embedded, onRequestClose, onFileOpenStart, - onOpenedFileDiff + onOpenedFileDiff, + onOpenHistory } = params const insets = useSafeAreaInsets() const { client, state: connState } = useHostClient(hostId) @@ -197,7 +201,8 @@ export function useMobileSourceControlState(params: MobileSourceControlStatePara setShowBranchPicker, setCreatedPrUrl, setCreatedPrWarning, - recordCommitFailure + recordCommitFailure, + onOpenHistory }) const createPrAction = useMobileSourceControlCreatePrAction({ client, diff --git a/mobile/src/terminal/TerminalWebView.tsx b/mobile/src/terminal/TerminalWebView.tsx index 1798fedd1d80..4b84e44081a3 100644 --- a/mobile/src/terminal/TerminalWebView.tsx +++ b/mobile/src/terminal/TerminalWebView.tsx @@ -1,13 +1,9 @@ import { useRef, useCallback, forwardRef, useImperativeHandle, useEffect, useMemo } from 'react' -import { View, type StyleProp, type ViewStyle } from 'react-native' +import { Platform, View } from 'react-native' import { WebView } from 'react-native-webview' import type { WebViewMessageEvent } from 'react-native-webview' import type { TerminalOscLinkRange } from './terminal-osc-link-ranges' -import type { - MobileTerminalTheme, - TerminalSelectionEvents, - TerminalWebViewHandle -} from './terminal-webview-contract' +import type { TerminalWebViewHandle, TerminalWebViewProps } from './terminal-webview-contract' import { TerminalWebViewEngineErrorOverlay, useTerminalWebViewEngineErrorState @@ -18,23 +14,9 @@ import { XTERM_WEBVIEW_SOURCE } from './terminal-webview-html' import type { TerminalWebViewCommand } from './terminal-webview-messages' import { createTerminalWebViewPendingMessages } from './terminal-webview-pending-messages' -export type { - MobileTerminalTheme, - TerminalKeyboardAvoidanceMetrics, - TerminalModes, - TerminalSelectionEvents, - TerminalWebViewHandle -} from './terminal-webview-contract' +type Props = TerminalWebViewProps -type Props = { - style?: StyleProp - terminalTheme?: MobileTerminalTheme - // Why: baseline zoom multiplier ("text size") applied on top of the fit-to-width - // scale; raw xterm fontSize can't drive apparent size because the fit cancels it. - textScale?: number - onWebReady?: () => void - onEngineError?: (message: string) => void -} & TerminalSelectionEvents +export type { TerminalWebViewHandle } from './terminal-webview-contract' export const TerminalWebView = forwardRef(function TerminalWebView( { @@ -61,6 +43,7 @@ export const TerminalWebView = forwardRef(function const isWebReadyRef = useRef(false) const pendingMessages = useMemo(() => createTerminalWebViewPendingMessages(), []) const messageIdRef = useRef(0) + const pendingPingIdRef = useRef(null) const terminalThemeKey = useMemo(() => JSON.stringify(terminalTheme ?? null), [terminalTheme]) const measureResolveRef = useRef< ((result: { cols: number; rows: number } | null) => void) | null @@ -80,7 +63,9 @@ export const TerminalWebView = forwardRef(function const sendToWebView = useCallback((msg: TerminalWebViewCommand) => { messageIdRef.current += 1 - webViewRef.current?.postMessage(JSON.stringify({ ...msg, id: messageIdRef.current })) + const id = messageIdRef.current + webViewRef.current?.postMessage(JSON.stringify({ ...msg, id })) + return id }, []) const flushPendingMessages = useCallback(() => { @@ -98,6 +83,30 @@ export const TerminalWebView = forwardRef(function [pendingMessages, sendToWebView] ) + const confirmWebReady = useCallback( + (notifyParent: boolean) => { + pendingPingIdRef.current = null + isWebReadyRef.current = true + clearWebReadyWatchdog() + clearEngineError() + if (notifyParent) { + onWebReady?.() + } + // Why: reload clears queued commands, so readiness must always restore the + // native-selected theme even when its value did not change in React. + sendToWebView({ type: 'set-theme', terminalTheme }) + flushPendingMessages() + }, + [ + clearEngineError, + clearWebReadyWatchdog, + flushPendingMessages, + onWebReady, + sendToWebView, + terminalTheme + ] + ) + const handleMessage = useCallback( (event: WebViewMessageEvent) => { let msg: Record @@ -108,11 +117,13 @@ export const TerminalWebView = forwardRef(function } if (msg.type === 'web-ready') { - isWebReadyRef.current = true - clearWebReadyWatchdog() - clearEngineError() - onWebReady?.() - flushPendingMessages() + confirmWebReady(true) + } else if ( + msg.type === 'pong' && + typeof msg.pingId === 'number' && + msg.pingId === pendingPingIdRef.current + ) { + confirmWebReady(false) } else if (msg.type === 'ready') { // Why: the WebView's init() rAF chain has run — term is open, // renderService is populated, first paint has happened. Resolve @@ -208,11 +219,8 @@ export const TerminalWebView = forwardRef(function } }, [ - flushPendingMessages, - clearEngineError, - clearWebReadyWatchdog, + confirmWebReady, reportEngineError, - onWebReady, onSelectionMode, onSelectionCopy, onSelectionEvicted, @@ -229,6 +237,7 @@ export const TerminalWebView = forwardRef(function const handleLoadStart = useCallback(() => { isWebReadyRef.current = false + pendingPingIdRef.current = null armWebReadyWatchdog() // Why: messages queued for a previous WebView generation are stale after a reload; // dropping them avoids replaying terminal chunks before the next init snapshot. @@ -240,6 +249,17 @@ export const TerminalWebView = forwardRef(function webViewRef.current?.reload() }, [clearEngineError]) + const handleContentProcessDidTerminate = useCallback(() => { + // Why: WKWebView content-process loss is recoverable; stale commands belong + // to the dead document and the replacement must prove readiness before replay. + isWebReadyRef.current = false + pendingPingIdRef.current = null + pendingMessages.clear() + clearEngineError() + armWebReadyWatchdog() + webViewRef.current?.reload() + }, [armWebReadyWatchdog, clearEngineError, pendingMessages]) + useEffect(() => { postMessage({ type: 'set-theme', terminalTheme }) }, [postMessage, terminalThemeKey, terminalTheme]) @@ -253,6 +273,16 @@ export const TerminalWebView = forwardRef(function useImperativeHandle( ref, () => ({ + prepareForForegroundRecovery() { + if (Platform.OS !== 'ios') { + return + } + // Why: direct ping is the only command allowed through while readiness is + // invalid; init/write commands queue until this exact document answers. + isWebReadyRef.current = false + armWebReadyWatchdog() + pendingPingIdRef.current = sendToWebView({ type: 'ping' }) + }, write(data: string) { postMessage({ type: 'write', data }) }, @@ -363,7 +393,7 @@ export const TerminalWebView = forwardRef(function }) } }), - [postMessage, sendToWebView, terminalTheme, textScale] + [armWebReadyWatchdog, postMessage, sendToWebView, terminalTheme, textScale] ) return ( @@ -389,9 +419,7 @@ export const TerminalWebView = forwardRef(function onRenderProcessGone={(event) => reportNativeEngineError('Terminal WebView render process ended', event) } - onContentProcessDidTerminate={(event) => - reportNativeEngineError('Terminal WebView content process ended', event) - } + onContentProcessDidTerminate={handleContentProcessDidTerminate} /> {engineError ? ( diff --git a/mobile/src/terminal/terminal-foreground-recovery.test.ts b/mobile/src/terminal/terminal-foreground-recovery.test.ts index 4eda53a9c22b..6aeceaaa14ae 100644 --- a/mobile/src/terminal/terminal-foreground-recovery.test.ts +++ b/mobile/src/terminal/terminal-foreground-recovery.test.ts @@ -127,5 +127,11 @@ describe('terminal foreground recovery', () => { expect(foregroundPredicate).toContain('Platform.OS') expect(sessionSource).toContain('recoverActiveTerminalAfterForeground({') expect(sessionSource).toContain("AppState.addEventListener('change'") + const readinessInvalidation = sessionSource.indexOf( + 'terminalRef.prepareForForegroundRecovery()' + ) + const replay = sessionSource.indexOf('recoverActiveTerminalAfterForeground({') + expect(readinessInvalidation).toBeGreaterThanOrEqual(0) + expect(replay).toBeGreaterThan(readinessInvalidation) }) }) diff --git a/mobile/src/terminal/terminal-ios-dictation-write-back.test.ts b/mobile/src/terminal/terminal-ios-dictation-write-back.test.ts new file mode 100644 index 000000000000..8dff075d85ef --- /dev/null +++ b/mobile/src/terminal/terminal-ios-dictation-write-back.test.ts @@ -0,0 +1,25 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' + +const sessionRouteSource = readFileSync( + new URL('../../app/h/[hostId]/session/[worktreeId].tsx', import.meta.url), + 'utf8' +) + +// Why: iOS terminates an active keyboard-dictation (and IME) session whenever +// JS writes a value into the focused field that differs from the native text +// (RN applies it via setTextAndSelection / _setAttributedString). Terminal +// inputs therefore must echo the raw field text in their controlled value and +// apply dash normalization only on the send/mirror path. See stablyai/orca#7925. +describe('terminal iOS dictation write-back', () => { + it('does not write normalized text back into the buffered command input value', () => { + expect(sessionRouteSource).toContain('onChangeText={setInput}') + expect(sessionRouteSource).not.toContain( + 'setInput((previousText) => normalizeTerminalTextInput' + ) + }) + + it('still normalizes the buffered command text at send time', () => { + expect(sessionRouteSource).toContain('normalizeTerminalTextInput(input)') + }) +}) diff --git a/mobile/src/terminal/terminal-keyboard-dismiss.test.ts b/mobile/src/terminal/terminal-keyboard-dismiss.test.ts new file mode 100644 index 000000000000..1e523b5d5c53 --- /dev/null +++ b/mobile/src/terminal/terminal-keyboard-dismiss.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it, vi } from 'vitest' + +import { dismissTerminalKeyboard } from './terminal-keyboard-dismiss' + +describe('dismissTerminalKeyboard', () => { + it('clears pending live input focus before blur and dismiss', () => { + const calls: string[] = [] + const clearPendingLiveInputFocus = vi.fn(() => calls.push('clear')) + const liveInput = { blur: vi.fn(() => calls.push('live-blur')) } + const commandInput = { blur: vi.fn(() => calls.push('command-blur')) } + const dismissKeyboard = vi.fn(() => calls.push('dismiss')) + + dismissTerminalKeyboard({ + clearPendingLiveInputFocus, + commandInput, + dismissKeyboard, + liveInput + }) + + expect(calls).toEqual(['clear', 'live-blur', 'command-blur', 'dismiss']) + }) + + it('blurs both live and buffered command inputs', () => { + const liveInput = { blur: vi.fn() } + const commandInput = { blur: vi.fn() } + + dismissTerminalKeyboard({ + clearPendingLiveInputFocus: vi.fn(), + commandInput, + dismissKeyboard: vi.fn(), + liveInput + }) + + expect(liveInput.blur).toHaveBeenCalledTimes(1) + expect(commandInput.blur).toHaveBeenCalledTimes(1) + }) + + it('dismisses the keyboard without a live input handle', () => { + const commandInput = { blur: vi.fn() } + const dismissKeyboard = vi.fn() + + dismissTerminalKeyboard({ + clearPendingLiveInputFocus: vi.fn(), + commandInput, + dismissKeyboard, + liveInput: null + }) + + expect(commandInput.blur).toHaveBeenCalledTimes(1) + expect(dismissKeyboard).toHaveBeenCalledTimes(1) + }) + + it('dismisses the keyboard without a buffered command input handle', () => { + const liveInput = { blur: vi.fn() } + const dismissKeyboard = vi.fn() + + dismissTerminalKeyboard({ + clearPendingLiveInputFocus: vi.fn(), + commandInput: undefined, + dismissKeyboard, + liveInput + }) + + expect(liveInput.blur).toHaveBeenCalledTimes(1) + expect(dismissKeyboard).toHaveBeenCalledTimes(1) + }) + + it('still clears focus and dismisses when both input handles are missing', () => { + const calls: string[] = [] + const clearPendingLiveInputFocus = vi.fn(() => calls.push('clear')) + const dismissKeyboard = vi.fn(() => calls.push('dismiss')) + + dismissTerminalKeyboard({ + clearPendingLiveInputFocus, + commandInput: undefined, + dismissKeyboard, + liveInput: null + }) + + expect(calls).toEqual(['clear', 'dismiss']) + }) +}) diff --git a/mobile/src/terminal/terminal-keyboard-dismiss.ts b/mobile/src/terminal/terminal-keyboard-dismiss.ts new file mode 100644 index 000000000000..502ed42750eb --- /dev/null +++ b/mobile/src/terminal/terminal-keyboard-dismiss.ts @@ -0,0 +1,17 @@ +export type TerminalKeyboardDismissHandle = { blur: () => void } | null | undefined + +export type DismissTerminalKeyboardOptions = { + clearPendingLiveInputFocus: () => void + commandInput: TerminalKeyboardDismissHandle + dismissKeyboard: () => void + liveInput: TerminalKeyboardDismissHandle +} + +export function dismissTerminalKeyboard(options: DismissTerminalKeyboardOptions): void { + // Why: clear the queued live-input focus before blurring/dismissing so a + // pending deferred focus cannot re-open the iOS keyboard right after Hide. + options.clearPendingLiveInputFocus() + options.liveInput?.blur() + options.commandInput?.blur() + options.dismissKeyboard() +} diff --git a/mobile/src/terminal/terminal-text-input-normalization.test.ts b/mobile/src/terminal/terminal-text-input-normalization.test.ts index 29e15ea321b3..c5213013e31e 100644 --- a/mobile/src/terminal/terminal-text-input-normalization.test.ts +++ b/mobile/src/terminal/terminal-text-input-normalization.test.ts @@ -11,10 +11,4 @@ describe('normalizeTerminalTextInput', () => { it('keeps ASCII hyphens unchanged', () => { expect(normalizeTerminalTextInput('git checkout -- file')).toBe('git checkout -- file') }) - - it('preserves longer trailing hyphen runs when iOS re-collapses the controlled value', () => { - expect(normalizeTerminalTextInput('—', '--')).toBe('---') - expect(normalizeTerminalTextInput('—', '---')).toBe('----') - expect(normalizeTerminalTextInput('git checkout —', 'git checkout --')).toBe('git checkout ---') - }) }) diff --git a/mobile/src/terminal/terminal-text-input-normalization.ts b/mobile/src/terminal/terminal-text-input-normalization.ts index 70500421b3b9..6316ce1bbaad 100644 --- a/mobile/src/terminal/terminal-text-input-normalization.ts +++ b/mobile/src/terminal/terminal-text-input-normalization.ts @@ -1,18 +1,9 @@ // Why: iOS smart punctuation can rewrite two ASCII hyphens into a single -// Unicode dash before React Native delivers terminal text input. +// Unicode dash before React Native delivers terminal text input. Each dash maps +// to exactly "--": recovering longer runs (#5222) needed the previous controlled +// value written back into the field, and that write-back kills iOS dictation (#7925). const IOS_SMART_DASH_REPLACEMENT_PATTERN = /[\u2013\u2014]/g -const IOS_SMART_DASH_REPLACEMENT_TEST = /[\u2013\u2014]/ -export function normalizeTerminalTextInput(text: string, previousText = ''): string { - const normalizedText = text.replace(IOS_SMART_DASH_REPLACEMENT_PATTERN, '--') - const previousTrailingHyphens = /-+$/.exec(previousText)?.[0] ?? '' - const previousPrefix = previousText.slice(0, previousText.length - previousTrailingHyphens.length) - const collapsedPreviousHyphenRun = - previousTrailingHyphens.length >= 2 && - IOS_SMART_DASH_REPLACEMENT_TEST.test(text) && - (text === `${previousPrefix}\u2013` || text === `${previousPrefix}\u2014`) - if (collapsedPreviousHyphenRun) { - return `${previousText}-` - } - return normalizedText +export function normalizeTerminalTextInput(text: string): string { + return text.replace(IOS_SMART_DASH_REPLACEMENT_PATTERN, '--') } diff --git a/mobile/src/terminal/terminal-viewport-refit.test.ts b/mobile/src/terminal/terminal-viewport-refit.test.ts index 4cd3794ad0f0..b658dad437a7 100644 --- a/mobile/src/terminal/terminal-viewport-refit.test.ts +++ b/mobile/src/terminal/terminal-viewport-refit.test.ts @@ -52,6 +52,36 @@ describe('terminal viewport refit', () => { expect(sessionSource).toContain('useTerminalViewportRefit({') expect(sessionSource).toContain('tabStripVisible: terminals.length > 1') expect(sessionSource).toContain('textScale: terminalTextScale') + expect(sessionSource).toContain('connState,') + }) + + it('forces a refit on iOS foreground and connection recovery', () => { + const foregroundEffect = hookSource.slice( + hookSource.indexOf("if (Platform.OS !== 'ios')"), + hookSource.indexOf('const previousConnStateRef') + ) + const reconnectEffect = hookSource.slice( + hookSource.indexOf('const previousConnStateRef'), + hookSource.indexOf('disposedRef.current = false') + ) + + expect(foregroundEffect).toContain("AppState.addEventListener('change'") + expect(foregroundEffect).toContain('viewportMeasuredRef.current = false') + expect(foregroundEffect).toContain('scheduleForcedViewportRefit()') + expect(reconnectEffect).toContain("connState !== 'connected'") + expect(reconnectEffect).toContain('viewportMeasuredRef.current = false') + expect(reconnectEffect).toContain('scheduleForcedViewportRefit()') + }) + + it('bypasses the equal-dimensions guard for resume and reconnect refits', () => { + expect(hookSource).toContain('const forceRefit = forceNextRefitRef.current') + expect(hookSource).toContain( + 'if (!forceRefit && prev && prev.cols === dims.cols && prev.rows === dims.rows)' + ) + const forceRead = hookSource.indexOf('const forceRefit = forceNextRefitRef.current') + const updateViewport = hookSource.indexOf("sendRequest('terminal.updateViewport'") + expect(forceRead).toBeGreaterThanOrEqual(0) + expect(updateViewport).toBeGreaterThan(forceRead) }) it('prefers the in-place updateViewport RPC over resubscribe', () => { diff --git a/mobile/src/terminal/terminal-viewport-refit.ts b/mobile/src/terminal/terminal-viewport-refit.ts index b8a823be8c7c..44c6a9b7e031 100644 --- a/mobile/src/terminal/terminal-viewport-refit.ts +++ b/mobile/src/terminal/terminal-viewport-refit.ts @@ -1,7 +1,9 @@ import { useCallback, useEffect, useRef, type RefObject } from 'react' -import { useWindowDimensions } from 'react-native' +import { AppState, Platform, useWindowDimensions, type AppStateStatus } from 'react-native' import type { RpcClient } from '../transport/rpc-client' +import type { ConnectionState } from '../transport/types' import type { TerminalWebViewHandle } from './TerminalWebView' +import { shouldRecoverTerminalOnAppStateChange } from './terminal-foreground-recovery' import { isTerminalUpdateViewportApplied, isTerminalUpdateViewportUpdated, @@ -19,6 +21,7 @@ type TerminalViewportRefitOptions = { clientRef: RefObject deviceTokenRef: RefObject initializedHandlesRef: RefObject> + connState: ConnectionState tabStripVisible: boolean // Why: terminal text size (font scale) — changing it changes the cell size, so // the PTY must be re-fitted to a new column count and reflowed. @@ -49,6 +52,7 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions): clientRef, deviceTokenRef, initializedHandlesRef, + connState, tabStripVisible, textScale, terminalFrameWidth, @@ -58,6 +62,7 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions): const refitTimerRef = useRef | null>(null) const refitRunSeqRef = useRef(0) + const forceNextRefitRef = useRef(false) const disposedRef = useRef(false) const scheduleViewportRefit = useCallback(() => { if (refitTimerRef.current) { @@ -93,8 +98,10 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions): if (!dims) { return } + const forceRefit = forceNextRefitRef.current + forceNextRefitRef.current = false const prev = viewportRef.current - if (prev && prev.cols === dims.cols && prev.rows === dims.rows) { + if (!forceRefit && prev && prev.cols === dims.cols && prev.rows === dims.rows) { return } viewportRef.current = dims @@ -152,6 +159,10 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions): unsubscribeTerminal, subscribeToTerminal ]) + const scheduleForcedViewportRefit = useCallback(() => { + forceNextRefitRef.current = true + scheduleViewportRefit() + }, [scheduleViewportRefit]) // Why: the tab strip is hidden when only one terminal exists and shown // once a second is created. Crossing the 1↔2 boundary changes the @@ -215,6 +226,42 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions): scheduleViewportRefit() }, [terminalFrameWidth, viewportMeasuredRef, scheduleViewportRefit]) + useEffect(() => { + if (Platform.OS !== 'ios') { + return + } + let previousAppState: AppStateStatus | null = AppState.currentState + const sub = AppState.addEventListener('change', (nextAppState: AppStateStatus) => { + const shouldRefit = shouldRecoverTerminalOnAppStateChange( + previousAppState, + nextAppState, + Platform.OS + ) + previousAppState = nextAppState + if (!shouldRefit) { + return + } + // Why: the cached grid can match while the host PTY changed in background; + // reasserting equal dimensions is the convergence signal after iOS resume. + viewportMeasuredRef.current = false + scheduleForcedViewportRefit() + }) + return () => sub.remove() + }, [viewportMeasuredRef, scheduleForcedViewportRefit]) + + const previousConnStateRef = useRef(connState) + useEffect(() => { + const previous = previousConnStateRef.current + previousConnStateRef.current = connState + if (previous === 'connected' || connState !== 'connected') { + return + } + // Why: reconnect can restore a PTY whose host-side size changed while the + // socket was down, so equal cached dimensions still need reassertion. + viewportMeasuredRef.current = false + scheduleForcedViewportRefit() + }, [connState, viewportMeasuredRef, scheduleForcedViewportRefit]) + useEffect(() => { disposedRef.current = false return () => { diff --git a/mobile/src/terminal/terminal-webview-contract.ts b/mobile/src/terminal/terminal-webview-contract.ts index aff86cecad25..808dece26487 100644 --- a/mobile/src/terminal/terminal-webview-contract.ts +++ b/mobile/src/terminal/terminal-webview-contract.ts @@ -1,4 +1,5 @@ import type { RuntimeMobileTerminalTheme } from '../../../src/shared/runtime-types' +import type { StyleProp, ViewStyle } from 'react-native' import type { TerminalOscLinkRange } from './terminal-osc-link-ranges' type TerminalMouseTrackingMode = 'none' | 'x10' | 'vt200' | 'drag' | 'any' @@ -37,7 +38,20 @@ export type TerminalSelectionEvents = { onTextScaleChange?: (scale: number) => void } +export type TerminalWebViewProps = { + style?: StyleProp + terminalTheme?: MobileTerminalTheme + // Why: baseline zoom multiplier applied on top of fit-to-width scale; raw + // xterm fontSize alone cannot drive apparent size because fitting cancels it. + textScale?: number + onWebReady?: () => void + onEngineError?: (message: string) => void +} & TerminalSelectionEvents + export type TerminalWebViewHandle = { + // Why: iOS can preserve the native view while discarding its JS/backing-store + // state; foreground recovery must wait for the document to answer before replay. + prepareForForegroundRecovery: () => void write: (data: string) => void init: ( cols: number, diff --git a/mobile/src/terminal/terminal-webview-engine-error.test.ts b/mobile/src/terminal/terminal-webview-engine-error.test.ts index 82267967b7cd..4e29c2873216 100644 --- a/mobile/src/terminal/terminal-webview-engine-error.test.ts +++ b/mobile/src/terminal/terminal-webview-engine-error.test.ts @@ -1,10 +1,18 @@ -import { createElement } from 'react' +import { createElement, createRef } from 'react' +import { Platform } from 'react-native' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import { TerminalWebView } from './TerminalWebView' +import type { TerminalWebViewHandle } from './terminal-webview-contract' + +const nativeWebViewMethods = vi.hoisted(() => ({ + postMessage: vi.fn<(message: string) => void>(), + reload: vi.fn<() => void>() +})) vi.mock('react-native', () => ({ AppState: { currentState: 'active' }, + Platform: { OS: 'ios' }, Pressable: 'Pressable', StyleSheet: { absoluteFillObject: { @@ -20,10 +28,14 @@ vi.mock('react-native', () => ({ View: 'View' })) -vi.mock('react-native-webview', () => ({ - WebView: 'WebView', - default: 'WebView' -})) +vi.mock('react-native-webview', async () => { + const React = await import('react') + const WebView = React.forwardRef((props: Record, ref) => { + React.useImperativeHandle(ref, () => nativeWebViewMethods) + return React.createElement('WebView', props) + }) + return { WebView, default: WebView } +}) vi.mock('lucide-react-native', () => ({ RefreshCw: 'RefreshCw' @@ -45,12 +57,15 @@ function suppressReactTestRendererDeprecationWarning(): () => void { // unmount so the timer can't survive into later tests and fire in teardown. let activeRenderer: ReactTestRenderer | null = null -function createTerminalWebViewRenderer(onEngineError = vi.fn()) { +function createTerminalWebViewRenderer( + onEngineError = vi.fn(), + props: Record = {} +) { let renderer: ReactTestRenderer | null = null const restoreConsoleError = suppressReactTestRendererDeprecationWarning() try { act(() => { - renderer = create(createElement(TerminalWebView, { onEngineError })) + renderer = create(createElement(TerminalWebView, { onEngineError, ...props })) }) } finally { restoreConsoleError() @@ -76,6 +91,10 @@ function renderedText(renderer: ReactTestRenderer): string { .join(' ') } +function postedCommands(): Array> { + return nativeWebViewMethods.postMessage.mock.calls.map(([message]) => JSON.parse(message)) +} + describe('TerminalWebView engine errors', () => { afterEach(() => { if (activeRenderer) { @@ -84,6 +103,7 @@ describe('TerminalWebView engine errors', () => { }) activeRenderer = null } + vi.clearAllMocks() vi.restoreAllMocks() }) @@ -175,4 +195,78 @@ describe('TerminalWebView engine errors', () => { vi.useRealTimers() } }) + + it('queues iOS foreground traffic until the current document answers its ping', () => { + const terminalRef = createRef() + const onWebReady = vi.fn() + const terminalTheme = { + mode: 'dark', + theme: { background: '#111111', foreground: '#eeeeee' } + } + const { renderer } = createTerminalWebViewRenderer(vi.fn(), { + ref: terminalRef, + onWebReady, + terminalTheme + }) + postWebViewMessage(renderer, { type: 'web-ready' }) + nativeWebViewMethods.postMessage.mockClear() + + act(() => { + terminalRef.current?.prepareForForegroundRecovery() + terminalRef.current?.write('queued output') + }) + + const ping = postedCommands()[0] + expect(postedCommands().map((command) => command.type)).toEqual(['ping']) + postWebViewMessage(renderer, { type: 'pong', pingId: Number(ping?.id) + 1 }) + expect(postedCommands().map((command) => command.type)).toEqual(['ping']) + + postWebViewMessage(renderer, { type: 'pong', pingId: ping?.id }) + expect(postedCommands().map((command) => command.type)).toEqual(['ping', 'set-theme', 'write']) + expect(onWebReady).toHaveBeenCalledTimes(1) + }) + + it('keeps Android foreground traffic on the existing ready document', () => { + const terminalRef = createRef() + const { renderer } = createTerminalWebViewRenderer(vi.fn(), { ref: terminalRef }) + postWebViewMessage(renderer, { type: 'web-ready' }) + nativeWebViewMethods.postMessage.mockClear() + const mutablePlatform = Platform as { OS: string } + mutablePlatform.OS = 'android' + try { + act(() => { + terminalRef.current?.prepareForForegroundRecovery() + terminalRef.current?.write('android output') + }) + expect(postedCommands().map((command) => command.type)).toEqual(['write']) + } finally { + mutablePlatform.OS = 'ios' + } + }) + + it('reloads a terminated iOS content process and restores theme on readiness', () => { + const terminalRef = createRef() + const { onEngineError, renderer } = createTerminalWebViewRenderer(vi.fn(), { + ref: terminalRef, + terminalTheme: { + mode: 'light', + theme: { background: '#ffffff', foreground: '#111111' } + } + }) + postWebViewMessage(renderer, { type: 'web-ready' }) + nativeWebViewMethods.postMessage.mockClear() + const webView = renderer.root.findByType('WebView') + + act(() => { + webView.props.onContentProcessDidTerminate({ nativeEvent: {} }) + terminalRef.current?.write('after termination') + }) + + expect(nativeWebViewMethods.reload).toHaveBeenCalledTimes(1) + expect(nativeWebViewMethods.postMessage).not.toHaveBeenCalled() + expect(onEngineError).not.toHaveBeenCalled() + + postWebViewMessage(renderer, { type: 'web-ready' }) + expect(postedCommands().map((command) => command.type)).toEqual(['set-theme', 'write']) + }) }) diff --git a/mobile/src/terminal/terminal-webview-engine.test.ts b/mobile/src/terminal/terminal-webview-engine.test.ts index 36c8c039493d..503a25a1961c 100644 --- a/mobile/src/terminal/terminal-webview-engine.test.ts +++ b/mobile/src/terminal/terminal-webview-engine.test.ts @@ -1,15 +1,95 @@ import { readFileSync } from 'node:fs' import { Script } from 'node:vm' import { parse } from 'acorn' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { XTERM_ENGINE_CSS, XTERM_ENGINE_JS } from './terminal-webview-engine.generated' import { XTERM_HTML } from './terminal-webview-html' +import { TERMINAL_WEBGL_RECOVERY_JS } from './terminal-webview-webgl-recovery-injected' const terminalHtmlSource = readFileSync( new URL('./terminal-webview-html.ts', import.meta.url), 'utf8' ) +function createWebglRecoveryHarness(failSecondAttach = false) { + const variablesStart = terminalHtmlSource.indexOf(' var webglAddon = null;') + const variablesEnd = terminalHtmlSource.indexOf( + '\n', + terminalHtmlSource.indexOf(' var webglRecoveryTimer = null;') + ) + expect(variablesStart).toBeGreaterThanOrEqual(0) + expect(variablesEnd).toBeGreaterThan(variablesStart) + + const timers: Array<() => void> = [] + const addons: Array<{ + clearTextureAtlas: ReturnType + dispose: ReturnType + fireContextLoss: () => void + }> = [] + const term = { + rows: 24, + refresh: vi.fn(), + loadAddon: vi.fn(() => { + if (failSecondAttach && addons.length === 2) { + throw new Error('retry unavailable') + } + }) + } + function WebglAddon() { + let contextLoss = () => {} + const addon = { + clearTextureAtlas: vi.fn(), + dispose: vi.fn(), + fireContextLoss: () => contextLoss() + } + addons.push(addon) + return Object.assign(addon, { + onContextLoss: (listener: () => void) => { + contextLoss = listener + } + }) + } + let visibilityChange = () => {} + const document = { + addEventListener: vi.fn((eventName: string, listener: () => void) => { + if (eventName === 'visibilitychange') { + visibilityChange = listener + } + }), + visibilityState: 'hidden' + } + const applyTerminalTheme = vi.fn() + const flog = vi.fn() + const terminalThemeInput = { mode: 'dark' } + const context = { + applyTerminalTheme, + clearTimeout: vi.fn(), + document, + flog, + setTimeout: (callback: () => void) => { + timers.push(callback) + return timers.length + }, + term, + terminalGeneration: 1, + terminalThemeInput, + window: { WebglAddon: { WebglAddon } } + } + new Script(`${terminalHtmlSource.slice(variablesStart, variablesEnd)} +${TERMINAL_WEBGL_RECOVERY_JS} +attachWebglAddon(true);`).runInNewContext(context) + return { + addons, + applyTerminalTheme, + document, + fireVisibilityChange: () => visibilityChange(), + flog, + term, + terminalThemeInput, + timers + } +} + describe('terminal WebView bundled engine', () => { it('keeps the assembled terminal HTML free of external engine URLs', () => { expect(XTERM_HTML).not.toMatch(/\bhttps?:\/\//) @@ -106,4 +186,57 @@ describe('terminal WebView bundled engine', () => { expect(capSites.length).toBe(2) expect(terminalHtmlSource).toContain('nonFatalErrorNotifies > 5') }) + + it('recreates WebGL once after context loss, then stays on the DOM renderer', () => { + const { addons, flog, term, timers } = createWebglRecoveryHarness() + + expect(addons).toHaveLength(1) + addons[0]?.fireContextLoss() + expect(flog).toHaveBeenCalledWith( + 'webgl-context-loss', + expect.objectContaining({ retry: true }) + ) + expect(addons[0]?.dispose).toHaveBeenCalledTimes(1) + expect(term.refresh).toHaveBeenCalledTimes(1) + expect(timers).toHaveLength(1) + + timers.shift()?.() + expect(addons).toHaveLength(2) + expect(addons[1]?.clearTextureAtlas).toHaveBeenCalledTimes(1) + expect(term.refresh).toHaveBeenCalledTimes(2) + addons[1]?.fireContextLoss() + expect(addons[1]?.dispose).toHaveBeenCalledTimes(1) + expect(term.refresh).toHaveBeenCalledTimes(3) + expect(timers).toHaveLength(0) + }) + + it('falls back to a refreshed DOM renderer when the delayed WebGL retry fails', () => { + const { addons, term, timers } = createWebglRecoveryHarness(true) + + addons[0]?.fireContextLoss() + timers.shift()?.() + + expect(addons).toHaveLength(2) + expect(addons[1]?.dispose).toHaveBeenCalledTimes(1) + expect(term.refresh).toHaveBeenCalledTimes(2) + }) + + it('reapplies theme, clears the active atlas, and refreshes when visible', () => { + const harness = createWebglRecoveryHarness() + + harness.fireVisibilityChange() + expect(harness.applyTerminalTheme).not.toHaveBeenCalled() + + harness.document.visibilityState = 'visible' + harness.fireVisibilityChange() + + expect(harness.applyTerminalTheme).toHaveBeenCalledWith(harness.terminalThemeInput) + expect(harness.addons[0]?.clearTextureAtlas).toHaveBeenCalledTimes(1) + expect(harness.term.refresh).toHaveBeenCalledTimes(1) + }) + + it('answers native readiness probes from the live document', () => { + expect(terminalHtmlSource).toContain("if (msg.type === 'ping')") + expect(terminalHtmlSource).toContain("notify({ type: 'pong', pingId: msg.id })") + }) }) diff --git a/mobile/src/terminal/terminal-webview-html.ts b/mobile/src/terminal/terminal-webview-html.ts index 63e4d2b9ed70..fcd5ea9cafaa 100644 --- a/mobile/src/terminal/terminal-webview-html.ts +++ b/mobile/src/terminal/terminal-webview-html.ts @@ -7,7 +7,9 @@ import { TERMINAL_PATH_TAP_JS } from './terminal-path-tap-injected' import { XTERM_ENGINE_CSS, XTERM_ENGINE_JS } from './terminal-webview-engine.generated' import { TERMINAL_REFLOW_JS } from './terminal-webview-reflow-injected' import { TERMINAL_TAP_DISPATCH_JS } from './terminal-webview-tap-dispatch-injected' +import { TERMINAL_WEBVIEW_THEME_JS } from './terminal-webview-theme-injected' import { URL_TAP_WEBVIEW_JS } from './terminal-webview-url-tap' +import { TERMINAL_WEBGL_RECOVERY_JS } from './terminal-webview-webgl-recovery-injected' const DEFAULT_TERMINAL_THEME: RuntimeMobileTerminalTheme['theme'] = { background: colors.terminalBg, @@ -292,7 +294,10 @@ window.onerror = function(msg) { var initRows = 24; var terminalGeneration = 0; var defaultTheme = ${JSON.stringify(DEFAULT_TERMINAL_THEME)}; + var terminalThemeInput = null; var terminalTheme = defaultTheme; + var webglAddon = null; + var webglRecoveryTimer = null; var activeAltScreenSnapshot = false; var trackedMouseTrackingMode = 'none'; var sgrMouseMode = false; @@ -380,27 +385,7 @@ window.onerror = function(msg) { }, 550); } - function normalizeTerminalTheme(input) { - var source = input && typeof input === 'object' && input.theme && typeof input.theme === 'object' - ? input.theme - : null; - if (!source) return defaultTheme; - var next = {}; - var keys = Object.keys(defaultTheme); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (typeof source[key] === 'string') next[key] = source[key]; - } - return Object.assign({}, defaultTheme, next); - } - - function applyTerminalTheme(input) { - terminalTheme = normalizeTerminalTheme(input); - var background = terminalTheme.background || '${colors.terminalBg}'; - document.documentElement.style.background = background; - document.body.style.background = background; - if (term) term.options.theme = terminalTheme; - } +${TERMINAL_WEBVIEW_THEME_JS} function getCellHeight() { if (!term || !term._core) return 15; @@ -679,6 +664,8 @@ window.onerror = function(msg) { pumpWrites(terminalGeneration); } +${TERMINAL_WEBGL_RECOVERY_JS} + function init(cols, rows, initialData, nextTheme, nextFontScale, preserveScroll, nextOscLinks) { if (typeof nextFontScale === 'number' && nextFontScale > 0) currentTextScale = nextFontScale; // Why: a width-reflow re-stream rewraps the same content at new cols. @@ -688,6 +675,8 @@ window.onerror = function(msg) { var scrollAnchorRows = prevB ? Math.max(0, (prevB.baseY || 0) - (prevB.viewportY || 0)) : -1; terminalGeneration++; var gen = terminalGeneration; + cancelWebglContextRecovery(); + webglAddon = null; ready = false; resetWriteQueue(); statusDotPendingSelector = false; @@ -750,9 +739,7 @@ window.onerror = function(msg) { allowProposedApi: true }); term.open(surface); - if (window.WebglAddon && window.WebglAddon.WebglAddon) { - try { var webglAddon = new window.WebglAddon.WebglAddon(); term.loadAddon(webglAddon); if (webglAddon.onContextLoss) webglAddon.onContextLoss(function() { try { webglAddon && webglAddon.dispose && webglAddon.dispose(); } catch (e) {} }); } catch (e) {} - } + attachWebglAddon(true); if (window.Unicode11Addon && window.Unicode11Addon.Unicode11Addon) try { term.loadAddon(new window.Unicode11Addon.Unicode11Addon()); term.unicode.activeVersion = '11'; } catch (e) {} if (typeof replayData === 'string' && replayData.length > 0) { enqueueWrite(replayData); @@ -936,7 +923,9 @@ window.onerror = function(msg) { handledMessageIds.push(msg.id); if (handledMessageIds.length > 256) handledMessageIds.shift(); } - if (msg.type === 'init') { + if (msg.type === 'ping') { + notify({ type: 'pong', pingId: msg.id }); + } else if (msg.type === 'init') { init(msg.cols, msg.rows, msg.initialData, msg.terminalTheme, msg.fontScale, msg.preserveScroll, msg.oscLinks); } else if (msg.type === 'set-font-scale') { // Why: ignore RN echoing back the value a pinch just set (msg.fontScale === diff --git a/mobile/src/terminal/terminal-webview-messages.ts b/mobile/src/terminal/terminal-webview-messages.ts index f38c5a1dfbb5..c031363268c1 100644 --- a/mobile/src/terminal/terminal-webview-messages.ts +++ b/mobile/src/terminal/terminal-webview-messages.ts @@ -2,6 +2,7 @@ import type { RuntimeMobileTerminalTheme } from '../../../src/shared/runtime-typ import type { TerminalOscLinkRange } from './terminal-osc-link-ranges' export type TerminalWebViewCommand = + | { type: 'ping'; id?: number } | { type: 'write'; id?: number; data: string } | { type: 'init' diff --git a/mobile/src/terminal/terminal-webview-text-zoom.test.ts b/mobile/src/terminal/terminal-webview-text-zoom.test.ts index aeb7785751c0..09aeb82d3f74 100644 --- a/mobile/src/terminal/terminal-webview-text-zoom.test.ts +++ b/mobile/src/terminal/terminal-webview-text-zoom.test.ts @@ -10,6 +10,10 @@ const terminalHtmlSource = readFileSync( new URL('./terminal-webview-html.ts', import.meta.url), 'utf8' ) +const terminalWebglRecoverySource = readFileSync( + new URL('./terminal-webview-webgl-recovery-injected.ts', import.meta.url), + 'utf8' +) function extractStatusDotNormalizer() { const declarationStart = terminalHtmlSource.indexOf(' var CLAUDE_STATUS_DOT =') @@ -148,12 +152,12 @@ describe('TerminalWebView text zoom', () => { it('uses the bundled WebGL-capable xterm stack and platform-safe font fallbacks', () => { expect(terminalHtmlSource).not.toContain('cdn.jsdelivr.net') - expect(terminalHtmlSource).toContain('window.WebglAddon.WebglAddon') + expect(terminalWebglRecoverySource).toContain('window.WebglAddon.WebglAddon') expect(terminalHtmlSource).toContain('function isIOSWebView()') expect(terminalHtmlSource).toContain('fontFamily: terminalFontFamily') expect(terminalHtmlSource).toContain("fontWeight: '300'") expect(terminalHtmlSource).toContain("fontWeightBold: '500'") - expect(terminalHtmlSource).toContain('new window.WebglAddon.WebglAddon()') + expect(terminalWebglRecoverySource).toContain('new window.WebglAddon.WebglAddon()') }) const IOS_IPHONE_NAVIGATOR = { diff --git a/mobile/src/terminal/terminal-webview-theme-injected.ts b/mobile/src/terminal/terminal-webview-theme-injected.ts new file mode 100644 index 000000000000..1f798fe337e5 --- /dev/null +++ b/mobile/src/terminal/terminal-webview-theme-injected.ts @@ -0,0 +1,27 @@ +import { colors } from '../theme/mobile-theme' + +// Theme normalization and page-surface painting injected into the WebView IIFE. +export const TERMINAL_WEBVIEW_THEME_JS = ` + function normalizeTerminalTheme(input) { + var source = input && typeof input === 'object' && input.theme && typeof input.theme === 'object' + ? input.theme + : null; + if (!source) return defaultTheme; + var next = {}; + var keys = Object.keys(defaultTheme); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (typeof source[key] === 'string') next[key] = source[key]; + } + return Object.assign({}, defaultTheme, next); + } + + function applyTerminalTheme(input) { + terminalThemeInput = input; + terminalTheme = normalizeTerminalTheme(input); + var background = terminalTheme.background || '${colors.terminalBg}'; + document.documentElement.style.background = background; + document.body.style.background = background; + if (term) term.options.theme = terminalTheme; + } +` diff --git a/mobile/src/terminal/terminal-webview-webgl-recovery-injected.ts b/mobile/src/terminal/terminal-webview-webgl-recovery-injected.ts new file mode 100644 index 000000000000..8e4d27c23486 --- /dev/null +++ b/mobile/src/terminal/terminal-webview-webgl-recovery-injected.ts @@ -0,0 +1,62 @@ +// WebGL loss and visibility recovery injected into the terminal WebView IIFE. +// It closes over term, terminalGeneration, theme state, and xterm's addon global. +export const TERMINAL_WEBGL_RECOVERY_JS = ` + function refreshTerminalSurface() { + if (!term) return; + try { term.refresh(0, Math.max(0, term.rows - 1)); } catch (e) {} + } + + function cancelWebglContextRecovery() { + if (!webglRecoveryTimer) return; + clearTimeout(webglRecoveryTimer); + webglRecoveryTimer = null; + } + + function attachWebglAddon(allowRecovery) { + if (!term || !window.WebglAddon || !window.WebglAddon.WebglAddon) return false; + var addon = null; + try { + addon = new window.WebglAddon.WebglAddon(); + webglAddon = addon; + if (addon.onContextLoss) addon.onContextLoss(function() { + if (webglAddon !== addon) return; + flog('webgl-context-loss', { retry: allowRecovery }); + webglAddon = null; + try { addon.dispose(); } catch (e) {} + refreshTerminalSurface(); + if (!allowRecovery) return; + // Why: one delayed retry handles transient iOS context loss without + // entering a GPU crash loop; a second loss stays on the DOM renderer. + cancelWebglContextRecovery(); + var recoveryTerm = term; + var recoveryGeneration = terminalGeneration; + webglRecoveryTimer = setTimeout(function() { + webglRecoveryTimer = null; + if (term !== recoveryTerm || terminalGeneration !== recoveryGeneration) return; + attachWebglAddon(false); + }, 100); + }); + term.loadAddon(addon); + if (!allowRecovery) { + try { if (addon.clearTextureAtlas) addon.clearTextureAtlas(); } catch (e) {} + refreshTerminalSurface(); + } + return true; + } catch (e) { + flog('webgl-attach-failed', { retry: !allowRecovery, message: String(e) }); + if (webglAddon === addon) webglAddon = null; + try { if (addon) addon.dispose(); } catch (disposeError) {} + refreshTerminalSurface(); + return false; + } + } + + document.addEventListener('visibilitychange', function() { + if (document.visibilityState !== 'visible') return; + // Why: iOS may restore the xterm model while discarding GPU pixels/theme + // paint state, so visibility must rebuild the atlas and repaint every row. + applyTerminalTheme(terminalThemeInput); + try { if (webglAddon && webglAddon.clearTextureAtlas) webglAddon.clearTextureAtlas(); } catch (e) {} + refreshTerminalSurface(); + }); +` diff --git a/mobile/src/terminal/use-terminal-live-input-commit.test.ts b/mobile/src/terminal/use-terminal-live-input-commit.test.ts index 3ddb88682707..b759e30d6150 100644 --- a/mobile/src/terminal/use-terminal-live-input-commit.test.ts +++ b/mobile/src/terminal/use-terminal-live-input-commit.test.ts @@ -202,6 +202,32 @@ describe('terminal live input commit hook', () => { await vi.waitFor(() => expect(sent).toEqual(['a', 'b'])) }) + it('Given iOS smart-dash text When the change arrives Then the capture echoes the raw field text and the PTY gets normalized bytes', async () => { + // Given + const { captures, handlers, sent } = createTerminalLiveInputCommitHarness() + + // When: iOS smart punctuation rewrote "--" into an en dash inside the field + handlers.handleLiveInputChange('a–') + + // Then: writing "a--" back into the controlled value would kill an active + // iOS dictation/IME session, so the capture must keep what iOS produced + expect(captures).toEqual(['a–']) + await vi.waitFor(() => expect(sent).toEqual(['a--'])) + }) + + it('Given dictation-style hypothesis revisions When changes arrive Then the field is never rewritten and the PTY converges', async () => { + // Given + const { captures, handlers, sent } = createTerminalLiveInputCommitHarness() + + // When: iOS dictation replaces its hypothesis as recognition refines + handlers.handleLiveInputChange('high') + handlers.handleLiveInputChange('hi there') + + // Then: captures only echo the field; the mirror repairs the PTY with DELs + expect(captures).toEqual(['high', 'hi there']) + await vi.waitFor(() => expect(sent).toEqual(['high', '\x7f\x7f there'])) + }) + it('Given a trailing space after Hangul When the change arrives Then the space commits the held syllable', async () => { // Given const { handlers, sent } = createTerminalLiveInputCommitHarness() diff --git a/mobile/src/terminal/use-terminal-live-input-commit.ts b/mobile/src/terminal/use-terminal-live-input-commit.ts index cdabe1bed491..9c707dfbb31f 100644 --- a/mobile/src/terminal/use-terminal-live-input-commit.ts +++ b/mobile/src/terminal/use-terminal-live-input-commit.ts @@ -109,9 +109,11 @@ export function useTerminalLiveInputCommit({ clearPendingLiveInputCommit() return } - const normalizedText = normalizeTerminalTextInput(text) - setLiveInputCapture(normalizedText) - applyLiveInputMirror(activeHandle, normalizedText) + // Why: iOS kills an active dictation/IME session when JS writes a value + // that differs from the native field text, so the controlled capture must + // echo the field verbatim; only the PTY mirror sees normalized text. + setLiveInputCapture(text) + applyLiveInputMirror(activeHandle, normalizeTerminalTextInput(text)) }, [ activeHandle, diff --git a/mobile/src/transport/client-context.test.ts b/mobile/src/transport/client-context.test.ts new file mode 100644 index 000000000000..e9a298b6a743 --- /dev/null +++ b/mobile/src/transport/client-context.test.ts @@ -0,0 +1,159 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { ConnectionState } from './types' +import type { RpcClient } from './rpc-client' + +const connectMock = vi.fn() +const loadHostsMock = vi.fn() + +vi.mock('./rpc-client', () => ({ + connect: (...args: unknown[]) => connectMock(...args) +})) +vi.mock('./host-store', () => ({ + loadHosts: () => loadHostsMock() +})) +vi.mock('./connection-revival-triggers', () => ({ + subscribeConnectionRevivalTriggers: () => () => {} +})) + +import { RpcClientProvider, useCloseHost, useHostClient } from './client-context' + +type FakeClient = RpcClient & { + emitState: (state: ConnectionState) => void + closeMock: ReturnType +} + +function makeFakeClient(initialState: ConnectionState): FakeClient { + let state = initialState + const listeners = new Set<(state: ConnectionState) => void>() + const closeMock = vi.fn() + return { + sendRequest: vi.fn(), + subscribe: vi.fn(() => () => {}), + updateTerminalSubscriptionViewport: vi.fn(), + getState: () => state, + getReconnectAttempt: () => 0, + getLastConnectedAt: () => null, + onStateChange: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + notifyForeground: vi.fn(), + close: closeMock, + closeMock, + emitState: (next) => { + state = next + for (const listener of listeners) { + listener(next) + } + } + } as FakeClient +} + +const HOST = { + id: 'host-1', + name: 'Host 1', + endpoint: 'ws://127.0.0.1:1', + deviceToken: 'token', + publicKeyB64: 'key', + lastConnected: 0 +} + +type Harness = { + readonly hook: ReturnType + readonly closeHost: (hostId: string) => void + readonly unmount: () => void +} + +function suppressReactTestRendererDeprecationWarning(): () => void { + const originalConsoleError = console.error + const spy = vi.spyOn(console, 'error').mockImplementation((...args) => { + const firstArg = args[0] + if (typeof firstArg === 'string' && firstArg.includes('react-test-renderer is deprecated')) { + return + } + originalConsoleError(...args) + }) + return () => spy.mockRestore() +} + +async function renderHarness(hostId: string): Promise { + let hook: ReturnType | null = null + let closeHost: ((hostId: string) => void) | null = null + let renderer: ReactTestRenderer | null = null + + function Probe(): null { + hook = useHostClient(hostId) + closeHost = useCloseHost() + return null + } + + const restore = suppressReactTestRendererDeprecationWarning() + try { + await act(async () => { + renderer = create(createElement(RpcClientProvider, null, createElement(Probe))) + }) + } finally { + restore() + } + if (!hook || !closeHost || !renderer) { + throw new Error('harness did not render') + } + const mounted = renderer as ReactTestRenderer + return { + get hook() { + if (!hook) { + throw new Error('hook not rendered') + } + return hook + }, + closeHost: (id) => { + if (!closeHost) { + throw new Error('closeHost not rendered') + } + closeHost(id) + }, + unmount: () => mounted.unmount() + } +} + +beforeEach(() => { + connectMock.mockReset() + loadHostsMock.mockReset() +}) + +describe('useHostClient', () => { + it('drops the closed client when the host entry is removed', async () => { + const fake = makeFakeClient('connected') + connectMock.mockReturnValue(fake) + loadHostsMock.mockResolvedValue([HOST]) + + const harness = await renderHarness(HOST.id) + expect(harness.hook.client).toBe(fake) + expect(harness.hook.state).toBe('connected') + + // Regression (STA-1511): closeHost deletes the entry; before the fix the + // hook kept handing out the closed client, so mounted screens kept + // driving requests that could never resolve. + await act(async () => { + harness.closeHost(HOST.id) + }) + expect(fake.closeMock).toHaveBeenCalled() + expect(harness.hook.client).toBeNull() + expect(harness.hook.state).toBe('disconnected') + + harness.unmount() + }) + + it('reports disconnected instead of hanging when the host id is unknown', async () => { + loadHostsMock.mockResolvedValue([]) + + const harness = await renderHarness('missing-host') + expect(connectMock).not.toHaveBeenCalled() + expect(harness.hook.client).toBeNull() + expect(harness.hook.state).toBe('disconnected') + + harness.unmount() + }) +}) diff --git a/mobile/src/transport/client-context.tsx b/mobile/src/transport/client-context.tsx index f889cba51ff1..41f1b5092e87 100644 --- a/mobile/src/transport/client-context.tsx +++ b/mobile/src/transport/client-context.tsx @@ -20,6 +20,7 @@ import { type ReactNode } from 'react' import { connect, type RpcClient } from './rpc-client' +import { connectionLogStore } from './connection-log-buffer' import { subscribeConnectionRevivalTriggers } from './connection-revival-triggers' import { loadHosts } from './host-store' import type { ConnectionState, HostProfile } from './types' @@ -133,6 +134,11 @@ export function RpcClientProvider({ children }: { children: ReactNode }) { return null } if (!host) { + // Why: returning silently leaves mounted screens on a permanent + // spinner (STA-1511) — surface 'disconnected' so they can render + // their waiting/retry affordance instead. + notifyHostState(hostId, 'disconnected') + notifyAllHosts() return null } } @@ -145,7 +151,12 @@ export function RpcClientProvider({ children }: { children: ReactNode }) { let client: RpcClient try { - client = connect(host.endpoint, host.deviceToken, host.publicKeyB64) + client = connect(host.endpoint, host.deviceToken, host.publicKeyB64, { + // Why: retain reconnect lifecycle events for the Connection Log + // screen — without this the reasons a host is stuck live only in + // console.log, which users can't see or share. + onLog: (entry) => connectionLogStore.append(hostId, entry) + }) } catch { // Why: connect() can throw synchronously if the public key is // malformed or the endpoint URL is invalid. Notify so the UI @@ -406,6 +417,12 @@ export function useHostClient(hostId: string | undefined): { if (found && found.client !== clientRef.current) { clientRef.current = found.client force((n) => n + 1) + } else if (!found && clientRef.current) { + // Why: closeHost deletes the entry without a replacement; holding the + // closed client would let screens keep issuing requests that can never + // resolve (STA-1511). Null it so they render disconnected states. + clientRef.current = null + force((n) => n + 1) } }) const initial = ctx.acquire(hostId) diff --git a/mobile/src/transport/connection-health.test.ts b/mobile/src/transport/connection-health.test.ts new file mode 100644 index 000000000000..22e752a6335f --- /dev/null +++ b/mobile/src/transport/connection-health.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest' +import { classifyConnection, verdictDisplayLabel } from './connection-health' + +describe('classifyConnection Tailscale hint', () => { + const base = { + state: 'reconnecting' as const, + lastConnectedAt: null, + nowMs: 1_000_000 + } + + it('adds the hint to the warning verdict for a tailnet CGNAT endpoint', () => { + const verdict = classifyConnection({ + ...base, + reconnectAttempts: 3, + endpoint: 'ws://100.65.9.106:6768' + }) + expect(verdict).toMatchObject({ kind: 'warning', hint: 'check Tailscale' }) + }) + + it('adds the hint to the unreachable verdict for a MagicDNS endpoint', () => { + const verdict = classifyConnection({ + ...base, + reconnectAttempts: 12, + endpoint: 'ws://my-desktop.tailnet-1234.ts.net:6768' + }) + expect(verdict).toMatchObject({ + kind: 'unreachable', + reason: 'never-connected', + hint: 'check Tailscale' + }) + }) + + it('keeps plain labels for LAN endpoints', () => { + const warning = classifyConnection({ + ...base, + reconnectAttempts: 3, + endpoint: 'ws://192.168.1.50:6768' + }) + expect(warning.kind).toBe('warning') + expect('hint' in warning && warning.hint).toBeFalsy() + }) + + it('keeps plain labels when no endpoint is provided', () => { + const verdict = classifyConnection({ ...base, reconnectAttempts: 3 }) + expect(verdict.kind).toBe('warning') + expect('hint' in verdict && verdict.hint).toBeFalsy() + }) + + it('never hints on healthy states', () => { + const verdict = classifyConnection({ + state: 'connected', + reconnectAttempts: 0, + lastConnectedAt: 999_000, + endpoint: 'ws://100.65.9.106:6768', + nowMs: 1_000_000 + }) + expect(verdict).toEqual({ kind: 'normal', label: 'Connected' }) + }) +}) + +describe('verdictDisplayLabel', () => { + it('appends the hint to warning and unreachable labels', () => { + expect( + verdictDisplayLabel({ kind: 'warning', label: "Can't connect", hint: 'check Tailscale' }) + ).toBe("Can't connect — check Tailscale") + expect( + verdictDisplayLabel({ + kind: 'unreachable', + label: "Can't reach desktop", + reason: 'stale', + hint: 'check Tailscale' + }) + ).toBe("Can't reach desktop — check Tailscale") + }) + + it('returns the bare label without a hint', () => { + expect(verdictDisplayLabel({ kind: 'warning', label: "Can't connect" })).toBe("Can't connect") + expect(verdictDisplayLabel({ kind: 'normal', label: 'Connected' })).toBe('Connected') + }) +}) diff --git a/mobile/src/transport/connection-health.ts b/mobile/src/transport/connection-health.ts index 4ce81beffd22..d3b8251fc1b0 100644 --- a/mobile/src/transport/connection-health.ts +++ b/mobile/src/transport/connection-health.ts @@ -1,3 +1,4 @@ +import { isTailscaleEndpoint } from '../../../src/shared/remote-runtime-tailscale-hint' import type { ConnectionState } from './types' // Why: thresholds for escalating connection UX from neutral @@ -11,7 +12,8 @@ import type { ConnectionState } from './types' // reuse the 60s cap). Combined with the never-connected / // stale-since-last-connect heuristic below, this is the trigger to // surface a "re-pair?" affordance. MUST stay aligned with -// rpc-client.ts GIVE_UP_AFTER_ATTEMPTS. +// rpc-client.ts GIVE_UP_AFTER_ATTEMPTS (past which the loop slows +// to a 90s trickle instead of parking). // - STALE_SINCE_LAST_CONNECT_MS: 60s → if we WERE connected this // session but haven't been for ≥ 1 minute despite the retry loop // spinning, treat the same as never-connected. Catches the case @@ -20,10 +22,21 @@ const WARNING_ATTEMPTS = 3 const UNREACHABLE_ATTEMPTS = 12 const STALE_SINCE_LAST_CONNECT_MS = 60_000 +// Why: a repeatedly-unreachable 100.x/*.ts.net endpoint almost always means +// the phone's Tailscale tunnel is down or wedged (a known iOS failure mode +// that only a manual toggle fixes) — not that the desktop moved. Say so +// instead of leaving the user staring at a generic "Can't connect". +const TAILSCALE_HINT = 'check Tailscale' + export type ConnectionVerdict = | { kind: 'normal'; label: string } - | { kind: 'warning'; label: string } // "Can't connect" - | { kind: 'unreachable'; label: string; reason: 'never-connected' | 'stale' } + | { kind: 'warning'; label: string; hint?: string } // "Can't connect" + | { + kind: 'unreachable' + label: string + reason: 'never-connected' | 'stale' + hint?: string + } | { kind: 'auth-failed'; label: string } // Why: the rpc-client's lastConnectedAt is a one-shot timestamp; we have @@ -33,10 +46,14 @@ export function classifyConnection(args: { state: ConnectionState reconnectAttempts: number lastConnectedAt: number | null + // Optional pinned host endpoint — enables the Tailscale hint on + // warning/unreachable verdicts. Callers without it get plain labels. + endpoint?: string | null nowMs?: number }): ConnectionVerdict { const { state, reconnectAttempts, lastConnectedAt } = args const now = args.nowMs ?? Date.now() + const hint = isTailscaleEndpoint(args.endpoint) ? TAILSCALE_HINT : undefined if (state === 'auth-failed') { return { kind: 'auth-failed', label: 'Auth failed' } @@ -60,21 +77,32 @@ export function classifyConnection(args: { return { kind: 'unreachable', label: "Can't reach desktop", - reason: 'never-connected' + reason: 'never-connected', + hint } } if (now - lastConnectedAt >= STALE_SINCE_LAST_CONNECT_MS) { return { kind: 'unreachable', label: "Can't reach desktop", - reason: 'stale' + reason: 'stale', + hint } } } if (reconnectAttempts >= WARNING_ATTEMPTS) { - return { kind: 'warning', label: "Can't connect" } + return { kind: 'warning', label: "Can't connect", hint } } return { kind: 'normal', label: 'Reconnecting…' } } + +// Why: single place that turns a verdict into display text so every screen +// renders the Tailscale hint the same way. +export function verdictDisplayLabel(verdict: ConnectionVerdict): string { + if ((verdict.kind === 'warning' || verdict.kind === 'unreachable') && verdict.hint) { + return `${verdict.label} — ${verdict.hint}` + } + return verdict.label +} diff --git a/mobile/src/transport/connection-log-buffer.test.ts b/mobile/src/transport/connection-log-buffer.test.ts new file mode 100644 index 000000000000..e7ce662534b3 --- /dev/null +++ b/mobile/src/transport/connection-log-buffer.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it, vi } from 'vitest' +import { createConnectionLogStore } from './connection-log-buffer' +import type { ConnectionLogEntry } from './types' + +function entry(id: number): ConnectionLogEntry { + return { id: `log-${id}`, ts: 1_000 + id, level: 'info', message: `event ${id}` } +} + +describe('connection log buffer', () => { + it('keeps entries per host without cross-talk', () => { + const store = createConnectionLogStore() + store.append('host-a', entry(1)) + store.append('host-b', entry(2)) + + expect(store.get('host-a').map((e) => e.id)).toEqual(['log-1']) + expect(store.get('host-b').map((e) => e.id)).toEqual(['log-2']) + }) + + it('drops the oldest entries past the cap', () => { + const store = createConnectionLogStore(3) + for (let i = 1; i <= 5; i++) { + store.append('host-a', entry(i)) + } + + expect(store.get('host-a').map((e) => e.id)).toEqual(['log-3', 'log-4', 'log-5']) + }) + + it('returns a stable snapshot reference until the next append', () => { + const store = createConnectionLogStore() + store.append('host-a', entry(1)) + + const first = store.get('host-a') + expect(store.get('host-a')).toBe(first) + + store.append('host-a', entry(2)) + expect(store.get('host-a')).not.toBe(first) + // Empty hosts must also be referentially stable (useSyncExternalStore). + expect(store.get('host-b')).toBe(store.get('host-b')) + }) + + it('notifies only the host being appended to and stops after unsubscribe', () => { + const store = createConnectionLogStore() + const onA = vi.fn() + const onB = vi.fn() + const unsubA = store.subscribe('host-a', onA) + store.subscribe('host-b', onB) + + store.append('host-a', entry(1)) + expect(onA).toHaveBeenCalledTimes(1) + expect(onB).not.toHaveBeenCalled() + + unsubA() + store.append('host-a', entry(2)) + expect(onA).toHaveBeenCalledTimes(1) + }) +}) diff --git a/mobile/src/transport/connection-log-buffer.ts b/mobile/src/transport/connection-log-buffer.ts new file mode 100644 index 000000000000..1b223ad8e1fe --- /dev/null +++ b/mobile/src/transport/connection-log-buffer.ts @@ -0,0 +1,84 @@ +import type { ConnectionLogEntry } from './types' + +// Why: the rpc-client's onLog entries were only wired during pairing; for +// long-lived host connections everything went to console.log, invisible to +// users. This buffer retains the recent lifecycle events per host so a +// "Connection log" screen (and copy-diagnostics) can show why a connection +// is stuck without a debug build. Module-level so the log survives client +// swaps (forceReconnect) and provider remounts (hot reload); bounded so an +// all-night reconnect loop can't grow memory unbounded. +const MAX_ENTRIES_PER_HOST = 200 + +export type ConnectionLogStore = { + append: (hostId: string, entry: ConnectionLogEntry) => void + get: (hostId: string) => readonly ConnectionLogEntry[] + subscribe: (hostId: string, listener: () => void) => () => void +} + +export function createConnectionLogStore( + maxEntriesPerHost: number = MAX_ENTRIES_PER_HOST +): ConnectionLogStore { + const entriesByHost = new Map() + const listenersByHost = new Map void>>() + // Why: useSyncExternalStore compares snapshots by reference — getSnapshot + // must return the SAME array until the data actually changes, or React + // loops re-rendering. Cache per host; invalidate on append. + const snapshotByHost = new Map() + const EMPTY: readonly ConnectionLogEntry[] = [] + + return { + append(hostId, entry) { + let entries = entriesByHost.get(hostId) + if (!entries) { + entries = [] + entriesByHost.set(hostId, entries) + } + entries.push(entry) + if (entries.length > maxEntriesPerHost) { + entries.splice(0, entries.length - maxEntriesPerHost) + } + snapshotByHost.delete(hostId) + const listeners = listenersByHost.get(hostId) + if (listeners) { + for (const listener of listeners) { + listener() + } + } + }, + + get(hostId) { + const cached = snapshotByHost.get(hostId) + if (cached) { + return cached + } + const entries = entriesByHost.get(hostId) + if (!entries || entries.length === 0) { + return EMPTY + } + const snapshot = Object.freeze([...entries]) + snapshotByHost.set(hostId, snapshot) + return snapshot + }, + + subscribe(hostId, listener) { + let listeners = listenersByHost.get(hostId) + if (!listeners) { + listeners = new Set() + listenersByHost.set(hostId, listeners) + } + listeners.add(listener) + return () => { + const set = listenersByHost.get(hostId) + if (!set) { + return + } + set.delete(listener) + if (set.size === 0) { + listenersByHost.delete(hostId) + } + } + } + } +} + +export const connectionLogStore = createConnectionLogStore() diff --git a/mobile/src/transport/rpc-client.test.ts b/mobile/src/transport/rpc-client.test.ts index e096ee659c97..b2adb18c4cea 100644 --- a/mobile/src/transport/rpc-client.test.ts +++ b/mobile/src/transport/rpc-client.test.ts @@ -618,28 +618,42 @@ describe('mobile rpc-client connection timeout', () => { return { client, socket } } - it('repro: a parked reconnect loop never retries on its own', async () => { + // Why 520_000ms: the 12 fast attempts cost Σ(RECONNECT_DELAYS) 360.5s of + // backoff plus 13 × 12s connect timeouts ≈ 516.5s, so 520s lands just + // past the give-up cap with the first trickle timer armed. + const PAST_GIVE_UP_CAP_MS = 520_000 + + it('keeps trickle-retrying after the give-up cap instead of parking', async () => { const client = connect('ws://desktop.invalid', 'token', 'server-key') openAndAuthenticate(mockSockets[0]!) mockSockets[0]!.close() - await vi.runAllTimersAsync() + await vi.advanceTimersByTimeAsync(PAST_GIVE_UP_CAP_MS) expect(client.getState()).toBe('reconnecting') - expect(client.getReconnectAttempt()).toBe(12) + expect(client.getReconnectAttempt()).toBeGreaterThanOrEqual(12) - // Stuck: arbitrary additional time produces no further attempts. + // A wedged VPN produces no revival nudge (issue #7824) — the loop must + // keep dialing on its own at the 90s trickle cadence. const socketsBefore = mockSockets.length - await vi.advanceTimersByTimeAsync(600_000) - expect(mockSockets.length).toBe(socketsBefore) + await vi.advanceTimersByTimeAsync(102_000) + expect(mockSockets.length).toBeGreaterThan(socketsBefore) + + // Once the tunnel heals, a trickle dial restores the session without + // any user action. 75s lands inside the next dial's 12s connect window + // (the prior dial failed mid-advance above, re-arming the 90s timer). + await vi.advanceTimersByTimeAsync(75_000) + openAndAuthenticate(mockSockets[mockSockets.length - 1]!) + expect(client.getState()).toBe('connected') + expect(client.getReconnectAttempt()).toBe(0) client.close() }) - it('restarts a parked reconnect loop on foreground', async () => { + it('restarts a backed-off reconnect loop on foreground without waiting out the trickle', async () => { const client = connect('ws://desktop.invalid', 'token', 'server-key') openAndAuthenticate(mockSockets[0]!) mockSockets[0]!.close() - await vi.runAllTimersAsync() + await vi.advanceTimersByTimeAsync(PAST_GIVE_UP_CAP_MS) expect(client.getReconnectAttempt()).toBe(12) const socketsBefore = mockSockets.length @@ -921,7 +935,7 @@ describe('mobile rpc-client connection timeout', () => { () => null, (error: Error) => error ) - await vi.runAllTimersAsync() + await vi.advanceTimersByTimeAsync(520_000) expect(client.getState()).toBe('reconnecting') expect(client.getReconnectAttempt()).toBe(12) diff --git a/mobile/src/transport/rpc-client.ts b/mobile/src/transport/rpc-client.ts index 2cd484de4b86..b9d0c9902615 100644 --- a/mobile/src/transport/rpc-client.ts +++ b/mobile/src/transport/rpc-client.ts @@ -103,16 +103,22 @@ export type RpcClient = { // time across all 12 attempts is ≈ 6 minutes before the give-up cap // fires (0.5+1+2+4+8+15+30+60+60+60+60+60 ≈ 360s). const RECONNECT_DELAYS = [500, 1000, 2000, 4000, 8000, 15_000, 30_000, 60_000] -// Why: cap auto-retry once we're clearly unreachable for a long time. +// Why: cap fast auto-retry once we're clearly unreachable for a long time. // With the tiered backoff above this is ≈ 6 minutes of continuous -// failure before we stop and surface the re-pair banner. The longer +// failure before the UI surfaces the re-pair banner. The longer // runway tolerates flaky AP-isolation routers and laptop sleep cycles // that briefly drop the LAN path. MUST stay aligned with // connection-health.ts UNREACHABLE_ATTEMPTS so the "unreachable" -// verdict matches the moment the loop actually pauses — if these -// drift the user sees "Reconnecting…" while the loop is silently -// parked. +// verdict matches the moment the loop slows to the trickle cadence. const GIVE_UP_AFTER_ATTEMPTS = 12 +// Why: past the cap the loop must never park permanently. A wedged +// Tailscale/VPN tunnel produces no AppState or network-type transition +// (still Wi-Fi, still "online"), so no revival nudge ever fires — users +// had to toggle Tailscale off/on just to force one. A slow trickle dial +// self-heals once the tunnel recovers while staying cheap: one TCP +// attempt per 90s, foreground-only (iOS/Android suspend JS timers in +// the background). +const TRICKLE_RECONNECT_DELAY_MS = 90_000 // Why: a single `unauthorized`/`e2ee_error` is not proof the pairing is dead. // Issue #5200: a tablet showed "Auth failed" and forced a needless re-pair // while the desktop still listed it as paired with a valid token — a transient @@ -280,9 +286,11 @@ export function connect( if (intentionallyClosed) { return Promise.reject(new Error('Client closed')) } - if (state === 'reconnecting' && reconnectAttempt >= GIVE_UP_AFTER_ATTEMPTS && !reconnectTimer) { - // Why: after the retry cap there is no future state transition to - // release callers waiting before their per-request timeout starts. + if (state === 'reconnecting' && reconnectAttempt >= GIVE_UP_AFTER_ATTEMPTS) { + // Why: past the retry cap the loop only trickles every 90s — callers + // must fail fast rather than hang on a host that's been unreachable + // for minutes. A trickle dial that succeeds flips state to 'connected' + // and later requests go through normally. return Promise.reject(new Error('Connection retry limit reached')) } return new Promise((resolve, reject) => { @@ -773,27 +781,35 @@ export function connect( } function scheduleReconnect() { - // Why: spinning reconnect forever drains battery and floods logs + // Why: spinning fast reconnects forever drains battery and floods logs // when the host is genuinely unreachable (wrong IP, port closed, - // host moved). Cap at GIVE_UP_AFTER_ATTEMPTS — the UI surfaces a - // "Can't reach desktop, re-pair?" banner at this point and the - // user can tap Retry (forceReconnect creates a fresh client, - // resetting the counter) or Re-pair. Without an explicit cap the - // worst-case is a phone left on the home screen burning a socket - // open every 4s indefinitely. - if (reconnectAttempt >= GIVE_UP_AFTER_ATTEMPTS) { - console.log('[net] reconnect-paused', { - attempt: reconnectAttempt, - reason: 'give-up-cap', - endpoint: redactedEndpoint(endpoint) - }) + // host moved). Past GIVE_UP_AFTER_ATTEMPTS the UI surfaces a + // "Can't reach desktop, re-pair?" banner and the loop drops to the + // 90s trickle cadence instead of parking — a permanently parked loop + // could only be revived by an AppState/network transition, which a + // wedged VPN tunnel never produces. + const pastGiveUpCap = reconnectAttempt >= GIVE_UP_AFTER_ATTEMPTS + let delay: number + if (pastGiveUpCap) { + // Why: the counter holds at the cap — connection-health thresholds and + // the "Can't reach desktop" verdict key off attempts >= 12, and a + // successful open resets it to 0 anyway. + delay = TRICKLE_RECONNECT_DELAY_MS rejectConnectWaiters('Connection retry limit reached') - return + } else { + delay = RECONNECT_DELAYS[Math.min(reconnectAttempt, RECONNECT_DELAYS.length - 1)]! + reconnectAttempt++ } - const delay = RECONNECT_DELAYS[Math.min(reconnectAttempt, RECONNECT_DELAYS.length - 1)]! - reconnectAttempt++ - console.log('[net] scheduleReconnect', { delayMs: delay, attempt: reconnectAttempt }) - emitLog('info', `Reconnect scheduled in ${delay}ms`, `Attempt ${reconnectAttempt}`) + console.log('[net] scheduleReconnect', { + delayMs: delay, + attempt: reconnectAttempt, + trickle: pastGiveUpCap + }) + emitLog( + 'info', + `Reconnect scheduled in ${delay}ms`, + pastGiveUpCap ? `Attempt ${reconnectAttempt} (slow retry)` : `Attempt ${reconnectAttempt}` + ) reconnectTimer = setTimeout(() => { reconnectTimer = null openConnection() @@ -1176,10 +1192,10 @@ export function connect( return } if (state === 'reconnecting') { - // Why: while backgrounded the retry loop may have parked at the - // give-up cap or be sitting on a 60s backoff timer. Returning to - // the foreground is a strong user signal — restart with a fresh - // attempt budget immediately instead of requiring an app restart. + // Why: while backgrounded the retry loop may be sitting on a 60s + // backoff or 90s trickle timer. Returning to the foreground is a + // strong user signal — restart with a fresh attempt budget + // immediately instead of waiting out the timer. console.log('[net] foreground — restarting reconnect loop', { attempt: reconnectAttempt, hadTimer: !!reconnectTimer diff --git a/mobile/src/transport/rpc-response-shape.test.ts b/mobile/src/transport/rpc-response-shape.test.ts index 52ae58e621d4..29a23d49cf9f 100644 --- a/mobile/src/transport/rpc-response-shape.test.ts +++ b/mobile/src/transport/rpc-response-shape.test.ts @@ -17,4 +17,23 @@ describe('isRpcResponse', () => { ).toBe(true) expect(isRpcResponse({ id: 'rpc-1', ok: false, error: { code: 'failed' } })).toBe(false) }) + + it('accepts additive future fields without weakening known-field validation', () => { + expect( + isRpcResponse({ + id: 'rpc-1', + ok: true, + result: { value: 1 }, + futureEnvelopeField: true + }) + ).toBe(true) + expect( + isRpcResponse({ + id: 'rpc-1', + ok: false, + error: { code: 500, message: 'Nope', futureErrorField: true }, + futureEnvelopeField: true + }) + ).toBe(false) + }) }) diff --git a/mobile/src/worktree/mobile-workspace-lineage.test.ts b/mobile/src/worktree/mobile-workspace-lineage.test.ts index f32219da431f..f844593e371e 100644 --- a/mobile/src/worktree/mobile-workspace-lineage.test.ts +++ b/mobile/src/worktree/mobile-workspace-lineage.test.ts @@ -25,11 +25,18 @@ function worktree(overrides: Partial = {}): Worktree { describe('applyMobileWorkspaceLineage', () => { it('places visible children directly under their parent', () => { - const parent = worktree({ worktreeId: 'parent', displayName: 'parent' }) + const parent = worktree({ + worktreeId: 'parent', + displayName: 'parent', + worktreeInstanceId: 'parent-instance' + }) const child = worktree({ worktreeId: 'child', displayName: 'child', - parentWorktreeId: 'parent' + parentWorktreeId: 'parent', + worktreeInstanceId: 'child-instance', + lineageWorktreeInstanceId: 'child-instance', + parentWorktreeInstanceId: 'parent-instance' }) const rows = applyMobileWorkspaceLineage([child, parent]) @@ -61,6 +68,31 @@ describe('applyMobileWorkspaceLineage', () => { expect(rows[0]?.lineageCollapsed).toBe(true) }) + it('keeps legacy host lineage nesting when instance ids are unavailable', () => { + const parent = worktree({ worktreeId: 'parent' }) + const child = worktree({ worktreeId: 'child', parentWorktreeId: 'parent' }) + + const rows = applyMobileWorkspaceLineage([child, parent]) + + expect(rows.map((row) => row.worktreeId)).toEqual(['parent', 'child']) + }) + + it('does not nest stale lineage when instance ids no longer match', () => { + const parent = worktree({ worktreeId: 'parent', worktreeInstanceId: 'new-parent-instance' }) + const child = worktree({ + worktreeId: 'child', + parentWorktreeId: 'parent', + worktreeInstanceId: 'child-instance', + lineageWorktreeInstanceId: 'child-instance', + parentWorktreeInstanceId: 'old-parent-instance' + }) + + const rows = applyMobileWorkspaceLineage([child, parent]) + + expect(rows.map((row) => row.worktreeId)).toEqual(['child', 'parent']) + expect(rows.map((row) => row.lineageDepth)).toEqual([0, 0]) + }) + it('keeps rows visible when lineage is cyclic', () => { const first = worktree({ worktreeId: 'first', parentWorktreeId: 'second' }) const second = worktree({ worktreeId: 'second', parentWorktreeId: 'first' }) diff --git a/mobile/src/worktree/mobile-workspace-lineage.ts b/mobile/src/worktree/mobile-workspace-lineage.ts index b28b7395928b..bdf1ae2d8a1a 100644 --- a/mobile/src/worktree/mobile-workspace-lineage.ts +++ b/mobile/src/worktree/mobile-workspace-lineage.ts @@ -4,17 +4,40 @@ export function getMobileWorkspaceLineageGroupKey(worktreeId: string): string { return `workspace-lineage:${encodeURIComponent(worktreeId)}` } +function hasValidLineageParent(worktree: Worktree, parent: Worktree): boolean { + if ( + worktree.lineageWorktreeInstanceId === undefined && + worktree.parentWorktreeInstanceId === undefined + ) { + return true + } + // Why: desktop rejects stale lineage when a path is reused by a new workspace + // instance; mobile needs the same guard before nesting parent/child rows. + return ( + worktree.worktreeInstanceId === worktree.lineageWorktreeInstanceId && + parent.worktreeInstanceId === worktree.parentWorktreeInstanceId + ) +} + export function applyMobileWorkspaceLineage( worktrees: readonly Worktree[], collapsedGroups: ReadonlySet = new Set() ): Worktree[] { const visibleIds = new Set(worktrees.map((worktree) => worktree.worktreeId)) + const worktreeById = new Map(worktrees.map((worktree) => [worktree.worktreeId, worktree])) const childrenByParentId = new Map() const childIds = new Set() for (const worktree of worktrees) { const parentId = worktree.parentWorktreeId - if (!parentId || parentId === worktree.worktreeId || !visibleIds.has(parentId)) { + const parent = parentId ? worktreeById.get(parentId) : undefined + if ( + !parentId || + parentId === worktree.worktreeId || + !visibleIds.has(parentId) || + !parent || + !hasValidLineageParent(worktree, parent) + ) { continue } childIds.add(worktree.worktreeId) diff --git a/mobile/src/worktree/workspace-list-ordering.ts b/mobile/src/worktree/workspace-list-ordering.ts new file mode 100644 index 000000000000..4654c6091e52 --- /dev/null +++ b/mobile/src/worktree/workspace-list-ordering.ts @@ -0,0 +1,124 @@ +import type { Worktree } from './workspace-list-types' +import type { MobileSortMode } from './workspace-view-settings' + +export const CREATE_GRACE_MS = 5 * 60 * 1000 + +function getManualSortRank(worktree: Worktree): number | null { + const rank = worktree.manualOrder ?? worktree.sortOrder + return typeof rank === 'number' && Number.isFinite(rank) ? rank : null +} + +function compareDisplayName(a: Worktree, b: Worktree): number { + return a.displayName.localeCompare(b.displayName) +} + +function getRecentActivity(worktree: Worktree): number { + const lastActivityAt = worktree.lastActivityAt ?? 0 + const lastOutputAt = worktree.lastOutputAt ?? 0 + // Why: headless serve hosts only stamp lastActivityAt at creation, so live + // terminal output must still count as recency for mobile-only pairings. + return Math.max( + Number.isFinite(lastActivityAt) ? lastActivityAt : 0, + Number.isFinite(lastOutputAt) ? lastOutputAt : 0 + ) +} + +function effectiveRecentActivity(worktree: Worktree, now: number): number { + const lastActivityAt = getRecentActivity(worktree) + const { createdAt } = worktree + if ( + createdAt === undefined || + !Number.isFinite(createdAt) || + now >= createdAt + CREATE_GRACE_MS + ) { + return lastActivityAt + } + return Math.max(lastActivityAt, createdAt + CREATE_GRACE_MS) +} + +function compareByRecent(a: Worktree, b: Worktree, now: number): number { + return ( + effectiveRecentActivity(b, now) - effectiveRecentActivity(a, now) || compareDisplayName(a, b) + ) +} + +const AGENT_ATTENTION_STATUS_ORDER = { permission: 0, working: 1, done: 2, active: 3, inactive: 4 } + +function compareByAgentAttention(a: Worktree, b: Worktree, now: number): number { + return ( + AGENT_ATTENTION_STATUS_ORDER[getWorktreeStatus(a)] - + AGENT_ATTENTION_STATUS_ORDER[getWorktreeStatus(b)] || compareByRecent(a, b, now) + ) +} + +export function sortWorktrees( + worktrees: Worktree[], + mode: MobileSortMode, + now = Date.now() +): Worktree[] { + if (mode === 'manual') { + return [...worktrees].sort((a, b) => { + const aRank = getManualSortRank(a) + const bRank = getManualSortRank(b) + if (aRank !== null && bRank !== null && aRank !== bRank) { + // Why: desktop assigns higher sort/manual ranks to earlier list positions. + return bRank - aRank + } + if (aRank !== null && bRank === null) { + return -1 + } + if (aRank === null && bRank !== null) { + return 1 + } + return compareDisplayName(a, b) + }) + } + return [...worktrees].sort((a, b) => { + if (mode === 'name') { + return compareDisplayName(a, b) + } + if (mode === 'recent') { + return compareByRecent(a, b, now) + } + if (mode === 'repo') { + const repoComparison = a.repo.localeCompare(b.repo) + return repoComparison || compareDisplayName(a, b) + } + const aRank = typeof a.sortOrder === 'number' && Number.isFinite(a.sortOrder) ? a.sortOrder : 0 + const bRank = typeof b.sortOrder === 'number' && Number.isFinite(b.sortOrder) ? b.sortOrder : 0 + if (aRank !== bRank) { + // Why: desktop persists its computed Agent activity order into sortOrder; + // mobile should render that source-of-truth before local fallback signals. + return bRank - aRank + } + if (aRank === 0) { + // Why: headless serve hosts never persist desktop smart ranks; unranked + // rows fall back to agent attention order instead of a frozen A-Z list. + return compareByAgentAttention(a, b, now) + } + return compareDisplayName(a, b) + }) +} + +export function getWorktreeStatus( + w: Worktree +): 'working' | 'active' | 'permission' | 'done' | 'inactive' { + // Why: desktop's sidebar activity is the parity source. Runtime status may + // still report retained/background PTYs as active after desktop hides them. + if (w.hasHostSidebarActivity === false) { + return 'inactive' + } + if (w.status && w.status !== 'inactive') { + return w.status + } + if (w.hasHostSidebarActivity === true) { + return 'active' + } + if (w.status) { + return w.status + } + if (w.liveTerminalCount > 0) { + return 'active' + } + return 'inactive' +} diff --git a/mobile/src/worktree/workspace-list-sections.test.ts b/mobile/src/worktree/workspace-list-sections.test.ts index e6de6d8f4665..d6d04d43d3e2 100644 --- a/mobile/src/worktree/workspace-list-sections.test.ts +++ b/mobile/src/worktree/workspace-list-sections.test.ts @@ -1,7 +1,13 @@ import { join } from 'node:path' import { describe, expect, it } from 'vitest' import type { Worktree } from './workspace-list-sections' -import { buildSections, filterWorktrees, getWorktreeStatus } from './workspace-list-sections' +import { + CREATE_GRACE_MS, + buildSections, + filterWorktrees, + getWorktreeStatus, + sortWorktrees +} from './workspace-list-sections' import { DEFAULT_MOBILE_WORKSPACE_STATUSES } from './mobile-workspace-statuses' function worktree(overrides: Partial = {}): Worktree { @@ -145,6 +151,16 @@ describe('getWorktreeStatus', () => { }) describe('buildSections', () => { + it('matches desktop Name sort by display name', () => { + const beta = worktree({ worktreeId: 'beta', displayName: 'Beta', repo: 'aaa' }) + const alpha = worktree({ worktreeId: 'alpha', displayName: 'Alpha', repo: 'zzz' }) + + expect(sortWorktrees([beta, alpha], 'name').map((item) => item.worktreeId)).toEqual([ + 'alpha', + 'beta' + ]) + }) + it('uses desktop manual order ranks in Manual sort mode', () => { const low = worktree({ worktreeId: 'low', displayName: 'low', manualOrder: 10 }) const high = worktree({ worktreeId: 'high', displayName: 'high', manualOrder: 30 }) @@ -168,6 +184,264 @@ describe('buildSections', () => { ]) }) + it('uses desktop display-name tie-breaks in Manual sort mode', () => { + const zed = worktree({ worktreeId: 'zed', displayName: 'Zed', manualOrder: 10 }) + const alpha = worktree({ worktreeId: 'alpha', displayName: 'Alpha', manualOrder: 10 }) + + expect(sortWorktrees([zed, alpha], 'manual').map((item) => item.worktreeId)).toEqual([ + 'alpha', + 'zed' + ]) + }) + + it('uses desktop-persisted smart order before mobile fallback signals', () => { + const desktopFirst = worktree({ + worktreeId: 'desktop-first', + displayName: 'desktop-first', + sortOrder: 30, + status: 'inactive', + unread: false, + lastOutputAt: 1 + }) + const mobileFallbackFirst = worktree({ + worktreeId: 'mobile-fallback-first', + displayName: 'mobile-fallback-first', + sortOrder: 10, + status: 'working', + unread: true, + lastOutputAt: 100 + }) + + const sections = buildSections( + [mobileFallbackFirst, desktopFirst], + 'smart', + { filterRepoIds: new Set(), hideSleeping: false, hideDefaultBranch: false }, + '', + 'workspaceStatus', + new Set(), + new Map(), + DEFAULT_MOBILE_WORKSPACE_STATUSES + ) + + expect(sections.flatMap((section) => section.data.map((item) => item.worktreeId))).toEqual([ + 'desktop-first', + 'mobile-fallback-first' + ]) + }) + + it('uses desktop display-name tie-breaks for equal persisted smart ranks', () => { + const zed = worktree({ worktreeId: 'zed', displayName: 'Zed', sortOrder: 20, unread: true }) + const alpha = worktree({ + worktreeId: 'alpha', + displayName: 'Alpha', + sortOrder: 20, + status: 'working', + lastOutputAt: 100 + }) + + expect(sortWorktrees([zed, alpha], 'smart').map((item) => item.worktreeId)).toEqual([ + 'alpha', + 'zed' + ]) + }) + + it('counts live terminal output as Recent activity for headless serve hosts', () => { + // Serve hosts only stamp lastActivityAt at creation, so output must rank. + const streamingOnServe = worktree({ + worktreeId: 'streaming', + displayName: 'streaming', + lastActivityAt: 100, + lastOutputAt: 1_000 + }) + const touchedOnDesktop = worktree({ + worktreeId: 'touched', + displayName: 'touched', + lastActivityAt: 200, + lastOutputAt: 1 + }) + + expect( + sortWorktrees([touchedOnDesktop, streamingOnServe], 'recent').map((item) => item.worktreeId) + ).toEqual(['streaming', 'touched']) + }) + + it('keeps desktop activity ranking in Recent when it is newest', () => { + const newerActivity = worktree({ + worktreeId: 'newer-activity', + displayName: 'newer', + lastActivityAt: 2_000, + lastOutputAt: 1 + }) + const quietOlder = worktree({ + worktreeId: 'quiet-older', + displayName: 'quiet', + lastActivityAt: 100, + lastOutputAt: 150 + }) + + expect( + sortWorktrees([quietOlder, newerActivity], 'recent').map((item) => item.worktreeId) + ).toEqual(['newer-activity', 'quiet-older']) + }) + + it('falls back to agent attention order in Smart when no desktop ranks exist', () => { + // Display names are deliberately reverse-alphabetical to prove status ranks. + const idle = worktree({ worktreeId: 'idle', displayName: 'Aardvark' }) + const needsPermission = worktree({ + worktreeId: 'needs-permission', + displayName: 'Zebra', + status: 'permission' + }) + const working = worktree({ worktreeId: 'working', displayName: 'Yak', status: 'working' }) + + expect( + sortWorktrees([idle, working, needsPermission], 'smart').map((item) => item.worktreeId) + ).toEqual(['needs-permission', 'working', 'idle']) + }) + + it('keeps desktop-ranked rows above unranked attention-fallback rows in Smart', () => { + const ranked = worktree({ worktreeId: 'ranked', displayName: 'Ranked', sortOrder: 5 }) + const unrankedWorking = worktree({ + worktreeId: 'unranked-working', + displayName: 'Working', + status: 'working' + }) + + expect( + sortWorktrees([unrankedWorking, ranked], 'smart').map((item) => item.worktreeId) + ).toEqual(['ranked', 'unranked-working']) + }) + + it('matches desktop Recent create grace for newly-created workspaces', () => { + const now = 10_000 + const created = worktree({ + worktreeId: 'created', + displayName: 'created', + lastActivityAt: 100, + createdAt: now - 1_000 + }) + const active = worktree({ + worktreeId: 'active', + displayName: 'active', + lastActivityAt: now + CREATE_GRACE_MS - 2_000 + }) + + expect(sortWorktrees([active, created], 'recent', now).map((item) => item.worktreeId)).toEqual([ + 'created', + 'active' + ]) + }) + + it('matches desktop Repo sort by repo display name then workspace display name', () => { + const betaAlpha = worktree({ + worktreeId: 'beta-alpha', + repo: 'Beta Repo', + displayName: 'Alpha' + }) + const alphaZed = worktree({ + worktreeId: 'alpha-zed', + repo: 'Alpha Repo', + displayName: 'Zed' + }) + const betaBravo = worktree({ + worktreeId: 'beta-bravo', + repo: 'Beta Repo', + displayName: 'Bravo' + }) + + expect( + sortWorktrees([betaBravo, betaAlpha, alphaZed], 'repo').map((item) => item.worktreeId) + ).toEqual(['alpha-zed', 'beta-alpha', 'beta-bravo']) + }) + + it('uses desktop localeCompare semantics for Repo sort names', () => { + const accentRepo = worktree({ + worktreeId: 'accent-repo', + repo: 'áb repo', + displayName: 'Alpha' + }) + const plainRepo = worktree({ + worktreeId: 'plain-repo', + repo: 'ab repo', + displayName: 'Zed' + }) + + expect(sortWorktrees([accentRepo, plainRepo], 'repo').map((item) => item.worktreeId)).toEqual([ + 'plain-repo', + 'accent-repo' + ]) + }) + + it('keeps a desktop-ranked parent and child stack above unrelated active rows', () => { + const parent = worktree({ + worktreeId: 'parent', + displayName: 'Add agents to mobile', + repo: 'orca', + sortOrder: 30, + status: 'inactive' + }) + const child = worktree({ + worktreeId: 'child', + displayName: 'Agent Session History resume (PR2)', + repo: 'orca', + parentWorktreeId: 'parent', + sortOrder: 20, + status: 'inactive' + }) + const unrelatedActive = worktree({ + worktreeId: 'active', + displayName: 'Overlapping tui output', + repo: 'orca', + sortOrder: 10, + status: 'working', + unread: true, + lastOutputAt: 100 + }) + + const sections = buildSections( + [unrelatedActive, child, parent], + 'smart', + { filterRepoIds: new Set(), hideSleeping: false, hideDefaultBranch: false }, + '', + 'repo', + new Set(), + new Map([['orca', 'repo-1']]), + DEFAULT_MOBILE_WORKSPACE_STATUSES + ) + + expect(sections[0]?.data.map((item) => item.worktreeId)).toEqual(['parent', 'child', 'active']) + expect(sections[0]?.data.map((item) => item.lineageDepth)).toEqual([0, 1, 0]) + }) + + it('keeps the main workspace first inside repo-grouped sections like desktop', () => { + const child = worktree({ + worktreeId: 'child', + displayName: 'Child', + repo: 'orca', + sortOrder: 30, + isMainWorktree: false + }) + const main = worktree({ + worktreeId: 'main', + displayName: 'Main', + repo: 'orca', + sortOrder: 10, + isMainWorktree: true + }) + + const sections = buildSections( + [child, main], + 'smart', + { filterRepoIds: new Set(), hideSleeping: false, hideDefaultBranch: false }, + '', + 'repo', + new Set(), + new Map([['orca', 'repo-1']]) + ) + + expect(sections[0]?.data.map((item) => item.worktreeId)).toEqual(['main', 'child']) + }) + it('renders empty repo sections from repo placeholders in repo grouping', () => { const sections = buildSections( [worktree({ repoId: 'repo-1', repo: 'orca' })], @@ -307,7 +581,7 @@ describe('buildSections', () => { expect(sections[0]?.data.map((worktree) => worktree.worktreeId)).toEqual(['progress']) }) - it('does not duplicate pinned worktrees in their canonical status group', () => { + it('keeps pinned worktrees in their canonical status group like desktop', () => { const pinned = worktree({ worktreeId: 'pinned', workspaceStatus: 'in-progress', @@ -326,7 +600,40 @@ describe('buildSections', () => { ) expect(withoutSectionListKeys(sections)).toEqual([ - { key: 'pinned', title: 'Pinned', icon: 'pin', data: [pinned] } + { key: 'pinned', title: 'Pinned', icon: 'pin', data: [pinned] }, + { key: 'workspace-status:in-progress', title: 'In progress', data: [pinned] } + ]) + }) + + it('renders one sorted All section when grouping is off like desktop', () => { + const inactiveFirst = worktree({ + worktreeId: 'inactive-first', + displayName: 'inactive-first', + manualOrder: 30, + status: 'inactive' + }) + const activeSecond = worktree({ + worktreeId: 'active-second', + displayName: 'active-second', + manualOrder: 10, + status: 'working' + }) + + const sections = buildSections( + [activeSecond, inactiveFirst], + 'manual', + { filterRepoIds: new Set(), hideSleeping: false, hideDefaultBranch: false }, + '', + 'none', + new Set(), + new Map(), + DEFAULT_MOBILE_WORKSPACE_STATUSES + ) + + expect(sections.map((section) => section.key)).toEqual(['all']) + expect(sections[0]?.data.map((worktree) => worktree.worktreeId)).toEqual([ + 'inactive-first', + 'active-second' ]) }) diff --git a/mobile/src/worktree/workspace-list-sections.ts b/mobile/src/worktree/workspace-list-sections.ts index 1691659e9f44..bdb9e4783e3c 100644 --- a/mobile/src/worktree/workspace-list-sections.ts +++ b/mobile/src/worktree/workspace-list-sections.ts @@ -9,8 +9,10 @@ import { applyMobileWorkspaceLineage } from './mobile-workspace-lineage' import { getPRGroupKey, PR_GROUP_LABELS, PR_GROUP_ORDER } from './workspace-pr-status-groups' import type { FilterState, Section, Worktree } from './workspace-list-types' import type { MobileGroupMode, MobileSortMode } from './workspace-view-settings' +import { sortWorktrees } from './workspace-list-ordering' export type { FilterState, Section, Worktree } from './workspace-list-types' +export { CREATE_GRACE_MS, getWorktreeStatus, sortWorktrees } from './workspace-list-ordering' function makeSection( key: string, @@ -31,29 +33,6 @@ function makeSection( } } -export function getWorktreeStatus( - w: Worktree -): 'working' | 'active' | 'permission' | 'done' | 'inactive' { - // Why: desktop's sidebar activity is the parity source. Runtime status may - // still report retained/background PTYs as active after desktop hides them. - if (w.hasHostSidebarActivity === false) { - return 'inactive' - } - if (w.status && w.status !== 'inactive') { - return w.status - } - if (w.hasHostSidebarActivity === true) { - return 'active' - } - if (w.status) { - return w.status - } - if (w.liveTerminalCount > 0) { - return 'active' - } - return 'inactive' -} - // Why: the previous 10-minute lastOutputAt window was too strict — most // worktrees with idle terminal prompts had no recent output and were excluded. // Any worktree with live terminals or unread output counts as "active". @@ -86,54 +65,12 @@ function isDefaultBranchWorkspace(w: Worktree): boolean { return branch === 'main' || branch === 'master' } -function getManualSortRank(worktree: Worktree): number | null { - const rank = worktree.manualOrder ?? worktree.sortOrder - return typeof rank === 'number' && Number.isFinite(rank) ? rank : null -} - -export function sortWorktrees(worktrees: Worktree[], mode: MobileSortMode): Worktree[] { - if (mode === 'manual') { - return [...worktrees].sort((a, b) => { - const aRank = getManualSortRank(a) - const bRank = getManualSortRank(b) - if (aRank !== null && bRank !== null && aRank !== bRank) { - // Why: desktop assigns higher sort/manual ranks to earlier list positions. - return bRank - aRank - } - if (aRank !== null && bRank === null) { - return -1 - } - if (aRank === null && bRank !== null) { - return 1 - } - return 0 - }) +function orderMainWorktreeFirst(worktrees: Worktree[]): Worktree[] { + const mainWorktrees = worktrees.filter((worktree) => worktree.isMainWorktree) + if (mainWorktrees.length === 0) { + return worktrees } - return [...worktrees].sort((a, b) => { - if (mode === 'name') { - return (a.displayName || a.repo).localeCompare(b.displayName || b.repo) - } - if (mode === 'recent') { - return (b.lastOutputAt ?? 0) - (a.lastOutputAt ?? 0) - } - if (mode === 'repo') { - const repoComparison = a.repo.localeCompare(b.repo, undefined, { sensitivity: 'base' }) - return repoComparison || (a.displayName || a.repo).localeCompare(b.displayName || b.repo) - } - if (a.unread !== b.unread) { - return a.unread ? -1 : 1 - } - const aStatus = getWorktreeStatus(a) - const bStatus = getWorktreeStatus(b) - const statusOrder = { permission: 0, working: 1, done: 2, active: 3, inactive: 4 } - if (statusOrder[aStatus] !== statusOrder[bStatus]) { - return statusOrder[aStatus] - statusOrder[bStatus] - } - if ((a.lastOutputAt ?? 0) !== (b.lastOutputAt ?? 0)) { - return (b.lastOutputAt ?? 0) - (a.lastOutputAt ?? 0) - } - return (a.displayName || a.repo).localeCompare(b.displayName || b.repo) - }) + return [...mainWorktrees, ...worktrees.filter((worktree) => !worktree.isMainWorktree)] } export function filterWorktrees( @@ -155,7 +92,7 @@ export function filterWorktrees( const q = search.toLowerCase() result = result.filter( (w) => - (w.displayName || w.repo).toLowerCase().includes(q) || + w.displayName.toLowerCase().includes(q) || w.branch.toLowerCase().includes(q) || w.repo.toLowerCase().includes(q) ) @@ -182,12 +119,9 @@ export function buildSections( const sorted = sortWorktrees(filtered, sortMode) const pinned = sorted.filter((w) => isWorktreePinned(w, pinnedIds)) - const unpinned = sorted.filter((w) => !isWorktreePinned(w, pinnedIds)) - // Why: mobile shows pinned workspaces once in the pinned section; duplicating - // them in status/project sections makes the phone list harder to scan. - const canonicalGroupWorktrees = unpinned - const active = canonicalGroupWorktrees.filter(isWorktreeActive) - const inactive = canonicalGroupWorktrees.filter((w) => !isWorktreeActive(w)) + // Why: desktop treats Pinned as an overlay. Keeping pinned rows in canonical + // groups preserves exact cross-surface order and literal section counts. + const canonicalGroupWorktrees = sorted const sections: Section[] = [] if (pinned.length > 0) { @@ -195,19 +129,8 @@ export function buildSections( } if (groupMode === 'none') { - if (active.length > 0) { - sections.push(makeSection('all-active', 'Active', active, undefined, collapsedGroups)) - } - if (inactive.length > 0) { - sections.push( - makeSection( - 'all', - pinned.length > 0 || active.length > 0 ? 'All' : '', - inactive, - undefined, - collapsedGroups - ) - ) + if (canonicalGroupWorktrees.length > 0) { + sections.push(makeSection('all', 'All', canonicalGroupWorktrees, undefined, collapsedGroups)) } } else if (groupMode === 'repo') { const byRepo = new Map() @@ -238,7 +161,9 @@ export function buildSections( } for (const [repo, items] of byRepo) { const key = `repo:${repoIdsByName.get(repo) ?? repo}` - sections.push(makeSection(key, repo, items, undefined, collapsedGroups)) + sections.push( + makeSection(key, repo, orderMainWorktreeFirst(items), undefined, collapsedGroups) + ) } } else if (groupMode === 'workspaceStatus') { const renderableWorkspaceStatuses = coerceMobileWorkspaceStatuses(workspaceStatuses) diff --git a/mobile/src/worktree/workspace-list-types.ts b/mobile/src/worktree/workspace-list-types.ts index 8418b2753ad6..4dfbc74fa534 100644 --- a/mobile/src/worktree/workspace-list-types.ts +++ b/mobile/src/worktree/workspace-list-types.ts @@ -1,3 +1,4 @@ +import type { ExecutionHostId } from '../../../src/shared/execution-host' import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' export type Worktree = { @@ -5,18 +6,25 @@ export type Worktree = { workspaceKind?: 'git' | 'folder-workspace' worktreeId: string repoId: string + hostId?: ExecutionHostId + terminalPlatform?: NodeJS.Platform repo: string branch: string displayName: string workspaceStatus?: string sortOrder?: number manualOrder?: number + lastActivityAt?: number + createdAt?: number // Why: on-disk worktree directory path. Needed by NewWorktreeModal so the // marine-creature fallback dedupes against filesystem basenames. path: string isArchived?: boolean isMainWorktree?: boolean hasHostSidebarActivity?: boolean + worktreeInstanceId?: string + lineageWorktreeInstanceId?: string + parentWorktreeInstanceId?: string parentWorktreeId?: string | null childWorktreeIds?: string[] lineageDepth?: number diff --git a/mobile/src/worktree/worktree-activation-result.test.ts b/mobile/src/worktree/worktree-activation-result.test.ts new file mode 100644 index 000000000000..11abc5e69703 --- /dev/null +++ b/mobile/src/worktree/worktree-activation-result.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest' +import { headlessActivationNeedsHostRenderer } from './worktree-activation-result' + +describe('headlessActivationNeedsHostRenderer', () => { + it('only reports the explicit sleeping-agent headless outcome', () => { + expect(headlessActivationNeedsHostRenderer({ sleepingAgentWake: 'unsupported-headless' })).toBe( + true + ) + expect(headlessActivationNeedsHostRenderer({ sleepingAgentWake: 'not-applicable' })).toBe(false) + expect(headlessActivationNeedsHostRenderer({ sleepingAgentWake: 'requested' })).toBe(false) + expect(headlessActivationNeedsHostRenderer(null)).toBe(false) + }) +}) diff --git a/mobile/src/worktree/worktree-activation-result.ts b/mobile/src/worktree/worktree-activation-result.ts new file mode 100644 index 000000000000..101fc2c6cd0f --- /dev/null +++ b/mobile/src/worktree/worktree-activation-result.ts @@ -0,0 +1,8 @@ +export function headlessActivationNeedsHostRenderer(result: unknown): boolean { + return Boolean( + result && + typeof result === 'object' && + 'sleepingAgentWake' in result && + result.sleepingAgentWake === 'unsupported-headless' + ) +} diff --git a/mobile/src/worktree/worktree-list-snapshot.test.ts b/mobile/src/worktree/worktree-list-snapshot.test.ts index 339d5d1c9a33..d6d3af1930cb 100644 --- a/mobile/src/worktree/worktree-list-snapshot.test.ts +++ b/mobile/src/worktree/worktree-list-snapshot.test.ts @@ -96,6 +96,31 @@ describe('areWorktreeListsEqual', () => { ).toBe(false) }) + it('detects desktop ordering field changes', () => { + expect( + areWorktreeListsEqual( + [worktree({ lastActivityAt: 10, createdAt: 1 })], + [worktree({ lastActivityAt: 20, createdAt: 1 })] + ) + ).toBe(false) + expect( + areWorktreeListsEqual( + [worktree({ lastActivityAt: 10, createdAt: 1 })], + [worktree({ lastActivityAt: 10, createdAt: 2 })] + ) + ).toBe(false) + }) + + it('detects resume host and terminal platform changes', () => { + expect(areWorktreeListsEqual([worktree()], [worktree({ hostId: 'ssh:box' })])).toBe(false) + expect( + areWorktreeListsEqual( + [worktree({ terminalPlatform: 'win32' })], + [worktree({ terminalPlatform: 'linux' })] + ) + ).toBe(false) + }) + it('detects lineage changes', () => { const base = worktree({ worktreeId: 'child', parentWorktreeId: 'parent-a' }) const changedParent = worktree({ worktreeId: 'child', parentWorktreeId: 'parent-b' }) @@ -109,6 +134,25 @@ describe('areWorktreeListsEqual', () => { expect(areWorktreeListsEqual([base], [changedChildren])).toBe(false) }) + it('detects lineage instance changes', () => { + const base = worktree({ + worktreeId: 'child', + parentWorktreeId: 'parent', + worktreeInstanceId: 'child-instance', + lineageWorktreeInstanceId: 'child-instance', + parentWorktreeInstanceId: 'parent-instance' + }) + const changedParentInstance = worktree({ + worktreeId: 'child', + parentWorktreeId: 'parent', + worktreeInstanceId: 'child-instance', + lineageWorktreeInstanceId: 'child-instance', + parentWorktreeInstanceId: 'new-parent-instance' + }) + + expect(areWorktreeListsEqual([base], [changedParentInstance])).toBe(false) + }) + it('detects agent status changes', () => { const first = [worktree({ agents: [agent({ state: 'working' })] })] const second = [worktree({ agents: [agent({ state: 'waiting' })] })] diff --git a/mobile/src/worktree/worktree-list-snapshot.ts b/mobile/src/worktree/worktree-list-snapshot.ts index c851bda24d9f..bb9df6cf9afe 100644 --- a/mobile/src/worktree/worktree-list-snapshot.ts +++ b/mobile/src/worktree/worktree-list-snapshot.ts @@ -25,14 +25,21 @@ function areWorktreesEqual(left: Worktree, right: Worktree): boolean { left.repoId === right.repoId && left.repo === right.repo && left.branch === right.branch && + (left.hostId ?? null) === (right.hostId ?? null) && + (left.terminalPlatform ?? null) === (right.terminalPlatform ?? null) && left.displayName === right.displayName && (left.workspaceStatus ?? null) === (right.workspaceStatus ?? null) && (left.sortOrder ?? null) === (right.sortOrder ?? null) && (left.manualOrder ?? null) === (right.manualOrder ?? null) && + (left.lastActivityAt ?? null) === (right.lastActivityAt ?? null) && + (left.createdAt ?? null) === (right.createdAt ?? null) && left.path === right.path && (left.isArchived ?? false) === (right.isArchived ?? false) && (left.isMainWorktree ?? false) === (right.isMainWorktree ?? false) && (left.hasHostSidebarActivity ?? false) === (right.hasHostSidebarActivity ?? false) && + (left.worktreeInstanceId ?? null) === (right.worktreeInstanceId ?? null) && + (left.lineageWorktreeInstanceId ?? null) === (right.lineageWorktreeInstanceId ?? null) && + (left.parentWorktreeInstanceId ?? null) === (right.parentWorktreeInstanceId ?? null) && (left.parentWorktreeId ?? null) === (right.parentWorktreeId ?? null) && areStringArraysEqual(left.childWorktreeIds ?? [], right.childWorktreeIds ?? []) && left.liveTerminalCount === right.liveTerminalCount && diff --git a/mobile/tsconfig.json b/mobile/tsconfig.json index 1e3a42479dc9..754545ed7270 100644 --- a/mobile/tsconfig.json +++ b/mobile/tsconfig.json @@ -1,8 +1,8 @@ { - "extends": "expo/tsconfig.base", + "extends": "expo/tsconfig.base.json", "compilerOptions": { - "baseUrl": ".", "strict": true, + // TypeScript 7 resolves path targets relative to this config without baseUrl. "paths": { "@/*": ["./src/*"], "tweetnacl": ["./node_modules/tweetnacl"], diff --git a/mobile/vitest.config.ts b/mobile/vitest.config.ts index ae56f5bdd2a1..9e7e3ecc59d1 100644 --- a/mobile/vitest.config.ts +++ b/mobile/vitest.config.ts @@ -1,25 +1,12 @@ import { defineConfig } from 'vitest/config' -const tsconfigRaw = JSON.stringify({ - compilerOptions: { - jsx: 'react-jsx', - module: 'esnext', - moduleResolution: 'bundler', - strict: true, - target: 'es2022' - } -}) +const vitestOxcConfig = { tsconfig: false } as never export default defineConfig({ root: import.meta.dirname, - esbuild: { - tsconfigRaw - }, - optimizeDeps: { - esbuildOptions: { - tsconfigRaw - } - }, + // Why: the app tsconfig intentionally excludes tests; Vite 8's OXC transform + // otherwise fails before Vitest can run the test modules. + oxc: vitestOxcConfig, test: { environment: 'node', include: ['src/**/*.test.ts'] diff --git a/native/notification-status-macos/main.swift b/native/notification-status-macos/main.swift new file mode 100644 index 000000000000..fa8c944ec4d9 --- /dev/null +++ b/native/notification-status-macos/main.swift @@ -0,0 +1,35 @@ +// Prints the app's macOS notification settings as JSON and exits. +// +// Why this exists: Electron exposes no API for UNUserNotificationCenter +// authorization, and scheduling silently succeeds even while macOS suppresses +// display, so the renderer cannot know whether the user actually receives +// notifications. This binary must run from inside the app bundle (NSBundle +// resolves the bundle by walking up from the executable path) and must be +// code-signed with the app's identifier — macOS keys notification records to +// the signing identifier, which is why the build embeds an Info.plist section +// with the target CFBundleIdentifier. +import Foundation +import UserNotifications + +let semaphore = DispatchSemaphore(value: 0) +var authorization = "unknown" +var alert = "unknown" +UNUserNotificationCenter.current().getNotificationSettings { settings in + switch settings.authorizationStatus { + case .authorized: authorization = "authorized" + case .provisional: authorization = "provisional" + case .ephemeral: authorization = "ephemeral" + case .denied: authorization = "denied" + case .notDetermined: authorization = "not-determined" + @unknown default: authorization = "unknown" + } + switch settings.alertSetting { + case .enabled: alert = "enabled" + case .disabled: alert = "disabled" + case .notSupported: alert = "not-supported" + @unknown default: alert = "unknown" + } + semaphore.signal() +} +_ = semaphore.wait(timeout: .now() + 3) +print("{\"authorization\":\"\(authorization)\",\"alert\":\"\(alert)\"}") diff --git a/notes/garble-fuzz-divergences.md b/notes/garble-fuzz-divergences.md new file mode 100644 index 000000000000..dde77ac2450d --- /dev/null +++ b/notes/garble-fuzz-divergences.md @@ -0,0 +1,296 @@ +# Garble differential fuzz — divergence log + +Findings from the HeadlessEmulator-vs-renderer-twin differential fuzz +(`src/main/daemon/headless-emulator-fidelity.fuzz.test.ts`). Each divergence is +a case where restoring a hidden terminal from its main-side snapshot +(`serialize → replay`, exactly as `applyMainBufferSnapshot` does on reveal) +produces a screen that differs from an always-visible renderer terminal fed the +same bytes. Any such diff is a user-visible garble on reveal. + +## Method + +- Corpus: seeded agent-TUI byte streams (`buildAgentTuiStreamOps`), 3 pane + sizes, PTY-style random chunk splitting. +- Differential: production `HeadlessEmulator` snapshot replayed into a fresh + renderer-parity terminal, compared cell-by-cell (text, per-cell style, + cursor, modes, scrollback) against an always-visible renderer-parity twin. +- Parity confirmed: `createRendererParityTerminal` mirrors the renderer pane's + buffer-affecting options exactly — `scrollback: 5000`, `allowProposedApi`, + `vtExtensions.kittyKeyboard`, `Unicode11Addon`, Orca ZWJ provider (verified + against `buildDefaultTerminalOptions` in + `src/renderer/src/lib/pane-manager/pane-terminal-options.ts` and + `pane-dom-creation.ts`). Render-only options (`minimumContrastRatio`, + `drawBoldTextInBrightColors`, font, cursor, scrollbar) do not alter stored + cell attributes, so their omission is not a source of false diffs. + `windowsMode` is unset in both (matches renderer). Addon versions: + `@xterm/addon-serialize` / `@xterm/headless` / `@xterm/addon-unicode11` all + `*-beta.287` (headless `6.1.0-beta.287`). +- Scan: seeds 1..2000. Every divergence is either the known serialize-wrap bug + (predicate `bufferHasSerializeHostileWrappedRow`, tolerated + counted) or is + listed below. + +## Inventory + +| bug | found by | seeds | classification | +| --- | --- | --- | --- | +| A — serialize wrap null-cell | fidelity (suite 1) | 31, 157, 171, 207, 423, 426, 502, 801, 815, 826, 865, 881, 923, 977, 1004, 1119, 1142, 1238, 1241, 1318, 1351, 1374, 1532, 1601, 1657, 1728, 1770 (27 in 1..2000) | (a) real serialize bug, pre-documented + pinned — STILL OPEN | +| B — SGR bold loss (`1;22`) | fidelity (suite 1) | 435, 770, 1321 | (a) real serialize bug — FIXED by the addon patch (intensity-group SGR reorder, config/patches) | +| C — cursor off-by-one at right margin | fidelity (suite 1) | 454, 1696 | (a) real serialize bug — FIXED Orca-side (absolute-cursor epilogue, serializeWithAbsoluteCursor) | +| D — DECSC saved-cursor lost across reveal | reconciliation (suite 2) | seed 3 | (a) real snapshot limitation — FIXED (snapshot re-saves the DECSC register, readSavedCursorRegister) | +| E — snapshot boundary mid-escape-sequence | reconciliation (suite 2) | seed 4 (+~24% of corpus) | (a) real snapshot limitation — FIXED (pendingEscapeTailAnsi carried out-of-band, terminal-partial-escape-tail.ts) | + +Status update (fix/snapshot-decsc-midescape): B/C/D/E repros are UNSKIPPED and +their corpus tolerances removed — only Bug A remains tolerated + counted. Bug D +carries position only (saved SGR/charset are not re-established — the synthetic +ESC 7 saves the serializer's final pen). Bug E's pending tail is a separate +snapshot field written LAST by restorers because any later ESC (e.g. the +post-replay reset) would abort the dangling sequence; its bytes are already +counted by the snapshot seq, so tail-slice arithmetic is unchanged. + +All five bug classes are reproduced by dedicated minimal `test.skip` repros so +they cannot silently regress, AND each is tolerated + counted by its suite's +corpus loop so deep mode surfaces only genuinely NEW divergences: + +- Suite 1 (fidelity): Bug A via `bufferHasSerializeHostileWrappedRow`, Bug B via + `snapshotHasSelfCancellingBoldReset` (matches the `1;22` in the serialized + snapshot), Bug C via `isMarginWrapPendingCursorOffByOne` (cursor x-1 with a + full-width content row). Green at the default 300 and at `FUZZ_ITERATIONS=2000`. +- Suite 2 (reconciliation): Bug E via `prefixEndsMidSequence`. Bug D and the + Bug-C cursor cascade are kept out of the corpus by an append-only racing tail + (no DECSC/cursor motion) and pinned only as standalone repros. Green at the + default 200 and at `FUZZ_ITERATIONS=1000`. + +Each tolerance has a `< max(3, ITERATIONS*0.5)` guard so a predicate that starts +tripping on most seeds fails the suite instead of silently swallowing it. + +Seed 113 (called out in the handoff as a "DECSC/DECRC detour writing colored +text mid-line") does not diverge on the current harness. It is a `savedCursor +Detour` op seed; DECSC/DECRC SGR carry is correctly preserved by both the +emulator and the serializer here. It was most likely an earlier observation +folded into Bug C (the DECRC cases 1696 also involve `\x1b7`/`\x1b8`), or a +transient during harness construction. No live divergence at 113. + +--- + +## Bug A — SerializeAddon drops null cells at a soft-wrap boundary + +**Classification: (a) real `@xterm/addon-serialize` bug.** Pre-existing; found +and minimized by the prior agent, pinned by two `test.skip` repros in the fuzz +suite (V1 seed 31, V2 seed 157). Full mechanism documented in +`bufferHasSerializeHostileWrappedRow` and the suite's headline comment. + +- **V1 (cell loss):** a wrapped continuation row starting with a NULL cell + passes the addon's wrap-validity ternary, gets skipped with `CUF` which clamps + at the right margin, overwriting the previous row's last cell and shifting the + tail left by one. `cols=20: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ12\r\n' then '\x1b[1A\x1b[1K'`. +- **V2 (stray `-` filler):** a wrapped pair whose source row is entirely null + takes the forced-wrap "magic" path; cleanup emits `ESC[0C` (param 0 → 1) so + the ECH erase lands one cell right and the first filler `-` survives. + +**Impact:** any snapshot consumer (hidden reveal, parked-tab reveal, sleep/wake, +mobile subscribe replay) paints lost/shifted characters or stray `-` fillers +when a TUI erases inside a soft-wrapped line. Tolerated + counted by the suite; +unskip the repros when upstream fixes or a local serialize post-processor lands. + +--- + +## Bug B — SerializeAddon loses BOLD when serializing a dim→bold-only transition + +**Classification: (a) real `@xterm/addon-serialize` bug.** New finding. + +**Seeds:** 435, 770 (alt-screen), 1321 (minimal, 2 ops). + +**Minimal repro (isolated, no fuzz corpus needed), cols=20:** + +``` +live bytes: "\x1b[2mA\x1b[22m\x1b[1mB" +SerializeAddon → : "\x1b[2mA\x1b[1;22mB" +live cell B: bold=1 dim=0 (style flags 100000) +restored cell B: bold=0 dim=0 (style flags 000000) ← BOLD LOST +``` + +**Mechanism:** cell A is dim, cell B is bold-only. The serializer diffs the pen +from A (dim on) to B (bold on, dim off). To clear dim it appends SGR 22 — but in +xterm/ECMA-48 **SGR 22 resets *both* bold and dim** (`normalIntensity`). So the +emitted `\x1b[1;22m` sets bold then immediately clears it: the restored cell is +neither dim nor bold. Verified directly: writing `\x1b[1;22mX` yields `bold=0`. +(`\x1b[1;2m` — the same-cell dim+bold case — round-trips fine, so the bug is +specific to a dim-cell → bold-only-cell attribute transition.) + +**Why it garbles a real pane:** agent TUIs routinely draw a dim body line then a +bold status/spinner line (Claude Code, Codex). On the live screen the status +line is bold; after a hide→reveal snapshot restore it renders normal-weight. +The seed-1321 live row `⠦ bash: pnpm typecheck` is bold live, non-bold restored. + +**Repro test:** `headless-emulator-fidelity.fuzz.test.ts` → +`it.skip('preserves bold when serializing a dim cell followed by a bold-only cell')`. +Tolerated + counted in the corpus via `snapshotHasSelfCancellingBoldReset`. + +--- + +## Bug C — SerializeAddon cursor restore is off-by-one when the last content row fills the right margin + +**Classification: (a) real `@xterm/addon-serialize` bug.** New finding. + +**Seeds:** 454 (minimal, plain CUP), 1696 (DECSC/DECRC + wide CJK). + +**Minimal repro (isolated, pure serializer replay), cols=10:** + +``` +live bytes: "0123456789\x1b[3;5H" (fill row 0 to the margin, CUP to r3c5) +SerializeAddon → : "0123456789\x1b[2B\x1b[6D" +live cursor: { x: 4, y: 2 } +restored cursor: { x: 3, y: 2 } ← ONE COLUMN SHORT +``` + +Control (`"012\x1b[3;5H"` — row 0 not full) serializes to `"012\x1b[2B\x1b[1C"` +and round-trips the cursor exactly, isolating the trigger to a full-width final +content row. + +**Mechanism:** after emitting a row filled to exactly `cols`, xterm is left in +the *wrap-pending* state (cursor visually on the last column, logically "one +past"). The serializer computes its final cursor-restore as relative +`CUD`/`CUB` moves from that ambiguous position; the horizontal delta is computed +one column short, so the restored cursor lands at `x-1`. Reproduced with pure +`serializeAddon.serialize()` replay into a fresh terminal — **no Orca preamble +or normalization involved**, confirming it is upstream, not Orca's snapshot +path. + +**Why it garbles a real pane:** the cursor is where the next keystroke echoes +and where the block/bar cursor is drawn. On reveal of a TUI whose bottom line +reached the right edge (wide status lines, long prompts), the cursor sits one +cell left of where the live pane had it — visible as a mispositioned prompt +caret or spinner, and subsequent input can overwrite the wrong cell. + +**Repro test:** `headless-emulator-fidelity.fuzz.test.ts` → +`it.skip('restores the cursor exactly when the last content row fills the right margin')`. +Tolerated + counted in the corpus via `isMarginWrapPendingCursorOffByOne`. + +--- + +## Bug D — snapshot does not preserve the DECSC saved-cursor register across a hide/reveal boundary + +**Classification: (a) real bug — a structural snapshot limitation.** New +finding, surfaced by the reveal-reconciliation fuzz (suite 2), not the fidelity +fuzz. + +**Minimal repro (cols=20):** + +``` +hidden bytes: "AB\x1b7\x1b[4;10HCD" (write AB, DECSC saves cursor at r0c2, + move to r3c9, write CD) +tail bytes: "\x1b8X" (DECRC restores the saved cursor, write X) + +live (always visible): rows ["ABX", " CD"] cursor { x: 3, y: 0 } +reveal (snapshot+tail): rows ["XB", " CD"] cursor { x: 1, y: 0 } + ^^ 'X' overwrote 'A' — DECRC landed at home, not r0c2 +snapshotAnsi: "AB\r\n\r\n\r\n\x1b[9CCD" (no saved-cursor state at all) +``` + +**Mechanism:** the snapshot is a serialized *screen* (SerializeAddon) plus a few +rehydrated modes. The VT100 DECSC/DECRC saved-cursor register (also `CSI s` / +`CSI u`) is runtime state that never appears in the serialized buffer, so it +cannot survive a snapshot. When a hidden TUI runs `\x1b7` (or `\x1b[s`) before +the reveal seq and the racing tail (or any post-reveal output) runs `\x1b8` (or +`\x1b[u`), the restore targets the fresh terminal's default saved position +(home) instead of where the TUI saved it — the next writes land at the wrong +cell and overwrite live content. + +**Why it garbles a real pane:** DECSC/DECRC is common in shell prompts and +status-line redraws (save cursor, jump to a corner to paint a clock/token +counter, restore). If the save happens while the pane is hidden and the restore +fires on reveal, the restored paint clobbers the wrong cells. Found by suite-2 +seed 3 (a `savedCursorDetour` op whose `\x1b7` fell in the hidden prefix and +whose `\x1b8` fell in the racing tail after chunk-splitting). + +**Handling:** suite 2 keeps its racing tail append-only (no DECSC/DECRC, cursor +motion, scroll regions, or alt frames) so the seq-reconciliation byte-stitch is +tested in isolation from this and the other terminal-state-loss garbles. Bug D +is instead pinned as a standalone repro, +`hidden-reveal-reconciliation.fuzz.test.ts` → +`it.skip('preserves the DECSC saved-cursor register across a hide/reveal …')`. + +**Fix (applied):** the snapshot epilogue re-establishes the register with +`CUP(saved) + ESC 7 + CUP(actual)` composed in `serializeWithAbsoluteCursor`, +reading the active buffer's core register via `readSavedCursorRegister` +(alt screen yields its own register). Position-only: saved SGR/charset are not +carried. + +--- + +## Bug E — snapshot boundary mid-escape-sequence drops the partial sequence + +**Classification: (a) real bug — a structural snapshot limitation.** New +finding, surfaced by the reveal-reconciliation fuzz (suite 2). + +**Minimal repro (cols=20):** + +``` +hidden prefix: "AB\x1b[3" (write AB, then ESC [ 3 — no final byte yet) +tail bytes: "mCD" ('m' completes ESC[3m = italic, then CD) + +live (always visible): rows ["ABCD"] (ESC[3m parsed atomically, CD italic) +reveal (snapshot+tail): rows ["ABmCD"] ← 'm' became a literal character +snapshotAnsi: "AB" (the partial ESC[3 is in the parser, gone) +``` + +**Mechanism:** a PTY read (one delivery record) can split an escape sequence. +If the pane is revealed while the emulator's parser sits mid-`ESC[…`, the +serialized SCREEN cannot carry the partial sequence (it lives in the parser +state machine, not the buffer). The racing tail supplies the sequence's +remaining bytes, but with the prefix gone the terminal parses them as literal +text. Reproduced end-to-end against the real `HeadlessEmulator.getSnapshot`. + +**Why it garbles a real pane:** any TUI whose output is heavy with escape +sequences (all of them) can have a read boundary fall mid-escape; if a reveal +lands in that window the continuation renders as stray literal bytes (a rogue +`m`, `H`, digits) injected into the visible text. + +**Reachability:** requires the reveal/snapshot to fire in the gap between the two +halves of a split escape. `main` writes each PTY read to the emulator and +records it as one delivery unit (`session.ts emitSubprocessOutput`), and the +snapshot is taken synchronously at a drain — so the window is a single delivered +record that ended mid-escape. Narrow but real. + +**Handling:** suite 2 tolerates + counts scenarios whose hidden prefix ends +mid-escape-sequence (`prefixEndsMidSequence`), the same way suite 1 tolerates the +serialize wrap bug — it fired on ~24% of the corpus, confirming the class is +common. Pinned by `hidden-reveal-reconciliation.fuzz.test.ts` → +`it.skip('completes an escape sequence split across the hide/reveal boundary')`. + +**Fix (applied):** the emulator tracks the unparsed trailing partial escape at +ingest (`terminal-partial-escape-tail.ts`, committed post-parse like the mouse +mirror) and ships it as `TerminalSnapshot.pendingEscapeTailAnsi`; restorers +write it LAST, after their post-replay resets, so the racing tail's +continuation completes it exactly as live. Snapshot seq already counted those +ingested bytes, so reconcile slicing is unchanged. + +--- + +## Known-legitimate normalization (NOT bugs) + +- **OSC 8 hyperlink underline** — classification (c). xterm marks OSC-8 link + cells underlined; SerializeAddon never re-emits OSC 8. Production restores the + link ranges out-of-band via `snapshot.oscLinks` + (`collectHeadlessOscLinkRanges`), so byte replay keeps the text but drops the + underline by design. Pinned by the passing + `it('drops OSC 8 underline from byte replay but preserves the range …')`. +- **P256→P16 color mode** — classification (c). SerializeAddon re-emits palette + indices 0–15 written as `38;5;N` using classic SGR 30–37/90–97, so a restored + cell reports `CM_P16` where live reported `CM_P256`. Both resolve through the + same 16 theme slots — no visual difference. Canonicalized by + `canonicalColorMode` in the parity fixture. + +--- + +## Corpus vs deep mode + +- **Suite 1** (`headless-emulator-fidelity.fuzz.test.ts`): default + `FUZZ_ITERATIONS=300` (~17s). `FUZZ_ITERATIONS=2000` (~113s) is green — Bugs A, + B, and C are each tolerated + counted by a predicate, so the corpus fails only + on a genuinely new divergence. +- **Suite 2** (`hidden-reveal-reconciliation.fuzz.test.ts`): default + `FUZZ_ITERATIONS=200` (~5s). `FUZZ_ITERATIONS=1000` is green — the racing tail + is append-only, so the only tolerated class is Bug E (`prefixEndsMidSequence`). +- Combined default runtime is ~19s (well under the 60s gate). +- `FUZZ_SEED=`: re-run exactly one seed for a repro (both suites). diff --git a/notes/orca-performance-branch-guide.md b/notes/orca-performance-branch-guide.md new file mode 100644 index 000000000000..870c38139114 --- /dev/null +++ b/notes/orca-performance-branch-guide.md @@ -0,0 +1,532 @@ +# orca-performance Branch Guide + +Agent-facing map of every optimization on this branch: what it does, why it exists, +where it lives, and the invariants you must not break when adding to it. The +chronological evidence trail (benchmarks, retractions, A/B protocols) is in +`notes/terminal-performance-initiative.md`; this doc is the _current-state_ view. + +**Context**: Orca's terminal was ~300× slower than Terminal.app under agent load +(DSR-under-load p50 134ms, p99 292ms on v1.4.91; agent-TUI throughput 2.0 MB/s). +As of v1.4.122-rc.1.perf: p50 13.3ms / p99 18.7ms, zero timeouts, throughput +11.8–15.5 MB/s — beats VS Code on 5 of 6 metrics. Goal line still open: 4.5ms +(10× Terminal.app). + +## The pipeline + +``` +shell → pty → daemon (persistence, headless model) → unix socket + → main (ipc/pty.ts: batching, delivery gate, flow control, snapshots) + → IPC → renderer (pty-dispatcher → pty-connection → output scheduler → xterm) +``` + +Main is on the hot path for every byte (unlike VS Code's ptyHost→renderer +MessagePort). The daemon owns sessions so they survive app restarts; it also runs +a headless xterm emulator per pty — the _model_ — which is the source of truth +for screen contents. The renderer terminal is a _view_ that can be discarded and +rebuilt from model snapshots. + +## Optimization inventory + +### 1. Renderer parse-path fixes (the original 16× on agent TUIs) + +- **Parse-clocked scheduler drains** (`pane-terminal-output-scheduler.ts`): drain + cadence follows xterm's actual parse completion instead of fixed timers, so the + queue never outruns the parser. +- **Windowed retained-tail redraw**: TUI repaints (erase-down + redraw) only + re-process a bounded window instead of the full retained tail. Guarded by + differential fuzz `retained-tail-redraw-window.equivalence.test.ts`. +- **Throttled wait-blocked check** (`orca-runtime.ts`): the per-chunk agent + wait-detection (two 256KB waitText builds + multi-pattern scans) now runs at + 50ms cadence with trailing edge + keyword pre-filter. Was ~85% of main's + per-chunk cost. + +### 2. term-speed-2 chain (model/view contract — the architecture) + +Revived from ~38 never-merged branches; kill-switched, default ON. Docs: +`docs/reference/terminal-model-view-contract.md`. + +- **Hidden view parking**: hidden tabs tear down their xterm view entirely + (memory: parked panes cost ~0). +- **Hidden delivery gate** (main): renderer-bound bytes for hidden ptys are + dropped at main — hidden panes receive nothing. Reveal rebuilds the view from a + model snapshot + live chunks after the snapshot's seq. +- **Side-effect authority**: main extracts side-effect facts (bell, title, cwd) + from the model so parked panes stay live in the UI without a view. +- **Model query authority**: main answers terminal queries (DSR/CPR, DA1, OSC + colors) deterministically from the model for hidden panes. +- **Seq/ordered-delivery bookkeeping**: every chunk carries a seq; reveal + reconciliation drops duplicates already covered by the snapshot baseline. + +### 3. Batching & scheduling cadence + +- **Batch windows 8ms → 2ms** in both `daemon-stream-data-batcher.ts` + (`STREAM_DATA_BATCH_INTERVAL_MS`) and `ipc/pty.ts` (`PTY_BATCH_INTERVAL_MS`). + At 9% utilization there is no queue — latency was literally the sum of fixed + batch windows. This one change took dev DSR-load 19→8ms. +- **MessageChannel zero-delay drains** (`pane-terminal-output-scheduler.ts`): + Chromium clamps nested `setTimeout(0)` to ~4ms; posted messages are macrotasks + without the clamp, preserving cooperative yield (input/paint still serviced). + Vitest keeps the timer path (fake timers can't advance channel posts). +- **Input write coalescing** (from main, #7205): renderer input writes coalesce + instead of queuing macrotask-per-keystroke. + +### 4. Backpressure (the correctness spine — read before touching delivery) + +Three cooperating layers, innermost first: + +- **ACK at parse-drain** (`deliverPtyDataWithDeferredAck`, scheduler + `ackCredit`): the renderer credits a chunk when xterm has _parsed_ it (or the + chunk is legitimately discarded), not when IPC delivered it. + **INVARIANT: every delivered chunk credits exactly once — parsed or + discarded.** Every scheduler/pty-connection discard path (backlog replacement, + disposed terminal, reconcile drop, split remainders) must fire the credit. +- **Cumulative ACKs + solicited resync** (`terminal-pty-ack-gate.ts`, + `applyCumulativeAck` in pty.ts): ACKs carry monotonic per-pty processed totals + (TCP-style); main max-merges, so lost ACKs self-heal. Data arriving for a + fully-gated pty triggers a resync probe instead of a timeout reset. The only + timer is a hygiene warn that mutates nothing. Main's 512KB per-pty in-flight + gate + 2MB pendingData cap sit on top. +- **Renderer-pull delivery watchdog** (`terminal-delivery-watchdog.ts`, + `pty:reportRendererDeliveryState` in pty.ts): recovers the field-confirmed + wedge where every main→renderer PUSH channel dies while invoke stays alive + (v1.4.121-rc.0 snapshot; electron#37067 class) — a state the push-ridden + resync probe can never reach. The 15s heartbeat costs one Map upsert per + received chunk and does no IPC while output flows; mutation stays + verified-state-only (the timer decides when to REPORT; the write-off derives + entirely from the renderer's cumulative received totals, never wall-clock, + and a received-but-unparsed window is never written off). Heal = re-attach + push listeners + pull restore markers through the modelRestoreNeeded router. + E2e blackhole harness: `__terminalDeliveryWatchdog`, + `terminal-push-delivery-loss-recovery.spec.ts`. +- **Stale-visibility proof for the hidden gate** (`stale-document-visibility.ts` + and the `shouldWritePtyOutputForeground` fallthrough in pty-connection.ts): + recovers the field-confirmed wedge where macOS occlusion tracking pins + `document.visibilityState` at `'hidden'` after display sleep and never fires + another visibilitychange (v1.4.124-rc.2.perf snapshot: 78MB hidden-gate + dropped across 2 pane-level-visible ptys, transport healthy). Real user + input (keydown/pointerdown/window focus) while the document claims hidden is + a physical contradiction — it latches an override, runs each pane's existing + visibilitychange resync (gate unhide + hidden-output restore), and a genuine + visibilitychange hands authority back. No timers; recovery is purely + event-proven, and the failure bias is safe (a wrong override only restores + pre-gate delivery cost, never drops bytes). Hot-path cost: zero when + visible (same single comparison); one property read per user-interaction + event. E2e: `terminal-stuck-occlusion-recovery.spec.ts` (pins both the + freeze repro and the keystroke recovery, plus the + `hiddenDeliveryGatedVisiblePtyCount` field discriminator). +- **One-paste freeze report** (`terminal-freeze-report.ts`, prod-installed + `await window.__orcaTerminalFreezeReport()`): a single DevTools command that + returns renderer state (visibilityState + stale override, pty:data listener + count, watchdog totals), main's snapshot with a per-pty delivery table + (sent/acked/pending, hidden vs visible-set membership, last send/ACK ages, + window focus flags, power suspend/resume ages, app version), and bounded + breadcrumb rings from BOTH processes (`pty-delivery-diagnostics.ts` shared + ring: 100 entries, same-kind coalescing) recording gate marks, visibility + trust changes, watchdog stalls/heals, restore markers, heal write-offs, + renderer lifecycle resets. Pty ids are redacted to their `@@` suffix — + daemon session ids embed worktree paths. Recording happens only on rare + transitions; the table/report is built only when read. This exists so a + field freeze report never needs a follow-up ask. +- **Hidden/parked exit teardown completeness** (pty-connection.ts kept-exit + guard + `terminal-parked-tab-watchers.ts` exit sidecar): two invariants that + keep a split pane's death near the hidden/park boundary from stranding state + (field incident: a closed setup-split leaf persisted in `root` with no + binding and remounted as a permanently blank pane, unreachable by + dead-session reconcile — it skips ptyId-null panes by design). + (1) The "keep a fresh split whose newborn PTY died" branch is **gated on + `isVisibleRef`** — hidden panes' bytes are gate-withheld, so "no output" + proves nothing there; a hidden newborn death must `closePane`, or the kept + pane becomes a binding-less ghost. (2) A PTY exit that lands **while parked** + reaches ONLY the parked watcher's exit sidecar (hosts' `onPtyExit` needs a + mounted TerminalPane), so the sidecar itself collapses the dead leaf out of + the stored layout via `detachTerminalLayoutLeaf` — a stale binding left + behind reattaches on reveal and the daemon re-creates the exited session id + as a fresh shell (silent pane resurrection). E2e: + `terminal-pane-close-layout-consistency.spec.ts` sweeps close/exit at every + lifecycle phase and asserts leaves(root) == bindings == live panes. +- **Producer flow control** (protocol v19 `pausePty`/`resumePty`, 256KB pause / + 32KB resume watermarks, keyed off **pendingData only** — never renderer + counters; kill switch `PRODUCER_FLOW_CONTROL_ENABLED`, ipc/pty.ts): when main's + buffer grows, the _shell_ blocks. For main-hosted ptys pause is synchronous + (drops impossible); for daemon ptys the pause notify has ~20-30ms socket + latency, so wire-speed bursts can still cross the 2MB cap (known follow-up: + daemon-side self-pacing watermark). +- **Shallow stream-socket write gate + per-session fairness** + (`daemon-stream-data-batcher.ts`, 128KB gate / 64KB safe-split slices / + 4KB small-session bypass / 32MB write-through valve; kill switch + `ORCA_DAEMON_SHALLOW_SOCKET_GATE=0`): the stream socket is one FIFO for + every session — bytes already written can never be overtaken, so a deep + user-space buffer buries a visible pane's echo behind other panes' bulk + (measured 192MB / 6+s under 12 flooding hidden agents). Bulk writes stop at + the gate and hold in the batcher, where the interactive flushSession path + and the deterministic small-session bypass still jump them; socket `drain` + refills. This layer alone bounds echo latency by the shallow depth. +- **Background keep-tail stream thinning + daemon fact authority** + (`daemon-stream-keep-tail-drop.ts` 1MB cap / 512KB keep-tail, + `daemon-background-transient-facts.ts`; kill switch + `ORCA_DAEMON_BACKGROUND_STREAM_DROP=0`): hidden-gated ptys are exempt from + pendingData flow control (main drops their bytes after ingestion), which + let N background agents run unbounded ahead of main. Main mirrors the + hidden-delivery gate to the daemon via the wire-tolerated + `setSessionBackground` notification (introduced in v19; authoritative + thinning requires v20 snapshots, so preserved v19 sessions are explicitly + unthinned; older daemons swallow it) — but a live remote view subscriber + (mobile/web) vetoes backgrounding (`hasRemoteTerminalViewSubscriber`). + Backgrounded sessions' queued output is keep-tail dropped (oldest bytes + replaced by an in-order `dataGap` event; reply-eliciting query bytes are + salvaged so hidden programs never hang on DSR/DA replies); producers are NEVER paused, + so reveal stays instant with zero catch-up. Un-background neither discards + nor force-flushes the queued tail — restore paths read MAIN's model + (hidden-output recovery buffer), so a discarded tail loses a finished + program's last output forever (caught by the ACK-backpressure e2e), and a + 16-pane force-flush dumps ~12MB onto the socket ahead of the reveal's own + bytes; the ordered drain loop delivers it within the budget below. Two + aggregate bounds make that budget real: (1) a GLOBAL background keep + budget (~2MB): per-session keep-tails shrink (512KB → floor 64KB) as more + backgrounded sessions hold queued data, and tighten retroactively when the + count grows — without this, N sub-cap sessions queue N×cap and a worktree + switch waits seconds behind the aggregate (measured 9MB → 2.5s hidden + restore vs the 1.5s budget, probe-verified drain overlap); (2) a + kernel-flush refill sentinel: a held flush pass arms one ~90B empty data + event whose write callback re-flushes when the kernel accepts the + in-flight bytes — without it, held bulk advances one gate-depth per + 'drain' (user-space empty) per event-loop turn (~8MB/s ceiling on a busy + daemon). NOTE: an empty `socket.write('')`'s callback fires immediately + even with megabytes buffered (verified) — the sentinel must be a real + protocol no-op line. Notifications are + structurally lossless: while backgrounded, the DAEMON runs the same shared + scanners main uses (`terminal-output-side-effects.ts`: bell / OSC 133 + command-finished / pr-link / DECSET 2031) over every byte BEFORE drop + decisions and relays facts as in-order `transientFact` events; ordered + `sessionBackgroundMarker` events hand scan authority back and forth + (main suppresses just those four scanners in between), and the emulator's + `partialEscapeTailAnsi` seeds each side's fresh scanner carry so a + sequence split across the handoff neither phantom-fires nor goes missing. + Titles/agent-status stay main-side (they converge from the kept tail and + fuse with synthetic spinner frames). On `dataGap`, main resets its + cross-chunk parse carries, drops the mobile headless mirror (rebuilds from + tail/seeds), and sends the model-restore-needed marker so any + renderer-side buffer heals from the snapshot. Visible ptys are never + touched by this layer. Backlog observability: + `ORCA_DAEMON_STREAM_BACKLOG_FILE=` JSONL + (`daemon-stream-backlog-probe.ts`; events incl. `backgroundKeepTailDrop`, + `setSessionBackground`, `mainBackgroundSync`, `heldWriteThrough`). + Causation A/B (`bench:multi-workspace-typing`): realistic steady rates + (8×192KB/s) don't reproduce even fix-off; burst rates on a loaded machine + do (8×512KB/s + 12 CPU spinners: fix-off p50 293ms/p90 647ms → fix-on p50 + 29ms); extreme 12×1MB/s: fix-off p50 6,146ms → 29ms. + +### 5. Flood resilience (why bulk output can't wedge or lie anymore) + +- **Restore-loop cut** (pty-connection.ts): the hidden-output-restore loop + abandons immediately when a foreground pane's live-chunk queue overflows + (3-iteration hard cap), and a 2s flood-suppression window stops main's own + backpressure drops (`droppedOutput`/`modelRestoreNeeded`) from re-arming + restore — bytes write through, ONE deferred repaint heals after the flood. + This killed a positive feedback loop (restore starves ACKs → main drops → + drop re-arms restore) that caused multi-second renderer stalls. +- **Query survival**: if the 2MB cap ever drops bulk output, embedded terminal + queries are extracted (`terminal-reply-query-extraction.ts`) and answered by + _synthesizing replies on the input path_ (CPR from live buffer, DA1 canned, + OSC via direct responder) — probes and TUIs never hang on a dropped reply. +- Drops are downstream of the model: the daemon ingests every byte, so the + post-flood repaint restores complete, correct content. + +### 6. Wake/sleep recovery + +- powerMonitor resume → `system:resumed` IPC → renderer wake recovery (fixes + WebGL-latch blank-after-sleep that DOM focus/visibilitychange missed). +- Cumulative ACKs make the historical "lost ACKs across suspend pin the global + window forever" wedge (BMW user bug) structurally impossible. + +### 7. Snapshot fidelity (the garble fixes — all fuzz-pinned) + +Reveal-from-snapshot multiplied exposure of serializer defects ~1000×. Five bugs +found by differential fuzzing; four fixed, one tolerated: + +- **B: SGR intensity ordering** — upstream `@xterm/addon-serialize` emitted + `1;22` (22 clears the bold 1 just set). Patched via pnpm patch + (`config/patches/@xterm__addon-serialize@*.patch`): clear-before-set for the + bold/dim group (+2 sibling bare-22 defects). +- **C: cursor off-by-one at wrap-pending margin** — bypassed entirely: + `serializeWithAbsoluteCursor` (`terminal-serialize-absolute-cursor.ts`) + appends absolute CUP from the source terminal's authoritative cursor + (skipped when wrap-pending, where CUP would corrupt). +- **D: DECSC saved-cursor register not serialized** — snapshot appends + `CUP(saved) + ESC 7 + CUP(actual)` when a register exists. +- **E: snapshot mid-escape-sequence** (fired on 24% of fuzz corpus) — + `terminal-partial-escape-tail.ts` is a fold-safe VT-parser-state scanner; the + unparsed tail ships as `TerminalSnapshot.pendingEscapeTailAnsi` and is written + LAST on restore so continuation bytes complete the sequence. Seq accounting + unchanged (the tail is a suffix of bytes ≤ snapshot seq). +- **A (tolerated)**: upstream wrap-null-cell serialize defect — fenced by + `bufferHasSerializeHostileWrappedRow`, the only remaining tolerance. + +## Correctness infrastructure (run these before merging delivery/restore changes) + +- `headless-emulator-fidelity.fuzz.test.ts` — differential: HeadlessEmulator vs + reference xterm, seeded TUI streams. `FUZZ_ITERATIONS=2000` for deep, + `FUZZ_SEED=n` to replay. +- `hidden-reveal-reconciliation.fuzz.test.ts` — property tests: random + hide/reveal boundaries × snapshot seq × racing chunks must equal an + always-visible reference. +- `terminal-snapshot-serialize-roundtrip.test.ts` — the garble repros (unskipped + = regression alarms). +- e2e: `terminal-hidden-view-parking` (incl. 25-cycle park/reveal drift test — + byte-identical vs control), `terminal-parked-memory`, + `terminal-sleep-wake-restore`. +- Scheduler credit-invariant + ack-gate deferred-credit + restore-flood tests + (pane-manager / terminal-pane suites). + +## Benchmarking protocol (hard-won rules) + +- Rig: `tools/benchmarks/terminal-pipeline-bench.mjs` — DSR idle + DSR under + 1MB/s agent-TUI load + DSR-fenced throughput on 4 fixtures. Run _inside_ the + terminal under test. +- Multi-workspace typing rig: `pnpm bench:multi-workspace-typing -- --panes 12 +--rate-kbps 1024 --keys 32 --cadence-ms 250 [--cpu-workers 8] --label ` + — real keystrokes (CDP) into a visible pane while N hidden-worktree panes + replay paced agent-TUI streams through real daemon ptys; decomposes each key + into input-half (keydown→pty, sidecar timestamps) and echo-half + (pty→screen). JSON in `tools/benchmarks/results/`. Noise band at 4×256KB/s: + p50 10-15ms, p90 ≤50ms. The latency signature lives in echo-half; renderer + timer drift staying ~15ms while echo-half grows means the backlog is + upstream of the renderer (daemon socket / main ingest). +- **Bench at 10MB** (`--size-mb 10`). The ACK-at-parse bug shipped because dev + benches used 3MB and never tripped the cap. +- Load-controlled A/B only: alternate builds within one session; dev carries ~2× + day-to-day variance. Never conclude from runs while agents/builds hammer the + machine (two false convictions came from this). +- Never set `ORCA_E2E_USER_DATA_DIR` for benches (arms the e2e ACK gate → hang). +- Packaged builds are truth; dev has ~2× overhead. + +## Release mechanics + +- Perf RCs: `release-cut.yml` workflow_dispatch, `kind=rc ref=orca-performance +version_suffix=perf` → tags like `v1.4.122-rc.1.perf`. The suffix sorts above + its base rc.N but below rc.N+1 (never hijacks the RC channel). The rc counter + (`release-rc-history.mjs`), telemetry identity classifier, and build guard are + all suffix-aware — a suffixed rc classifies as `rc`. +- cmd/ctrl-click "Check for Updates" fetches the latest perf-tagged release + (PR #7278; merged here) — perf-line users self-update after one manual install. + +## Syncing with main: MERGE, never rebase + +`orca-performance` is a long-lived, shared, continuously-pushed integration +branch — RCs are cut from it and agents branch off it. **Always +`git merge origin/main`; never rebase** (rebasing rewrites pushed history and +strands every RC tag, fix branch, and worktree based on the old commits). +Conflict pattern, established over ~6 syncs: + +1. **Our structure wins; main's semantics graft in.** This branch deliberately + restructures terminal code (shared scanners, single-policy handlers, + model/view split). When main adds a feature inside code we've restructured, + keep our shape and port their new behavior into it. Example: main inlined an + OSC 133 parser to add `onCommandStarted` (133;C); we kept the shared + `createOsc133CommandFinishedScanner` (main's side-effect tracker must parse + byte-identically) and added 133;C support to the shared scanner instead. +2. Preserve the invariants in **Guardrails** below through every resolution — + especially chunk-credit, `pendingData`-keyed flow control, and the + single `handleCommandFinished` policy (byte path AND sideEffect-fact path + route through it). +3. After resolving: `pnpm typecheck`, the terminal-pane + ipc/pty + daemon + suites, and both fuzz suites. Commit the merge with a message stating what + was kept from each side; push. If the push races a moved remote, merge the + remote tip — never `pull --rebase` a merge. +4. If a sync lands anything on the delivery/restore path, re-run a 10MB bench + before the next RC cut. + +## Known limits / next levers (in rough priority order) + +1. Daemon self-pacing: daemon-hosted ptys can cross the 2MB cap for ~20-30ms at + wire speed before `pausePty` bites. Fix: daemon enforces its own watermark + locally (VS Code does this server-side for remotes). +2. Cadence floor to the 4.5ms goal: xterm's 12ms parse slices and remaining + drain cadence dominate the 13.3ms prod p50. +3. utilityProcess router endgame: take main off the per-byte hot path + (VS Code's ptyHost→renderer MessagePort shape). +4. SerializeAddon full-buffer stalls at 50k-row scrollbacks (#5096 follow-up). +5. Peel PRs to main: throughput fixes → batch+MessageChannel → flow control → + term-speed-2 last. PR #7214 is the integration overview; #7260 (wake/ACK) + is open against main separately. + +## Guardrails for future agents + +- The chunk-credit invariant (§4) is the load-bearing one. If you add ANY path + that receives, defers, drops, or splits pty data in the renderer, prove it + credits exactly once. The credit-invariant unit tests are the gate. +- Flow control keys off `pendingData` only. Do not couple it to renderer + counters; the two layers compose because they are independent. +- Snapshot changes must keep seq semantics: a snapshot covers _exactly_ bytes + ≤ its seq (Bug E made this true; don't regress it). Chunks after restore are + reconciled by seq — off-by-N re-triggers duplicate-drop garble. +- Hidden panes must receive nothing (delivery gate) but side-effects and query + replies must stay live via the model. If you add a new query type, wire it + through model authority AND the drop-path synthesis. +- Never add timeout-based recovery that mutates counters (user requirement — + design decision from #7260). Deterministic resync or nothing; hygiene timers + may only log. +- Any change on the delivery/restore path: run both fuzz suites, the roundtrip + tests, the chain e2e trio, AND a 10MB bench before calling it done. + +## Audit 1 + +Completed 2026-07-10 against `orca-performance`. Scope: the daemon → main → +renderer terminal path, with particular attention to hidden delivery, parking, +stream thinning, snapshot fidelity, ACK/backpressure semantics, wake/reattach, +mobile/remote composition, SSH routing, and teardown. The audit treated model +state and user scrollback as correctness requirements, not expendable memory. + +### Findings and fixes + +1. **Hidden-gate handoff owners could undo one another.** A parked watcher and + an unmounting/remounting pane shared one boolean hidden mark; likewise a + retiring pane could report `visible=false` after its replacement had already + reported `visible=true`. Hidden claims are now reference-counted and + visibility is counted per owner (`pty-renderer-delivery-claims.ts`). Eager + pre-mount buffers no longer hold raw-byte delivery interest: they are not a + side-effect consumer, and model-backed hidden output can restore from a + snapshot. This removes the ownership and eager-interest races formerly + listed in Known limits item 6 without weakening parked side effects. The + remaining transient-visibility concern was checked separately: bind and + reconnect reports read `TerminalPane`'s synchronously refreshed + `isVisible && isWorktreeActive` ref, the global effect uses the same + expression, and owner counting prevents a retiring pane from overriding its + replacement. No hidden-worktree `visible=true` report site remains. + +2. **A natural/synthetic daemon exit could overtake final output.** When a + shallow-gated socket had queued data, `daemon-server.ts` wrote the exit event + directly. The final bytes could therefore arrive after `exit`. Exit is now an + ordered control event in `DaemonStreamDataBatcher`; both natural and + synthetic exits flush through the same FIFO. A deep-socket regression test + pins final-data-before-exit ordering. + +3. **Keep-tail thinning could permanently reduce scrollback to the retained + tail.** On `dataGap`, main discarded its headless model, then rebuilt it from + later tail bytes even though the daemon still owned the complete model. Live + daemon snapshots now carry `outputSequence`; the provider exposes an + authoritative `getBufferSnapshot`, accepts the requested scrollback depth, + and main requires that provider snapshot after a gap. Reconciliation starts + in the pre-snapshot absolute sequence domain and runtime sequence accounting + advances across dropped bytes. The daemon remains the source of complete + scrollback instead of making a transport optimization destructive. If that + authoritative RPC is temporarily unavailable, main now returns no snapshot + and lets the renderer retry; it never paints main's known-incomplete tail as + a full recovery. + +4. **Query-salvage copies corrupted the absolute sequence domain.** DSR/DA + bytes salvaged from a dropped region are copies of bytes already counted by + the daemon, not new output. Stream events now distinguish delivered text + from `sequenceChars`; salvaged query data advances by zero while the gap + advances by the original characters. Main can still parse/deliver the query + copy without shifting every later snapshot baseline. + +5. **“Parse-deferred” ACKs were submission-deferred, not parse-deferred.** ACK + credit fired when bytes entered `terminal.write`, before xterm's callback. + Split scheduler chunks also attached `onParsed` to the first slice. ACK + credit is now owned by `pane-terminal-output-ack-credit.ts`, fires after the + final xterm parse callback, and is released exactly once on throw, discard, + or terminal disposal. Submitted-but-unparsed credit is retained until parse + or disposal, so main's flow-control window measures parser work rather than + renderer submission. + +6. **Hidden restore ignored configured scrollback.** The renderer always asked + for 5,000 rows, so users configured for 10k–50k silently lost older history + on a hide/reveal rebuild. Restore now reads the pane's xterm scrollback + option and clamps it through the shared 0–50,000 policy + (`terminal-hidden-restore-scrollback.ts`). + +7. **Active alternate-screen snapshots discarded the normal shell buffer.** + SerializeAddon emits `normal buffer + ?1049h + alternate buffer`; the old + normalization sliced away everything before the last `?1049h`. A restored + TUI looked correct until it exited alternate mode, then returned to empty + history. Snapshots now carry the normal buffer separately in + `scrollbackAnsi`. Fresh reattach and mobile/remote snapshot streams compose + both buffers; an already-alt renderer exits alt, clears/rebuilds the normal + buffer, then re-enters and rebuilds alt. History replay also composes both + buffers, including legacy empty-field compatibility. + + Deep fuzz then found a second two-buffer issue: normal-buffer serialization + can leave its SGR pen active while the separately serialized alternate body + assumes default SGR. The rehydrate boundary now emits `SGR 0` before + `?1049h`, preventing a shell color from tinting restored TUI cells. The + regression proves the TUI is visible immediately and `?1049l` returns to the + original shell history. + +8. **Daemon provider wrappers forwarded only part of the recovery contract.** + A preserved current/legacy daemon could emit `dataGap` through a provider + wrapper, but `DegradedDaemonPtyProvider` omitted `getBufferSnapshot`, while + the ordinary multi-version `DaemonPtyRouter` omitted background hints, gap + events, snapshots, and explicit `sequenceChars`. Both wrappers now route the + complete contract to the provider that owns the session, including requested + 50,000-row recovery and zero-advance query-salvage events. + +9. **Sequence-safe recovery was added without advancing the daemon protocol.** + An already-running v19 daemon could accept background-thinning hints but + could not return the new `outputSequence`, making any resulting gap + impossible to reconcile safely. The authoritative snapshot contract is now + protocol v20. Preserved v19 sessions remain live but are explicitly marked + unthinned; their stale background hint is cleared on the ordered control + socket before `createOrAttach`, while fresh v20 sessions retain keep-tail + performance and full-model recovery. + +### Static audit conclusions + +- Model query authority still captures ownership synchronously at ingestion; + seed/hydration/snapshot writes remain reply-silent, remote view subscribers + retain view authority, and replies use the provider input path (including + daemon shell-ready queuing and SSH routing). +- Hidden/visibility/interest/background-sync/provider-snapshot state is cleared + by the centralized PTY teardown path. Parked watcher timers, byte sidecars, + fact consumers, exit subscriptions, hidden claims, and runtime-title slots + dispose on reveal/exit/worktree shutdown. +- Remote-runtime and SSH PTYs remain excluded from cold parking. SSH hidden + panes still have a main-owned headless model, so mounted hidden-gate restore + is valid; live remote viewers veto daemon background thinning. The new + two-buffer payload is recomposed before mobile/remote snapshot frames. +- Wake recovery keeps its focus/visibility/system-resume listener symmetry and + cancels its settled animation frame on cleanup. No timeout was added that + mutates ACK or delivery counters. +- The one documented upstream SerializeAddon null-cell/wrapped-row defect + remains tolerated. Deep reveal fuzz now uses the same narrow hostile-row + predicate as fidelity fuzz, rather than misclassifying that known serializer + defect as sequence-reconciliation loss. + +### Validation evidence + +- Focused ownership/connection/dispatcher tests: 422 passed. +- Daemon server/batcher/order tests passed, including deep queued-socket exit. +- Broad main/daemon/runtime/RPC/SSH run: 1,854 passed, 5 skipped. Three stale + mocks were updated to assert the new explicit `sequenceChars` argument; the + production behavior was already correct. +- Broad renderer terminal/pane/scheduler/runtime-stream run: 1,934 passed. +- Final restore/roundtrip/history/adapter/runtime/scheduler sweep: 1,315 passed. +- Post-protocol completion sweep: 1,106 affected main/daemon tests passed; + 484 renderer/restore tests passed with 2 expected skips. +- Scheduler throughput harness passed with `ORCA_TERMINAL_PERF_BENCH=1`. +- Required hidden-view parking, parked-memory, and sleep/wake E2E trio: + 7 passed on a fresh v20 Electron build, including byte-identical output + across 25 park/reveal cycles. +- `FUZZ_ITERATIONS=2000` headless-emulator fidelity: passed (120.19s). +- `FUZZ_ITERATIONS=2000` hidden reveal reconciliation: passed (69.77s). It + reproducibly found the SGR boundary bug at seed 16 and the known upstream + wrapped-null-cell case at seed 1221 before the final green run. +- Snapshot roundtrip, retained-tail equivalence, ACK gate, PTY connection, and + remote incomplete-escape regression suites passed. +- Fullscreen real-app headful flow: a real shell wrote normal history, entered + a TUI while its worktree was hidden, restored on reveal, then exited with + `?1049l` back to the original history. The BrowserWindow was fullscreen; + no click/focus occurred before evidence; the restored frame settled for + 1.5s before capture. Measurements: window 1710×1073 at DPR 2; xterm 133×63; + `fitAddon.proposeDimensions()` 133×63; cell width 8px; screen-to-xterm gap + 11px (the scrollbar/remainder, with grid and proposed dimensions equal). + Artifacts: `.tmp/terminal-audit-headful/fullscreen-alt-restore.png` and + `.tmp/terminal-audit-headful/fullscreen-alt-restore-metrics.json`. +- Visible, non-E2E current-build Orca 10MB agent-TUI bench: 10.14 MB/s + (986ms for 10.0MB), DSR idle p50/p90/p99 0.64/6.47/57.82ms, + DSR-under-load 6.72/9.86/13.87ms, zero timeouts. The pane was 115×39, + reported app version 1.4.131-rc.2, and ran on a v20 daemon/session. Result: + `tools/benchmarks/results/terminal-pipeline-audit-v20-20260710-2026-07-10T10-54-45-990Z.json`. +- `pnpm typecheck`, oxlint on every touched TypeScript file, + `pnpm check:max-lines-ratchet`, `git diff --check`, and the E2E production + build all passed. No max-lines bypass was added. diff --git a/notes/terminal-performance-initiative.md b/notes/terminal-performance-initiative.md new file mode 100644 index 000000000000..2ac56bbf9e49 --- /dev/null +++ b/notes/terminal-performance-initiative.md @@ -0,0 +1,583 @@ +# Terminal Performance Initiative + +Working plan for the `orca-performance` branch. Goal: make Orca's terminal as +performant as the architecture allows, with every claim backed by a number. +Started 2026-07-02. + +## Why (user-reported, from the team meeting) + +1. Typing in the terminal is sometimes laggy — occasionally seconds of delay. +2. Users say the terminal is slower than iTerm (unclear if typing or scrolling). +3. Scrolling in Claude Code / OpenCode is slow. +4. Idle memory is high (1–2 GB). +5. Battery usage is high. + +Goals: legit performance complaints ≤ 1/week; sampled P90 typing/scrolling +latency down significantly; lower memory with 0–1 agents. + +## Ground truth (verified against source, 2026-07-02) + +Research corpus: xterm.js 6 / VS Code / Ghostty internals study (verified +file:line claims) — see the archived digest and the "xterm.js vs Ghostty" +deep-dive. The Orca-specific findings below were re-verified against this +repo's code: + +- **Electron main sits on every terminal byte's path** (daemon → main → + renderer). VS Code ships the same xterm.js but bypasses main entirely: its + ptyHost is a UtilityProcess with a direct MessagePort to each renderer. +- **The PTY producer is never paused.** `acknowledgeDataEvent` is a no-op in + both `LocalPtyProvider` and `DaemonPtyAdapter`. Only main→renderer delivery + is watermarked (512 KB, `src/main/ipc/pty.ts:1374`); main's own buffer can + grow toward a 512 MB cap under flood. VS Code pauses the actual pty at 100k + unacked chars (kernel backpressure blocks the shell). +- Renderer terminals share one thread with the entire React app; xterm.js + parses in 12 ms slices at a documented 5–35 MB/s ceiling. +- Renderer scrollback default is 5,000 rows (`src/shared/terminal-scrollback-policy.ts`), + 5× VS Code's default; 12 B/cell plus per-line JS objects; O(all lines) + reflow on column resize. +- Latency physics: Ghostty ~4 ms median keypress latency, VS Code ~31 ms + (same-library reference), native class 5–10 ms. Realistic target: beat + VS Code, close on iTerm2, eliminate the stall/jank class entirely (P99 + dominates perception). + +## Current state + +Branch `orca-performance` (long-lived testing line, from main @ `8e8a08ac7`): + +1. `tools/benchmarks/terminal-pipeline-bench.mjs` — cross-terminal rig + (see Benchmark protocol below). +2. Merge of PR #7153 = #7150 (freeze/memory: backlog caps, wedge guards, + probe-certified replay release) + #7139 (cooperative drain: paced backlog + draining keeps typing responsive under floods). Post-merge on this base: + `pnpm typecheck` clean, 626 targeted tests green (scheduler, guards, + pty/pty-connection/pty-transport suites). #7153 itself is a disposable + testing PR; #7139 and #7150 land separately on main. + +## Workstreams + +### 1. Baseline benchmarks (now; human-in-terminal required) + +Run the rig in each terminal on the same machine — Orca pane, iTerm2, Ghostty, +Terminal.app, VS Code (T3Code if available): + +``` +node tools/benchmarks/terminal-pipeline-bench.mjs --label - +node tools/benchmarks/terminal-pipeline-bench.mjs report +``` + +These numbers answer "are we actually slower than iTerm, and where," and are +the before/after for everything below. + +### 2. Validate #7153 on orca-performance (this week, extended testing) + +Watch for: typing responsiveness under agent floods, bounded memory, +skip-notice + snapshot repaint on overflow, no permanent input loss. When +validated, land #7139 and #7150 as separate PRs on main. + +### 3. Revive term-speed-2 (the headline structural work) + +History: nwparker's ~38-branch chain (+20k lines) implementing the terminal +model/view contract — hidden view parking, hidden delivery gate, side-effect +authority in main, model query authority, skip-grammar deletion — all +kill-switched, documented in +`origin/nwparker/term-speed-2-architecture-docs:docs/reference/terminal-model-view-contract.md`. +It shipped only in v1.4.78-rc.1, a deliberate personal-testing build; it was +never rejected and never reached main. Directly targets complaints 3–5 +(hidden panes stop receiving bytes and unmount their xterm + WebGL atlases). + +Merge scout (2026-07-02, chain tip into orca-performance): 144 files, 34 +conflicted, 115 hunks. Hotspots: `pty-connection.ts` (31), `pty.ts` (16), +`daemon-pty-adapter.ts` (6), `orca-runtime.ts` (5). +`pane-terminal-output-scheduler.ts` does NOT conflict — #7139/#7150 and the +chain touch different layers; runtime interaction (drain pacing × hidden +gate) still needs deliberate testing. + +Execution: dedicated focused session; resolve on `revive/term-speed-2` off +orca-performance; keep both sides' kill switches; validate with typecheck + +the contract tests listed in the model-view-contract doc + #7153's suites; +merge back to orca-performance for extended testing. Estimated ~1 day of +careful resolution + validation. + +### 4. Remaining stall-bug fixes (parallel, independently shippable) + +The "seconds of delay" class = discrete thread-blocking events, not +steady-state latency: + +- PR #7105 (open): skip synchronous cold-restore replay for live daemon + sessions in doSpawn. +- `SerializeAddon.serialize()` audit: ~1.2 s renderer block at 50k scrollback + rows (#5096 follow-up, never done). Call sites include the mobile snapshot + path (`pty-connection.ts:2861`) and sleep/hibernate serialization. +- #2836 frozen-terminal leads: replay-guard latch, codex-stale gate, uncapped + buffers (repro harness exists). +- Checkpoint-RPC main-thread scrub (measured ~2–10 ms bursts per hot 5 s + tick; small, part of the same program). + +### 5. Producer-side PTY flow control + +Ack-driven pause/resume of the actual PTY through the daemon protocol +(node-pty supports it), watermarks per the xterm.js flow-control guide +(≤500 KB). Converts flood-induced buffered lag into shell blocking — the +correct physics. Sequence after #7139 lands (interacts with its drain pacing). + +Design (2026-07-03, implement after the term-speed-2 revival merges — +same files): + +- Signal source: main already tracks per-pty pending + in-flight + (`pendingData`, `rendererInFlightCharsByPty` in `ipc/pty.ts`). When a + pty's pending exceeds HIGH (256 KB), main asks the producer to pause; + below LOW (32 KB), resume. +- Producer side: two new protocol notifications (`pausePty`/`resumePty`, + protocol vNext, version-gated like `supportsIncrementalCheckpoints`); + daemon `Session` calls node-pty `pause()`/`resume()` — stops reading the + pty fd, kernel buffer fills, the shell blocks on write: true kernel + backpressure, identical physics to VS Code's 100k/5k design. + `LocalPtyProvider` calls pause/resume directly. +- Safety invariants: (1) failsafe auto-resume after 5 s regardless of + watermark, so a lost resume can never wedge a shell; (2) resume on + detach/exit/kill/daemon-reconnect; (3) pause must not suppress the + interactive-echo bypass — with the pipeline fixed (11.5 MB/s dev), the + HIGH watermark is only reachable during genuine floods where echo is + already queued; (4) PTY reads never stop for model/tail ingestion + (term-speed-2 invariant #1) — pause gates the fd read, so daemon-side + emulator state pauses with it, which is correct (state = what was read). +- Tests: watermark transition unit tests, lost-resume failsafe, kill/exit + cleanup, plus an e2e pressure scenario asserting bounded main memory and + a blocked producer (`yes` exits promptly on SIGINT while paused). + +### 6. Extend the measurement rig + +- True keypress→pixel latency: Typometer manual protocol (the DSR probe stops + at the parser reply, before paint). +- Idle memory + battery: per-process RSS breakdown + `powermetrics` sampling + at 0/1/5 agents (goal-3 metric). +- FPS under flood; event-loop-delay probes (`monitorEventLoopDelay`) in + main/daemon/renderer behind a debug flag for pipeline attribution. + +### 7. utilityProcess terminal router (structural endgame; gated on data) + +An Electron UtilityProcess owns the daemon socket and hands each renderer a +MessagePort — VS Code's topology while keeping Orca's detached daemon (warm +reattach). Takes main off the terminal data path entirely; daemon-side +history persistence falls out naturally. Prototype only after baselines show +how much tail latency lives in the main hop. + +### 8. Production P90 telemetry + +Sampled keypress→echo latency + long-task/stall counts from real users; +defines the success criterion and becomes the permanent regression gate. +Design after the local rig stabilizes so the metrics match. + +## Benchmark protocol + +`tools/benchmarks/terminal-pipeline-bench.mjs` measures, from inside any +terminal: + +- **DSR idle latency** — ESC[6n round trips (p50/p90/p99); replies come only + after the parser reaches the query, so it proxies the input pipeline + without keystroke injection. +- **Fenced throughput** — 4 deterministic fixtures (`ascii-log`, `cjk-emoji`, + `agent-tui` — Claude-Code-shaped transcript + DEC-2026 status repaints — + and labeled-pathological `styles-stress`), each run ended by a DSR fence so + xterm.js-class ingest queues can't flatter the result. +- **DSR under load** — latency sampled during a paced 1 MB/s agent-TUI + stream: "typing while the agent works," quantified. + +Rules: same machine, AC power, comparable window size, no tmux/screen, hands +off the keyboard during runs. Never compare numbers across machines. + +## Sequencing + +``` +now: [1] baselines [2] #7153 testing (parallel) +next: [3] term-speed-2 revival (dedicated session) +parallel: [4] stall fixes, [6] rig extensions +after 2/3: [5] flow control +gated: [7] utility router [8] telemetry +``` + +BMW-group crash work remains the team's priority gate above all of this +(#7150's wedge guards overlap it); this plan runs measurement and revival +prep in parallel without displacing it. + +## Findings log + +### 2026-07-02 — baseline + decomposition (results committed in tools/benchmarks/results/) + +Same machine, unattended serial runs (Orca 1.4.91 prod, Terminal.app, Ghostty +1.3.1; iTerm2 not installed, VS Code pending): + +| metric | Orca prod | Terminal.app | Ghostty | +|---|---|---|---| +| DSR idle p50/p99 (ms) | 0.69 / 22.7 | 0.35 / 0.68 | 0.19 / 0.72 | +| DSR under 1 MB/s agent load p50/p99 (ms) | **134 / 292** | 0.45 / 7.9 | 0.21 / 6.1 | +| agent-tui fenced throughput | **2.0 MB/s** | 37 | 78 | +| ascii-log fenced throughput | 13 MB/s | 39 | 93 | + +Decomposition of the 51× agent-tui gap — both pipeline ends are fast: + +- Bare `@xterm/headless` (114×85, scrollback 5000): agent-tui **103 MB/s** + (`terminal-headless-parse-bench.mjs`). The xterm parser is not the problem. +- Daemon `Session` ingest (emulator + pending-output recording + fanout): + agent-tui **103 MB/s** (`session-ingest-throughput.bench.test.ts`, + `ORCA_TERMINAL_PERF_BENCH=1`). The daemon is not the problem. + +Conclusions: (1) idle latency is fine — the extra process hop costs ~0.5 ms, +so the utilityProcess router is deprioritized by data; (2) the crisis is +queueing between daemon egress and renderer parse completion — main +per-chunk processing, the 512 KB delivery/ACK pacing (ACKs fire after +renderer write callbacks, so renderer slowness throttles delivery +multiplicatively), and renderer per-chunk layers above xterm; (3) the +agent-TUI shape (DEC-2026 frames + erase/repaint) is 6.5× worse than plain +text inside Orca while being equal-cost everywhere else — profile it in the +renderer first (task #9). + +### 2026-07-02 — dev-build check of #7139/#7150 (confounded; directional only) + +Dev build of orca-performance (282-col window, 3MB fixtures, dev-mode +overhead): DSR idle p50 0.64 ms (unchanged), **DSR under load p50 161 ms** — +the cooperative-drain branch does not move the under-load class. In +hindsight this is structural: DSR replies are ordered within the output +stream, so the metric measures output-queue depth; #7139 paces draining to +protect input-send responsiveness but cannot reorder the queue. Implications: +(1) the 134 ms-class number is fixed only by shrinking the queue (producer +flow control) or raising drain rate (the 51× throughput hunt); (2) #7153's +own wins (freeze class, bounded memory, input-loss guards) must be validated +with freeze scenarios and real typing, not DSR. Also learned: dev-mode runs +are ~2× slower across the board and fences need `--dsr-timeout-ms` headroom. + +### 2026-07-02 — 51× loss attributed: scheduler fixed-nap drip (task #9) + +The renderer output scheduler (`pane-terminal-output-scheduler.ts`) drained +at most 2×16KB per tick, then slept 4ms (high-priority) / 16ms (background) +regardless of parse speed. Isolation bench (fake timers, instant-parse +terminal — `pane-terminal-output-scheduler-throughput.bench.test.ts`, +`ORCA_TERMINAL_PERF_BENCH=1`): **background cadence = 1.9 MB/s — matching +prod's measured 2.0 MB/s agent-tui ceiling**; foreground = 27 MB/s (only +when arrivals re-poke 0ms drains; Chromium's ~4ms timer clamp makes the +sustained real-world HP ceiling ~8 MB/s). Classification: pty-connection's +`isLatencySensitiveForegroundOutput` routes sizable no-recent-input chunks +to the queue, so floods always ride the drip. + +Fix (committed 9e8bb2243): high-priority drains are now **parse-clocked** — +a pacer re-arms a 0ms drain when xterm's write callback confirms the batch +parsed — and carry 8 writes/tick (128KB ≈ 1.3ms parse). Isolation ceiling: +27 → **117.6 MB/s** (parse-limited). Background cadence deliberately +unchanged (protects the focused pane; hidden panes are term-speed-2's job). +`DRAIN_TIME_BUDGET_MS` still bounds tick work (cooperative-drain intent of +#7139 preserved; its budget-yield test still passes). 621 tests green. + +Open follow-ups from this attribution: (a) end-to-end dev verification (in +progress); (b) whether main's `background:true` delivery marking demotes +visible-pane floods to the background drip — check +`window.__terminalOutputSchedulerDebug` counters in a dev run; (c) ascii-log +gap (13 vs 83 MB/s headless) — likely per-chunk `beforeWrite` side-effect +scanning; profile after (a). + +### 2026-07-03 — THE WHALE: main's retained-tail redraw path is O(tail) per chunk + +Parse-clock fix didn't move end-to-end (agent-tui still 0.7 MB/s dev). Layered +probes (renderer scheduler counters → main whole-method timer → per-section +timers → targeted micro-benches) attributed it fully: + +- Renderer receives only ~350–770 KB/s — it is **starved**, not slow. +- `OrcaRuntime.onPtyData` consumes **~93% of main's event loop** during the + flood (~950 ms/s at ~450 chunks/s ≈ 2.1 ms/chunk). +- All wrapped sub-calls (OSC scanners, agent detect, watchers, headless + track, leaves loop, mobile touch) together: **~3.5%**. The remainder is the + pty-record tail block. +- Micro-bench (`appendNormalizedToTailBuffer` with a real agent-TUI frame + containing `ESC[10A ESC[0J`): **0.888 ms/chunk at a 2,000-line tail** — 32× + the plain-append path. Cause: `appendNormalizedToMultilineTailBuffer` + materializes ~2,001 row objects per chunk (orca-runtime.ts:22324) and + `finalizeRetainedTerminalRows` allocates them all again plus runs a + trailing-whitespace regex per row (:22458) — ~4k allocations + 2k regexes + per tiny chunk, twice the tail length in O(n) passes. Every Claude-Code + frame (cursor-up + erase-below) takes this path; plain logs don't — which + is exactly the measured agent-tui vs ascii asymmetry. + +Chain: TUI flood → O(tail) work per chunk in main → main event loop +saturates → daemon socket backpressures → renderer starved at ~0.4 MB/s → +deep queue → 134 ms DSR-under-load. + +Fix (in progress): run the existing algorithm on a lazy suffix window (the +cursor's maximum upward reach, computed from the chunk) with the untouched +prefix shared by reference; differential fuzz test proves output equality +against the original implementation. Worst case (pathological full-height +cursor-up) falls back to today's cost. + +### 2026-07-03 — windowed-tail fix: partial end-to-end win; next suspect queued + +Dev-build bench after the windowed redraw-tail fix (label dev-tailfix, same +protocol as dev-parseclock): agent-tui **0.7 → 1.0 MB/s (+43%)**, DSR-under- +load **p50 161 → 108 ms, p99 624 → 154 ms (4×)**. Real movement for the +first time, but the pipeline is still far from the renderer's 27–117 MB/s +capacity — another main-side consumer remains hot. + +Next cycle (exact recipe): re-apply the whole-method main probe +(`onPtyDataMs` sampler in `pty.ts` bindProviderListeners) on the fixed +build. If onPtyData still dominates, the remaining O(tail)/per-chunk +suspects in priority order: (1) `buildTerminalWaitText` ×2 per chunk (full +tail join, 0.116 ms/chunk in prod-node isolation — likely 2-4× that in +dev); (2) `normalizeTerminalChunk` (regex over every chunk, never measured); +(3) the per-leaf duplicate tail path when `tailStateMatches` fails. If +onPtyData no longer dominates, probe the main→renderer delivery batching +next. The probe/bench cycle is mechanical: relaunch dev +(`ELECTRON_ENABLE_LOGGING=1 pnpm dev`), `orca-dev terminal create --command +" --label X --size-mb 3 --dsr-timeout-ms 120000"`, grep the log. + +### 2026-07-03 — post-fix attribution: `blockedCheck` is the remaining whale + +Post-windowed-tail probe run (dev build, agent-tui): `onPtyData` still +~90% of main's event loop (~930 ms/s). Bucket split per second: +**blockedCheck ≈ 700–790 ms (~85%)**, waitText ≈ 70, append ≈ 25 (windowed +fix confirmed), normalize ≈ 7, preview ≈ 0. + +Mechanism (orca-runtime.ts:23128 `nextTailHasNewerBlockedReason` + its +callers): per chunk, TWO full wait texts are built (`buildTerminalWaitText` +joins the whole ≤256KB tail), then the check calls `.toLowerCase()` on both +(another ~512KB of string allocation per chunk) and runs multi-pattern +blocked/ready scans (`findTerminalWaitBlockedSignal`, +`findKnownReadyPromptIndex` — lastIndexOf/regex passes over the full text) +— all to timestamp `waitBlockedAt` for `terminal wait`. + +Fix design (next session): blocked/ready prompts are end-anchored — an +actionable prompt is at the END of output. (1) Run the check on a bounded +suffix of the wait text (last ~64 lines / 16KB) instead of the full tail; +(2) cheap pre-filter: skip entirely unless the appended chunk (plus a small +carry for split keywords) can contain a blocked keyword; (3) build the two +wait texts only when the check runs. Verification mirrors the windowed-tail +pattern: keep the full-text check as reference + differential fuzz over +randomized tails/prompts (split-across-chunks cases included — the +`appendCandidateSignal` ordering semantics at :23146 must be preserved), +plus the terminal-wait contract tests. Expected effect: removes ~85% of +remaining onPtyData cost; combined with the two landed fixes should +finally unlock the pipeline toward the renderer's measured 27–117 MB/s. + +### 2026-07-03 — pipeline unlocked: three stacked fixes, 16× throughput, 9× latency + +Dev-build bench with all three fixes (parse-clocked drains 9e8bb2243, +windowed tail 4e08a28cd, throttled blocked-check 66f20258e), label +dev-blockedfix, same protocol/config as prior dev rows: + +| metric | pre-fix dev | +tail fix | +blocked fix | +|---|---|---|---| +| agent-tui MB/s | 0.7 | 1.0 | **11.5** | +| DSR load p50/p99 (ms) | 161 / 624 | 108 / 154 | **18.8 / 24.9** | +| DSR idle p50/p99 (ms) | 0.95 / 21 | 1.09 / 18 | **0.52 / 8.6** | +| ascii-log MB/s | 6.4 | 4.7 | **9.6** | + +The agent-TUI-specific penalty is gone (agent-tui ≈ cjk ≈ ascii now). The +throttled blocked-check delivered the predicted ~85% cut. Dev mode carries +~2× overhead vs prod, so the prod build should land near ~10ms DSR-under- +load — from the 134ms baseline (~13×) — pending a packaged-build rerun. +Remaining floor is structural cadence (8ms daemon batch + 4ms HP drain +ticks + xterm 12ms slices), which flow control (#6) does not target; +re-evaluate the "within 10× of Terminal.app" goal line after a prod +measurement. Next: term-speed-2 revival (#4), then flow control (#6). + +### 2026-07-03 — term-speed-2 revival: merged, green, NOT yet mergeable (perf gate) + +`revive/term-speed-2` pushed (merge a5052c35f, tip 64b6f7abe): 144 files, +typecheck clean, ~2,776 targeted tests green, all three of our fixes +verified present, chain features present and kill-switched (subagent's +six review risks recorded in its report). Bench verdict on the revived +build (dev): DSR-load p50 ~19ms holds, but **throughput regressed ~35% +unconditionally** (agent-tui 11.5 → 7.2–7.4 MB/s; all-switches-OFF round +proved the kill switches are NOT the cost) and idle p50 doubled. + +Attribution so far: main exonerated (whole-method probe: onPtyData ~60ms/s +≈ 6%); renderer reconcile + HP-first selection O(1)-checked; **daemon +CONVICTED by unit bench — `Session` ingest 103 → 39.5/47.7 MB/s (2.2–2.6×) +on the revive branch** (`session-ingest-throughput.bench.test.ts`, +ORCA_TERMINAL_PERF_BENCH=1). Cause: the chain's headless-emulator +restructure (scanner classes / query-reply forwarding / view-attribute +responder) added per-byte cost to the daemon hot path. Chunks reaching +main are now ~5.8KB vs ~650B (daemon emits slower, batches bigger). + +NEXT (fast inner loop — pure unit bench, no app restarts): on +revive/term-speed-2, diff `headless-emulator.ts`/`session.ts` vs +7839fb9db, find the per-chunk scanner cost, restore our bounded-parser +fast paths (the daemon emulator must never pay per-byte JS scanning for +bytes that contain no ESC — same pre-filter pattern as the blocked-check +keyword bypass), verify with the ingest bench back at ~100 MB/s, then +full dev bench expecting blockedfix parity (~11.5 MB/s), THEN merge to +orca-performance. A residual renderer-side share is possible once the +daemon is fixed — re-attribute after. + +Merge gate: revive branch merges only at ≥ blockedfix numbers. + +**RETRACTION (2026-07-03, later):** the daemon conviction above was a +confounded measurement — the 39–48 MB/s ingest runs executed while a dev +app was still running. On a quiet machine the revive branch ingests at +**82–109 MB/s** (≈ pre-merge) and its HeadlessEmulator alone does 99.5 MB/s +vs raw xterm 77.7. The daemon is innocent. Consequently the end-to-end +revival delta (11.5 → 7.2/7.4 dev) is also UNTRUSTED — none of those runs +were load-controlled, and unit benches show up to 2.6× machine-load +variance. Scanner pre-filters landed anyway on revive (71c89da9b; +strictly positive, 641 daemon tests green). + +**New measurement protocol (mandatory from here):** quiet machine (no dev +apps or benches concurrent), paired A/B runs back-to-back alternating +branches, n≥2 per side, report spread not just p50. The merge-gate +comparison (blockedfix vs revive) must be redone under this protocol +before any verdict. Next: run the controlled A/B; if the delta +disappears, merge revive into orca-performance and proceed to flow +control (#6); if it persists, resume attribution renderer-side (probe +pty-connection dataCallback additions per chunk). + +### 2026-07-03 — A/B gate passed; term-speed-2 MERGED to orca-performance + +Load-controlled alternating A/B (fresh app per run, n=2/side, agent-tui + +DSR-load): perf 6.7/5.2 MB/s, dsr p50 19.9/21.3, p99 107.8/218.1; revive +6.1/3.6 MB/s, dsr p50 21.4/20.3, **p99 63.4/26.1**. Verdict: latency p50 +tied, p99 better on revive, throughput within overlapping noise (revive2's +3.6 followed two runtime-busy create failures). The earlier "35% +regression" is confirmed noise. Note: both branches ~5-7 MB/s today vs +11.5 yesterday — dev benches carry ~2x day-to-day machine variance; +absolute dev numbers are only comparable within one A/B session. + +Merged revive/term-speed-2 → orca-performance; typecheck clean, 288 +post-merge spot tests green. orca-performance now = main-ish base + #7153 ++ three perf fixes + full term-speed-2 chain (kill-switched, default ON) ++ scanner pre-filters. Extended user testing now covers everything. +Remaining from the revival agent's risk list: gate×drain e2e specs +(terminal-hidden-*, parked-memory, sleep-wake) still not run — queue them. +Next: producer flow control (#6) per design §5; prod packaged-build bench +for the real headline numbers. + +### 2026-07-03 — flow control merged; goal-state accounting + +Producer flow control merged to orca-performance (348aeb325): protocol +v19 `pausePty`/`resumePty`, 256KB/32KB watermarks on main's pendingData, +node-pty kernel backpressure, 5s daemon-side lost-resume failsafe + +main-side pause re-assert, resume on every teardown path, version-gated +(v≤18/SSH no-op), kill switch `PRODUCER_FLOW_CONTROL_ENABLED` +(ipc/pty.ts:143), 29 new tests. Typecheck + 292 post-merge spot tests +green. + +**Definition-of-done accounting:** +- 51× loss: ATTRIBUTED AND FIXED (three fixes; agent-tui 0.7→11.5 MB/s + and DSR-load p50 161→18.8 dev, results committed). +- term-speed-2: REVIVED AND MERGED (A/B gate passed). +- Flow control: IMPLEMENTED AND MERGED. +- "Within 10× of Terminal.app (4.5ms)": RE-SCOPED to pending a packaged + RC measurement. Evidence: dev = 18.8ms with ~2× dev overhead → prod + projection ~9-10ms ≈ 20× Terminal.app (vs 300× at baseline). The + remaining gap is structural cadence (daemon 8ms batch, renderer drain + ticks, xterm 12ms parse slices) — tunable follow-ups, distinct from the + waste class this initiative eliminated. Prod verification path: + electron-vite preview CANNOT host the bench (CLI-created panes are not + adopted by the preview window's renderer → no ACKs → pending-cap drop; + two attempts, documented) — measure on the next packaged RC cut from + orca-performance using the committed rig + protocol instead. + +**Deferred, ordered:** (1) sync orca-performance with main — conflicts +incl. stream-opcode collision (chain `Ack=12` vs main's #7205-era +`Metadata=12`; renumber chain side, audit mobile/web stream consumers); +(2) chain's e2e specs (hidden parking / parked memory / sleep-wake) — +gate×drain risk; (3) cadence tuning toward the 10× line; (4) rig +extensions + P90 telemetry (tasks #3/#8). + +### 2026-07-03 — PROD VERDICT: v1.4.121-rc.0 benchmarked (the headline numbers) + +Same rig, same protocol, same machine as the 1.4.91 baseline: + +| metric | 1.4.91 baseline | v1.4.121-rc.0 | change | +|---|---|---|---| +| DSR idle p50 | 0.69 ms | **0.44 ms** | = Terminal.app (0.45) | +| DSR under load p50 | 134 ms | **18.6 ms** | 7.2x | +| DSR under load p99 | 292 ms | **29.7 ms** | 9.8x | +| agent-tui | 2.0 MB/s | **11.2 MB/s** | 5.6x | +| styles-stress | 7.8 MB/s | **10.4 MB/s** | 1.3x | +| ascii-log | 13 MB/s | 11.0 MB/s | ~0.85x | +| cjk-emoji | 15 MB/s | 12.2 MB/s | ~0.81x | + +Reading: the anomalous TUI penalty is GONE — all four fixtures now sit at +a uniform ~11-12 MB/s, which is the scheduler pacing ceiling, not parse +CPU (prod ≈ dev for both latency and throughput; the pipeline is +cadence-bound, so faster prod code changes nothing). That uniform cap +also explains plain-text dipping slightly below baseline: ascii/cjk used +to run unpaced ahead of the old scheduler; now everything flows through +the same parse-clocked path. Goal line check: 18.6 ms = 41x Terminal.app +under load (goal was 10x = 4.5 ms) — NOT met; down from 300x. Idle IS at +parity. The remaining 4x is the named cadence stack (daemon 8 ms batch, +scheduler drain ticks + 8x16KB per-tick budget, xterm 12 ms slices) — +next lever, tunable, tracked as follow-up. p99 tail (the freeze class) +is 29.7 ms — users cannot perceive it. + +Caveat: measured on the user's live app (this session active in it); +idle p99 118 ms reflects that activity, not the terminal path. + +### 2026-07-03 — Same-engine reference: VS Code head-to-head (same machine, same rig) + +| metric | Orca v1.4.121-rc.0 | VS Code | verdict | +|---|---|---|---| +| DSR idle p50 | **0.44 ms** | 7.00 ms | Orca 16x faster | +| DSR load p50 | 18.6 ms | **7.18 ms** | VS Code 2.6x faster | +| DSR load p99 | **29.7 ms** | 43.4 ms | Orca 1.5x better tail | +| ascii-log | **11.0 MB/s** | 9.0 | Orca +22% | +| cjk-emoji | 12.2 | 11.3 | tie | +| agent-tui | 11.2 | 11.7 | tie | +| styles-stress | **10.4 MB/s** | 2.0 | Orca 5.2x | + +Orca now beats or ties the best-known xterm.js terminal on 5 of 6 +metrics — including 16x at idle (what users feel all day) and 5x on +SGR-heavy output — and holds a better p99 tail under load. Throughput +sits at the shared engine ceiling (~9-12 MB/s), confirming the class +limit. + +The one loss (load p50) has a clean mechanism: VS Code's producer flow +control caps unacked output at ~100KB, so its standing queue is +~100KB / 11.7 MB/s ≈ 8.5 ms — matching its 7.18. Our standing queue +(18.6 ms ≈ ~200KB at 11 MB/s) is set by the main→renderer ACK window +(512KB/pty high water) + drain re-arm cadence (Chromium clamps nested +setTimeout to ~4ms). Two levers, both cheap to test: (1) MessageChannel +drain scheduling (sub-ms re-arm; also raises the throughput ceiling); +(2) tighter effective in-flight window on the renderer delivery path. +Target: VS Code's ~7ms class or below without giving back throughput. + +### 2026-07-03 — Batch windows were the gap: dev DSR-load p50 19 -> 8.0ms + +Lever results (dev, 3MB protocol, same session): +- MessageChannel drains (2434dfaae): 19.01ms — NO change. Proved the + ~19ms was NOT queue depth: at 1MB/s vs ~11MB/s capacity (9% util) + there is no standing queue. Kept (correct, removes a real clamp). +- Batch windows 8->2ms on BOTH hops (e67a91d7a: daemon + STREAM_DATA_BATCH_INTERVAL_MS + main PTY_BATCH_INTERVAL_MS): + **p50 8.00 / p90 10.13 / p99 12.26ms** (from 19.01/22.7/28.1). + Throughput unchanged (agent-tui 9.8 vs 9.1, ambient noise). 239 + batcher+pty tests green after timing updates. + +Dev-mode 8.0ms already matches VS Code prod (7.18); prod build should +land BELOW VS Code. p99: ours 12.3 vs VS Code 43.4. The remaining +fixed-latency terms are renderer/xterm-internal (12ms parse slices). +Note: main's interactive bypass (input-gated) means real keystroke echo +skips batching entirely — the DSR metric understates real typing +responsiveness; VS Code measured on the same freight path, comparison +fair. + +Next: cut RC, confirm in prod, re-baseline vs Terminal.app (expect +~8-15x from 300x at baseline; goal line 10x = 4.5ms now plausibly in +reach). + +### 2026-07-03 — Chain e2e debt PAID: all 6 hidden-pane specs green + +terminal-hidden-view-parking (parks + restores rich TUI on reveal; bell/ +title side effects live while parked), terminal-sleep-wake-restore +(output restored + input accepted after wake), terminal-parked-memory +(renderer memory released on park; views retained when kill-switched +off): 6/6 passed, electron-headless, 1.1m. The gate x drain interplay — +the revival's top flagged risk — now has e2e coverage on the exact +branch the RC ships from. Remaining garble-hardening: differential +hide/reveal fuzz harness (next build), reveal-time seq diagnostics. + +## Success criteria (baseline-relative; finalize after task 1) + +- DSR-under-load p90 in Orca within striking distance of iTerm2 on the same + box; zero DSR timeouts (today's freeze class). +- Fenced agent-tui throughput ≥ VS Code on the same box. +- Idle RSS with 0–1 agents materially down (target set after the memory + harness lands; hidden-pane parking is the main lever). +- Zero >100 ms event-loop stalls in main/renderer during a 10 MB flood. +- Production P90 typing latency down and monitored continuously. diff --git a/package.json b/package.json index a793e5c51af9..e6870ba41027 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca", - "version": "1.4.126", + "version": "1.4.135-rc.5", "description": "Next-gen IDE for parallel agentic development", "homepage": "https://github.com/stablyai/orca", "author": "stablyai", @@ -27,10 +27,10 @@ "tc:cli": "pnpm run typecheck:cli", "tc:web": "pnpm run typecheck:web", "tc": "pnpm run typecheck", - "typecheck:node": "tsgo --noEmit -p config/tsconfig.node.json", - "typecheck:cli": "tsgo --noEmit -p config/tsconfig.tc.cli.json", - "typecheck:web": "tsgo --noEmit -p config/tsconfig.tc.web.json", - "typecheck": "tsgo --noEmit -p config/tsconfig.node.json && tsgo --noEmit -p config/tsconfig.tc.cli.json && tsgo --noEmit -p config/tsconfig.tc.web.json", + "typecheck:node": "tsc --noEmit -p config/tsconfig.node.json", + "typecheck:cli": "tsc --noEmit -p config/tsconfig.tc.cli.json", + "typecheck:web": "tsc --noEmit -p config/tsconfig.tc.web.json", + "typecheck": "tsc --noEmit -p config/tsconfig.node.json && tsc --noEmit -p config/tsconfig.tc.cli.json && tsc --noEmit -p config/tsconfig.tc.web.json", "typecheck:tsc:node": "tsc --noEmit -p config/tsconfig.node.json --composite false", "typecheck:tsc:cli": "tsc --noEmit -p config/tsconfig.cli.json --composite false", "typecheck:tsc:web": "tsc --noEmit -p config/tsconfig.web.json --composite false", @@ -42,6 +42,7 @@ "dev:web": "vite --config vite.web.config.ts --host 127.0.0.1", "build:relay": "node config/scripts/build-relay.mjs", "build:computer-macos": "node config/scripts/build-computer-macos.mjs", + "build:notification-status-macos": "node config/scripts/build-notification-status-macos.mjs", "build:native": "node config/scripts/build-native-for-platform.mjs", "smoke:computer": "node config/scripts/computer-use-smoke.mjs", "verify:computer-native": "node config/scripts/verify-computer-native.mjs", @@ -68,8 +69,8 @@ "build:unpack": "pnpm run build && pnpm run ensure:electron-runtime && electron-builder --config config/electron-builder.config.cjs --dir", "build:win": "pnpm run build:desktop && pnpm run ensure:electron-runtime && electron-builder --config config/electron-builder.config.cjs --win", "build:icons": "bash resources/icon-source/generate.sh", - "build:mac": "pnpm run build:desktop && pnpm run build:computer-macos && pnpm run ensure:electron-runtime && electron-builder --config config/electron-builder.config.cjs --mac", - "build:mac:release": "node config/scripts/verify-macos-release-env.mjs && ORCA_MAC_RELEASE=1 pnpm run build:desktop && ORCA_MAC_RELEASE=1 pnpm run build:computer-macos && pnpm run ensure:electron-runtime && ORCA_MAC_RELEASE=1 electron-builder --config config/electron-builder.config.cjs --mac", + "build:mac": "pnpm run build:desktop && pnpm run build:computer-macos && pnpm run build:notification-status-macos && pnpm run ensure:electron-runtime && electron-builder --config config/electron-builder.config.cjs --mac", + "build:mac:release": "node config/scripts/verify-macos-release-env.mjs && ORCA_MAC_RELEASE=1 pnpm run build:desktop && ORCA_MAC_RELEASE=1 pnpm run build:computer-macos && ORCA_MAC_RELEASE=1 pnpm run build:notification-status-macos && pnpm run ensure:electron-runtime && ORCA_MAC_RELEASE=1 electron-builder --config config/electron-builder.config.cjs --mac", "build:linux": "pnpm run build:desktop && pnpm run ensure:electron-runtime && electron-builder --config config/electron-builder.config.cjs --linux AppImage deb", "test:e2e": "pnpm run ensure:electron-runtime && npx playwright test --config tests/playwright.config.ts --project electron-headless", "test:e2e:floating-mobile-emulator": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/floating-mobile-emulator-tab.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -80,7 +81,10 @@ "test:e2e:terminal-perf:scale:report": "pnpm run ensure:electron-runtime && node config/scripts/run-terminal-scale-perf-report-gate.mjs", "test:e2e:terminal-perf:check-report": "node config/scripts/check-terminal-perf-report-budgets.mjs", "test:e2e:terminal-perf:summarize": "node config/scripts/summarize-terminal-perf-report.mjs", + "test:e2e:terminal-perf:html-report": "node config/scripts/generate-terminal-perf-html-report.mjs", "test:e2e:ssh-docker-perf": "node config/scripts/run-ssh-docker-perf-e2e.mjs", + "test:e2e:source-control-scale": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/source-control-large-file-count.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "win-update-e2e": "node tools/win-update-e2e/run.mjs", "test:e2e:ssh-codex-artifacts-repro": "node config/scripts/run-ssh-codex-artifacts-repro-e2e.mjs", "test:e2e:headful": "pnpm run ensure:electron-runtime && npx playwright test --config tests/playwright.config.ts --project electron-headful", "test:e2e:computer": "vitest run --config tests/e2e/vitest.config.ts", @@ -88,6 +92,7 @@ "bench:startup": "pnpm run ensure:electron-runtime && node tools/benchmarks/startup-time-bench.mjs", "bench:daemon-coldstart": "pnpm run ensure:electron-runtime && node tools/benchmarks/daemon-coldstart-bench.mjs", "bench:main-thread-jank": "pnpm run ensure:electron-runtime && node tools/benchmarks/main-thread-jank-bench.mjs", + "bench:multi-workspace-typing": "pnpm run ensure:electron-runtime && node config/scripts/run-multi-workspace-typing-bench.mjs", "bench:compare": "node config/scripts/compare-benchmark-artifacts.mjs" }, "dependencies": { @@ -118,7 +123,7 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@electron-toolkit/tsconfig": "^2.0.0", - "@electron/rebuild": "^4.0.4", + "@electron/rebuild": "^4.2.0", "@monaco-editor/react": "^4.7.0", "@playwright/test": "^1.59.1", "@stablyai/playwright-test": "^2.1.14", @@ -149,7 +154,6 @@ "@types/react-dom": "^19.2.3", "@types/ssh2": "^1.15.5", "@types/ws": "^8.18.1", - "@typescript/native-preview": "7.0.0-dev.20260421.2", "@vitejs/plugin-react": "^5.2.0", "@xterm/addon-fit": "0.12.0-beta.287", "@xterm/addon-ligatures": "0.11.0-beta.287", @@ -162,7 +166,7 @@ "clsx": "^2.1.1", "cmdk": "^1.1.1", "dompurify": "^3.4.11", - "electron": "^42.3.3", + "electron": "^43.1.0", "electron-builder": "^26.8.1", "electron-vite": "^5.0.0", "emoji-picker-react": "^4.19.1", @@ -201,7 +205,8 @@ "tailwind-merge": "^3.5.0", "tailwindcss": "^4.2.4", "tw-animate-css": "^1.4.0", - "typescript": "^5.9.3", + "typescript": "^7.0.2", + "typescript-api": "npm:typescript@6.0.3", "unified": "^11.0.5", "vite": "^7.3.6", "vitest": "^4.1.5", @@ -231,6 +236,9 @@ }, "packageManager": "pnpm@10.24.0+sha512.01ff8ae71b4419903b65c60fb2dc9d34cf8bb6e06d03bde112ef38f7a34d6904c424ba66bea5cdcf12890230bf39f9580473140ed9c946fef328b6e5238a345a", "pnpm": { + "overrides": { + "monaco-editor>dompurify": "3.4.11" + }, "supportedArchitectures": { "os": [ "current", @@ -254,7 +262,8 @@ "patchedDependencies": { "node-pty@1.1.0": "config/patches/node-pty@1.1.0.patch", "@xterm/addon-ligatures@0.11.0-beta.287": "config/patches/@xterm__addon-ligatures@0.11.0-beta.287.patch", - "@xterm/addon-webgl@0.20.0-beta.286": "config/patches/@xterm__addon-webgl@0.20.0-beta.286.patch" + "@xterm/addon-webgl@0.20.0-beta.286": "config/patches/@xterm__addon-webgl@0.20.0-beta.286.patch", + "@xterm/addon-serialize@0.15.0-beta.287": "config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch" } }, "reactDoctor": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 12052fba2e09..b48ad9b4f299 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4,12 +4,18 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +overrides: + monaco-editor>dompurify: 3.4.11 + patchedDependencies: '@xterm/addon-ligatures@0.11.0-beta.287': hash: 47405b9994b5acf1b4e90b49250358c1ca03649854d59560e7732b72fe336920 path: config/patches/@xterm__addon-ligatures@0.11.0-beta.287.patch + '@xterm/addon-serialize@0.15.0-beta.287': + hash: 81575700d58b62f9262d302aa4ae43b445a6273d579cd75dd6729c8883011ab9 + path: config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch '@xterm/addon-webgl@0.20.0-beta.286': - hash: 296e716bb67c0aa3d4ff47d493b9fd9ba9518b7e9f6597005fd680ac04274145 + hash: c32044ff5e9bfa651090eedbec19a13b2343fca3cc163fa8eec04c97880a3e19 path: config/patches/@xterm__addon-webgl@0.20.0-beta.286.patch node-pty@1.1.0: hash: 407ae07e1e0e2ff2e8b58696449c54c31e51d87535bc6aa4a7a7b0b561407282 @@ -21,10 +27,10 @@ importers: dependencies: '@electron-toolkit/preload': specifier: ^3.0.2 - version: 3.0.2(electron@42.3.3) + version: 3.0.2(electron@43.1.0) '@electron-toolkit/utils': specifier: ^4.0.0 - version: 4.0.0(electron@42.3.3) + version: 4.0.0(electron@43.1.0) '@floating-ui/dom': specifier: 1.7.6 version: 1.7.6 @@ -36,7 +42,7 @@ importers: version: 2.5.6 '@xterm/addon-serialize': specifier: 0.15.0-beta.287 - version: 0.15.0-beta.287(@xterm/xterm@6.1.0-beta.287) + version: 0.15.0-beta.287(patch_hash=81575700d58b62f9262d302aa4ae43b445a6273d579cd75dd6729c8883011ab9)(@xterm/xterm@6.1.0-beta.287) '@xterm/headless': specifier: 6.1.0-beta.287 version: 6.1.0-beta.287 @@ -48,7 +54,7 @@ importers: version: 6.8.3 i18next: specifier: ^26.3.1 - version: 26.3.1(typescript@5.9.3) + version: 26.3.1(typescript@7.0.2) jsonc-parser: specifier: ^3.3.1 version: 3.3.1 @@ -63,10 +69,10 @@ importers: version: 1.5.4 react-i18next: specifier: ^17.0.8 - version: 17.0.8(i18next@26.3.1(typescript@5.9.3))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)(typescript@5.9.3) + version: 17.0.8(i18next@26.3.1(typescript@7.0.2))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)(typescript@7.0.2) serve-sim: specifier: ^0.1.40 - version: 0.1.40(typescript@5.9.3) + version: 0.1.40(typescript@7.0.2) sherpa-onnx: specifier: 1.12.37 version: 1.12.37 @@ -96,8 +102,8 @@ importers: specifier: ^2.0.0 version: 2.0.0(@types/node@25.6.0) '@electron/rebuild': - specifier: ^4.0.4 - version: 4.0.4 + specifier: ^4.2.0 + version: 4.2.0 '@monaco-editor/react': specifier: ^4.7.0 version: 4.7.0(monaco-editor@0.55.1)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) @@ -188,9 +194,6 @@ importers: '@types/ws': specifier: ^8.18.1 version: 8.18.1 - '@typescript/native-preview': - specifier: 7.0.0-dev.20260421.2 - version: 7.0.0-dev.20260421.2 '@vitejs/plugin-react': specifier: ^5.2.0 version: 5.2.0(vite@7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)) @@ -211,7 +214,7 @@ importers: version: 0.13.0-beta.287(@xterm/xterm@6.1.0-beta.287) '@xterm/addon-webgl': specifier: 0.20.0-beta.286 - version: 0.20.0-beta.286(patch_hash=296e716bb67c0aa3d4ff47d493b9fd9ba9518b7e9f6597005fd680ac04274145)(@xterm/xterm@6.1.0-beta.287) + version: 0.20.0-beta.286(patch_hash=c32044ff5e9bfa651090eedbec19a13b2343fca3cc163fa8eec04c97880a3e19)(@xterm/xterm@6.1.0-beta.287) '@xterm/xterm': specifier: 6.1.0-beta.287 version: 6.1.0-beta.287 @@ -228,8 +231,8 @@ importers: specifier: ^3.4.11 version: 3.4.11 electron: - specifier: ^42.3.3 - version: 42.3.3 + specifier: ^43.1.0 + version: 43.1.0 electron-builder: specifier: ^26.8.1 version: 26.8.1(electron-builder-squirrel-windows@26.8.1) @@ -331,7 +334,7 @@ importers: version: 11.0.0 shadcn: specifier: ^4.7.0 - version: 4.7.0(@types/node@25.6.0)(typescript@5.9.3) + version: 4.7.0(@types/node@25.6.0)(typescript@7.0.2) sonner: specifier: ^2.0.7 version: 2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5) @@ -345,8 +348,11 @@ importers: specifier: ^1.4.0 version: 1.4.0 typescript: - specifier: ^5.9.3 - version: 5.9.3 + specifier: ^7.0.2 + version: 7.0.2 + typescript-api: + specifier: npm:typescript@6.0.3 + version: typescript@6.0.3 unified: specifier: ^11.0.5 version: 11.0.5 @@ -355,7 +361,7 @@ importers: version: 7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4) vitest: specifier: ^4.1.5 - version: 4.1.5(@types/node@25.6.0)(happy-dom@20.9.0)(msw@2.14.3(@types/node@25.6.0)(typescript@5.9.3))(vite@7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)) + version: 4.1.5(@types/node@25.6.0)(happy-dom@20.9.0)(msw@2.14.3(@types/node@25.6.0)(typescript@7.0.2))(vite@7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)) vscode-oniguruma: specifier: ^2.0.1 version: 2.0.1 @@ -637,6 +643,10 @@ packages: peerDependencies: '@noble/ciphers': ^1.0.0 + '@electron-internal/extract-zip@1.0.4': + resolution: {integrity: sha512-Zr1Vs7E9tpCNhZHDAbFVXc2gEVCG9RqPDjrno5+bdgB6LRAuvgyMHJut4NCVyYwtAieapMzc3fiQ3CSTi75ARg==} + engines: {node: '>=22.12.0'} + '@electron-toolkit/preload@3.0.2': resolution: {integrity: sha512-TWWPToXd8qPRfSXwzf5KVhpXMfONaUuRAZJHsKthKgZR/+LqX1dZVSSClQ8OTAEduvLGdecljCsoT2jSshfoUg==} peerDependencies: @@ -678,8 +688,8 @@ packages: engines: {node: '>=12.0.0'} hasBin: true - '@electron/rebuild@4.0.4': - resolution: {integrity: sha512-Rzc39XPdk/+/wBG8MfwAHohXflep0ITUfulb6Rgz3R0NeSB1noE+E9/M/cb8ftCAiyDD9PPhLuuWgE1GaInbKg==} + '@electron/rebuild@4.2.0': + resolution: {integrity: sha512-RKL/O+jGoXJMxrx/5771y1n0xTKmFuOYGO3gMmwypBM6rsH0kou0mswwdXA2JrhIkE4xyC7v9vGk0n6NPzgOxQ==} engines: {node: '>=22.12.0'} hasBin: true @@ -3083,51 +3093,129 @@ packages: '@types/ws@8.18.1': resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} - '@types/yauzl@2.10.3': - resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==} - '@typescript-eslint/types@8.60.0': resolution: {integrity: sha512-AsE7x2XaAK+CVbeih0Fvbn+r1qHxtpLDJ3XUuFcIinT318T90yHMJC+Zgv+jUuDjQQd06HKwxnDu6sz1IcTilA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript/native-preview-darwin-arm64@7.0.0-dev.20260421.2': - resolution: {integrity: sha512-fHv1r3ZmVo6zxuAIFmuX3w9QxbcauoG0SsWhmDwm6VmRubLlOJIcmTtlmV3JAb9oOnq8LuzZljzT7Q39fSMQDw==} + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} cpu: [arm64] os: [darwin] - '@typescript/native-preview-darwin-x64@7.0.0-dev.20260421.2': - resolution: {integrity: sha512-KWTR6xbW9t+JS7D5DQIzo75pqVXVWUxF9PMv/+S6xsnOjCVd6g0ixHcFpFMJMKSUQpGPr8Z5f7b8ks6LHW01jg==} + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} cpu: [x64] os: [darwin] - '@typescript/native-preview-linux-arm64@7.0.0-dev.20260421.2': - resolution: {integrity: sha512-VLMEuml3BhUb+jaL0TXQ4xvVODxJF+RhkI+tBWvlynsJI4khTXEiwWh+wPOJrsfBRYFRMXEu28Odl/HXkYze8w==} + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} cpu: [arm64] os: [linux] - '@typescript/native-preview-linux-arm@7.0.0-dev.20260421.2': - resolution: {integrity: sha512-BWLQO3nemLDSV5PoE5GPHe1dU9Dth77Kv8/cle9Ujcp4LhPo0KincdPqFH/qKeU/xvW25mgFueflZ1nc4rKuww==} + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} cpu: [arm] os: [linux] - '@typescript/native-preview-linux-x64@7.0.0-dev.20260421.2': - resolution: {integrity: sha512-qUrJWTB5/wv4wnRG0TRXElAxc2kykNiRNyEIEqBbLmzDlrcvAW7RRy8MXoY1ZyTiKGMu14itZ3x9oW6+blFpRw==} + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} cpu: [x64] os: [linux] - '@typescript/native-preview-win32-arm64@7.0.0-dev.20260421.2': - resolution: {integrity: sha512-Rc6NsWlZmCs5YUKVzKgwoBOoRUGsPzct4BDMRX0csD1devLBBc4AbUXWKsJRbpwIAnqMO1ld4sNHEb+wXgfNHQ==} + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} cpu: [arm64] - os: [win32] + os: [netbsd] - '@typescript/native-preview-win32-x64@7.0.0-dev.20260421.2': - resolution: {integrity: sha512-GQv1+dya1t6EqF2Cpsb+xoozovdX10JUSf6Kl/8xNkTapzmlHd+uMr+8ku3jIASTxoRGn0Mklgjj3MDKrOTuLg==} + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] os: [win32] - '@typescript/native-preview@7.0.0-dev.20260421.2': - resolution: {integrity: sha512-CmajHI25HpVWE9R1XFoxr+cphJPxoYD3eFioQtAvXYkMFKnLdICMS9pXre9Pybizb75ejRxjKD5/CVG055rEIg==} - hasBin: true + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] '@ungap/structured-clone@1.3.1': resolution: {integrity: sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==} @@ -3369,7 +3457,6 @@ packages: boolean@3.2.0: resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==} - deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. brace-expansion@1.1.14: resolution: {integrity: sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==} @@ -3390,9 +3477,6 @@ packages: engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true - buffer-crc32@0.2.13: - resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==} - buffer-from@1.1.2: resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} @@ -3938,9 +4022,6 @@ packages: dom-accessibility-api@0.6.3: resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==} - dompurify@3.2.7: - resolution: {integrity: sha512-WhL/YuveyGXJaerVlMYGWhvQswa7myDG17P7Vu65EWC05o8vfeNbvNf4d/BOvH99+ZW+LlQsc1GDKMa1vNK6dw==} - dompurify@3.4.11: resolution: {integrity: sha512-zhlUV12GsaRzMsf9q5M254YhA4+VuF0fG+QFqu6aYpoGlKtz+w8//jBcGVYBgQkR5GHjUomejY84AV+/uPbWdw==} @@ -4004,8 +4085,8 @@ packages: resolution: {integrity: sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==} engines: {node: '>=8.0.0'} - electron@42.3.3: - resolution: {integrity: sha512-0MwYp9wTb7TrtTalOYqeW+suqd9T/Znstr/nDLKqFGIjHdBZX339guo3mQqTPURRZ/UQmYM4uMpzKpI5wLptfQ==} + electron@43.1.0: + resolution: {integrity: sha512-DPfxpQLd4NL3BJ8DBxYAfmLUKKesF5Rx9dQx5FyczAP8bhOPScjHE48GArVeXu68LlAainuwkmQTQvdZwpIIAQ==} engines: {node: '>= 22.12.0'} hasBin: true @@ -4178,11 +4259,6 @@ packages: extend@3.0.2: resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} - extract-zip@2.0.1: - resolution: {integrity: sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==} - engines: {node: '>= 10.17.0'} - hasBin: true - extsprintf@1.4.1: resolution: {integrity: sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==} engines: {'0': node >=0.6.0} @@ -4219,9 +4295,6 @@ packages: fault@2.0.1: resolution: {integrity: sha512-WtySTkS4OKev5JtpHXnib4Gxiurzh5NCGvWrFaZ34m6JehfTUhKZvn9njTfw48t6JumVQOmrKqpmGcdwxnhqBQ==} - fd-slicer@1.1.0: - resolution: {integrity: sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==} - fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -4289,6 +4362,10 @@ packages: resolution: {integrity: sha512-eKpRKAovdpZtR1WopLHxlBWvAgPny3c4gX1G5Jhwmmw4XJj0ifSD5qB5TOo8hmA0wlRKDAOAhEE1yVPgs6Fgcg==} engines: {node: '>=14.14'} + fs-extra@11.3.6: + resolution: {integrity: sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA==} + engines: {node: '>=14.14'} + fs-extra@7.0.1: resolution: {integrity: sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==} engines: {node: '>=6 <7 || >=8'} @@ -4369,7 +4446,6 @@ packages: glob@7.2.3: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} - deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me global-agent@3.0.0: resolution: {integrity: sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==} @@ -4566,7 +4642,6 @@ packages: inflight@1.0.6: resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} - deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} @@ -4892,7 +4967,6 @@ packages: lodash.isequal@4.5.0: resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==} - deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead. lodash@4.18.1: resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} @@ -5240,8 +5314,8 @@ packages: resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==} engines: {node: '>= 0.6'} - node-abi@4.30.0: - resolution: {integrity: sha512-D7v3slBz2jgsBLCY9FnFsD0nlXvuKd49Pl9L+Vj+7ZlivHsLK2mkekQo7vZwYco+kyb4OJlaWfYdr3+27vfYtA==} + node-abi@4.33.0: + resolution: {integrity: sha512-vLBWCKb+7LWsX+TbfzWOkw0W81m377tyx3hOweBTjO43CXZnRGS1/JPWs20fr0PgZyDXk6ROYrylsEycK8raDA==} engines: {node: '>=22.12.0'} node-addon-api@1.7.2: @@ -5256,7 +5330,6 @@ packages: node-domexception@1.0.0: resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==} engines: {node: '>=10.5.0'} - deprecated: Use your platform's native DOMException instead node-fetch@3.3.2: resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==} @@ -5468,9 +5541,6 @@ packages: resolution: {integrity: sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==} engines: {node: '>=12', npm: '>=6'} - pend@1.2.0: - resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==} - picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -6271,11 +6341,16 @@ packages: resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} engines: {node: '>= 18'} - typescript@5.9.3: - resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} engines: {node: '>=14.17'} hasBin: true + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + ufo@1.6.4: resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==} @@ -6610,9 +6685,6 @@ packages: resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} engines: {node: '>=12'} - yauzl@2.10.0: - resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==} - yocto-queue@0.1.0: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} @@ -6987,17 +7059,19 @@ snapshots: dependencies: '@noble/ciphers': 1.3.0 - '@electron-toolkit/preload@3.0.2(electron@42.3.3)': + '@electron-internal/extract-zip@1.0.4': {} + + '@electron-toolkit/preload@3.0.2(electron@43.1.0)': dependencies: - electron: 42.3.3 + electron: 43.1.0 '@electron-toolkit/tsconfig@2.0.0(@types/node@25.6.0)': dependencies: '@types/node': 25.6.0 - '@electron-toolkit/utils@4.0.0(electron@42.3.3)': + '@electron-toolkit/utils@4.0.0(electron@43.1.0)': dependencies: - electron: 42.3.3 + electron: 43.1.0 '@electron/asar@3.4.1': dependencies: @@ -7057,11 +7131,11 @@ snapshots: transitivePeerDependencies: - supports-color - '@electron/rebuild@4.0.4': + '@electron/rebuild@4.2.0': dependencies: '@malept/cross-spawn-promise': 2.0.0 debug: 4.4.3 - node-abi: 4.30.0 + node-abi: 4.33.0 node-api-version: 0.2.1 node-gyp: 12.3.0 read-binary-file-arch: 1.0.6 @@ -7084,7 +7158,7 @@ snapshots: dependencies: cross-dirname: 0.1.0 debug: 4.4.3 - fs-extra: 11.3.5 + fs-extra: 11.3.6 minimist: 1.2.8 postject: 1.0.0-alpha.6 transitivePeerDependencies: @@ -9170,43 +9244,67 @@ snapshots: dependencies: '@types/node': 25.6.0 - '@types/yauzl@2.10.3': - dependencies: - '@types/node': 25.6.0 + '@typescript-eslint/types@8.60.0': {} + + '@typescript/typescript-aix-ppc64@7.0.2': optional: true - '@typescript-eslint/types@8.60.0': {} + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true - '@typescript/native-preview-darwin-arm64@7.0.0-dev.20260421.2': + '@typescript/typescript-darwin-x64@7.0.2': optional: true - '@typescript/native-preview-darwin-x64@7.0.0-dev.20260421.2': + '@typescript/typescript-freebsd-arm64@7.0.2': optional: true - '@typescript/native-preview-linux-arm64@7.0.0-dev.20260421.2': + '@typescript/typescript-freebsd-x64@7.0.2': optional: true - '@typescript/native-preview-linux-arm@7.0.0-dev.20260421.2': + '@typescript/typescript-linux-arm64@7.0.2': optional: true - '@typescript/native-preview-linux-x64@7.0.0-dev.20260421.2': + '@typescript/typescript-linux-arm@7.0.2': optional: true - '@typescript/native-preview-win32-arm64@7.0.0-dev.20260421.2': + '@typescript/typescript-linux-loong64@7.0.2': optional: true - '@typescript/native-preview-win32-x64@7.0.0-dev.20260421.2': + '@typescript/typescript-linux-mips64el@7.0.2': optional: true - '@typescript/native-preview@7.0.0-dev.20260421.2': - optionalDependencies: - '@typescript/native-preview-darwin-arm64': 7.0.0-dev.20260421.2 - '@typescript/native-preview-darwin-x64': 7.0.0-dev.20260421.2 - '@typescript/native-preview-linux-arm': 7.0.0-dev.20260421.2 - '@typescript/native-preview-linux-arm64': 7.0.0-dev.20260421.2 - '@typescript/native-preview-linux-x64': 7.0.0-dev.20260421.2 - '@typescript/native-preview-win32-arm64': 7.0.0-dev.20260421.2 - '@typescript/native-preview-win32-x64': 7.0.0-dev.20260421.2 + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true '@ungap/structured-clone@1.3.1': {} @@ -9236,13 +9334,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.5(msw@2.14.3(@types/node@25.6.0)(typescript@5.9.3))(vite@7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4))': + '@vitest/mocker@4.1.5(msw@2.14.3(@types/node@25.6.0)(typescript@7.0.2))(vite@7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4))': dependencies: '@vitest/spy': 4.1.5 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - msw: 2.14.3(@types/node@25.6.0)(typescript@5.9.3) + msw: 2.14.3(@types/node@25.6.0)(typescript@7.0.2) vite: 7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4) '@vitest/pretty-format@4.1.5': @@ -9288,7 +9386,7 @@ snapshots: dependencies: '@xterm/xterm': 6.1.0-beta.287 - '@xterm/addon-serialize@0.15.0-beta.287(@xterm/xterm@6.1.0-beta.287)': + '@xterm/addon-serialize@0.15.0-beta.287(patch_hash=81575700d58b62f9262d302aa4ae43b445a6273d579cd75dd6729c8883011ab9)(@xterm/xterm@6.1.0-beta.287)': dependencies: '@xterm/xterm': 6.1.0-beta.287 @@ -9300,7 +9398,7 @@ snapshots: dependencies: '@xterm/xterm': 6.1.0-beta.287 - '@xterm/addon-webgl@0.20.0-beta.286(patch_hash=296e716bb67c0aa3d4ff47d493b9fd9ba9518b7e9f6597005fd680ac04274145)(@xterm/xterm@6.1.0-beta.287)': + '@xterm/addon-webgl@0.20.0-beta.286(patch_hash=c32044ff5e9bfa651090eedbec19a13b2343fca3cc163fa8eec04c97880a3e19)(@xterm/xterm@6.1.0-beta.287)': dependencies: '@xterm/xterm': 6.1.0-beta.287 @@ -9369,7 +9467,7 @@ snapshots: '@electron/get': 3.1.0 '@electron/notarize': 2.5.0 '@electron/osx-sign': 1.3.3 - '@electron/rebuild': 4.0.4 + '@electron/rebuild': 4.2.0 '@electron/universal': 2.0.3 '@malept/flatpak-bundler': 0.4.0 '@types/fs-extra': 9.0.13 @@ -9498,8 +9596,6 @@ snapshots: node-releases: 2.0.38 update-browserslist-db: 1.2.3(browserslist@4.28.2) - buffer-crc32@0.2.13: {} - buffer-from@1.1.2: {} buffer@5.7.1: @@ -9722,14 +9818,14 @@ snapshots: dependencies: layout-base: 2.0.1 - cosmiconfig@9.0.1(typescript@5.9.3): + cosmiconfig@9.0.1(typescript@7.0.2): dependencies: env-paths: 2.2.1 import-fresh: 3.3.1 js-yaml: 4.2.0 parse-json: 5.2.0 optionalDependencies: - typescript: 5.9.3 + typescript: 7.0.2 cpu-features@0.0.10: dependencies: @@ -10047,10 +10143,6 @@ snapshots: dom-accessibility-api@0.6.3: {} - dompurify@3.2.7: - optionalDependencies: - '@types/trusted-types': 2.0.7 - dompurify@3.4.11: optionalDependencies: '@types/trusted-types': 2.0.7 @@ -10159,11 +10251,11 @@ snapshots: transitivePeerDependencies: - supports-color - electron@42.3.3: + electron@43.1.0: dependencies: + '@electron-internal/extract-zip': 1.0.4 '@electron/get': 5.0.0 '@types/node': 24.12.4 - extract-zip: 2.0.1 transitivePeerDependencies: - supports-color @@ -10396,16 +10488,6 @@ snapshots: extend@3.0.2: {} - extract-zip@2.0.1: - dependencies: - debug: 4.4.3 - get-stream: 5.2.0 - yauzl: 2.10.0 - optionalDependencies: - '@types/yauzl': 2.10.3 - transitivePeerDependencies: - - supports-color - extsprintf@1.4.1: optional: true @@ -10443,10 +10525,6 @@ snapshots: dependencies: format: 0.2.2 - fd-slicer@1.1.0: - dependencies: - pend: 1.2.0 - fdir@6.5.0(picomatch@4.0.4): optionalDependencies: picomatch: 4.0.4 @@ -10522,6 +10600,13 @@ snapshots: jsonfile: 6.2.1 universalify: 2.0.1 + fs-extra@11.3.6: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.1 + universalify: 2.0.1 + optional: true + fs-extra@7.0.1: dependencies: graceful-fs: 4.2.11 @@ -10852,9 +10937,9 @@ snapshots: husky@9.1.7: {} - i18next@26.3.1(typescript@5.9.3): + i18next@26.3.1(typescript@7.0.2): optionalDependencies: - typescript: 5.9.3 + typescript: 7.0.2 iconv-corefoundation@1.1.7: dependencies: @@ -10893,9 +10978,9 @@ snapshots: inline-style-parser@0.2.7: {} - inspect-webkit@0.0.5(typescript@5.9.3): + inspect-webkit@0.0.5(typescript@7.0.2): dependencies: - typescript: 5.9.3 + typescript: 7.0.2 internmap@1.0.1: {} @@ -11674,12 +11759,12 @@ snapshots: monaco-editor@0.55.1: dependencies: - dompurify: 3.2.7 + dompurify: 3.4.11 marked: 14.0.0 ms@2.1.3: {} - msw@2.14.3(@types/node@25.6.0)(typescript@5.9.3): + msw@2.14.3(@types/node@25.6.0)(typescript@7.0.2): dependencies: '@inquirer/confirm': 6.0.12(@types/node@25.6.0) '@mswjs/interceptors': 0.41.8 @@ -11700,7 +11785,7 @@ snapshots: until-async: 3.0.2 yargs: 17.7.2 optionalDependencies: - typescript: 5.9.3 + typescript: 7.0.2 transitivePeerDependencies: - '@types/node' @@ -11713,9 +11798,9 @@ snapshots: negotiator@1.0.0: {} - node-abi@4.30.0: + node-abi@4.33.0: dependencies: - semver: 7.7.4 + semver: 7.8.1 node-addon-api@1.7.2: optional: true @@ -11724,7 +11809,7 @@ snapshots: node-api-version@0.2.1: dependencies: - semver: 7.7.4 + semver: 7.8.1 node-domexception@1.0.0: {} @@ -11741,7 +11826,7 @@ snapshots: graceful-fs: 4.2.11 nopt: 9.0.0 proc-log: 6.1.0 - semver: 7.7.4 + semver: 7.8.1 tar: 7.5.16 tinyglobby: 0.2.16 undici: 6.27.0 @@ -11971,8 +12056,6 @@ snapshots: pe-library@0.4.1: {} - pend@1.2.0: {} - picocolors@1.1.1: {} picomatch@2.3.2: {} @@ -12257,16 +12340,16 @@ snapshots: optionalDependencies: react: 19.2.5 - react-i18next@17.0.8(i18next@26.3.1(typescript@5.9.3))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)(typescript@5.9.3): + react-i18next@17.0.8(i18next@26.3.1(typescript@7.0.2))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)(typescript@7.0.2): dependencies: '@babel/runtime': 7.29.7 html-parse-stringify: 3.0.1 - i18next: 26.3.1(typescript@5.9.3) + i18next: 26.3.1(typescript@7.0.2) react: 19.2.5 use-sync-external-store: 1.6.0(react@19.2.5) optionalDependencies: react-dom: 19.2.5(react@19.2.5) - typescript: 5.9.3 + typescript: 7.0.2 react-is@17.0.2: {} @@ -12582,9 +12665,9 @@ snapshots: type-fest: 0.13.1 optional: true - serve-sim@0.1.40(typescript@5.9.3): + serve-sim@0.1.40(typescript@7.0.2): dependencies: - inspect-webkit: 0.0.5(typescript@5.9.3) + inspect-webkit: 0.0.5(typescript@7.0.2) transitivePeerDependencies: - typescript @@ -12603,7 +12686,7 @@ snapshots: setprototypeof@1.2.0: {} - shadcn@4.7.0(@types/node@25.6.0)(typescript@5.9.3): + shadcn@4.7.0(@types/node@25.6.0)(typescript@7.0.2): dependencies: '@babel/core': 7.29.7 '@babel/parser': 7.29.3 @@ -12614,7 +12697,7 @@ snapshots: '@types/validate-npm-package-name': 4.0.2 browserslist: 4.28.2 commander: 14.0.3 - cosmiconfig: 9.0.1(typescript@5.9.3) + cosmiconfig: 9.0.1(typescript@7.0.2) dedent: 1.7.2 deepmerge: 4.3.1 diff: 8.0.4 @@ -12624,7 +12707,7 @@ snapshots: fuzzysort: 3.1.0 https-proxy-agent: 7.0.6 kleur: 4.1.5 - msw: 2.14.3(@types/node@25.6.0)(typescript@5.9.3) + msw: 2.14.3(@types/node@25.6.0)(typescript@7.0.2) node-fetch: 3.3.2 open: 11.0.0 ora: 8.2.0 @@ -12953,7 +13036,30 @@ snapshots: media-typer: 1.1.0 mime-types: 3.0.2 - typescript@5.9.3: {} + typescript@6.0.3: {} + + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 ufo@1.6.4: {} @@ -13097,10 +13203,10 @@ snapshots: lightningcss: 1.32.0 yaml: 2.8.4 - vitest@4.1.5(@types/node@25.6.0)(happy-dom@20.9.0)(msw@2.14.3(@types/node@25.6.0)(typescript@5.9.3))(vite@7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)): + vitest@4.1.5(@types/node@25.6.0)(happy-dom@20.9.0)(msw@2.14.3(@types/node@25.6.0)(typescript@7.0.2))(vite@7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)): dependencies: '@vitest/expect': 4.1.5 - '@vitest/mocker': 4.1.5(msw@2.14.3(@types/node@25.6.0)(typescript@5.9.3))(vite@7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)) + '@vitest/mocker': 4.1.5(msw@2.14.3(@types/node@25.6.0)(typescript@7.0.2))(vite@7.3.6(@types/node@25.6.0)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)) '@vitest/pretty-format': 4.1.5 '@vitest/runner': 4.1.5 '@vitest/snapshot': 4.1.5 @@ -13234,11 +13340,6 @@ snapshots: y18n: 5.0.8 yargs-parser: 21.1.1 - yauzl@2.10.0: - dependencies: - buffer-crc32: 0.2.13 - fd-slicer: 1.1.0 - yocto-queue@0.1.0: {} yocto-spinner@1.2.0: diff --git a/previews/mobile-driver-overlay-preview.html b/previews/mobile-driver-overlay-preview.html deleted file mode 100644 index 8c300f3dcadd..000000000000 --- a/previews/mobile-driver-overlay-preview.html +++ /dev/null @@ -1,523 +0,0 @@ - - - - - - Mobile Driver Overlay — Orca Preview - - - -

    -

    Mobile Driver Overlay — production layout preview

    -
    - - - -
    -
    - -
    -
    -
    -
    - bash — fix-phone-resizing -
    - -
    - - - - - - - - - - -
    -
    -
    -
    - - - - \ No newline at end of file diff --git a/src/cli/agent-context.test.ts b/src/cli/agent-context.test.ts new file mode 100644 index 000000000000..4574b795c006 --- /dev/null +++ b/src/cli/agent-context.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest' + +import type { CommandSpec } from './args' +import { buildAgentContext, formatAgentContextSummary } from './agent-context' +import { COMMAND_SPECS } from './specs' + +describe('buildAgentContext', () => { + const specs: CommandSpec[] = [ + { + path: ['worktree', 'rm'], + aliases: [ + ['worktree', 'remove'], + ['worktree', 'delete'] + ], + summary: 'Remove a worktree', + usage: 'orca worktree rm', + allowedFlags: ['worktree', 'force'] + }, + { + path: ['agent-context'], + summary: 'Print the schema', + usage: 'orca agent-context', + allowedFlags: [] + } + ] + + it('emits a versioned envelope with a command count', () => { + const schema = buildAgentContext(specs) + expect(schema.schemaVersion).toBe(1) + expect(schema.commandCount).toBe(2) + expect(schema.commands).toHaveLength(2) + }) + + it('includes resolved aliases for a command', () => { + const schema = buildAgentContext(specs) + const rm = schema.commands.find((command) => command.command === 'worktree rm') + expect(rm?.aliases).toEqual([ + ['worktree', 'remove'], + ['worktree', 'delete'] + ]) + }) + + it('reports effective flags including globals, not just allowedFlags', () => { + const schema = buildAgentContext(specs) + const rm = schema.commands.find((command) => command.command === 'worktree rm') + expect(rm?.flags).toContain('worktree') + expect(rm?.flags).toContain('force') + expect(rm?.flags).toContain('json') + expect(rm?.flags).toContain('help') + }) + + it('orders commands deterministically', () => { + const schema = buildAgentContext(specs) + expect(schema.commands.map((command) => command.command)).toEqual([ + 'agent-context', + 'worktree rm' + ]) + }) + + it('defaults optional fields to empty arrays', () => { + const schema = buildAgentContext(specs) + const agentContext = schema.commands.find((command) => command.command === 'agent-context') + expect(agentContext?.aliases).toEqual([]) + expect(agentContext?.examples).toEqual([]) + }) +}) + +describe('agent-context over the live registry', () => { + it('exposes the worktree rm command with its remove/delete aliases', () => { + const schema = buildAgentContext(COMMAND_SPECS) + const rm = schema.commands.find((command) => command.command === 'worktree rm') + expect(rm).toBeDefined() + expect(rm?.aliases).toContainEqual(['worktree', 'remove']) + }) + + it('human summary count matches the command count', () => { + const schema = buildAgentContext(COMMAND_SPECS) + expect(formatAgentContextSummary(schema)).toContain(`${schema.commandCount} commands`) + }) + + it('does not advertise browser page targeting for local discovery', () => { + const schema = buildAgentContext(COMMAND_SPECS) + const agentContext = schema.commands.find((command) => command.command === 'agent-context') + expect(agentContext?.flags).not.toContain('page') + }) + + it('marks raw passthrough commands without synthesizing Orca flags', () => { + const schema = buildAgentContext(COMMAND_SPECS) + const claudeTeams = schema.commands.find((command) => command.command === 'claude-teams') + expect(claudeTeams?.argumentMode).toBe('passthrough') + expect(claudeTeams?.flags).toEqual([]) + }) +}) diff --git a/src/cli/agent-context.ts b/src/cli/agent-context.ts new file mode 100644 index 000000000000..ca718cc0fe6e --- /dev/null +++ b/src/cli/agent-context.ts @@ -0,0 +1,60 @@ +import type { CommandSpec } from './args' +import { effectiveAllowedFlags } from './args' + +// Why: serialize the live spec table so agent discovery cannot drift from the +// command surface it describes. + +const SCHEMA_VERSION = 1 + +export type AgentContextCommand = { + command: string + path: string[] + aliases: string[][] + argumentMode: 'parsed' | 'passthrough' + summary: string + usage: string + flags: string[] + positionalArgs: string[] + examples: string[] + notes: string[] +} + +export type AgentContextSchema = { + schemaVersion: number + commandCount: number + commands: AgentContextCommand[] +} + +export function buildAgentContext(specs: CommandSpec[]): AgentContextSchema { + const commands = specs + .map((spec) => ({ + command: spec.path.join(' '), + path: spec.path, + aliases: spec.aliases ?? [], + argumentMode: spec.argumentMode ?? 'parsed', + summary: spec.summary, + usage: spec.usage, + // Why: the effective accepted set (globals + conditional --page), not just + // allowedFlags — otherwise agents treat --json/--help as unsupported. + flags: effectiveAllowedFlags(spec), + positionalArgs: spec.positionalArgs ?? [], + examples: spec.examples ?? [], + notes: spec.notes ?? [] + })) + // Why: deterministic ordering so the JSON diffs cleanly across runs. + .sort((a, b) => a.command.localeCompare(b.command)) + return { + schemaVersion: SCHEMA_VERSION, + commandCount: commands.length, + commands + } +} + +export function formatAgentContextSummary(schema: AgentContextSchema): string { + // Why: keep the default (human) output bounded — the full surface is large, so + // point the reader at --json rather than dumping every command. + return [ + `${schema.commandCount} commands (schema v${schema.schemaVersion}).`, + 'Run `orca agent-context --json` for the full machine-readable command schema.' + ].join('\n') +} diff --git a/src/cli/args.test.ts b/src/cli/args.test.ts index 6755fca0a2b6..f6f721115658 100644 --- a/src/cli/args.test.ts +++ b/src/cli/args.test.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from 'vitest' +import type { CommandSpec } from './args' import { REPEATED_FLAG_SEPARATOR, + findCommandSpec, normalizeCommandPositionals, parseArgs, supportsBrowserPageFlag, @@ -44,6 +46,73 @@ describe('parseArgs', () => { expect(parsed.flags.get('url')).toBe('https://example.com') }) + it('does not consume a command token after an unknown flag', () => { + const parsed = parseArgs(['--jso', 'worktree', 'list'], [['worktree', 'list']]) + + expect(parsed.commandPath).toEqual(['worktree', 'list']) + expect(parsed.flags.get('jso')).toBe(true) + }) + + it('does not consume a command token after a flag valid on another command', () => { + const parsed = parseArgs(['--workspace', 'worktree', 'list'], [['worktree', 'list']]) + + expect(parsed.commandPath).toEqual(['worktree', 'list']) + expect(parsed.flags.get('workspace')).toBe(true) + }) + + it('recognizes a command path with a boolean flag between its segments', () => { + const parsed = parseArgs(['--jso', 'worktree', '--json', 'list'], [['worktree', 'list']]) + + expect(parsed.commandPath).toEqual(['worktree', 'list']) + expect(parsed.flags.get('jso')).toBe(true) + expect(parsed.flags.get('json')).toBe(true) + }) + + it('recognizes a command path with a value flag between its segments', () => { + const parsed = parseArgs( + ['--jso', 'worktree', '--repo', 'id:abc', 'list'], + [['worktree', 'list']] + ) + + expect(parsed.commandPath).toEqual(['worktree', 'list']) + expect(parsed.flags.get('jso')).toBe(true) + expect(parsed.flags.get('repo')).toBe('id:abc') + }) + + it('still consumes a pre-command flag value before a later command path', () => { + const parsed = parseArgs(['--workspace', 'team-1', 'linear', 'list'], [['linear', 'list']]) + + expect(parsed.commandPath).toEqual(['linear', 'list']) + expect(parsed.flags.get('workspace')).toBe('team-1') + }) + + it('preserves existing pre-command selector values', () => { + const parsed = parseArgs(['--repo', 'id:abc', 'worktree', 'list'], [['worktree', 'list']]) + + expect(parsed.commandPath).toEqual(['worktree', 'list']) + expect(parsed.flags.get('repo')).toBe('id:abc') + }) + + it('preserves a selector value that is also a registered command', () => { + const parsed = parseArgs( + ['--environment', 'status', 'worktree', 'list'], + [['status'], ['worktree', 'list']] + ) + + expect(parsed.commandPath).toEqual(['worktree', 'list']) + expect(parsed.flags.get('environment')).toBe('status') + }) + + it('preserves a selector value that is also a command group', () => { + const parsed = parseArgs( + ['--environment', 'worktree', 'status'], + [['status'], ['worktree', 'list']] + ) + + expect(parsed.commandPath).toEqual(['status']) + expect(parsed.flags.get('environment')).toBe('worktree') + }) + it('parses emulator reinstall as a boolean flag', () => { const parsed = parseArgs(['emulator', 'install', 'app.apk', '--reinstall', '--device', 'emu']) @@ -94,10 +163,75 @@ describe('parseArgs', () => { }) }) +describe('command aliases', () => { + const specs: CommandSpec[] = [ + { + path: ['worktree', 'rm'], + aliases: [ + ['worktree', 'remove'], + ['worktree', 'delete'] + ], + summary: 'Remove a worktree', + usage: 'orca worktree rm --worktree ', + allowedFlags: ['worktree', 'force'] + }, + { + path: ['repo', 'show'], + summary: 'Show a repo', + usage: 'orca repo show --repo ', + allowedFlags: ['repo'], + positionalArgs: ['repo'] + } + ] + + it('resolves an exact canonical path to its spec', () => { + expect(findCommandSpec(specs, ['worktree', 'rm'])?.path).toEqual(['worktree', 'rm']) + }) + + it('resolves an aliased path to the canonical spec', () => { + expect(findCommandSpec(specs, ['worktree', 'remove'])?.path).toEqual(['worktree', 'rm']) + }) + + it('resolves each declared alias to the canonical spec', () => { + expect(findCommandSpec(specs, ['worktree', 'delete'])?.path).toEqual(['worktree', 'rm']) + }) + + it('returns undefined for a path matching neither canonical nor alias', () => { + expect(findCommandSpec(specs, ['worktree', 'destroy'])).toBeUndefined() + }) + + it('canonicalizes an aliased command path during normalization', () => { + const normalized = normalizeCommandPositionals( + specs, + parseArgs(['worktree', 'remove', '--force']) + ) + + expect(normalized.commandPath).toEqual(['worktree', 'rm']) + expect(normalized.flags.get('force')).toBe(true) + }) + + it('leaves a canonical command path unchanged during normalization', () => { + const normalized = normalizeCommandPositionals(specs, parseArgs(['worktree', 'rm'])) + + expect(normalized.commandPath).toEqual(['worktree', 'rm']) + }) + + it('binds a trailing positional after canonicalizing the base path', () => { + const normalized = normalizeCommandPositionals(specs, parseArgs(['repo', 'show', 'id:abc'])) + + expect(normalized.commandPath).toEqual(['repo', 'show']) + expect(normalized.flags.get('repo')).toBe('id:abc') + }) +}) + describe('supportsBrowserPageFlag', () => { it('does not expose browser page targeting on orchestration commands', () => { expect(supportsBrowserPageFlag(['orchestration', 'send'])).toBe(false) }) + + it('does not expose browser page targeting on local agent discovery', () => { + expect(supportsBrowserPageFlag(['agent-context'])).toBe(false) + }) }) describe('validateCommandAndFlags', () => { @@ -123,6 +257,18 @@ describe('validateCommandAndFlags', () => { expect(() => validateCommandAndFlags(specs, parsed)).not.toThrow() }) + it.each(['environment', 'pairing-code'])('rejects --%s without a value', (flag) => { + const parsed = parseArgs([`--${flag}`, 'demo'], [['demo']]) + + expect(() => validateCommandAndFlags(specs, parsed)).toThrow(`Flag --${flag} requires a value.`) + }) + + it.each(['environment', 'pairing-code'])('rejects an empty --%s= value', (flag) => { + const parsed = parseArgs(['demo', `--${flag}=`]) + + expect(() => validateCommandAndFlags(specs, parsed)).toThrow(`Flag --${flag} requires a value.`) + }) + it('still rejects unknown command-specific flags', () => { const parsed = parseArgs(['demo', '--bogus']) @@ -130,4 +276,48 @@ describe('validateCommandAndFlags', () => { 'Unknown flag --bogus for command: demo' ) }) + + it('enumerates valid flags and suggests a near-miss on unknown-flag errors', () => { + const flagSpecs: CommandSpec[] = [ + { + path: ['worktree', 'rm'], + summary: 'Remove a worktree', + usage: 'orca worktree rm', + allowedFlags: ['worktree', 'force', 'run-hooks'] + } + ] + const parsed = parseArgs(['worktree', 'rm', '--forcce']) + + try { + validateCommandAndFlags(flagSpecs, parsed) + throw new Error('expected validateCommandAndFlags to throw') + } catch (error) { + const data = (error as { data?: { validFlags: string[]; nextSteps: string[] } }).data + expect(data?.validFlags).toContain('force') + expect(data?.validFlags).toContain('json') + expect(data?.nextSteps.join('\n')).toContain('--force') + expect(data?.nextSteps.join('\n')).toContain('Valid flags:') + } + }) + + it('attaches did-you-mean suggestions to unknown-command errors', () => { + const suggestSpecs: CommandSpec[] = [ + { + path: ['worktree', 'rm'], + summary: 'Remove a worktree', + usage: 'orca worktree rm', + allowedFlags: [] + } + ] + const parsed = parseArgs(['worktree', 'remov']) + + try { + validateCommandAndFlags(suggestSpecs, parsed) + throw new Error('expected validateCommandAndFlags to throw') + } catch (error) { + const data = (error as { data?: { suggestions: string[]; nextSteps: string[] } }).data + expect(data?.suggestions).toContain('worktree rm') + expect(data?.nextSteps[0]).toContain('orca worktree rm') + } + }) }) diff --git a/src/cli/args.ts b/src/cli/args.ts index 5700a17ebefb..aa1289867f6a 100644 --- a/src/cli/args.ts +++ b/src/cli/args.ts @@ -1,4 +1,5 @@ import { RuntimeClientError } from './runtime-client' +import { unknownCommandData, unknownFlagData } from './command-suggestion' export type ParsedArgs = { commandPath: string[] @@ -8,6 +9,10 @@ export type ParsedArgs = { export type CommandSpec = { path: string[] + // Why: conventional alternate verbs should resolve without duplicating specs + // or handler registrations. + aliases?: string[][] + argumentMode?: 'parsed' | 'passthrough' summary: string usage: string allowedFlags: string[] @@ -17,6 +22,7 @@ export type CommandSpec = { } export const GLOBAL_FLAGS = ['help', 'json', 'pairing-code', 'environment'] +const GLOBAL_VALUE_FLAGS = new Set(['pairing-code', 'environment']) export const BOOLEAN_FLAGS = new Set([ 'all', 'attachments', @@ -68,7 +74,23 @@ function setFlagValue(flags: Map, name: string, value: flags.set(name, value) } -export function parseArgs(argv: string[]): ParsedArgs { +function commandPathStartsAt(argv: string[], tokenIndex: number, path: string[]): boolean { + let cursor = tokenIndex + for (const part of path) { + while (argv[cursor]?.startsWith('--')) { + const assignment = argv[cursor].slice(2) + const flag = assignment.split('=', 1)[0] + cursor += assignment.includes('=') || BOOLEAN_FLAGS.has(flag) ? 1 : 2 + } + if (argv[cursor] !== part) { + return false + } + cursor += 1 + } + return true +} + +export function parseArgs(argv: string[], commandPaths?: readonly string[][]): ParsedArgs { const commandPath: string[] = [] const flags = new Map() @@ -94,6 +116,13 @@ export function parseArgs(argv: string[]): ParsedArgs { flags.set(flag, true) continue } + // Why: a pre-command flag must not consume a registry-resolvable command path. + const startsCommandAt = (tokenIndex: number): boolean => + commandPaths?.some((path) => commandPathStartsAt(argv, tokenIndex, path)) ?? false + if (commandPath.length === 0 && startsCommandAt(i + 1) && !startsCommandAt(i + 2)) { + flags.set(flag, true) + continue + } const hasNext = i + 1 < argv.length const next = argv[i + 1] if (!hasNext || next.startsWith('--')) { @@ -123,6 +152,12 @@ export function matches(actual: string[], expected: string[]): boolean { ) } +// Why: a spec is reachable by its canonical path plus any declared aliases — one +// definition so resolution, validation, help, and agent-context never disagree. +export function specPaths(spec: CommandSpec): string[][] { + return spec.aliases ? [spec.path, ...spec.aliases] : [spec.path] +} + export function supportsBrowserPageFlag(commandPath: string[]): boolean { const joined = commandPath.join(' ') if (['open', 'status'].includes(commandPath[0])) { @@ -141,7 +176,8 @@ export function supportsBrowserPageFlag(commandPath: string[]): boolean { 'emulator', 'note', 'diagnostics', - 'linear' + 'linear', + 'agent-context' ].includes(commandPath[0]) ) { return false @@ -156,6 +192,20 @@ export function supportsBrowserPageFlag(commandPath: string[]): boolean { ].includes(joined) } +// Why: validation and agent discovery must expose the same effective flag set. +export function effectiveAllowedFlags(spec: CommandSpec): string[] { + if (spec.argumentMode === 'passthrough') { + return [] + } + return [ + ...new Set([ + ...GLOBAL_FLAGS, + ...spec.allowedFlags, + ...(supportsBrowserPageFlag(spec.path) ? ['page'] : []) + ]) + ] +} + export function isCommandGroup(commandPath: string[]): boolean { return ( (commandPath.length === 1 && @@ -194,29 +244,35 @@ export function isCommandGroup(commandPath: string[]): boolean { export function normalizeCommandPositionals(specs: CommandSpec[], parsed: ParsedArgs): ParsedArgs { for (const spec of specs) { const positionalArgs = spec.positionalArgs ?? [] - if (positionalArgs.length === 0) { - continue - } - const positionalCount = parsed.commandPath.length - spec.path.length - if (positionalCount <= 0 || positionalCount > positionalArgs.length) { + // Why: aliased paths still need canonicalization when there are no positionals. + if (positionalArgs.length === 0 && !spec.aliases) { continue } - if (!matches(parsed.commandPath.slice(0, spec.path.length), spec.path)) { - continue - } - const flags = new Map(parsed.flags) - const values = parsed.commandPath.slice(spec.path.length) - // Why: validation runs inside main's error-reporting path, so normalization - // records ambiguity instead of throwing before CLI errors can be formatted. - const providedPositionals = values.map((_, index) => positionalArgs[index]) - const positionalFlagConflicts = providedPositionals.filter((name) => flags.has(name)) - values.forEach((value, index) => { - const name = positionalArgs[index] - if (!flags.has(name)) { - flags.set(name, value) + // Why: canonicalize aliases before validation and dispatch so both use one key. + for (const base of specPaths(spec)) { + // Why: `< 0` (not `<= 0`) so an exact base match with zero positionals + // still canonicalizes an aliased path; upper bound guards over-consumption. + const positionalCount = parsed.commandPath.length - base.length + if (positionalCount < 0 || positionalCount > positionalArgs.length) { + continue + } + if (!matches(parsed.commandPath.slice(0, base.length), base)) { + continue } - }) - return { commandPath: spec.path, flags, positionalFlagConflicts } + const flags = new Map(parsed.flags) + const values = parsed.commandPath.slice(base.length) + // Why: validation runs inside main's error-reporting path, so normalization + // records ambiguity instead of throwing before CLI errors can be formatted. + const providedPositionals = values.map((_, index) => positionalArgs[index]) + const positionalFlagConflicts = providedPositionals.filter((name) => flags.has(name)) + values.forEach((value, index) => { + const name = positionalArgs[index] + if (!flags.has(name)) { + flags.set(name, value) + } + }) + return { commandPath: spec.path, flags, positionalFlagConflicts } + } } return parsed } @@ -225,7 +281,7 @@ export function findCommandSpec( specs: CommandSpec[], commandPath: string[] ): CommandSpec | undefined { - return specs.find((spec) => matches(spec.path, commandPath)) + return specs.find((spec) => specPaths(spec).some((candidate) => matches(candidate, commandPath))) } export function validateCommandAndFlags(specs: CommandSpec[], parsed: ParsedArgs): void { @@ -233,7 +289,8 @@ export function validateCommandAndFlags(specs: CommandSpec[], parsed: ParsedArgs if (!spec) { throw new RuntimeClientError( 'invalid_argument', - `Unknown command: ${parsed.commandPath.join(' ')}` + `Unknown command: ${parsed.commandPath.join(' ')}`, + unknownCommandData(specs, parsed.commandPath) ) } @@ -246,16 +303,17 @@ export function validateCommandAndFlags(specs: CommandSpec[], parsed: ParsedArgs ) } - for (const flag of parsed.flags.keys()) { + const pageAllowed = supportsBrowserPageFlag(spec.path) + for (const [flag, value] of parsed.flags) { const isGlobalFlag = GLOBAL_FLAGS.includes(flag) - if ( - !isGlobalFlag && - !spec.allowedFlags.includes(flag) && - !(flag === 'page' && supportsBrowserPageFlag(spec.path)) - ) { + if (GLOBAL_VALUE_FLAGS.has(flag) && (typeof value !== 'string' || value.length === 0)) { + throw new RuntimeClientError('invalid_argument', `Flag --${flag} requires a value.`) + } + if (!isGlobalFlag && !spec.allowedFlags.includes(flag) && !(flag === 'page' && pageAllowed)) { throw new RuntimeClientError( 'invalid_argument', - `Unknown flag --${flag} for command: ${spec.path.join(' ')}` + `Unknown flag --${flag} for command: ${spec.path.join(' ')}`, + unknownFlagData(flag, effectiveAllowedFlags(spec)) ) } } diff --git a/src/cli/command-suggestion.test.ts b/src/cli/command-suggestion.test.ts new file mode 100644 index 000000000000..b5c70e021c6f --- /dev/null +++ b/src/cli/command-suggestion.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest' + +import type { CommandSpec } from './args' +import { levenshtein, suggestCommands, unknownCommandData } from './command-suggestion' + +const specs: CommandSpec[] = [ + { + path: ['worktree', 'rm'], + aliases: [['worktree', 'remove']], + summary: 'Remove a worktree', + usage: 'orca worktree rm', + allowedFlags: [] + }, + { + path: ['worktree', 'list'], + summary: 'List worktrees', + usage: 'orca worktree list', + allowedFlags: [] + }, + { + path: ['terminal', 'send'], + summary: 'Send input', + usage: 'orca terminal send', + allowedFlags: [] + } +] + +describe('levenshtein', () => { + it('returns 0 for identical strings', () => { + expect(levenshtein('rm', 'rm')).toBe(0) + }) + + it('counts single-edit distance', () => { + expect(levenshtein('remov', 'remove')).toBe(1) + }) + + it('handles empty operands', () => { + expect(levenshtein('', 'abc')).toBe(3) + expect(levenshtein('abc', '')).toBe(3) + }) +}) + +describe('suggestCommands', () => { + it('suggests the closest command for a near-miss verb', () => { + expect(suggestCommands(specs, ['worktree', 'remov'])).toContain('worktree rm') + }) + + it('includes alias paths among suggestions', () => { + // `worktree remove` is the alias; a typo near it should surface it (an exact + // match would resolve as a real command, not trigger a suggestion). + expect(suggestCommands(specs, ['worktree', 'remov'])).toContain('worktree remove') + }) + + it('returns nothing for a wildly-off token', () => { + expect(suggestCommands(specs, ['worktree', 'zzzzz'])).toEqual([]) + }) + + it('only considers commands of the same depth', () => { + expect(suggestCommands(specs, ['worktree', 'list', 'extra'])).toEqual([]) + }) + + it('suggests a top-level command group near-miss', () => { + expect(suggestCommands(specs, ['worktre'])).toEqual(['worktree']) + }) + + it('ranks closer matches first', () => { + const result = suggestCommands(specs, ['terminal', 'sen']) + expect(result[0]).toBe('terminal send') + }) +}) + +describe('unknownCommandData', () => { + it('produces a human nextSteps line when a suggestion exists', () => { + const data = unknownCommandData(specs, ['worktree', 'remov']) + expect(data.suggestions).toContain('worktree rm') + expect(data.nextSteps[0]).toContain('Did you mean') + expect(data.nextSteps[0]).toContain('orca worktree rm') + }) + + it('produces empty nextSteps when nothing is close', () => { + const data = unknownCommandData(specs, ['worktree', 'zzzzz']) + expect(data.suggestions).toEqual([]) + expect(data.nextSteps).toEqual([]) + }) +}) diff --git a/src/cli/command-suggestion.ts b/src/cli/command-suggestion.ts new file mode 100644 index 000000000000..ccc3712b40bd --- /dev/null +++ b/src/cli/command-suggestion.ts @@ -0,0 +1,101 @@ +import type { CommandSpec } from './args' +import { specPaths } from './args' + +// Why: rank the live registry so typo recovery cannot drift from accepted paths. + +const SUGGESTION_THRESHOLD = 3 +const MAX_SUGGESTIONS = 3 + +export type CommandErrorData = { + suggestions: string[] + nextSteps: string[] +} + +export function levenshtein(a: string, b: string): number { + const m = a.length + const n = b.length + if (m === 0) { + return n + } + if (n === 0) { + return m + } + let prev = Array.from({ length: n + 1 }, (_, index) => index) + let curr = Array.from({ length: n + 1 }, () => 0) + for (let i = 1; i <= m; i += 1) { + curr[0] = i + for (let j = 1; j <= n; j += 1) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1 + curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost) + } + const swap = prev + prev = curr + curr = swap + } + return prev[n] +} + +// Why: one bounded near-match ranking keeps command and flag recovery consistent. +function rankByDistance(scored: { label: string; distance: number }[]): string[] { + return scored + .filter((entry) => entry.distance > 0 && entry.distance <= SUGGESTION_THRESHOLD) + .sort((a, b) => a.distance - b.distance || a.label.localeCompare(b.label)) + .slice(0, MAX_SUGGESTIONS) + .map((entry) => entry.label) +} + +// Why: same-depth matching avoids suggesting parent groups or unrelated commands. +export function suggestCommands(specs: CommandSpec[], commandPath: string[]): string[] { + const input = commandPath.join(' ') + const seen = new Set() + const scored: { label: string; distance: number }[] = [] + for (const spec of specs) { + const candidates = specPaths(spec).map((path) => + commandPath.length === 1 ? path.slice(0, 1) : path + ) + for (const candidate of candidates) { + if (candidate.length !== commandPath.length) { + continue + } + const joined = candidate.join(' ') + if (seen.has(joined)) { + continue + } + seen.add(joined) + scored.push({ label: joined, distance: levenshtein(input, joined) }) + } + } + return rankByDistance(scored) +} + +export function unknownCommandData(specs: CommandSpec[], commandPath: string[]): CommandErrorData { + const suggestions = suggestCommands(specs, commandPath) + const nextSteps = suggestions.length + ? [`Did you mean: ${suggestions.map((path) => `orca ${path}`).join(', ')}`] + : [] + return { suggestions, nextSteps } +} + +export type FlagErrorData = { + validFlags: string[] + suggestions: string[] + nextSteps: string[] +} + +function suggestFlags(flag: string, validFlags: string[]): string[] { + return rankByDistance( + validFlags.map((candidate) => ({ label: candidate, distance: levenshtein(flag, candidate) })) + ) +} + +// Why: include the accepted set so agents can recover without another help call. +export function unknownFlagData(flag: string, validFlags: string[]): FlagErrorData { + const sortedValid = [...validFlags].sort((a, b) => a.localeCompare(b)) + const suggestions = suggestFlags(flag, sortedValid) + const nextSteps: string[] = [] + if (suggestions.length > 0) { + nextSteps.push(`Did you mean: ${suggestions.map((name) => `--${name}`).join(', ')}`) + } + nextSteps.push(`Valid flags: ${sortedValid.map((name) => `--${name}`).join(', ')}`) + return { validFlags: sortedValid, suggestions, nextSteps } +} diff --git a/src/cli/dispatch.ts b/src/cli/dispatch.ts index 85faf69364f9..24582318e741 100644 --- a/src/cli/dispatch.ts +++ b/src/cli/dispatch.ts @@ -20,6 +20,7 @@ import { COMPUTER_HANDLERS } from './handlers/computer' import { ENVIRONMENT_HANDLERS } from './handlers/environment' import { AGENT_HOOK_HANDLERS } from './handlers/agent-hooks' import { DIAGNOSTICS_HANDLERS } from './handlers/diagnostics' +import { INTROSPECTION_HANDLERS } from './handlers/introspection' import { EMULATOR_HANDLERS } from './handlers/emulator' import { LINEAR_HANDLERS } from './handlers/linear' import { VM_HANDLERS } from './handlers/vm' @@ -57,6 +58,7 @@ function buildHandlers(): Map { COMPUTER_HANDLERS, AGENT_HOOK_HANDLERS, DIAGNOSTICS_HANDLERS, + INTROSPECTION_HANDLERS, ENVIRONMENT_HANDLERS, LINEAR_HANDLERS, VM_HANDLERS @@ -74,6 +76,10 @@ function buildHandlers(): Map { const HANDLERS = buildHandlers() +// Why: exposes only the canonical command keys (not the handler internals) so the +// registry-parity guard can check specs↔handlers without rebuilding the table. +export const HANDLER_COMMAND_KEYS: ReadonlySet = new Set(HANDLERS.keys()) + export async function dispatch(commandPath: string[], ctx: HandlerContext): Promise { const handler = HANDLERS.get(commandPath.join(' ')) if (!handler) { diff --git a/src/cli/format-recovery.test.ts b/src/cli/format-recovery.test.ts new file mode 100644 index 000000000000..9646c32d85b7 --- /dev/null +++ b/src/cli/format-recovery.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest' + +import { formatCliError } from './format' +import { RuntimeClientError, RuntimeRpcFailureError } from './runtime-client' + +describe('CLI error recovery', () => { + it('prints did-you-mean next steps for an unknown-command error carrying data', () => { + const error = new RuntimeClientError('invalid_argument', 'Unknown command: worktree remov', { + suggestions: ['worktree rm'], + nextSteps: ['Did you mean: orca worktree rm'] + }) + + const output = formatCliError(error) + + expect(output).toContain('Unknown command: worktree remov') + expect(output).toContain('Next step: Did you mean: orca worktree rm') + }) + + it('prefers structured recovery over generic computer hints in text output', () => { + const error = new RuntimeClientError('invalid_argument', 'Unknown flag --forcce', { + nextSteps: ['Did you mean: --force'] + }) + + const output = formatCliError(error, { commandPath: ['computer', 'click'] }) + + expect(output).toContain('Next step: Did you mean: --force') + expect(output).not.toContain('Fix the command flags or RPC params') + }) + + it('prefers RPC recovery over generic computer hints in text output', () => { + const error = new RuntimeRpcFailureError({ + id: 'req_rpc_recovery', + ok: false, + error: { + code: 'invalid_argument', + message: 'Unknown runtime argument', + data: { nextSteps: ['Use the runtime-specific option'] } + }, + _meta: { runtimeId: 'runtime_local' } + }) + + const output = formatCliError(error, { commandPath: ['computer', 'click'] }) + + expect(output).toContain('Next step: Use the runtime-specific option') + expect(output).not.toContain('Fix the command flags or RPC params') + }) + + it('keeps generic computer hints when an RPC error has no recovery data', () => { + const error = new RuntimeRpcFailureError({ + id: 'req_rpc_fallback', + ok: false, + error: { code: 'invalid_argument', message: 'Invalid computer argument' }, + _meta: { runtimeId: 'runtime_local' } + }) + + const output = formatCliError(error, { commandPath: ['computer', 'click'] }) + + expect(output).toContain('Fix the command flags or RPC params') + }) +}) diff --git a/src/cli/format.ts b/src/cli/format.ts index e6b751d42eb5..80c621418e87 100644 --- a/src/cli/format.ts +++ b/src/cli/format.ts @@ -80,15 +80,18 @@ export function formatCliError(error: unknown, context: CliErrorContext = {}): s if (error instanceof RuntimeClientError && error.code === 'runtime_unavailable') { return `${message}\nOrca is not running. Run 'orca open' first.` } - if ( - error instanceof RuntimeClientError && - error.code === 'invalid_argument' && - context.commandPath?.[0] === 'computer' - ) { - return formatMessageWithNextSteps( - message, - computerUseErrorRecoveryData('invalid_argument')?.nextSteps ?? [] - ) + // Why: error-specific recovery must win over the generic computer fallback. + if (error instanceof RuntimeClientError) { + const nextSteps = nextStepsFromData(error.data) + if (nextSteps.length > 0) { + return formatMessageWithNextSteps(message, nextSteps) + } + if (error.code === 'invalid_argument' && context.commandPath?.[0] === 'computer') { + return formatMessageWithNextSteps( + message, + computerUseErrorRecoveryData('invalid_argument')?.nextSteps ?? [] + ) + } } if ( error instanceof RuntimeRpcFailureError && @@ -97,14 +100,7 @@ export function formatCliError(error: unknown, context: CliErrorContext = {}): s return `${message}\nOrca is not running. Run 'orca open' first.` } if (error instanceof RuntimeRpcFailureError) { - const data = error.response.error.data - const nextSteps = - data && typeof data === 'object' && Array.isArray((data as { nextSteps?: unknown }).nextSteps) - ? (data as { nextSteps: unknown[] }).nextSteps.filter( - (step): step is string => typeof step === 'string' - ) - : [] - return formatMessageWithNextSteps(message, nextSteps) + return formatMessageWithNextSteps(message, nextStepsFromData(error.response.error.data)) } return message } @@ -140,7 +136,24 @@ function formatMessageWithNextSteps(message: string, nextSteps: readonly string[ return `${message}\n${nextSteps.map((step) => `Next step: ${step}`).join('\n')}` } +function nextStepsFromData(data: unknown): string[] { + if ( + data && + typeof data === 'object' && + Array.isArray((data as { nextSteps?: unknown }).nextSteps) + ) { + return (data as { nextSteps: unknown[] }).nextSteps.filter( + (step): step is string => typeof step === 'string' + ) + } + return [] +} + function localCliErrorData(error: unknown, context: CliErrorContext): unknown { + // Why: error-specific recovery must win over the generic computer fallback. + if (error instanceof RuntimeClientError && error.data !== undefined) { + return error.data + } if ( error instanceof RuntimeClientError && error.code === 'invalid_argument' && diff --git a/src/cli/handlers/agent-hooks.test.ts b/src/cli/handlers/agent-hooks.test.ts index 5ed9578685a8..4ae4c962d595 100644 --- a/src/cli/handlers/agent-hooks.test.ts +++ b/src/cli/handlers/agent-hooks.test.ts @@ -92,32 +92,32 @@ describe('agent hooks CLI handler', () => { rmSync(userDataPath, { recursive: true, force: true }) }) - it('keeps the fresh-profile new card style default when creating offline settings', async () => { + it('keeps new card style off when creating offline settings for a fresh profile', async () => { await runAgentHooksOff(userDataPath) const persisted = readDataFile(userDataPath) - expect(persisted.settings.experimentalNewWorktreeCardStyle).toBe(true) + expect(persisted.settings.experimentalNewWorktreeCardStyle).toBe(false) expect(persisted.settings.agentStatusHooksEnabled).toBe(false) }) - it('defaults missing new card style on while offline-updated onboarding is open', async () => { + it('keeps missing new card style off when updating offline settings', async () => { const existing = getDefaultPersistedState(userDataPath) delete existing.settings.experimentalNewWorktreeCardStyle writeDataFile(userDataPath, existing) await runAgentHooksOff(userDataPath) - expect(readDataFile(userDataPath).settings.experimentalNewWorktreeCardStyle).toBe(true) + expect(readDataFile(userDataPath).settings.experimentalNewWorktreeCardStyle).toBe(false) }) - it('preserves an existing explicit new card style opt-out when updating offline settings', async () => { + it('preserves an existing explicit new card style opt-in when updating offline settings', async () => { const existing = getDefaultPersistedState(userDataPath) - existing.settings.experimentalNewWorktreeCardStyle = false + existing.settings.experimentalNewWorktreeCardStyle = true writeDataFile(userDataPath, existing) await runAgentHooksOff(userDataPath) - expect(readDataFile(userDataPath).settings.experimentalNewWorktreeCardStyle).toBe(false) + expect(readDataFile(userDataPath).settings.experimentalNewWorktreeCardStyle).toBe(true) }) }) diff --git a/src/cli/handlers/agent-hooks.ts b/src/cli/handlers/agent-hooks.ts index 2419be2733f7..2b83f5c15ea3 100644 --- a/src/cli/handlers/agent-hooks.ts +++ b/src/cli/handlers/agent-hooks.ts @@ -31,16 +31,7 @@ function isRecord(value: unknown): value is Record { function readPersistedState(dataPath: string): PersistedState { if (!existsSync(dataPath)) { - const defaults = getDefaultPersistedState(homedir()) - return { - ...defaults, - settings: { - ...defaults.settings, - // Why: offline CLI can create the first profile before desktop load; - // match the Store fresh-install default instead of pinning old cards. - experimentalNewWorktreeCardStyle: true - } - } + return getDefaultPersistedState(homedir()) } try { const parsed = JSON.parse(readFileSync(dataPath, 'utf-8')) @@ -83,14 +74,9 @@ function readEnabledFromDisk(): boolean { function updateEnabledOnDisk(enabled: boolean): string { const dataPath = getDataPath() const state = readPersistedState(dataPath) - const experimentalNewWorktreeCardStyle = - state.settings?.experimentalNewWorktreeCardStyle ?? state.onboarding?.closedAt === null state.settings = { ...getDefaultPersistedState(homedir()).settings, ...state.settings, - // Why: offline CLI can run before Store.load(); mirror its open-onboarding - // default without overriding a saved user opt-out. - experimentalNewWorktreeCardStyle, agentStatusHooksEnabled: enabled } writePersistedState(dataPath, state) diff --git a/src/cli/handlers/introspection.ts b/src/cli/handlers/introspection.ts new file mode 100644 index 000000000000..92cef638e10f --- /dev/null +++ b/src/cli/handlers/introspection.ts @@ -0,0 +1,16 @@ +import type { CommandHandler } from '../dispatch' +import { COMMAND_SPECS } from '../specs' +import { buildAgentContext, formatAgentContextSummary } from '../agent-context' + +export const INTROSPECTION_HANDLERS: Record = { + // Why: pure local command — reads the static spec registry and prints it, with + // no runtime RPC, so it works when the Orca app is not running (SSH/headless). + 'agent-context': async ({ json }) => { + const schema = buildAgentContext(COMMAND_SPECS) + if (json) { + console.log(JSON.stringify(schema, null, 2)) + return + } + console.log(formatAgentContextSummary(schema)) + } +} diff --git a/src/cli/handlers/terminal.ts b/src/cli/handlers/terminal.ts index d329e1e9d966..fb2eefc3748e 100644 --- a/src/cli/handlers/terminal.ts +++ b/src/cli/handlers/terminal.ts @@ -147,9 +147,7 @@ export const TERMINAL_HANDLERS: Record = { }) printResult(result, json, formatTerminalCreate) }, - // Why: `focus` and `switch` are aliases — register the same handler under - // both keys so the dispatch table stays a plain command-path lookup. - 'terminal focus': terminalFocusHandler, + // `focus` resolves to this canonical path via CommandSpec.aliases before dispatch. 'terminal switch': terminalFocusHandler, 'terminal close': async ({ flags, client, cwd, json }) => { const result = await client.call<{ close: RuntimeTerminalClose }>('terminal.close', { diff --git a/src/cli/help.ts b/src/cli/help.ts index 8c1cce60757b..494e29699151 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -1,6 +1,7 @@ /* eslint-disable max-lines -- Why: root and generated command help text live together so CLI discovery stays greppable. */ import type { CommandSpec } from './args' import { findCommandSpec, isCommandGroup, supportsBrowserPageFlag } from './args' +import { unknownCommandData } from './command-suggestion' const ROOT_HELP_TEXT = `orca @@ -14,6 +15,9 @@ Startup: Diagnostics: diagnostics memory Collect a memory snapshot for Orca and managed terminals +Agent Discovery: + agent-context Print the machine-readable command schema for agents + Environments: environment add Save a remote Orca runtime from a pairing code environment list List saved remote Orca runtimes @@ -192,6 +196,7 @@ Common Commands: orca serve [--port ] [--pairing-address ] [--mobile-pairing] [--no-pairing] [--project-root ] [--recipe-json] [--json] orca status [--json] orca diagnostics memory [--json] + orca agent-context [--json] orca environment add --name --pairing-code [--json] orca environment list [--json] orca environment show --environment [--json] @@ -339,7 +344,9 @@ export function printHelp(specs: CommandSpec[], commandPath: string[] = []): voi } if (commandPath.length > 0) { - console.log(`Unknown command: ${commandPath.join(' ')}\n`) + const { nextSteps } = unknownCommandData(specs, commandPath) + const recovery = nextSteps.map((step) => `Next step: ${step}`).join('\n') + console.log(`Unknown command: ${commandPath.join(' ')}${recovery ? `\n${recovery}` : ''}\n`) } console.log(ROOT_HELP_TEXT) @@ -347,9 +354,12 @@ export function printHelp(specs: CommandSpec[], commandPath: string[] = []): voi export function formatCommandHelp(spec: CommandSpec): string { const lines = [`orca ${spec.path.join(' ')}`, '', `Usage: ${spec.usage}`, '', spec.summary] - const displayedFlags = supportsBrowserPageFlag(spec.path) - ? [...spec.allowedFlags, 'page'] - : spec.allowedFlags + const displayedFlags = + spec.argumentMode === 'passthrough' + ? [] + : supportsBrowserPageFlag(spec.path) + ? [...spec.allowedFlags, 'page'] + : spec.allowedFlags if (displayedFlags.length > 0) { lines.push('', 'Options:') diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 12d4a64eef9e..2309b7a77f5f 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { callMock, + runtimeClientConstructorMock, serveOrcaAppMock, getDefaultUserDataPathMock, addEnvironmentFromPairingCodeMock, @@ -13,6 +14,7 @@ const { spawnMock } = vi.hoisted(() => ({ callMock: vi.fn(), + runtimeClientConstructorMock: vi.fn(), serveOrcaAppMock: vi.fn(), getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), addEnvironmentFromPairingCodeMock: vi.fn(), @@ -33,6 +35,7 @@ vi.mock('./runtime-client', () => { remotePairingCode?: string | null, environmentSelector?: string | null ) { + runtimeClientConstructorMock() const effectivePairingCode = remotePairingCode === undefined ? (process.env.ORCA_PAIRING_CODE ?? process.env.ORCA_REMOTE_PAIRING) @@ -51,10 +54,12 @@ vi.mock('./runtime-client', () => { class RuntimeClientError extends Error { readonly code: string + readonly data?: unknown - constructor(code: string, message: string) { + constructor(code: string, message: string, data?: unknown) { super(message) this.code = code + this.data = data } } @@ -111,18 +116,21 @@ import { main, normalizeWorktreeSelector } from './index' -import { GLOBAL_FLAGS } from './args' +import { GLOBAL_FLAGS, specPaths } from './args' import { RuntimeRpcFailureError } from './runtime-client' import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from './test-fixtures' import { encodePairingOffer, PAIRING_OFFER_VERSION } from '../shared/pairing' describe('COMMAND_SPECS collision check', () => { - it('has no duplicate command paths', () => { + it('has no duplicate command or alias paths', () => { + // Why: first-match resolution would silently shadow duplicate aliases. const seen = new Set() for (const spec of COMMAND_SPECS) { - const key = spec.path.join(' ') - expect(seen.has(key), `Duplicate COMMAND_SPECS path: "${key}"`).toBe(false) - seen.add(key) + for (const path of specPaths(spec)) { + const key = path.join(' ') + expect(seen.has(key), `Duplicate command/alias path: "${key}"`).toBe(false) + seen.add(key) + } } }) @@ -141,7 +149,174 @@ describe('COMMAND_SPECS collision check', () => { }) }) +describe('command aliases dispatch to the canonical handler', () => { + let logSpy: ReturnType + + beforeEach(() => { + callMock.mockReset() + logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + }) + + afterEach(() => { + callMock.mockReset() + // Why: restore console.log so a downstream describe's vi.spyOn starts from a + // clean spy — otherwise this block's --json output leaks into its calls[0]. + logSpy.mockRestore() + }) + + it('runs `worktree remove` as the canonical `worktree rm` (the incident)', async () => { + queueFixtures(callMock, okFixture('req', { removed: true })) + + await main(['worktree', 'remove', '--worktree', 'id:wt-1', '--force', '--json'], '/tmp/repo') + + expect(callMock).toHaveBeenCalledWith( + 'worktree.rm', + expect.objectContaining({ worktree: 'id:wt-1', force: true }) + ) + }) + + it('runs `worktree delete` as the canonical `worktree rm`', async () => { + queueFixtures(callMock, okFixture('req', { removed: true })) + + await main(['worktree', 'delete', '--worktree', 'id:wt-1', '--json'], '/tmp/repo') + + expect(callMock).toHaveBeenCalledWith( + 'worktree.rm', + expect.objectContaining({ worktree: 'id:wt-1' }) + ) + }) + + it('still runs `terminal focus` after the handler de-duplication', async () => { + queueFixtures(callMock, okFixture('req', { focus: { ok: true } })) + + await main(['terminal', 'focus', '--terminal', 'term_abc', '--json'], '/tmp/repo') + + expect(callMock).toHaveBeenCalledWith('terminal.focus', expect.objectContaining({})) + }) + + it('serves `agent-context --json` without contacting the runtime', async () => { + runtimeClientConstructorMock.mockClear() + await main(['agent-context', '--json'], '/tmp/repo') + + // Why: pure local read — proves the SSH/offline property (no RPC). + expect(runtimeClientConstructorMock).not.toHaveBeenCalled() + expect(callMock).not.toHaveBeenCalled() + const schema = JSON.parse(String(logSpy.mock.calls.at(-1)?.[0])) + expect(schema.schemaVersion).toBe(1) + const rm = schema.commands.find( + (command: { command: string }) => command.command === 'worktree rm' + ) + expect(rm.aliases).toContainEqual(['worktree', 'remove']) + }) + + it('keeps `agent-context` local when remote environment variables are set', async () => { + vi.stubEnv('ORCA_PAIRING_CODE', 'pairing-code') + vi.stubEnv('ORCA_ENVIRONMENT', 'stale-environment') + try { + await main(['agent-context', '--json'], '/tmp/repo') + + expect(process.exitCode).not.toBe(1) + expect(callMock).not.toHaveBeenCalled() + } finally { + vi.unstubAllEnvs() + } + }) +}) + +describe('unknown command surfaces a suggestion', () => { + let errorSpy: ReturnType + + beforeEach(() => { + callMock.mockReset() + errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + }) + + afterEach(() => { + errorSpy.mockRestore() + process.exitCode = 0 + }) + + it('prints did-you-mean for a near-miss command and exits non-zero', async () => { + await main(['worktree', 'remov'], '/tmp/repo') + + expect(process.exitCode).toBe(1) + const stderr = errorSpy.mock.calls.map((call) => String(call[0])).join('\n') + expect(stderr).toContain('Unknown command: worktree remov') + expect(stderr).toContain('orca worktree') + }) + + it('reports a mistyped pre-command flag without swallowing the command', async () => { + await main(['--jso', 'worktree', 'list'], '/tmp/repo') + + expect(process.exitCode).toBe(1) + const stderr = errorSpy.mock.calls.map((call) => String(call[0])).join('\n') + expect(stderr).toContain('Unknown flag --jso for command: worktree list') + expect(stderr).toContain('--json') + }) + + it('reports a pre-command flag that belongs to another command', async () => { + await main(['--workspace', 'worktree', 'list'], '/tmp/repo') + + expect(process.exitCode).toBe(1) + const stderr = errorSpy.mock.calls.map((call) => String(call[0])).join('\n') + expect(stderr).toContain('Unknown flag --workspace for command: worktree list') + }) + + it('reports a pre-command typo when a global flag splits the command path', async () => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['--jso', 'worktree', '--json', 'list'], '/tmp/repo') + + expect(process.exitCode).toBe(1) + expect(logSpy.mock.calls.flat().join('\n')).toContain( + 'Unknown flag --jso for command: worktree list' + ) + expect(callMock).not.toHaveBeenCalled() + logSpy.mockRestore() + }) + + it.each(['environment', 'pairing-code'])( + 'rejects --%s without a selector before runtime construction', + async (flag) => { + runtimeClientConstructorMock.mockClear() + + await main([`--${flag}`, 'worktree', 'list'], '/tmp/repo') + + expect(process.exitCode).toBe(1) + const stderr = errorSpy.mock.calls.map((call) => String(call[0])).join('\n') + expect(stderr).toContain(`Flag --${flag} requires a value.`) + expect(runtimeClientConstructorMock).not.toHaveBeenCalled() + expect(callMock).not.toHaveBeenCalled() + } + ) +}) + +describe('unknown help command surfaces a suggestion', () => { + it.each([ + ['help prefix', ['help', 'worktree', 'remov']], + ['help flag', ['worktree', 'remov', '--help']] + ])('prints did-you-mean for the %s form', async (_label, argv) => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(argv, '/tmp/repo') + + expect(process.exitCode).toBe(1) + expect(logSpy.mock.calls.flat().join('\n')).toContain('Did you mean: orca worktree') + logSpy.mockRestore() + process.exitCode = 0 + }) +}) + describe('orca root help', () => { + it('advertises machine-readable agent discovery', async () => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main([], '/tmp/repo') + + expect(logSpy.mock.calls.flat().join('\n')).toContain('agent-context') + logSpy.mockRestore() + }) + it('advertises computer-use capabilities discovery', async () => { const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) @@ -434,6 +609,38 @@ describe('orca cli worktree awareness', () => { expect(logSpy).toHaveBeenCalledTimes(1) }) + it('resolves the invocation cwd from ORCA_CLI_CWD when no cwd is passed', async () => { + // Why: the SSH relay bridge runs the CLI on the Orca host with the remote + // shell's cwd carried in ORCA_CLI_CWD (#7716); cwd-based selectors must + // resolve against it, not the host process cwd. + process.env.ORCA_CLI_CWD = '/tmp/repo/feature/src' + try { + queueFixtures( + callMock, + worktreeListFixture([ + buildWorktree('/tmp/repo', 'main'), + buildWorktree('/tmp/repo/feature', 'feature/foo') + ]), + okFixture('req_1', { + worktree: { + id: 'repo::/tmp/repo/feature', + branch: 'feature/foo', + path: '/tmp/repo/feature' + } + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['worktree', 'current', '--json']) + + expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.show', { + worktree: 'id:repo::/tmp/repo/feature' + }) + } finally { + delete process.env.ORCA_CLI_CWD + } + }) + it.skipIf(process.platform === 'win32')( 'prepares and starts Claude Agent Teams in the current Orca terminal', async () => { diff --git a/src/cli/index.ts b/src/cli/index.ts index e2934812ff57..c35559123d15 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -5,6 +5,7 @@ import { normalizeCommandPositionals, parseArgs, resolveHelpPath, + specPaths, validateCommandAndFlags } from './args' import { dispatch } from './dispatch' @@ -16,16 +17,31 @@ import { COMMAND_SPECS } from './specs' export { COMMAND_SPECS } from './specs' export { buildCurrentWorktreeSelector, normalizeWorktreeSelector } from './selectors' +const COMMAND_PATHS = COMMAND_SPECS.flatMap((spec) => specPaths(spec)) + function shouldIgnoreRemoteSelection(commandPath: string[]): boolean { return ( commandPath[0] === 'environment' || commandPath[0] === 'serve' || commandPath[0] === 'agent' || - commandPath[0] === 'vm' + commandPath[0] === 'vm' || + commandPath[0] === 'agent-context' ) } -export async function main(argv = process.argv.slice(2), cwd = process.cwd()): Promise { +// Why: the SSH relay bridge executes this CLI on the Orca host while the +// caller's shell cwd lives on the remote machine (which cannot be chdir'd +// into). ORCA_CLI_CWD carries that remote cwd so cwd-based selectors like +// `--worktree active` resolve against the caller's directory. +function resolveInvocationCwd(): string { + const override = process.env.ORCA_CLI_CWD + return typeof override === 'string' && override.length > 0 ? override : process.cwd() +} + +export async function main( + argv = process.argv.slice(2), + cwd = resolveInvocationCwd() +): Promise { if (argv[0] === 'agent-teams-tmux') { await runAgentTeamsTmuxShim(argv.slice(1)) return @@ -34,7 +50,7 @@ export async function main(argv = process.argv.slice(2), cwd = process.cwd()): P await runClaudeTeams(argv.slice(1), cwd) return } - const parsed = normalizeCommandPositionals(COMMAND_SPECS, parseArgs(argv)) + const parsed = normalizeCommandPositionals(COMMAND_SPECS, parseArgs(argv, COMMAND_PATHS)) const helpPath = resolveHelpPath(parsed) if (helpPath !== null) { printHelp(COMMAND_SPECS, helpPath) @@ -65,19 +81,23 @@ export async function main(argv = process.argv.slice(2), cwd = process.cwd()): P // so the RuntimeClient default parameter does not re-activate the // ORCA_PAIRING_CODE / ORCA_ENVIRONMENT env-var fallback for commands // that must run locally (environment / serve). - const client = new RuntimeClient( - undefined, - undefined, - typeof pairingCode === 'string' ? pairingCode : ignoreRemoteSelection ? null : undefined, - typeof environmentSelector === 'string' - ? environmentSelector - : ignoreRemoteSelection - ? null - : undefined - ) + let client: RuntimeClient | undefined await dispatch(parsed.commandPath, { flags: parsed.flags, - client, + // Why: local-only handlers must not resolve runtime metadata just to dispatch. + get client() { + client ??= new RuntimeClient( + undefined, + undefined, + typeof pairingCode === 'string' ? pairingCode : ignoreRemoteSelection ? null : undefined, + typeof environmentSelector === 'string' + ? environmentSelector + : ignoreRemoteSelection + ? null + : undefined + ) + return client + }, cwd, json }) diff --git a/src/cli/registry-parity.test.ts b/src/cli/registry-parity.test.ts new file mode 100644 index 000000000000..588a4e14d087 --- /dev/null +++ b/src/cli/registry-parity.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' + +import type { CommandSpec } from './args' +import { HANDLER_COMMAND_KEYS } from './dispatch' +import { findRegistryParityGaps } from './registry-parity' +import { COMMAND_SPECS } from './specs' + +describe('registry parity (live tree)', () => { + const handlerKeys = [...HANDLER_COMMAND_KEYS] + + it('has a handler for every canonical spec path', () => { + const { specsWithoutHandler } = findRegistryParityGaps(COMMAND_SPECS, handlerKeys) + expect(specsWithoutHandler).toEqual([]) + }) + + it('has a spec for every handler key', () => { + const { handlersWithoutSpec } = findRegistryParityGaps(COMMAND_SPECS, handlerKeys) + expect(handlersWithoutSpec).toEqual([]) + }) +}) + +describe('findRegistryParityGaps (fixtures)', () => { + const spec = (path: string[], aliases?: string[][]): CommandSpec => ({ + path, + aliases, + summary: 's', + usage: 'u', + allowedFlags: [] + }) + + it('flags a spec with no handler', () => { + const gaps = findRegistryParityGaps([spec(['foo', 'bar'])], []) + expect(gaps.specsWithoutHandler).toEqual(['foo bar']) + }) + + it('flags a handler with no spec', () => { + const gaps = findRegistryParityGaps([spec(['foo', 'bar'])], ['foo bar', 'ghost cmd']) + expect(gaps.handlersWithoutSpec).toEqual(['ghost cmd']) + }) + + it('does not require a handler for an alias path', () => { + const gaps = findRegistryParityGaps([spec(['foo', 'rm'], [['foo', 'remove']])], ['foo rm']) + expect(gaps.specsWithoutHandler).toEqual([]) + expect(gaps.handlersWithoutSpec).toEqual([]) + }) +}) diff --git a/src/cli/registry-parity.ts b/src/cli/registry-parity.ts new file mode 100644 index 000000000000..27c0130b555c --- /dev/null +++ b/src/cli/registry-parity.ts @@ -0,0 +1,21 @@ +import type { CommandSpec } from './args' + +// Why: validation/help and dispatch use parallel registries that must not drift. + +export type RegistryParityGaps = { + handlersWithoutSpec: string[] + specsWithoutHandler: string[] +} + +export function findRegistryParityGaps( + specs: CommandSpec[], + handlerKeys: Iterable +): RegistryParityGaps { + // Why: aliases resolve before dispatch and deliberately have no handler key. + const canonical = new Set(specs.map((spec) => spec.path.join(' '))) + const handlers = new Set(handlerKeys) + return { + handlersWithoutSpec: [...handlers].filter((key) => !canonical.has(key)), + specsWithoutHandler: [...canonical].filter((key) => !handlers.has(key)) + } +} diff --git a/src/cli/runtime/envelope-schema.test.ts b/src/cli/runtime/envelope-schema.test.ts index 263bdf380963..0e83de3ab448 100644 --- a/src/cli/runtime/envelope-schema.test.ts +++ b/src/cli/runtime/envelope-schema.test.ts @@ -12,6 +12,26 @@ describe('RuntimeRpcEnvelopeSchema', () => { expect(parsed.success).toBe(true) }) + it('accepts and strips additive future success fields', () => { + const parsed = RuntimeRpcEnvelopeSchema.safeParse({ + id: 'req-1', + ok: true, + result: { value: 1, futureResultField: true }, + futureEnvelopeField: 'new', + _meta: { runtimeId: 'runtime-1', futureMetaField: 2 } + }) + + expect(parsed).toEqual({ + success: true, + data: { + id: 'req-1', + ok: true, + result: { value: 1, futureResultField: true }, + _meta: { runtimeId: 'runtime-1' } + } + }) + }) + it('accepts a well-formed failure envelope', () => { const parsed = RuntimeRpcEnvelopeSchema.safeParse({ id: 'req-1', @@ -39,6 +59,31 @@ describe('RuntimeRpcEnvelopeSchema', () => { expect(parsed.success).toBe(true) }) + it('accepts and strips additive future failure fields', () => { + const parsed = RuntimeRpcEnvelopeSchema.safeParse({ + id: 'req-1', + ok: false, + futureEnvelopeField: 'new', + error: { + code: 'failed', + message: 'Nope', + data: { retryable: true }, + futureErrorField: 2 + }, + _meta: { runtimeId: 'runtime-1', futureMetaField: 3 } + }) + + expect(parsed).toEqual({ + success: true, + data: { + id: 'req-1', + ok: false, + error: { code: 'failed', message: 'Nope', data: { retryable: true } }, + _meta: { runtimeId: 'runtime-1' } + } + }) + }) + it('accepts a failure envelope without _meta', () => { // Why: the runtime may fail before it has resolved its own runtimeId, in // which case _meta is omitted. The schema must tolerate that rather than @@ -70,6 +115,17 @@ describe('RuntimeRpcEnvelopeSchema', () => { expect(parsed.success).toBe(false) }) + it('still rejects malformed known fields when future fields are present', () => { + const parsed = RuntimeRpcEnvelopeSchema.safeParse({ + id: 'req-1', + ok: false, + error: { code: 500, message: 'Nope', futureErrorField: true }, + futureEnvelopeField: 'new' + }) + + expect(parsed.success).toBe(false) + }) + it('rejects a frame with unrelated fields only', () => { const parsed = RuntimeRpcEnvelopeSchema.safeParse({ hello: 'world' }) expect(parsed.success).toBe(false) diff --git a/src/cli/runtime/types.ts b/src/cli/runtime/types.ts index 220d3e3aba51..ea347efe09f6 100644 --- a/src/cli/runtime/types.ts +++ b/src/cli/runtime/types.ts @@ -8,10 +8,14 @@ export type { export class RuntimeClientError extends Error { readonly code: string + // Why: optional structured recovery payload (e.g. did-you-mean suggestions, + // valid-flag enumeration) surfaced into both the human and --json error output. + readonly data?: unknown - constructor(code: string, message: string) { + constructor(code: string, message: string, data?: unknown) { super(message) this.code = code + this.data = data } } @@ -19,7 +23,8 @@ export class RuntimeRpcFailureError extends RuntimeClientError { readonly response: RuntimeRpcFailure constructor(response: RuntimeRpcFailure) { - super(response.error.code, response.error.message) + // Why: all client errors expose recovery through the same inherited channel. + super(response.error.code, response.error.message, response.error.data) this.response = response } } diff --git a/src/cli/specs/core.ts b/src/cli/specs/core.ts index 1c9fdc4b63b5..e4f2ffe9f917 100644 --- a/src/cli/specs/core.ts +++ b/src/cli/specs/core.ts @@ -20,6 +20,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ }, { path: ['claude-teams'], + argumentMode: 'passthrough', summary: 'Start Claude Code Agent Teams in the current Orca terminal', usage: 'orca claude-teams [claude args...]', allowedFlags: [...GLOBAL_FLAGS], @@ -157,6 +158,12 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ }, { path: ['worktree', 'rm'], + // Why: agents reach for git's `remove`/`delete` verbs; accept them as + // aliases so a conventional guess resolves instead of dead-ending. + aliases: [ + ['worktree', 'remove'], + ['worktree', 'delete'] + ], summary: 'Remove a worktree from Orca and git', usage: 'orca worktree rm --worktree [--force] [--run-hooks] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'force', 'run-hooks'], @@ -235,18 +242,14 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ }, { path: ['terminal', 'switch'], + // Why: `focus` is the legacy verb for this action; keep it working as an + // alias rather than a duplicate spec + handler registration. + aliases: [['terminal', 'focus']], summary: 'Switch to a terminal tab in the UI', usage: 'orca terminal switch [--terminal ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'terminal'], examples: ['orca terminal switch --terminal term_abc123'] }, - { - path: ['terminal', 'focus'], - summary: 'Switch to a terminal tab in the UI (alias for terminal switch)', - usage: 'orca terminal focus [--terminal ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'terminal'], - examples: ['orca terminal focus --terminal term_abc123'] - }, { path: ['terminal', 'close'], summary: 'Close a terminal tab (kills PTY if running)', diff --git a/src/cli/specs/index.ts b/src/cli/specs/index.ts index df090fcebcad..5521b39d7c58 100644 --- a/src/cli/specs/index.ts +++ b/src/cli/specs/index.ts @@ -11,6 +11,7 @@ import { ENVIRONMENT_COMMAND_SPECS } from './environment' import { AGENT_HOOK_COMMAND_SPECS } from './agent-hooks' import { DIAGNOSTICS_COMMAND_SPECS } from './diagnostics' import { EMULATOR_COMMAND_SPECS } from './emulator' +import { INTROSPECTION_COMMAND_SPECS } from './introspection' import { LINEAR_COMMAND_SPECS } from './linear' import { VM_COMMAND_SPECS } from './vm' @@ -25,6 +26,7 @@ export const COMMAND_SPECS: CommandSpec[] = [ ...COMPUTER_COMMAND_SPECS, ...AGENT_HOOK_COMMAND_SPECS, ...DIAGNOSTICS_COMMAND_SPECS, + ...INTROSPECTION_COMMAND_SPECS, ...ENVIRONMENT_COMMAND_SPECS, ...LINEAR_COMMAND_SPECS, ...VM_COMMAND_SPECS, diff --git a/src/cli/specs/introspection.ts b/src/cli/specs/introspection.ts new file mode 100644 index 000000000000..fda273df13f0 --- /dev/null +++ b/src/cli/specs/introspection.ts @@ -0,0 +1,15 @@ +import type { CommandSpec } from '../args' +import { GLOBAL_FLAGS } from '../args' + +export const INTROSPECTION_COMMAND_SPECS: CommandSpec[] = [ + { + path: ['agent-context'], + summary: 'Print the machine-readable command schema for agents', + usage: 'orca agent-context [--json]', + allowedFlags: [...GLOBAL_FLAGS], + notes: [ + 'Pure local read of the command registry — works without a running Orca app, so it is safe over SSH and in headless contexts.' + ], + examples: ['orca agent-context --json'] + } +] diff --git a/src/cli/vocabulary-policy.test.ts b/src/cli/vocabulary-policy.test.ts new file mode 100644 index 000000000000..409a6304d09c --- /dev/null +++ b/src/cli/vocabulary-policy.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from 'vitest' + +import type { CommandSpec } from './args' +import { COMMAND_SPECS } from './specs' +import { findVocabularyViolations } from './vocabulary-policy' + +const spec = (path: string[], aliases?: string[][]): CommandSpec => ({ + path, + aliases, + summary: 's', + usage: 'u', + allowedFlags: [] +}) + +describe('vocabulary policy (live tree)', () => { + it('has no off-policy verbs that are not grandfathered or alias-bridged', () => { + expect(findVocabularyViolations(COMMAND_SPECS)).toEqual([]) + }) +}) + +describe('findVocabularyViolations (fixtures)', () => { + it('flags a new deletion command using an off-policy verb', () => { + const violations = findVocabularyViolations([spec(['gadget', 'delete'])]) + expect(violations).toHaveLength(1) + expect(violations[0]).toMatchObject({ command: 'gadget delete', canonical: 'rm' }) + }) + + it('passes a deletion command that bridges to the canonical verb via an alias', () => { + const violations = findVocabularyViolations([spec(['gadget', 'delete'], [['gadget', 'rm']])]) + expect(violations).toEqual([]) + }) + + it('rejects a canonical verb alias under an unrelated command prefix', () => { + const violations = findVocabularyViolations([spec(['gadget', 'delete'], [['other', 'rm']])]) + expect(violations).toHaveLength(1) + }) + + it('rejects a canonical verb alias at a different command depth', () => { + const violations = findVocabularyViolations([ + spec(['gadget', 'delete'], [['gadget', 'nested', 'rm']]) + ]) + expect(violations).toHaveLength(1) + }) + + it('passes the canonical deletion verb outright', () => { + expect(findVocabularyViolations([spec(['gadget', 'rm'])])).toEqual([]) + }) + + it('flags a new single-item read using get instead of show', () => { + const violations = findVocabularyViolations([spec(['gadget', 'get'])]) + expect(violations[0]).toMatchObject({ verb: 'get', canonical: 'show' }) + }) +}) diff --git a/src/cli/vocabulary-policy.ts b/src/cli/vocabulary-policy.ts new file mode 100644 index 000000000000..311d22c8c1a7 --- /dev/null +++ b/src/cli/vocabulary-policy.ts @@ -0,0 +1,73 @@ +import type { CommandSpec } from './args' + +// Why: predictable verbs prevent failed agent guesses; existing divergences stay +// grandfathered because renaming them would break compatibility. + +type VerbFamily = { + name: string + offPolicyVerbs: Set + canonical: string + allowlist: Set +} + +const FAMILIES: VerbFamily[] = [ + { + name: 'deletion', + offPolicyVerbs: new Set(['remove', 'delete', 'destroy']), + canonical: 'rm', + allowlist: new Set([ + 'cookie delete', + 'tab profile delete', + 'automations remove', + 'linear label remove' + ]) + }, + { + name: 'single-item read', + offPolicyVerbs: new Set(['get']), + canonical: 'show', + allowlist: new Set(['get', 'cookie get', 'storage local get', 'storage session get']) + } +] + +export type VocabularyViolation = { + command: string + verb: string + family: string + canonical: string +} + +function terminalVerb(path: string[]): string { + return path.at(-1) ?? '' +} + +function hasCanonicalAlias(spec: CommandSpec, canonical: string): boolean { + const expected = [...spec.path.slice(0, -1), canonical] + return (spec.aliases ?? []).some( + (alias) => + alias.length === expected.length && alias.every((part, index) => part === expected[index]) + ) +} + +export function findVocabularyViolations(specs: CommandSpec[]): VocabularyViolation[] { + const violations: VocabularyViolation[] = [] + for (const spec of specs) { + const command = spec.path.join(' ') + const verb = terminalVerb(spec.path) + for (const family of FAMILIES) { + if (!family.offPolicyVerbs.has(verb)) { + continue + } + if (family.allowlist.has(command)) { + continue + } + // Why: an alias on the canonical verb makes the command reachable the + // canonical way, which satisfies the policy without a rename. + if (hasCanonicalAlias(spec, family.canonical)) { + continue + } + violations.push({ command, verb, family: family.name, canonical: family.canonical }) + } + } + return violations +} diff --git a/src/main/agent-hooks/first-work-branch-rename.test.ts b/src/main/agent-hooks/first-work-branch-rename.test.ts index e704a8fe54f2..e84cd3d0cf40 100644 --- a/src/main/agent-hooks/first-work-branch-rename.test.ts +++ b/src/main/agent-hooks/first-work-branch-rename.test.ts @@ -373,6 +373,40 @@ describe('maybeAutoRenameBranchOnFirstWork', () => { expect(onRenamed).not.toHaveBeenCalled() }) + it('surfaces a failed upstream probe and retries instead of settling silently (issue #7808)', async () => { + // Localized git (gettext + de_DE) translates even the `fatal:` prefix, so + // the no-upstream error is unrecognizable. This must not settle as "has + // upstream" — the badge goes up and a later event may still succeed. + const localizedError = new Error( + 'Command failed: git rev-parse --abbrev-ref HEAD@{u}\n' + + "Schwerwiegend: Kein Upstream-Branch für Branch 'you/Nautilus' konfiguriert." + ) + const plainResponder = gitResponder({ currentBranch: 'you/Nautilus', hasUpstream: false }) + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'rev-parse' && args.some((arg) => arg.includes('@{u}'))) { + throw localizedError + } + return plainResponder(args) + }) + const { deps, onRenamed, setRenameError } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(generateBranchNameMock).not.toHaveBeenCalled() + expect(onRenamed).not.toHaveBeenCalled() + expect(setRenameError).toHaveBeenCalledWith( + WORKTREE_ID, + expect.stringContaining('Schwerwiegend') + ) + + // Once git output is readable again, the same worktree retries and renames. + gitExecFileAsyncMock.mockImplementation(plainResponder) + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['branch', '-m', 'you/fix-auth'], + expect.objectContaining({ cwd: '/repo/wt' }) + ) + expect(setRenameError).toHaveBeenLastCalledWith(WORKTREE_ID, null) + }) + it('leaves ineligible branches untouched even when their leaf is a creature name', async () => { const { deps, onRenamed } = makeDeps({ canRenameOrcaCreatedBranch: () => false }) await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) diff --git a/src/main/agent-hooks/first-work-branch-rename.ts b/src/main/agent-hooks/first-work-branch-rename.ts index cd8f7fb4b7ad..fabf508b1417 100644 --- a/src/main/agent-hooks/first-work-branch-rename.ts +++ b/src/main/agent-hooks/first-work-branch-rename.ts @@ -18,7 +18,7 @@ import { gitExecFileAsync } from '../git/runner' import { getSshGitUsername, resolveLocalGitUsername } from '../git/git-username' import { getSshGitProvider } from '../providers/ssh-git-dispatch' import { - branchHasUpstream, + probeBranchUpstream, renameCurrentBranch, resolveUniqueBranchName, type GitExec @@ -207,9 +207,20 @@ async function runAutoRename( return stop(`branch "${currentBranch}" is not an auto-generated name`, true) } // Never rewrite a branch that's already been published. - if (await branchHasUpstream(exec)) { + const upstreamProbe = await probeBranchUpstream(exec) + if (upstreamProbe.outcome === 'has-upstream') { return stop(`branch "${currentBranch}" already has an upstream`, true) } + if (upstreamProbe.outcome === 'probe-failed') { + // Why: settling an unreadable probe as "has upstream" made this failure + // silent and permanent via the settled cache (issue #7808). + const probeError = upstreamProbe.message.replace(/\s+/g, ' ').trim() + deps.setRenameError( + worktreeId, + `Could not check whether the branch is published: ${probeError}` + ) + return retry(`upstream probe failed: ${probeError}`) + } const settings = deps.getSettings() const hostKey = getCommitMessageModelDiscoveryHostKey(repo.connectionId ?? null) @@ -249,8 +260,13 @@ async function runAutoRename( if (branchNow !== currentBranch) { return retry(`branch changed during generation (${currentBranch} -> ${branchNow})`) } - if (await branchHasUpstream(exec)) { - return retry(`branch "${currentBranch}" was pushed during generation`) + const postGenerationProbe = await probeBranchUpstream(exec) + if (postGenerationProbe.outcome !== 'no-upstream') { + return retry( + postGenerationProbe.outcome === 'has-upstream' + ? `branch "${currentBranch}" was pushed during generation` + : `upstream probe failed after generation: ${postGenerationProbe.message}` + ) } const username = provider diff --git a/src/main/agent-hooks/remote-hook-service-installers.test.ts b/src/main/agent-hooks/remote-hook-service-installers.test.ts index 8a85128cdefd..90726a2d7a76 100644 --- a/src/main/agent-hooks/remote-hook-service-installers.test.ts +++ b/src/main/agent-hooks/remote-hook-service-installers.test.ts @@ -8,6 +8,7 @@ vi.mock('electron', () => ({ })) import { CodexHookService } from '../codex/hook-service' +import { DroidHookService } from '../droid/hook-service' import { CursorHookService } from '../cursor/hook-service' import { CommandCodeHookService } from '../command-code/hook-service' import { GeminiHookService } from '../gemini/hook-service' @@ -20,6 +21,24 @@ import { HermesHookService } from '../hermes/hook-service' import { DevinHookService } from '../devin/hook-service' import { KimiHookService } from '../kimi/hook-service' import { openClaudeHookService } from '../openclaude/hook-service' +import { ampHookService } from '../amp/hook-service' +import { antigravityHookService } from '../antigravity/hook-service' +import { claudeHookService } from '../claude/hook-service' +import { codexHookService } from '../codex/hook-service' +import { copilotHookService } from '../copilot/hook-service' +import { cursorHookService } from '../cursor/hook-service' +import { droidHookService } from '../droid/hook-service' +import { commandCodeHookService } from '../command-code/hook-service' +import { geminiHookService } from '../gemini/hook-service' +import { devinHookService } from '../devin/hook-service' +import { grokHookService } from '../grok/hook-service' +import { hermesHookService } from '../hermes/hook-service' +import { kimiHookService } from '../kimi/hook-service' +import { MANAGED_AGENT_HOOK_INSTALLERS } from './managed-agent-hook-controls' +import { + installRemoteManagedAgentHooks, + REMOTE_MANAGED_HOOK_INSTALLER_AGENTS +} from './remote-managed-hook-installers' type FakeFs = { files: Map @@ -166,6 +185,10 @@ describe('remote hook service installers', () => { { path: '/home/dev/.orca/agent-hooks/devin-hook.sh', install: (sftp: SFTPWrapper) => new DevinHookService().installRemote(sftp, '/home/dev') + }, + { + path: '/home/dev/.orca/agent-hooks/droid-hook.sh', + install: (sftp: SFTPWrapper) => new DroidHookService().installRemote(sftp, '/home/dev') } ] @@ -230,6 +253,48 @@ describe('remote hook service installers', () => { expect(toml).toContain('trusted_hash = "sha256:') }) + it('installs Codex hooks into an explicit redirected CODEX_HOME (WSL managed runtime home)', async () => { + const runtimeHome = '/home/dev/.local/share/orca/codex-runtime-home/home' + const { sftp, fs } = createFakeSftp({ + [`${runtimeHome}/config.toml`]: 'model = "gpt-5.2-codex"\n' + }) + + const status = await new CodexHookService().installRemote(sftp, '/home/dev', { + codexHomeDir: runtimeHome, + deferTrustUntilConfigToml: true + }) + + expect(status.state).toBe('installed') + expect(status.configPath).toBe(`${runtimeHome}/hooks.json`) + expect(fs.files.has('/home/dev/.codex/hooks.json')).toBe(false) + const hooks = JSON.parse(fs.files.get(`${runtimeHome}/hooks.json`)!) as { + hooks: Record + } + expect(hooks.hooks.Stop?.[0]?.hooks?.[0]?.command).toContain( + '/home/dev/.orca/agent-hooks/codex-hook.sh' + ) + const toml = fs.files.get(`${runtimeHome}/config.toml`) + expect(toml).toContain('model = "gpt-5.2-codex"') + expect(toml).toContain(`${runtimeHome}/hooks.json:stop:0:0`) + }) + + it('defers Codex trust writes until the redirected config.toml exists (launch-path seed race)', async () => { + const runtimeHome = '/home/dev/.local/share/orca/codex-runtime-home/home' + const { sftp, fs } = createFakeSftp() + + const status = await new CodexHookService().installRemote(sftp, '/home/dev', { + codexHomeDir: runtimeHome, + deferTrustUntilConfigToml: true + }) + + expect(status.state).toBe('installed') + expect(status.detail).toContain('deferred') + expect(fs.files.get(`${runtimeHome}/hooks.json`)).toContain('codex-hook.sh') + // Why: creating config.toml here would make the launch path's + // only-if-absent seed skip the user's real config. + expect(fs.files.has(`${runtimeHome}/config.toml`)).toBe(false) + }) + it('reports Codex trust-write failures without rolling back installed hooks', async () => { const { sftp, fs } = createFakeSftp() fs.failRenameTo.add('/home/dev/.codex/config.toml') @@ -346,6 +411,7 @@ describe('remote hook service installers', () => { 'SessionStart', 'UserPromptSubmit', 'Stop', + 'StopFailure', 'SessionEnd', 'PreToolUse', 'PostToolUse', @@ -357,7 +423,10 @@ describe('remote hook service installers', () => { expect(command).toContain('/home/dev/.orca/agent-hooks/grok-hook.sh') expect(command).toMatch(/^if \[ -x /) } - expect(grokConfig.hooks.PreToolUse?.[0]?.matcher).toBe('*') + // Why: Grok tool matchers are real regexes; bare `*` is invalid match-all. + expect(grokConfig.hooks.PreToolUse?.[0]?.matcher).toBe('.*') + expect(grokConfig.hooks.PostToolUse?.[0]?.matcher).toBe('.*') + expect(grokConfig.hooks.StopFailure?.[0]?.matcher).toBeUndefined() const devinConfig = JSON.parse(devin.fs.files.get('/home/dev/.config/devin/config.json')!) as { permissions: { mode: string } @@ -386,6 +455,35 @@ describe('remote hook service installers', () => { expect(devin.fs.files.get('/home/dev/.orca/agent-hooks/devin-hook.sh')).toContain('/hook/devin') }) + it('installs remote Grok config in the explicit guest GROK_HOME', async () => { + const { sftp, fs } = createFakeSftp() + + const status = await new GrokHookService().installRemote( + sftp, + '/home/dev', + '/srv/grok profile/' + ) + + expect(status.configPath).toBe('/srv/grok profile/hooks/orca-status.json') + expect(fs.files.has('/srv/grok profile/hooks/orca-status.json')).toBe(true) + expect(fs.files.has('/home/dev/.grok/hooks/orca-status.json')).toBe(false) + const script = fs.files.get('/home/dev/.orca/agent-hooks/grok-hook.sh')! + expect(script).toContain('${#GROK_HOME}" -le 4096') + expect(script).toContain('--data-urlencode "grokHome=${grok_home}"') + }) + + it.each(['relative/grok', '/bad\\grok', `/${'x'.repeat(4096)}`])( + 'falls back to login-home Grok config for invalid remote home %s', + async (remoteGrokHome) => { + const { sftp, fs } = createFakeSftp() + + const status = await new GrokHookService().installRemote(sftp, '/home/dev', remoteGrokHome) + + expect(status.configPath).toBe('/home/dev/.grok/hooks/orca-status.json') + expect(fs.files.has('/home/dev/.grok/hooks/orca-status.json')).toBe(true) + } + ) + it('installs remote Kimi hooks as a managed config.toml block preserving user config', async () => { const userConfig = 'default_model = "kimi-k2.6"\n\n[providers."mine"]\napi_key = "sk-secret"\n' const { sftp, fs } = createFakeSftp({ '/home/dev/.kimi-code/config.toml': userConfig }) @@ -582,6 +680,107 @@ describe('remote hook service installers', () => { expect(fs.modes.get('/home/dev/.orca/agent-hooks/copilot-hook.sh')).toBe(0o755) }) + // Why: Droid (and Copilot) each shipped a working installRemote but were never + // registered in REMOTE_MANAGED_HOOK_INSTALLERS, so their status silently never + // appeared over SSH (issue #7253). Guard the whole bug class, not one agent: + // every locally-managed hook service that implements installRemote MUST be + // wired into the remote installer. + it('registers every managed agent that implements installRemote in the remote installer (issue #7253)', () => { + const servicesByAgent = new Map([ + ['claude', claudeHookService], + ['openclaude', openClaudeHookService], + ['codex', codexHookService], + ['gemini', geminiHookService], + ['antigravity', antigravityHookService], + ['amp', ampHookService], + ['cursor', cursorHookService], + ['droid', droidHookService], + ['command-code', commandCodeHookService], + ['grok', grokHookService], + ['copilot', copilotHookService], + ['hermes', hermesHookService], + ['devin', devinHookService], + ['kimi', kimiHookService] + ]) + + // Guard against a service silently missing from the map above as new agents land. + for (const [agent] of MANAGED_AGENT_HOOK_INSTALLERS) { + expect(servicesByAgent.has(agent)).toBe(true) + } + + const registered = new Set(REMOTE_MANAGED_HOOK_INSTALLER_AGENTS) + const missing: string[] = [] + for (const [agent, service] of servicesByAgent) { + if (typeof service.installRemote === 'function' && !registered.has(agent)) { + missing.push(agent) + } + } + expect(missing).toEqual([]) + }) + + it('installs Droid and Copilot when running the aggregate remote installer (issue #7253)', async () => { + const { sftp } = createFakeSftp() + const results = await installRemoteManagedAgentHooks(sftp, '/home/dev') + const byAgent = new Map(results.map((r) => [r.agent, r.state])) + expect(byAgent.get('droid')).toBe('installed') + expect(byAgent.get('copilot')).toBe('installed') + }) + + it('installs remote Droid hooks into Factory settings.json (issue #7253)', async () => { + const { sftp, fs } = createFakeSftp() + + const status = await new DroidHookService().installRemote(sftp, '/home/dev') + + expect(status.state).toBe('installed') + expect(status.configPath).toBe('/home/dev/.factory/settings.json') + const config = JSON.parse(fs.files.get('/home/dev/.factory/settings.json')!) as { + hooks: Record + } + for (const eventName of [ + 'SessionStart', + 'UserPromptSubmit', + 'Stop', + 'SubagentStop', + 'PreToolUse', + 'PostToolUse', + 'PermissionRequest', + 'Notification' + ]) { + const definition = config.hooks[eventName]?.[0] + const command = definition?.hooks?.[0]?.command + expect(command).toContain('/home/dev/.orca/agent-hooks/droid-hook.sh') + expect(command).toMatch(/^if \[ -x /) + } + // Tool/permission events carry a `*` matcher; lifecycle events do not. + expect(config.hooks.PreToolUse?.[0]?.matcher).toBe('*') + expect(config.hooks.PostToolUse?.[0]?.matcher).toBe('*') + expect(config.hooks.PermissionRequest?.[0]?.matcher).toBe('*') + expect(config.hooks.Stop?.[0]?.matcher).toBeUndefined() + const script = fs.files.get('/home/dev/.orca/agent-hooks/droid-hook.sh') + expect(script).toContain('#!/bin/sh') + expect(script).toContain('/hook/droid') + expect(fs.modes.get('/home/dev/.orca/agent-hooks/droid-hook.sh')).toBe(0o755) + }) + + it('does not overwrite a malformed remote Factory settings.json', async () => { + const original = '{"hooks": }' + const { sftp, fs } = createFakeSftp({ + '/home/dev/.factory/settings.json': original + }) + + const status = await new DroidHookService().installRemote(sftp, '/home/dev') + + expect(status).toMatchObject({ + agent: 'droid', + state: 'error', + configPath: '/home/dev/.factory/settings.json', + managedHooksPresent: false, + detail: 'Could not parse remote Factory settings.json' + }) + expect(fs.files.get('/home/dev/.factory/settings.json')).toBe(original) + expect(fs.files.get('/home/dev/.orca/agent-hooks/droid-hook.sh')).toBeUndefined() + }) + it('installs remote Hermes plugin files and enables the plugin', async () => { const { sftp, fs } = createFakeSftp() diff --git a/src/main/agent-hooks/remote-managed-hook-installers.ts b/src/main/agent-hooks/remote-managed-hook-installers.ts index 7913b8635773..39507f091f23 100644 --- a/src/main/agent-hooks/remote-managed-hook-installers.ts +++ b/src/main/agent-hooks/remote-managed-hook-installers.ts @@ -7,40 +7,79 @@ import { geminiHookService } from '../gemini/hook-service' import { antigravityHookService } from '../antigravity/hook-service' import { cursorHookService } from '../cursor/hook-service' import { commandCodeHookService } from '../command-code/hook-service' +import { copilotHookService } from '../copilot/hook-service' import { devinHookService } from '../devin/hook-service' +import { droidHookService } from '../droid/hook-service' import { grokHookService } from '../grok/hook-service' import { hermesHookService } from '../hermes/hook-service' import { kimiHookService } from '../kimi/hook-service' import { openClaudeHookService } from '../openclaude/hook-service' +export type RemoteManagedHookInstallOptions = { + /** Explicit CODEX_HOME dir for redirected runtimes (WSL managed runtime + * home). Codex-only: it is the one agent whose home Orca redirects. Also + * defers the config.toml trust write until that file exists, so the + * launch path's only-if-absent seed is never pre-empted. */ + codexHomeDir?: string + /** Explicit GROK_HOME for remote runtimes that redirect Grok's config. */ + grokHomeDir?: string +} + type RemoteManagedHookInstaller = readonly [ AgentHookInstallStatus['agent'], - (sftp: SFTPWrapper, remoteHome: string) => Promise + ( + sftp: SFTPWrapper, + remoteHome: string, + options?: RemoteManagedHookInstallOptions + ) => Promise ] const REMOTE_MANAGED_HOOK_INSTALLERS: readonly RemoteManagedHookInstaller[] = [ ['claude', (sftp, remoteHome) => claudeHookService.installRemote(sftp, remoteHome)], ['openclaude', (sftp, remoteHome) => openClaudeHookService.installRemote(sftp, remoteHome)], - ['codex', (sftp, remoteHome) => codexHookService.installRemote(sftp, remoteHome)], + [ + 'codex', + (sftp, remoteHome, options) => + codexHookService.installRemote( + sftp, + remoteHome, + options?.codexHomeDir + ? { codexHomeDir: options.codexHomeDir, deferTrustUntilConfigToml: true } + : undefined + ) + ], ['gemini', (sftp, remoteHome) => geminiHookService.installRemote(sftp, remoteHome)], ['antigravity', (sftp, remoteHome) => antigravityHookService.installRemote(sftp, remoteHome)], ['amp', (sftp, remoteHome) => ampHookService.installRemote(sftp, remoteHome)], ['cursor', (sftp, remoteHome) => cursorHookService.installRemote(sftp, remoteHome)], ['command-code', (sftp, remoteHome) => commandCodeHookService.installRemote(sftp, remoteHome)], - ['grok', (sftp, remoteHome) => grokHookService.installRemote(sftp, remoteHome)], + ['copilot', (sftp, remoteHome) => copilotHookService.installRemote(sftp, remoteHome)], + [ + 'grok', + (sftp, remoteHome, options) => + grokHookService.installRemote(sftp, remoteHome, options?.grokHomeDir) + ], + ['droid', (sftp, remoteHome) => droidHookService.installRemote(sftp, remoteHome)], ['hermes', (sftp, remoteHome) => hermesHookService.installRemote(sftp, remoteHome)], ['devin', (sftp, remoteHome) => devinHookService.installRemote(sftp, remoteHome)], ['kimi', (sftp, remoteHome) => kimiHookService.installRemote(sftp, remoteHome)] ] +/** Agents wired into the remote (SSH) hook installer. Exported so an invariant + * test can assert every locally-managed agent that implements `installRemote` + * is registered here — the omission that hid Droid/Copilot status over SSH. */ +export const REMOTE_MANAGED_HOOK_INSTALLER_AGENTS: readonly AgentHookInstallStatus['agent'][] = + REMOTE_MANAGED_HOOK_INSTALLERS.map(([agent]) => agent) + export async function installRemoteManagedAgentHooks( sftp: SFTPWrapper, - remoteHome: string + remoteHome: string, + options?: RemoteManagedHookInstallOptions ): Promise { const results: AgentHookInstallStatus[] = [] for (const [agent, install] of REMOTE_MANAGED_HOOK_INSTALLERS) { try { - const result = await install(sftp, remoteHome) + const result = await install(sftp, remoteHome, options) results.push(result) if (result.state === 'error') { console.warn( diff --git a/src/main/agent-hooks/server-grok-discovery.test.ts b/src/main/agent-hooks/server-grok-discovery.test.ts new file mode 100644 index 000000000000..cea007c3d2fa --- /dev/null +++ b/src/main/agent-hooks/server-grok-discovery.test.ts @@ -0,0 +1,119 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import * as agentHookListener from '../../shared/agent-hook-listener' +import { makePaneKey } from '../../shared/stable-pane-id' +import { AgentHookServer } from './server' + +const PANE_KEY = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111') + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() +}) + +function hookBody(payload: Record): Record { + return { + paneKey: PANE_KEY, + tabId: 'tab-1', + worktreeId: 'wt-1', + env: 'production', + payload + } +} + +async function postGrokHook( + endpoint: { port: string; token: string }, + payload: Record +): Promise { + return fetch(`http://127.0.0.1:${endpoint.port}/hook/grok`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Orca-Agent-Hook-Token': endpoint.token + }, + body: JSON.stringify(hookBody(payload)) + }) +} + +describe('AgentHookServer Grok discovery retries', () => { + it('waits for delayed discovery beyond the transcript retry window', async () => { + let releaseDiscovery!: () => void + const discovery = new Promise((resolve) => { + releaseDiscovery = resolve + }) + vi.spyOn(agentHookListener, 'preparePendingGrokResultDiscovery').mockReturnValue(discovery) + const server = new AgentHookServer() + const root = mkdtempSync(join(tmpdir(), 'orca-grok-delayed-discovery-')) + const sessionId = '019e37f4-5135-7b63-a4ab-6d13aa6bf532' + const cwd = join(root, 'workspace') + const sessionDir = join(root, '.grok', 'sessions', encodeURIComponent(cwd), sessionId) + mkdirSync(sessionDir, { recursive: true }) + const history = join(sessionDir, 'chat_history.jsonl') + writeFileSync(history, '') + vi.stubEnv('HOME', root) + vi.stubEnv('USERPROFILE', root) + await server.start({ env: 'production' }) + try { + const env = server.buildPtyEnv() + const endpoint = { port: env.ORCA_AGENT_HOOK_PORT, token: env.ORCA_AGENT_HOOK_TOKEN } + const listener = vi.fn() + server.setListener(listener) + + await postGrokHook(endpoint, { hookEventName: 'UserPromptSubmit', prompt: 'delayed result' }) + await postGrokHook(endpoint, { hookEventName: 'Stop', sessionId, cwd }) + await new Promise((resolve) => setTimeout(resolve, 300)) + expect(listener.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBeUndefined() + + writeFileSync( + history, + `${JSON.stringify({ type: 'assistant', content: 'Found after discovery.' })}\n` + ) + releaseDiscovery() + + await vi.waitFor(() => { + expect(listener.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBe( + 'Found after discovery.' + ) + }) + } finally { + server.stop() + rmSync(root, { recursive: true, force: true }) + } + }) + + it('does not overwrite a newer same-text prompt when delayed discovery completes', async () => { + let releaseDiscovery!: () => void + const discovery = new Promise((resolve) => { + releaseDiscovery = resolve + }) + vi.spyOn(agentHookListener, 'preparePendingGrokResultDiscovery').mockReturnValue(discovery) + const server = new AgentHookServer() + const root = mkdtempSync(join(tmpdir(), 'orca-grok-stale-discovery-')) + vi.stubEnv('HOME', root) + vi.stubEnv('USERPROFILE', root) + await server.start({ env: 'production' }) + try { + const env = server.buildPtyEnv() + const endpoint = { port: env.ORCA_AGENT_HOOK_PORT, token: env.ORCA_AGENT_HOOK_TOKEN } + await postGrokHook(endpoint, { hookEventName: 'UserPromptSubmit', prompt: 'old prompt' }) + await postGrokHook(endpoint, { + hookEventName: 'Stop', + sessionId: '019e37f4-5135-7b63-a4ab-6d13aa6bf533', + cwd: join(root, 'workspace') + }) + await postGrokHook(endpoint, { hookEventName: 'UserPromptSubmit', prompt: 'old prompt' }) + + releaseDiscovery() + await new Promise((resolve) => setTimeout(resolve, 80)) + + expect(server.getStatusSnapshot()).toEqual([ + expect.objectContaining({ state: 'working', prompt: 'old prompt', agentType: 'grok' }) + ]) + } finally { + server.stop() + rmSync(root, { recursive: true, force: true }) + } + }) +}) diff --git a/src/main/agent-hooks/server.test.ts b/src/main/agent-hooks/server.test.ts index 91b0dc660510..bf3cf0c8f848 100644 --- a/src/main/agent-hooks/server.test.ts +++ b/src/main/agent-hooks/server.test.ts @@ -5305,6 +5305,8 @@ describe('Copilot hook normalization', () => { }) ) + // Let the first 50ms retry miss so continuation across SessionEnd is proven. + await new Promise((resolve) => setTimeout(resolve, 70)) writeFileSync( transcriptPath, `${JSON.stringify({ diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index 167331765cfa..da33b4231cb1 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -31,6 +31,7 @@ import { parseFormEncodedBody, readRequestBody, resolveHookSource, + preparePendingGrokResultDiscovery, warnOnHookEnvOrVersionMismatch, writeEndpointFile, type AgentHookEventPayload, @@ -804,7 +805,8 @@ export class AgentHookServer { source: AgentHookSource, body: unknown, original: EnrichedAgentHookEventPayload, - attempt = 1 + attempt = 1, + discoveryReady = false ): void { if ( original.payload.lastAssistantMessage || @@ -814,28 +816,27 @@ export class AgentHookServer { return } this.clearAssistantMessageRetry(original.paneKey) + if (!discoveryReady) { + const discovery = preparePendingGrokResultDiscovery(source, body) + if (discovery) { + // Why: slug-group discovery can outlive the bounded transcript-flush + // timers. Its completion must drive the first retry deterministically. + void discovery + .then(() => { + if (this.server) { + this.applyAssistantMessageRetry(source, body, original, 1, true) + } + }) + .catch((err) => { + console.error('[agent-hooks] Grok result discovery failed:', err) + }) + return + } + } const timer = setTimeout(() => { try { this.assistantMessageRetryTimers.delete(original.paneKey) - const current = this.state.lastStatusByPaneKey.get(original.paneKey) as - | EnrichedAgentHookEventPayload - | undefined - if ( - !current || - current.payload.agentType !== original.payload.agentType || - current.payload.prompt !== original.payload.prompt || - current.payload.lastAssistantMessage - ) { - return - } - const normalized = normalizeHookPayload(this.state, source, body, this.env) - if (!normalized?.payload.lastAssistantMessage) { - this.scheduleAssistantMessageRetry(source, body, original, attempt + 1) - return - } - // Why: some agents POST Stop before their transcript/chat-history line - // is flushed. Retry from a timer so the hook request returns immediately. - this.applyNormalizedStatus(normalized) + this.applyAssistantMessageRetry(source, body, original, attempt + 1, discoveryReady) } catch (err) { console.error('[agent-hooks] assistant message retry failed:', err) } @@ -846,6 +847,35 @@ export class AgentHookServer { } } + private applyAssistantMessageRetry( + source: AgentHookSource, + body: unknown, + original: EnrichedAgentHookEventPayload, + nextAttempt: number, + requireExactOriginal: boolean + ): void { + const current = this.state.lastStatusByPaneKey.get(original.paneKey) as + | EnrichedAgentHookEventPayload + | undefined + if ( + !current || + (requireExactOriginal && current !== original) || + current.payload.agentType !== original.payload.agentType || + current.payload.prompt !== original.payload.prompt || + current.payload.lastAssistantMessage + ) { + return + } + const normalized = normalizeHookPayload(this.state, source, body, this.env) + if (!normalized?.payload.lastAssistantMessage) { + this.scheduleAssistantMessageRetry(source, body, original, nextAttempt, requireExactOriginal) + return + } + // Why: some agents POST Stop before their transcript/chat-history line is + // flushed. Discovery is event-driven; subsequent content retries stay timed. + this.applyNormalizedStatus(normalized) + } + setPaneKeyAliasPersistenceListener(listener: PaneKeyAliasPersistenceListener | null): void { this.paneKeyAliasPersistenceListener = listener } diff --git a/src/main/agent-hooks/wsl-hook-fs-adapter.ts b/src/main/agent-hooks/wsl-hook-fs-adapter.ts new file mode 100644 index 000000000000..d47dd400199c --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-fs-adapter.ts @@ -0,0 +1,136 @@ +// SFTP-shaped adapter over the WSL hook relay's fs bridge. Lets the +// unchanged SSH remote hook installers (`installRemoteManagedAgentHooks`) +// write into a WSL distro's home over the relay's already-open stdio channel +// — the WSL twin of the SSH flow's real SFTPWrapper. Only the primitives +// `installer-utils-remote.ts` touches are implemented. +import type { SFTPWrapper } from 'ssh2' + +import type { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' +import type { SshChannelMultiplexer } from '../ssh/ssh-channel-multiplexer' +import { wslCodexRuntimeHomeForGuestHome } from '../pty/codex-home-wsl-env' +import { WSL_HOOK_FS_METHODS, type WslFsResult } from '../../shared/wsl-hook-relay-contract' + +/** Run the shared remote hook installers against a WSL guest over the relay's + * fs bridge. Codex is the one agent whose home Orca redirects for WSL + * sessions, so its hooks go to the managed runtime home. */ +export async function installWslGuestHooks(options: { + mux: SshChannelMultiplexer + guestHome: string + distro: string + installHooks: typeof installRemoteManagedAgentHooks + warn: (message: string) => void +}): Promise { + const { mux, guestHome, distro, installHooks, warn } = options + const results = await installHooks(createWslHookSftpAdapter(mux), guestHome, { + codexHomeDir: wslCodexRuntimeHomeForGuestHome(guestHome) + }) + const failed = results.filter((r) => r.state === 'error').length + if (failed > 0) { + warn( + `[agent-hooks] WSL hook install for '${distro}': ${failed}/${results.length} agents failed` + ) + } +} + +type SftpCallback = (err: Error | null, value?: T) => void + +// Why: installer-utils-remote classifies errors by ssh2's numeric SFTP status +// codes (ENOENT=2, already-exists=4). Map guest POSIX errno onto those so the +// shared classifiers keep working across transports. +const ERRNO_TO_SFTP_CODE: Record = { + ENOENT: 2, + ENOTDIR: 2, + EACCES: 3, + EEXIST: 4 +} + +function toSftpError(failure: { errno?: string; message?: string }): Error { + const err = new Error(failure.message ?? 'wsl fs bridge failure') as Error & { code?: number } + err.code = ERRNO_TO_SFTP_CODE[failure.errno ?? ''] ?? 5 + return err +} + +export function createWslHookSftpAdapter(mux: SshChannelMultiplexer): SFTPWrapper { + const call = ( + method: string, + params: Record, + callback: SftpCallback, + pick: (result: { ok: true } & Wire) => Value + ): void => { + mux + .request(method, params) + .then((raw) => { + const result = raw as WslFsResult + if (!result || typeof result !== 'object' || result.ok !== true) { + callback(toSftpError((result ?? {}) as { errno?: string; message?: string })) + return + } + callback(null, pick(result)) + }) + .catch((err) => callback(err instanceof Error ? err : new Error(String(err)))) + } + const callVoid = ( + method: string, + params: Record, + callback: SftpCallback + ): void => { + call, undefined>(method, params, callback, () => undefined) + } + + const adapter = { + readFile(path: string, _encoding: unknown, callback: SftpCallback): void { + call<{ content: string }, string>( + WSL_HOOK_FS_METHODS.readFile, + { path }, + callback, + (r) => r.content + ) + }, + writeFile( + path: string, + content: string, + options: { mode?: number }, + callback: SftpCallback + ): void { + callVoid(WSL_HOOK_FS_METHODS.writeFile, { path, content, mode: options?.mode }, callback) + }, + stat(path: string, callback: SftpCallback<{ mode: number }>): void { + call<{ mode: number }, { mode: number }>( + WSL_HOOK_FS_METHODS.stat, + { path }, + callback, + (r) => ({ + mode: r.mode + }) + ) + }, + // Why: POSIX rename overwrites atomically, which is exactly the OpenSSH + // overwrite-rename semantics the installers prefer — so the extension is + // "supported" here and plain rename shares the implementation. + ext_openssh_rename(src: string, dst: string, callback: SftpCallback): void { + callVoid(WSL_HOOK_FS_METHODS.rename, { src, dst }, callback) + }, + rename(src: string, dst: string, callback: SftpCallback): void { + callVoid(WSL_HOOK_FS_METHODS.rename, { src, dst }, callback) + }, + unlink(path: string, callback: SftpCallback): void { + callVoid(WSL_HOOK_FS_METHODS.unlink, { path }, callback) + }, + chmod(path: string, mode: number, callback: SftpCallback): void { + callVoid(WSL_HOOK_FS_METHODS.chmod, { path, mode }, callback) + }, + readdir(path: string, callback: SftpCallback<{ filename: string }[]>): void { + call<{ entries: { filename: string }[] }, { filename: string }[]>( + WSL_HOOK_FS_METHODS.readdir, + { path }, + callback, + (r) => r.entries + ) + }, + mkdir(path: string, callback: SftpCallback): void { + callVoid(WSL_HOOK_FS_METHODS.mkdir, { path }, callback) + } + } + + return adapter as unknown as SFTPWrapper +} diff --git a/src/main/agent-hooks/wsl-hook-relay-deps.ts b/src/main/agent-hooks/wsl-hook-relay-deps.ts new file mode 100644 index 000000000000..2c30739e25b2 --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-relay-deps.ts @@ -0,0 +1,90 @@ +// DI seam for WslHookRelayManager: the full dependency contract plus the +// production wiring. Tests construct the manager with fakes for everything +// that spawns wsl.exe or touches the live agentHookServer. +import { createHash } from 'node:crypto' +import { readFileSync } from 'node:fs' + +import { agentHookServer } from './server' +import { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' +import { + isWslDistroRunning, + resolveWslHookRelayBundle, + runWslInstallProcess, + spawnWslRelayProcess +} from './wsl-hook-relay-launch' +import { waitForWslRelaySentinel } from './wsl-hook-relay-sentinel' +import { listWslDistrosAsync } from '../wsl' +import { isRemoteAgentHooksEnabled } from '../../shared/agent-hook-relay' + +// Why: fresh WSL intermittently throws "Catastrophic failure (E_UNEXPECTED)" +// under concurrent wsl.exe spawn load; the retry pause is a dep so tests can +// collapse it. +export const WSL_RELAY_TRANSIENT_RETRY_DELAY_MS = 2_000 + +// Restart/cooldown policy for the manager's state machine. +export const FAILURE_COOLDOWN_BASE_MS = 60_000 +export const FAILURE_COOLDOWN_MAX_MS = 10 * 60_000 +// Why: a distro without node >= 18 will not grow one mid-session; probe +// rarely instead of once per PTY spawn. +export const NO_NODE_COOLDOWN_MS = 10 * 60_000 +// Why: a previously-healthy relay dying mid-session (mux protocol error, WSL +// restart) must self-recover — a live agent session produces no new PTY +// spawns, so waiting for the next ensure would leave status dead for good. +export const RUNNING_TEARDOWN_COOLDOWN_MS = 10_000 +// Why: only a relay that stayed up this long resets the failure counter — a +// connect-then-crash loop must keep escalating its cooldown, not sit at the +// running-teardown base forever. +export const STABLE_UPTIME_MS = 2 * 60_000 +// Why: re-running the (byte-equality idempotent) installers picks up configs +// that appear after first install — e.g. Codex's runtime-home config.toml is +// seeded by the launch path, so its hook-trust entries can only be written +// once that file exists. The one-shot timer covers single-spawn sessions. +export const REINSTALL_MIN_INTERVAL_MS = 30_000 +export const REINSTALL_ONE_SHOT_DELAY_MS = 60_000 + +export type WslHookRelayManagerDeps = { + platform: () => NodeJS.Platform + remoteHooksEnabled: () => boolean + hookCoordsEnv: () => Record + /** Restart-stable, instance-unique key for the guest endpoint dir. */ + instanceKey: () => string | null + resolveBundle: typeof resolveWslHookRelayBundle + readBundle: (jsPath: string) => Buffer + listDistros: () => Promise + isDistroRunning: typeof isWslDistroRunning + spawnRelay: typeof spawnWslRelayProcess + runInstall: typeof runWslInstallProcess + waitForSentinel: typeof waitForWslRelaySentinel + ingest: (envelope: Record, connectionId: string) => void + installHooks: typeof installRemoteManagedAgentHooks + warn: (message: string) => void + transientRetryDelayMs: number +} + +export const defaultWslHookRelayDeps: WslHookRelayManagerDeps = { + platform: () => process.platform, + remoteHooksEnabled: () => isRemoteAgentHooksEnabled(), + hookCoordsEnv: () => agentHookServer.buildPtyEnv(), + // Why: the Windows endpoint file path (userData + namespace) is stable + // across app restarts and distinct per instance — exactly the identity the + // guest endpoint dir must carry so surviving agents re-coordinate. + instanceKey: () => { + const source = agentHookServer.endpointFilePath + return source ? createHash('sha256').update(source).digest('hex').slice(0, 12) : null + }, + resolveBundle: resolveWslHookRelayBundle, + readBundle: (jsPath) => readFileSync(jsPath), + listDistros: () => listWslDistrosAsync(), + isDistroRunning: isWslDistroRunning, + spawnRelay: spawnWslRelayProcess, + runInstall: runWslInstallProcess, + waitForSentinel: waitForWslRelaySentinel, + ingest: (envelope, connectionId) => + agentHookServer.ingestRemote( + envelope as Parameters[0], + connectionId + ), + installHooks: installRemoteManagedAgentHooks, + warn: (message) => console.warn(message), + transientRetryDelayMs: WSL_RELAY_TRANSIENT_RETRY_DELAY_MS +} diff --git a/src/main/agent-hooks/wsl-hook-relay-launch.ts b/src/main/agent-hooks/wsl-hook-relay-launch.ts new file mode 100644 index 000000000000..72ff3bb0c234 --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-relay-launch.ts @@ -0,0 +1,330 @@ +// Launch/install plumbing for the guest-resident WSL agent-hook relay: +// bundle resolution on the Windows side, the guest launch/install scripts, +// and the sentinel wait that turns a wsl.exe child's stdio into a +// MultiplexerTransport. Kept separate from the manager so the state machine +// stays readable. See docs/agent-status-over-wsl.md (STA-1515). +import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process' +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { app } from 'electron' + +import type { MultiplexerTransport } from '../ssh/ssh-channel-multiplexer' +import { + decodeWslText, + MAX_STARTUP_BUFFER_BYTES, + type waitForWslRelaySentinel, + type WslRelayStartupFailure +} from './wsl-hook-relay-sentinel' +import { addOrcaWslInteropEnv } from '../pty/wsl-orca-env' +import { + WSL_HOOK_RELAY_BUNDLE_NAME, + WSL_HOOK_RELAY_DIR, + WSL_HOOK_RELAY_INSTANCE_ENV, + WSL_HOOK_RELAY_NO_NODE_EXIT_CODE, + WSL_HOOK_RELAY_STALE_EXIT_CODE, + WSL_HOOK_RELAY_VERSION_ENV, + WSL_HOOK_RELAY_VERSION_FILE +} from '../../shared/wsl-hook-relay-contract' + +const INSTALL_TIMEOUT_MS = 30_000 + +export type WslHookRelayBundle = { jsPath: string; version: string } + +export function resolveWslHookRelayBundle(): WslHookRelayBundle | null { + // Mirrors getLocalRelayCandidates in ssh-relay-deploy: env override for + // tests/dev, then packaged extraResources, then dev out/ paths. + const candidates: string[] = [] + if (process.env.ORCA_RELAY_PATH) { + candidates.push(join(process.env.ORCA_RELAY_PATH, 'wsl')) + } + if (process.resourcesPath) { + candidates.push(join(process.resourcesPath, 'relay', 'wsl')) + candidates.push(join(process.resourcesPath, 'app.asar.unpacked', 'out', 'relay', 'wsl')) + } + try { + const appPath = app.getAppPath() + candidates.push(join(appPath, 'resources', 'relay', 'wsl')) + candidates.push(join(appPath, 'out', 'relay', 'wsl')) + } catch { + // app not ready in some test contexts — env/resources candidates suffice. + } + for (const dir of candidates) { + const jsPath = join(dir, WSL_HOOK_RELAY_BUNDLE_NAME) + const versionPath = join(dir, WSL_HOOK_RELAY_VERSION_FILE) + if (existsSync(jsPath) && existsSync(versionPath)) { + const version = readFileSync(versionPath, 'utf8').trim() + // Why: the version lands inside single-quoted guest shell text and in + // a guest path segment — refuse anything outside the safe alphabet. + if (/^[A-Za-z0-9+.-]+$/.test(version)) { + return { jsPath, version } + } + } + } + return null +} + +// Why: the install dir is namespaced by bundle version so concurrent Orca +// instances with different bundles (dev + prod) never reinstall over each +// other; each instance launches exactly the version it shipped. +function guestRelayDirExpr(version: string): string { + return `$HOME/${WSL_HOOK_RELAY_DIR}/${version}` +} + +/** Guest launcher, installed alongside the bundle. The `.version` marker is + * written last by the installer, so the check rejects partial installs; + * node resolution probes each candidate's version because `sh -c` does not + * source interactive profiles (an apt node 12 on PATH must not shadow an + * nvm node 20 off PATH). */ +export function buildGuestLaunchScript(version: string): string { + const dir = guestRelayDirExpr(version) + return [ + '#!/bin/sh', + `d="${dir}"`, + `v="$(cat "$d/${WSL_HOOK_RELAY_VERSION_FILE}" 2>/dev/null || true)"`, + `[ -n "$${WSL_HOOK_RELAY_VERSION_ENV}" ] && [ "$v" = "$${WSL_HOOK_RELAY_VERSION_ENV}" ] || exit ${WSL_HOOK_RELAY_STALE_EXIT_CODE}`, + 'n=""', + 'for c in "$(command -v node 2>/dev/null || true)" "$HOME/.nvm/versions/node"/*/bin/node /usr/local/bin/node /usr/bin/node "$HOME/.local/bin/node"; do', + ' [ -n "$c" ] && [ -x "$c" ] || continue', + ` if "$c" -e 'process.exit(Number(process.versions.node.split(".")[0])>=18?0:1)' 2>/dev/null; then`, + ' n="$c"', + ' break', + ' fi', + 'done', + `[ -n "$n" ] || exit ${WSL_HOOK_RELAY_NO_NODE_EXIT_CODE}`, + `exec "$n" "$d/${WSL_HOOK_RELAY_BUNDLE_NAME}"`, + '' + ].join('\n') +} + +/** Idempotent install script, piped to `sh -s` over stdin. Heredocs with + * quoted delimiters carry the bundle (base64) and launcher verbatim, so no + * argv quoting crosses the wsl.exe boundary. Tmp names carry the guest PID + * so same-version concurrent installs cannot corrupt each other. */ +export function buildGuestInstallScript(bundleJs: Buffer, version: string): string { + const b64 = bundleJs.toString('base64').replace(/(.{1,120})/g, '$1\n') + return [ + 'set -e', + 'umask 077', + `d="${guestRelayDirExpr(version)}"`, + 'mkdir -p "$d"', + `base64 -d > "$d/bundle.$$.tmp" << 'ORCA_EOF_BUNDLE'`, + b64.trimEnd(), + 'ORCA_EOF_BUNDLE', + `mv "$d/bundle.$$.tmp" "$d/${WSL_HOOK_RELAY_BUNDLE_NAME}"`, + `cat > "$d/launch.$$.tmp" << 'ORCA_EOF_LAUNCH'`, + buildGuestLaunchScript(version).trimEnd(), + 'ORCA_EOF_LAUNCH', + 'mv "$d/launch.$$.tmp" "$d/launch.sh"', + 'chmod 700 "$d/launch.sh"', + // Version marker last: a partial install stays "stale" and reinstalls. + `printf '%s' '${version}' > "$d/${WSL_HOOK_RELAY_VERSION_FILE}"`, + '' + ].join('\n') +} + +export function spawnWslRelayProcess( + distro: string, + env: NodeJS.ProcessEnv, + version: string +): ChildProcessWithoutNullStreams { + // Why: --exec bypasses the distro's default login shell — a bare `--` + // routes through it (a fish/nushell chsh could mangle the command) and + // triggers wsl.exe's `$`-preprocessing of Windows argv. --exec passes argv + // verbatim (same form as the Codex WSL login spawn), so `$HOME` reaches + // sh unescaped and expands guest-side. + const command = `exec sh "${guestRelayDirExpr(version)}/launch.sh"` + return spawn('wsl.exe', ['-d', distro, '--exec', 'sh', '-c', command], { + env, + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true + }) +} + +/** True when the distro shows in `wsl --list --running`. Listing does NOT + * boot anything — unlike `wsl -d`, which starts a stopped distro. The + * restart timer must check this so relay recovery never resurrects a VM the + * user shut down with `wsl --shutdown`. Fails CLOSED (false) on probe + * errors: booting a VM the user shut down is worse than a skipped restart + * (the next WSL PTY spawn re-ensures), and a wsl.exe too wedged to list + * distros would not have launched the relay anyway. */ +export function isWslDistroRunning(distro: string): Promise { + return new Promise((resolve) => { + execFile( + 'wsl.exe', + ['--list', '--running', '--quiet'], + // Why: WSL_UTF8=1 forces UTF-8 output; without it wsl.exe emits + // UTF-16LE that reads as NUL-riddled text. + { env: { ...process.env, WSL_UTF8: '1' }, timeout: 10_000, windowsHide: true }, + (err, stdout) => { + if (err) { + resolve(false) + return + } + const wanted = distro.trim().toLowerCase() + const running = decodeWslText(String(stdout)) + .split(/\r?\n/) + .map((line) => line.trim().toLowerCase()) + .filter(Boolean) + resolve(running.includes(wanted)) + } + ) + }) +} + +export function runWslInstallProcess( + distro: string, + script: string, + env: NodeJS.ProcessEnv +): Promise<{ code: number | null; stderr: string }> { + return new Promise((resolve, reject) => { + // Why: --exec skips the default login shell; the script rides stdin so + // no quoting crosses the wsl.exe boundary at all. + const child = spawn('wsl.exe', ['-d', distro, '--exec', 'sh', '-s'], { + env, + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true + }) + let stderr = '' + let settled = false + // Why: a wedged wsl.exe here would otherwise pin the manager's state at + // 'starting' forever — the one unbounded await on the ensure path. + const timeout = setTimeout(() => { + if (!settled) { + settled = true + child.kill() + resolve({ + code: null, + stderr: `${stderr}\ninstall timed out after ${INSTALL_TIMEOUT_MS}ms` + }) + } + }, INSTALL_TIMEOUT_MS) + child.stderr.on('data', (d: Buffer) => { + stderr = (stderr + decodeWslText(d.toString('utf8'))).slice(-MAX_STARTUP_BUFFER_BYTES) + }) + child.on('error', (err) => { + if (!settled) { + settled = true + clearTimeout(timeout) + reject(err) + } + }) + child.on('close', (code) => { + if (!settled) { + settled = true + clearTimeout(timeout) + resolve({ code, stderr }) + } + }) + child.stdin.on('error', () => { + // Guest exited before consuming stdin — surfaced via close/code. + }) + child.stdin.write(script) + child.stdin.end() + }) +} + +const TRANSIENT_RETRY_LIMIT = 2 + +export type WslRelayLaunchIo = { + spawnRelay: typeof spawnWslRelayProcess + waitForSentinel: typeof waitForWslRelaySentinel + runInstall: typeof runWslInstallProcess + readBundle: (jsPath: string) => Buffer + transientRetryDelayMs: number +} + +/** Spawn → sentinel → connect, with the guest-install/retry policy: stale or + * missing installs get exactly one streamed reinstall, wsl.exe's transient + * "Catastrophic failure (E_UNEXPECTED)" gets a bounded retry, a distro + * without node >= 18 reports through `onNoNode`. Terminal failures report + * through `onFailure`; non-startup errors propagate to the caller. */ +export async function launchWslRelayWithInstall(options: { + distro: string + env: NodeJS.ProcessEnv + bundleJsPath: string + version: string + io: WslRelayLaunchIo + isDisposed: () => boolean + onChild: (child: ChildProcessWithoutNullStreams) => void + onNoNode: () => void + onFailure: (message: string) => void + connect: (transport: MultiplexerTransport, child: ChildProcessWithoutNullStreams) => Promise +}): Promise { + const { distro, env, bundleJsPath, version, io } = options + let installTried = false + let transientRetries = 0 + for (;;) { + if (options.isDisposed()) { + return + } + const child = io.spawnRelay(distro, env, version) + options.onChild(child) + try { + const transport = await io.waitForSentinel(child) + await options.connect(transport, child) + return + } catch (err) { + const failure = (err as { startup?: WslRelayStartupFailure }).startup + if (!failure) { + throw err + } + if (failure.code === WSL_HOOK_RELAY_NO_NODE_EXIT_CODE) { + options.onNoNode() + return + } + if ( + /catastrophic failure/i.test(failure.stderr) && + transientRetries < TRANSIENT_RETRY_LIMIT + ) { + transientRetries++ + await new Promise((resolve) => setTimeout(resolve, io.transientRetryDelayMs)) + continue + } + if (!installTried) { + installTried = true + const script = buildGuestInstallScript(io.readBundle(bundleJsPath), version) + const result = await io.runInstall(distro, script, env) + if (result.code === 0) { + continue + } + options.onFailure( + `guest install failed (code ${result.code ?? 'unknown'}): ${result.stderr.trim()}` + ) + return + } + options.onFailure(formatWslRelayFailure(failure)) + return + } + } +} + +export function formatWslRelayFailure(failure: WslRelayStartupFailure): string { + const detail = failure.stderr.trim() + return `startup failed (${failure.kind}, code ${failure.code ?? 'unknown'})${detail ? `: ${detail}` : ''}` +} + +/** Env for the relay's wsl.exe spawn: the live hook coordinates, the + * host-expected bundle version, and the stable instance key, all crossed + * via WSLENV. WSL_UTF8 keeps wsl.exe's own error text (e.g. "Catastrophic + * failure") UTF-8 so stderr matching and breadcrumbs stay readable. */ +export function buildWslRelaySpawnEnv( + coords: Record, + bundleVersion: string, + instanceKey: string +): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { + ...process.env, + WSL_UTF8: '1', + ORCA_AGENT_HOOK_PORT: coords.ORCA_AGENT_HOOK_PORT, + ORCA_AGENT_HOOK_TOKEN: coords.ORCA_AGENT_HOOK_TOKEN, + ORCA_AGENT_HOOK_ENV: coords.ORCA_AGENT_HOOK_ENV, + ORCA_AGENT_HOOK_VERSION: coords.ORCA_AGENT_HOOK_VERSION, + [WSL_HOOK_RELAY_VERSION_ENV]: bundleVersion, + [WSL_HOOK_RELAY_INSTANCE_ENV]: instanceKey + } + // Why: the relay derives its own guest endpoint path; a /p-translated + // Windows endpoint here would only add WSLENV noise. + delete env.ORCA_AGENT_HOOK_ENDPOINT + addOrcaWslInteropEnv(env as Record) + return env +} diff --git a/src/main/agent-hooks/wsl-hook-relay-link.ts b/src/main/agent-hooks/wsl-hook-relay-link.ts new file mode 100644 index 000000000000..2e9fede95127 --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-relay-link.ts @@ -0,0 +1,58 @@ +// Envelope forwarding and death handling for one live WSL relay link. +// Extracted from the manager so its state machine stays readable; the manager +// decides what a dead link means (cooldown, restart), this module guarantees +// it finds out exactly once, whichever signal fires first. +import type { ChildProcessWithoutNullStreams } from 'node:child_process' + +import type { SshChannelMultiplexer } from '../ssh/ssh-channel-multiplexer' +import { AGENT_HOOK_NOTIFICATION_METHOD } from '../../shared/agent-hook-relay' +import { wslHookRelayConnectionId } from '../../shared/wsl-hook-relay-contract' + +export type WslRelayLinkOptions = { + mux: SshChannelMultiplexer + child: ChildProcessWithoutNullStreams + distro: string + ingest: (envelope: Record, connectionId: string) => void + warn: (message: string) => void + /** Called exactly once when the link dies — from EITHER a mux dispose + * (protocol error, keepalive timeout) or the child exiting. A mux death + * without child death would otherwise blackhole every later envelope + * while the guest keeps returning 204 to hook clients. */ + onDead: (reason: string) => void +} + +export function wireWslRelayLink(options: WslRelayLinkOptions): void { + const { mux, child, distro, ingest, warn, onDead } = options + const connectionId = wslHookRelayConnectionId(distro) + + mux.onNotification((method, params) => { + if (method !== AGENT_HOOK_NOTIFICATION_METHOD) { + return + } + if (typeof (params as { paneKey?: unknown }).paneKey !== 'string') { + return + } + if (process.env.ORCA_WSL_HOOK_RELAY_DEBUG === '1') { + const p = params as { paneKey?: string; payload?: { state?: string } } + warn( + `[agent-hooks] WSL relay envelope (${distro}): pane=${p.paneKey} state=${p.payload?.state ?? '?'}` + ) + } + // Trust boundary: ingestRemote re-validates paneKey/tabId and + // re-normalizes the payload, same as the SSH relay path. + ingest(params, connectionId) + }) + + let dead = false + const die = (reason: string): void => { + if (dead) { + return + } + dead = true + mux.dispose() + child.kill() + onDead(reason) + } + mux.onDispose((reason) => die(`mux disposed (${reason})`)) + child.on('close', () => die('process exited')) +} diff --git a/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts b/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts new file mode 100644 index 000000000000..89b0987a5826 --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts @@ -0,0 +1,203 @@ +// Live end-to-end oracle for the WSL hook relay HOST side: the real esbuild +// bundle runs as a real child process (spawned via `node` instead of wsl.exe +// — everything else identical), the real manager connects over the child's +// actual stdio pipes, the real installers write through the fs bridge, and a +// real HTTP POST in the exact Claude hook shape must land in a real +// AgentHookServer.ingestRemote. This is the chain the Windows-rig GUI run +// exercises minus the wsl.exe byte transport (validated separately on-rig). +import { execFileSync, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process' +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createServer } from 'node:net' +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' + +import { AgentHookServer } from './server' +import { WslHookRelayManager } from './wsl-hook-relay-manager' + +const BUNDLE_DIR = join(process.cwd(), 'out', 'relay', 'wsl') +const BUNDLE_JS = join(BUNDLE_DIR, 'wsl-agent-hook-relay.js') +const LEAF = '11111111-1111-4111-8111-111111111111' + +async function pickFreePort(): Promise { + const probe = createServer() + const port = await new Promise((resolve) => { + probe.listen(0, '127.0.0.1', () => { + const address = probe.address() + resolve(typeof address === 'object' && address ? address.port : 0) + }) + }) + await new Promise((resolve) => probe.close(() => resolve())) + return port +} + +// Why skipIf: the guest is always POSIX — the bundle derives its home from +// $HOME, which os.homedir() ignores on Windows. Windows coverage comes from +// the live rig runs against a real distro. +describe.skipIf(process.platform === 'win32')( + 'WSL hook relay live host chain (real bundle over real child stdio)', + () => { + let fakeHome: string + let manager: WslHookRelayManager | null + let orcaServer: AgentHookServer | null + let child: ChildProcessWithoutNullStreams | null + + beforeAll(() => { + if (!existsSync(BUNDLE_JS)) { + execFileSync(process.execPath, [join('config', 'scripts', 'build-relay.mjs')], { + cwd: process.cwd(), + stdio: 'ignore' + }) + } + }, 120_000) + + afterEach(() => { + manager?.disposeAll() + orcaServer?.stop() + child?.kill() + rmSync(fakeHome, { recursive: true, force: true }) + }) + + it('delivers a Claude hook POST from the live relay into ingestRemote and installs guest hooks', async () => { + fakeHome = mkdtempSync(join(tmpdir(), 'wsl-live-home-')) + const preferredPort = await pickFreePort() + const version = readFileSync(join(BUNDLE_DIR, '.version'), 'utf8').trim() + + orcaServer = new AgentHookServer() + const events: { paneKey: string; payload: unknown; connectionId: string | null }[] = [] + orcaServer.setListener((event) => { + events.push({ + paneKey: event.paneKey, + payload: event.payload, + connectionId: event.connectionId + }) + }) + const server = orcaServer + + const warns: string[] = [] + manager = new WslHookRelayManager({ + platform: () => 'win32', + remoteHooksEnabled: () => true, + hookCoordsEnv: () => ({ + ORCA_AGENT_HOOK_PORT: String(preferredPort), + ORCA_AGENT_HOOK_TOKEN: 'live-token', + ORCA_AGENT_HOOK_ENV: 'production', + ORCA_AGENT_HOOK_VERSION: '1' + }), + instanceKey: () => 'liveinstance', + resolveBundle: () => ({ jsPath: BUNDLE_JS, version }), + listDistros: async () => ['LiveDistro'], + spawnRelay: (_distro, env) => { + child = spawn(process.execPath, [BUNDLE_JS], { + env: { ...env, HOME: fakeHome }, + stdio: ['pipe', 'pipe', 'pipe'] + }) as ChildProcessWithoutNullStreams + return child + }, + runInstall: async () => { + throw new Error('guest install must not run for a direct node spawn') + }, + ingest: (envelope, connectionId) => + server.ingestRemote( + envelope as Parameters[0], + connectionId + ), + warn: (message) => warns.push(message), + transientRetryDelayMs: 1 + }) + + manager.ensureForDistro('LiveDistro') + + // Codex hooks land in the redirected managed runtime home. Waiting on + // this artifact (not Claude's, which is written first) keeps the + // assertions behind the still-running 14-agent installer loop. + const codexRuntimeHome = join( + fakeHome, + '.local', + 'share', + 'orca', + 'codex-runtime-home', + 'home' + ) + await vi.waitFor(() => expect(existsSync(join(codexRuntimeHome, 'hooks.json'))).toBe(true), { + timeout: 15_000 + }) + expect(existsSync(join(fakeHome, '.claude', 'settings.json'))).toBe(true) + const claudeScript = readFileSync( + join(fakeHome, '.orca', 'agent-hooks', 'claude-hook.sh'), + 'utf8' + ) + expect(claudeScript).toContain('/hook/claude') + + // Trust TOML is deferred so the launch-path seed is never pre-empted. + expect(existsSync(join(codexRuntimeHome, 'config.toml'))).toBe(false) + expect(existsSync(join(fakeHome, '.codex', 'hooks.json'))).toBe(false) + + // Re-coordinate exactly like a hook script: read the relay-written + // endpoint file rather than assuming the preferred port bind won. + const endpointFile = join( + fakeHome, + '.orca-wsl', + 'agent-hooks', + 'instance-liveinstance', + 'endpoint.env' + ) + expect(existsSync(endpointFile)).toBe(true) + const endpointText = readFileSync(endpointFile, 'utf8') + const port = Number(/ORCA_AGENT_HOOK_PORT=['"]?(\d+)/.exec(endpointText)?.[1]) + const token = /ORCA_AGENT_HOOK_TOKEN=['"]?([A-Za-z0-9-]+)/.exec(endpointText)?.[1] + expect(port).toBeGreaterThan(0) + expect(token).toBe('live-token') + + const paneKey = `tab-live:${LEAF}` + const postClaude = async (payload: Record): Promise => + fetch(`http://127.0.0.1:${port}/hook/claude`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Orca-Agent-Hook-Token': token ?? '' + }, + body: JSON.stringify({ + paneKey, + tabId: 'tab-live', + worktreeId: 'wt-live', + env: 'remote', + version: '1', + payload + }) + }) + + const promptRes = await postClaude({ + hook_event_name: 'UserPromptSubmit', + prompt: 'live roundtrip' + }) + expect(promptRes.status).toBe(204) + await vi.waitFor(() => expect(events.length).toBeGreaterThan(0), { timeout: 10_000 }) + expect(events[0].paneKey).toBe(paneKey) + expect(events[0].connectionId).toBe('wsl:LiveDistro') + const working = events[0].payload as { state: string; prompt: string; agentType: string } + expect(working.state).toBe('working') + expect(working.prompt).toBe('live roundtrip') + expect(working.agentType).toBe('claude') + + const stopRes = await postClaude({ hook_event_name: 'Stop' }) + expect(stopRes.status).toBe(204) + await vi.waitFor( + () => { + const done = events.find((e) => (e.payload as { state?: string }).state === 'done') + expect(done).toBeTruthy() + }, + { timeout: 10_000 } + ) + + // Link death must be breadcrumbed and scheduled for restart — a silent + // mux/child death would blackhole every later envelope while the guest + // keeps returning 204 (the exact failure signature from the Windows rig). + child?.kill() + await vi.waitFor( + () => expect(warns.some((w) => w.includes('scheduling restart'))).toBe(true), + { timeout: 10_000 } + ) + }, 40_000) + } +) diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts b/src/main/agent-hooks/wsl-hook-relay-manager.test.ts new file mode 100644 index 000000000000..7e341d408dae --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-relay-manager.test.ts @@ -0,0 +1,389 @@ +// WSL hook relay host side: the SFTP-shaped fs adapter over the relay's fs +// bridge (including a full run of the unchanged remote hook installers), and +// the per-distro relay manager state machine with fault injection. +import { EventEmitter } from 'node:events' +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { RelayDispatcher } from '../../relay/dispatcher' +import { registerWslHookFsHandlers } from '../../relay/wsl-hook-fs-bridge' +import { SshChannelMultiplexer, type MultiplexerTransport } from '../ssh/ssh-channel-multiplexer' +import { createWslHookSftpAdapter } from './wsl-hook-fs-adapter' +import { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' +import { WslHookRelayManager } from './wsl-hook-relay-manager' +import { FAILURE_COOLDOWN_BASE_MS, type WslHookRelayManagerDeps } from './wsl-hook-relay-deps' +import { + AGENT_HOOK_NOTIFICATION_METHOD, + AGENT_HOOK_REQUEST_REPLAY_METHOD +} from '../../shared/agent-hook-relay' + +type GuestHarness = { + transport: MultiplexerTransport + guestDispatcher: RelayDispatcher + mux: SshChannelMultiplexer +} + +/** In-memory stdio pair: host mux on one end, guest dispatcher on the other + * (same harness shape as the relay agent-hook integration test). */ +function createGuestHarness(): GuestHarness { + let relayFeed: ((data: Buffer) => void) | undefined + const clientDataCallbacks: ((data: Buffer) => void)[] = [] + const closeCallbacks: (() => void)[] = [] + const transport: MultiplexerTransport = { + write: (data) => { + setImmediate(() => relayFeed?.(data)) + }, + onData: (cb) => { + clientDataCallbacks.push(cb) + }, + onClose: (cb) => { + closeCallbacks.push(cb) + } + } + const guestDispatcher = new RelayDispatcher((data: Buffer) => { + setImmediate(() => { + for (const cb of clientDataCallbacks) { + cb(data) + } + }) + }) + relayFeed = (data) => guestDispatcher.feed(data) + const mux = new SshChannelMultiplexer(transport) + return { transport, guestDispatcher, mux } +} + +// Why skipIf: the fs bridge runs inside the Linux guest and is POSIX-only by +// design (posix.resolve). On a Windows dev host tmpdir() yields C:\ paths the +// bridge correctly refuses; Windows coverage comes from the live rig runs. +describe.skipIf(process.platform === 'win32')( + 'createWslHookSftpAdapter over the guest fs bridge', + () => { + let home: string + let harness: GuestHarness + + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), 'wsl-guest-home-')) + harness = createGuestHarness() + registerWslHookFsHandlers(harness.guestDispatcher, home) + }) + + afterEach(() => { + harness.mux.dispose() + harness.guestDispatcher.dispose() + rmSync(home, { recursive: true, force: true }) + }) + + it('maps guest ENOENT onto ssh2 status code 2', async () => { + const adapter = createWslHookSftpAdapter(harness.mux) + const err = await new Promise((resolve) => { + adapter.readFile(`${home}/missing.json`, 'utf8', ((e: Error) => resolve(e)) as never) + }) + expect(err).toBeInstanceOf(Error) + expect(err.code).toBe(2) + }) + + it('round-trips write/read/stat/rename and rejects paths outside home', async () => { + const adapter = createWslHookSftpAdapter(harness.mux) + await new Promise((resolve, reject) => { + adapter.writeFile( + `${home}/a.txt`, + 'hello', + { encoding: 'utf8', mode: 0o600 } as never, + ((e: Error | null) => (e ? reject(e) : resolve())) as never + ) + }) + const content = await new Promise((resolve, reject) => { + adapter.readFile(`${home}/a.txt`, 'utf8', ((e: Error | null, value: string) => + e ? reject(e) : resolve(value)) as never) + }) + expect(content).toBe('hello') + + await new Promise((resolve, reject) => { + adapter.ext_openssh_rename(`${home}/a.txt`, `${home}/b.txt`, ((e: Error | null) => + e ? reject(e) : resolve()) as never) + }) + expect(existsSync(`${home}/b.txt`)).toBe(true) + + const outside = await new Promise((resolve) => { + adapter.readFile('/etc/passwd', 'utf8', ((e: Error) => resolve(e)) as never) + }) + expect(outside).toBeInstanceOf(Error) + }) + + it('runs the unchanged remote managed hook installers against a WSL guest home', async () => { + const adapter = createWslHookSftpAdapter(harness.mux) + const results = await installRemoteManagedAgentHooks(adapter, home) + + expect(results.length).toBeGreaterThan(0) + expect(results.every((r) => r.state !== 'error')).toBe(true) + + const claudeSettings = JSON.parse( + readFileSync(join(home, '.claude', 'settings.json'), 'utf8') + ) + expect(claudeSettings.hooks).toBeTruthy() + const script = readFileSync(join(home, '.orca', 'agent-hooks', 'claude-hook.sh'), 'utf8') + expect(script).toContain('/hook/claude') + }, 20_000) + } +) + +describe('WslHookRelayManager', () => { + // Why: a fixed POSIX guest home keeps this suite runnable on Windows dev + // hosts — installHooks is mocked here, so the fs bridge only ever serves + // the wslfs.home request and never touches the real filesystem. + const home = '/home/wsl-test-user' + let harnesses: GuestHarness[] + + beforeEach(() => { + harnesses = [] + }) + + afterEach(() => { + for (const h of harnesses) { + h.mux.dispose() + h.guestDispatcher.dispose() + } + }) + + function fakeChild(): ChildProcessWithoutNullStreams & { emitClose: () => void } { + const child = new EventEmitter() as EventEmitter & { + stdout: EventEmitter + stderr: EventEmitter + stdin: { write: () => boolean; end: () => void; on: () => void } + kill: () => void + emitClose: () => void + } + child.stdout = new EventEmitter() + child.stderr = new EventEmitter() + child.stdin = { write: () => true, end: () => {}, on: () => {} } + child.kill = () => {} + child.emitClose = () => child.emit('close', 0) + return child as unknown as ChildProcessWithoutNullStreams & { emitClose: () => void } + } + + function guestTransport(): MultiplexerTransport { + const harness = createGuestHarness() + harnesses.push(harness) + registerWslHookFsHandlers(harness.guestDispatcher, home) + harness.guestDispatcher.onRequest(AGENT_HOOK_REQUEST_REPLAY_METHOD, async () => ({ + replayed: 0 + })) + return harness.transport + } + + function startupError(code: number | null, stderr = ''): Error { + return Object.assign(new Error(`exit ${code}`), { + startup: { kind: 'exit' as const, code, stderr } + }) + } + + function createManager(overrides: Partial): { + manager: WslHookRelayManager + deps: WslHookRelayManagerDeps + } { + const deps: WslHookRelayManagerDeps = { + platform: () => 'win32', + remoteHooksEnabled: () => true, + hookCoordsEnv: () => ({ + ORCA_AGENT_HOOK_PORT: '43117', + ORCA_AGENT_HOOK_TOKEN: 'tok', + ORCA_AGENT_HOOK_ENV: 'production', + ORCA_AGENT_HOOK_VERSION: '1' + }), + instanceKey: () => 'testinstance', + resolveBundle: () => ({ jsPath: '/fake/wsl-agent-hook-relay.js', version: '0.1.0+abc' }), + readBundle: () => Buffer.from('// bundle'), + listDistros: async () => ['Ubuntu'], + isDistroRunning: vi.fn(async () => true), + spawnRelay: vi.fn(() => fakeChild()), + runInstall: vi.fn(async () => ({ code: 0, stderr: '' })), + waitForSentinel: vi.fn(async () => guestTransport()), + ingest: vi.fn(), + installHooks: vi.fn(async () => []), + warn: vi.fn(), + transientRetryDelayMs: 1, + ...overrides + } + return { manager: new WslHookRelayManager(deps), deps } + } + + it('starts one relay per distro, installs hooks, exposes the guest endpoint path, and forwards envelopes', async () => { + const { manager, deps } = createManager({}) + manager.ensureForDistro('Ubuntu') + manager.ensureForDistro('Ubuntu') + await vi.waitFor(() => expect(deps.installHooks).toHaveBeenCalledTimes(1)) + expect(deps.spawnRelay).toHaveBeenCalledTimes(1) + // Codex is the one agent whose home Orca redirects for WSL sessions. + expect(deps.installHooks).toHaveBeenCalledWith(expect.anything(), home, { + codexHomeDir: `${home}/.local/share/orca/codex-runtime-home/home` + }) + + expect(manager.getGuestEndpointFilePath('Ubuntu')).toBe( + `${home}/.orca-wsl/agent-hooks/instance-testinstance/endpoint.env` + ) + + const guest = harnesses[0].guestDispatcher + guest.notify(AGENT_HOOK_NOTIFICATION_METHOD, { + paneKey: 'tab:leaf', + payload: { state: 'working' } + }) + await vi.waitFor(() => + expect(deps.ingest).toHaveBeenCalledWith( + expect.objectContaining({ paneKey: 'tab:leaf' }), + 'wsl:Ubuntu' + ) + ) + + guest.notify(AGENT_HOOK_NOTIFICATION_METHOD, { payload: { state: 'working' } }) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(deps.ingest).toHaveBeenCalledTimes(1) + manager.disposeAll() + }) + + it('resolves the default distro for null and dedupes it with the explicit name', async () => { + const { manager, deps } = createManager({}) + manager.ensureForDistro(null) + await vi.waitFor(() => expect(deps.installHooks).toHaveBeenCalledTimes(1)) + manager.ensureForDistro('Ubuntu') + manager.ensureForDistro(null) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(deps.spawnRelay).toHaveBeenCalledTimes(1) + expect(manager.getGuestEndpointFilePath(null)).toBe( + `${home}/.orca-wsl/agent-hooks/instance-testinstance/endpoint.env` + ) + manager.disposeAll() + }) + + it('reinstalls once on a stale-version exit (42) and then connects', async () => { + const waitForSentinel = vi + .fn() + .mockRejectedValueOnce(startupError(42)) + .mockImplementationOnce(async () => guestTransport()) + const { manager, deps } = createManager({ waitForSentinel }) + manager.ensureForDistro('Ubuntu') + await vi.waitFor(() => expect(deps.installHooks).toHaveBeenCalledTimes(1)) + expect(deps.runInstall).toHaveBeenCalledTimes(1) + expect(deps.spawnRelay).toHaveBeenCalledTimes(2) + manager.disposeAll() + }) + + it('gives up without installing when the guest has no node (43)', async () => { + const waitForSentinel = vi.fn().mockRejectedValue(startupError(43)) + const { manager, deps } = createManager({ waitForSentinel }) + manager.ensureForDistro('Ubuntu') + await vi.waitFor(() => + expect(deps.warn).toHaveBeenCalledWith(expect.stringContaining('no node')) + ) + expect(deps.runInstall).not.toHaveBeenCalled() + // Cooldown: an immediate re-ensure must not spawn again. + manager.ensureForDistro('Ubuntu') + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(deps.spawnRelay).toHaveBeenCalledTimes(1) + manager.disposeAll() + }) + + it('retries a bounded number of times on catastrophic wsl.exe failures', async () => { + const waitForSentinel = vi + .fn() + .mockRejectedValueOnce(startupError(1, 'Catastrophic failure (E_UNEXPECTED)')) + .mockRejectedValueOnce(startupError(1, 'Catastrophic failure (E_UNEXPECTED)')) + .mockImplementationOnce(async () => guestTransport()) + const { manager, deps } = createManager({ waitForSentinel }) + manager.ensureForDistro('Ubuntu') + await vi.waitFor(() => expect(deps.installHooks).toHaveBeenCalledTimes(1)) + expect(deps.spawnRelay).toHaveBeenCalledTimes(3) + expect(deps.runInstall).not.toHaveBeenCalled() + manager.disposeAll() + }) + + it('marks the distro failed when the relay exits and re-ensures only after cooldown', async () => { + const children: ReturnType[] = [] + const spawnRelay = vi.fn(() => { + const child = fakeChild() + children.push(child) + return child + }) + const { manager, deps } = createManager({ spawnRelay }) + manager.ensureForDistro('Ubuntu') + await vi.waitFor(() => expect(deps.installHooks).toHaveBeenCalledTimes(1)) + + children[0].emitClose() + await vi.waitFor(() => + expect(deps.warn).toHaveBeenCalledWith(expect.stringContaining('exited')) + ) + manager.ensureForDistro('Ubuntu') + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(spawnRelay).toHaveBeenCalledTimes(1) + manager.disposeAll() + }) + + it('is inert off-Windows and when remote hooks are disabled', async () => { + const offPlatform = createManager({ platform: () => 'darwin' }) + offPlatform.manager.ensureForDistro('Ubuntu') + const disabled = createManager({ remoteHooksEnabled: () => false }) + disabled.manager.ensureForDistro('Ubuntu') + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(offPlatform.deps.spawnRelay).not.toHaveBeenCalled() + expect(disabled.deps.spawnRelay).not.toHaveBeenCalled() + }) + + it('requires WSL fs-bridge home coordinates before exposing an endpoint path', () => { + const { manager } = createManager({}) + expect(manager.getGuestEndpointFilePath('Ubuntu')).toBeNull() + expect(manager.getGuestEndpointFilePath(null)).toBeNull() + }) + + it('keeps a fresh state that replaced a failed one while its restart probe was in flight', async () => { + // Drain microtasks under fake timers (queueMicrotask is not a faked timer). + const flush = async (): Promise => { + for (let i = 0; i < 25; i++) { + await Promise.resolve() + } + } + let resolveProbe: ((running: boolean) => void) | undefined + const isDistroRunning = vi.fn(() => new Promise((resolve) => (resolveProbe = resolve))) + const spawnRelay = vi.fn(() => fakeChild()) + // First launch fails outright; the replacement launch never reaches the + // sentinel, so its state stays 'starting' with no live mux to clean up. + const waitForSentinel = vi + .fn() + .mockRejectedValueOnce(new Error('relay died before sentinel')) + .mockReturnValueOnce(new Promise(() => {})) + const { manager, deps } = createManager({ isDistroRunning, spawnRelay, waitForSentinel }) + + vi.useFakeTimers() + try { + manager.ensureForDistro('Ubuntu') + await flush() + expect(spawnRelay).toHaveBeenCalledTimes(1) + expect(deps.warn).toHaveBeenCalledWith(expect.stringContaining('relay died before sentinel')) + + // Fire the restart timer; recovery blocks awaiting the distro-running probe. + await vi.advanceTimersByTimeAsync(FAILURE_COOLDOWN_BASE_MS + 300) + expect(isDistroRunning).toHaveBeenCalledTimes(1) + + // A new WSL PTY spawn re-ensures past the elapsed cooldown, replacing the + // failed state in the map while the old state's probe is still pending. + manager.ensureForDistro('Ubuntu') + await flush() + expect(spawnRelay).toHaveBeenCalledTimes(2) + + // Probe resolves 'not running' after the swap: the drop must be skipped so + // the replacement's live relay is not orphaned. + resolveProbe?.(false) + await flush() + expect(deps.warn).not.toHaveBeenCalledWith(expect.stringContaining('distro not running')) + + // Fresh state survived: a further ensure dedupes instead of spawning again. + manager.ensureForDistro('Ubuntu') + await flush() + expect(spawnRelay).toHaveBeenCalledTimes(2) + } finally { + manager.disposeAll() + vi.useRealTimers() + } + }) +}) diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.ts b/src/main/agent-hooks/wsl-hook-relay-manager.ts new file mode 100644 index 000000000000..0c70d3a48c94 --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-relay-manager.ts @@ -0,0 +1,328 @@ +// Host-side lifecycle manager for the guest-resident WSL agent-hook relay +// (STA-1515): one relay per distro per instance, ensured from every WSL PTY +// spawn, forwarding envelopes into ingestRemote and installing guest hooks. +import type { ChildProcessWithoutNullStreams } from 'node:child_process' + +import { installWslGuestHooks } from './wsl-hook-fs-adapter' +import { buildWslRelaySpawnEnv, launchWslRelayWithInstall } from './wsl-hook-relay-launch' +import { + defaultWslHookRelayDeps, + FAILURE_COOLDOWN_BASE_MS, + FAILURE_COOLDOWN_MAX_MS, + NO_NODE_COOLDOWN_MS, + REINSTALL_MIN_INTERVAL_MS, + REINSTALL_ONE_SHOT_DELAY_MS, + RUNNING_TEARDOWN_COOLDOWN_MS, + STABLE_UPTIME_MS, + type WslHookRelayManagerDeps +} from './wsl-hook-relay-deps' +import { wireWslRelayLink } from './wsl-hook-relay-link' +import { WslRelayRecovery } from './wsl-hook-relay-recovery' +import { SshChannelMultiplexer, type MultiplexerTransport } from '../ssh/ssh-channel-multiplexer' +import { AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../../shared/agent-hook-relay' +import { + sanitizeWslHookInstanceKey, + WSL_HOOK_FS_METHODS, + wslHookRelayEndpointFilePath +} from '../../shared/wsl-hook-relay-contract' + +type DistroState = { + /** Original casing for wsl.exe argv and breadcrumbs; map keys are lowercased. */ + distro: string + phase: 'starting' | 'running' | 'failed' + child?: ChildProcessWithoutNullStreams + mux?: SshChannelMultiplexer + guestHome?: string + guestEndpointFilePath?: string + failures: number + cooldownUntil: number + connectedAt?: number + restartTimer?: ReturnType + reinstallTimer?: ReturnType + lastInstallAt?: number +} + +function distroKey(distro: string): string { + return distro.trim().toLowerCase() +} + +export class WslHookRelayManager { + private deps: WslHookRelayManagerDeps + private recovery: WslRelayRecovery + private states = new Map() + private defaultDistro: string | null = null + private disposed = false + private warnedBundleMissing = false + + constructor(deps: Partial = {}) { + this.deps = { ...defaultWslHookRelayDeps, ...deps } + this.recovery = new WslRelayRecovery({ + isDistroRunning: (distro) => this.deps.isDistroRunning(distro), + warn: (message) => this.deps.warn(message), + isDisposed: () => this.disposed, + isCurrent: (state) => this.states.get(distroKey(state.distro)) === state, + restart: (distro) => this.ensureForDistro(distro), + dropState: (state) => { + // Why: identity-guarded — a fresh ensure() may own this key by now; + // deleting by key alone would orphan its live relay child. + const key = distroKey(state.distro) + if (this.states.get(key) === state) { + this.states.delete(key) + } + } + }) + } + + /** Fire-and-forget from every WSL PTY spawn-env build; errors breadcrumb. */ + ensureForDistro(distro: string | null): void { + if (this.disposed || this.deps.platform() !== 'win32' || !this.deps.remoteHooksEnabled()) { + return + } + void this.ensureInternal(distro).catch((err) => { + this.deps.warn( + `[agent-hooks] WSL hook relay ensure failed: ${err instanceof Error ? err.message : String(err)}` + ) + }) + } + + /** Guest endpoint file path once known; null before first connect + * (callers keep the /p-translated Windows endpoint path until then). */ + getGuestEndpointFilePath(distro: string | null): string | null { + const name = distro ?? this.defaultDistro + if (!name) { + return null + } + return this.states.get(distroKey(name))?.guestEndpointFilePath ?? null + } + + disposeAll(): void { + this.disposed = true + for (const state of this.states.values()) { + this.recovery.clearTimers(state) + state.mux?.dispose() + state.child?.kill() + } + this.states.clear() + } + + private async ensureInternal(requestedDistro: string | null): Promise { + const distro = requestedDistro ?? (await this.resolveDefaultDistro()) + if (!distro || this.disposed) { + return + } + const key = distroKey(distro) + const existing = this.states.get(key) + if (existing) { + if (existing.phase === 'running') { + void this.maybeReinstallHooks(existing) + return + } + if (existing.phase !== 'failed' || Date.now() < existing.cooldownUntil) { + return + } + } + const coords = this.deps.hookCoordsEnv() + const port = Number(coords.ORCA_AGENT_HOOK_PORT ?? '') + if (!Number.isInteger(port) || port <= 0 || !coords.ORCA_AGENT_HOOK_TOKEN) { + return + } + const bundle = this.deps.resolveBundle() + if (!bundle) { + if (!this.warnedBundleMissing) { + this.warnedBundleMissing = true + this.deps.warn('[agent-hooks] WSL hook relay bundle not found; run build:relay') + } + return + } + // Why: restart-stable instance identity keeps the guest endpoint file at + // ONE path across restarts so daemon-surviving agents re-coordinate. + const instanceKey = + sanitizeWslHookInstanceKey(this.deps.instanceKey() ?? undefined) ?? `port${port}` + if (existing) { + this.recovery.clearTimers(existing) + } + const state: DistroState = { + distro, + phase: 'starting', + failures: existing?.failures ?? 0, + cooldownUntil: 0 + } + this.states.set(key, state) + + const env = buildWslRelaySpawnEnv(coords, bundle.version, instanceKey) + + try { + await launchWslRelayWithInstall({ + distro: state.distro, + env, + bundleJsPath: bundle.jsPath, + version: bundle.version, + io: this.deps, + isDisposed: () => this.disposed, + onChild: (child) => { + state.child = child + }, + onNoNode: () => + this.markFailed( + state, + `no node >= 18 found in distro '${state.distro}'; agent hooks stay degraded there`, + { cooldownBaseMs: NO_NODE_COOLDOWN_MS } + ), + onFailure: (message) => + this.markFailed(state, message, { cooldownBaseMs: FAILURE_COOLDOWN_BASE_MS }), + connect: (transport, child) => this.connect(state, transport, child, instanceKey) + }) + } catch (err) { + // Why: teardown may have already recorded this failure; don't double- + // count. A request-level error can leave a live child — never leak it. + state.child?.kill() + state.mux?.dispose() + if (state.phase !== 'failed') { + this.markFailed(state, err instanceof Error ? err.message : String(err), { + cooldownBaseMs: FAILURE_COOLDOWN_BASE_MS + }) + } + } + } + + private async connect( + state: DistroState, + transport: MultiplexerTransport, + child: ChildProcessWithoutNullStreams, + instanceKey: string + ): Promise { + const mux = new SshChannelMultiplexer(transport) + state.mux = mux + wireWslRelayLink({ + mux, + child, + distro: state.distro, + ingest: this.deps.ingest, + warn: this.deps.warn, + onDead: (reason) => { + if (this.disposed || state.mux !== mux) { + return + } + state.mux = undefined + const wasRunning = state.phase === 'running' + // Why: only a stable run forgives past failures — a connect-then-die + // loop must escalate, not retry every 10s. + if ( + wasRunning && + state.connectedAt !== undefined && + Date.now() - state.connectedAt >= STABLE_UPTIME_MS + ) { + state.failures = 0 + } + this.markFailed(state, `relay link for '${state.distro}' ${reason}; scheduling restart`, { + cooldownBaseMs: wasRunning ? RUNNING_TEARDOWN_COOLDOWN_MS : FAILURE_COOLDOWN_BASE_MS + }) + } + }) + + const homeResult = (await mux.request(WSL_HOOK_FS_METHODS.home)) as { + ok?: boolean + home?: string + portFallback?: boolean + boundPort?: number + } + if (homeResult?.ok !== true || typeof homeResult.home !== 'string') { + throw new Error(`relay for '${state.distro}' returned no home dir`) + } + if (homeResult.portFallback === true) { + this.deps.warn( + `[agent-hooks] WSL hook relay (${state.distro}): preferred port occupied in guest; bound ${homeResult.boundPort ?? 'unknown'} (endpoint-file re-coordination)` + ) + } + state.guestHome = homeResult.home + state.guestEndpointFilePath = wslHookRelayEndpointFilePath(homeResult.home, instanceKey) + await this.runInstallers(state, mux, homeResult.home) + + if (state.phase === 'failed' || state.mux !== mux) { + // Child died while installing — already recorded; don't revive. + return + } + state.phase = 'running' + state.connectedAt = Date.now() + // Why: one-shot catch-up so a single-spawn session (no later ensure) + // still writes Codex's deferred trust after the launch path seeds config.toml. + this.recovery.scheduleOneShotReinstall(state, REINSTALL_ONE_SHOT_DELAY_MS, () => { + void this.maybeReinstallHooks(state) + }) + void mux.request(AGENT_HOOK_REQUEST_REPLAY_METHOD).catch(() => { + // Fresh relays have nothing to replay; tolerate. + }) + } + + private async runInstallers( + state: DistroState, + mux: SshChannelMultiplexer, + guestHome: string + ): Promise { + state.lastInstallAt = Date.now() + await installWslGuestHooks({ + mux, + guestHome, + distro: state.distro, + installHooks: this.deps.installHooks, + warn: this.deps.warn + }) + } + + private async maybeReinstallHooks(state: DistroState): Promise { + const mux = state.mux + const guestHome = state.guestHome + if ( + !mux || + !guestHome || + mux.isDisposed() || + Date.now() - (state.lastInstallAt ?? 0) < REINSTALL_MIN_INTERVAL_MS + ) { + return + } + try { + await this.runInstallers(state, mux, guestHome) + } catch (err) { + this.deps.warn( + `[agent-hooks] WSL hook reinstall for '${state.distro}' failed: ${err instanceof Error ? err.message : String(err)}` + ) + } + } + + /** Records + breadcrumbs the failure and always arms the restart timer — + * one failed relaunch must not end self-recovery; the timer's + * distro-running probe keeps this from booting stopped distros. */ + private markFailed( + state: DistroState, + message: string, + options: { cooldownBaseMs: number } + ): void { + state.phase = 'failed' + state.failures++ + state.child = undefined + state.mux = undefined + if (state.reinstallTimer) { + clearTimeout(state.reinstallTimer) + state.reinstallTimer = undefined + } + state.cooldownUntil = + Date.now() + Math.min(options.cooldownBaseMs * state.failures, FAILURE_COOLDOWN_MAX_MS) + this.deps.warn(`[agent-hooks] WSL hook relay (${state.distro}): ${message}`) + this.recovery.scheduleRestart(state) + } + + private async resolveDefaultDistro(): Promise { + if (this.defaultDistro) { + return this.defaultDistro + } + try { + const distros = await this.deps.listDistros() + this.defaultDistro = distros[0] ?? null + } catch { + this.defaultDistro = null + } + return this.defaultDistro + } +} + +export const wslHookRelayManager = new WslHookRelayManager() diff --git a/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts b/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts new file mode 100644 index 000000000000..018d91019153 --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts @@ -0,0 +1,155 @@ +// Restart-timer policy: recovery must re-ensure a running distro, must NOT +// boot a stopped one (wsl -d starts stopped distros), and must respect state +// currency and disposal. +import { describe, expect, it, vi } from 'vitest' + +import { WslRelayRecovery, type WslRelayRecoveryState } from './wsl-hook-relay-recovery' + +function makeState(): WslRelayRecoveryState { + return { distro: 'Ubuntu', cooldownUntil: Date.now() - 1_000 } +} + +function waitFor(condition: () => boolean, timeoutMs = 3_000): Promise { + return vi.waitFor(() => expect(condition()).toBe(true), { timeout: timeoutMs }) +} + +describe('WslRelayRecovery', () => { + it('re-ensures the distro when the restart timer fires and the distro is running', async () => { + const restart = vi.fn() + const recovery = new WslRelayRecovery({ + isDistroRunning: async () => true, + warn: vi.fn(), + isDisposed: () => false, + isCurrent: () => true, + restart, + dropState: vi.fn() + }) + const state = makeState() + recovery.scheduleRestart(state) + await waitFor(() => restart.mock.calls.length === 1) + expect(restart).toHaveBeenCalledWith('Ubuntu') + }) + + it('drops the state instead of booting a stopped distro', async () => { + const restart = vi.fn() + const dropState = vi.fn() + const warn = vi.fn() + const recovery = new WslRelayRecovery({ + isDistroRunning: async () => false, + warn, + isDisposed: () => false, + isCurrent: () => true, + restart, + dropState + }) + const state = makeState() + recovery.scheduleRestart(state) + await waitFor(() => dropState.mock.calls.length === 1) + expect(restart).not.toHaveBeenCalled() + expect(warn).toHaveBeenCalledWith(expect.stringContaining('distro not running')) + }) + + it('does nothing when the state was replaced or the manager is disposed', async () => { + const restart = vi.fn() + const probe = vi.fn(async () => true) + const recovery = new WslRelayRecovery({ + isDistroRunning: probe, + warn: vi.fn(), + isDisposed: () => false, + isCurrent: () => false, + restart, + dropState: vi.fn() + }) + const state = makeState() + recovery.scheduleRestart(state) + await new Promise((resolve) => setTimeout(resolve, 500)) + expect(probe).not.toHaveBeenCalled() + expect(restart).not.toHaveBeenCalled() + }) + + it('does not drop or restart when the state was replaced mid-probe (probe false)', async () => { + let current = true + let resolveProbe: ((running: boolean) => void) | undefined + const probe = vi.fn(() => new Promise((resolve) => (resolveProbe = resolve))) + const restart = vi.fn() + const dropState = vi.fn() + const recovery = new WslRelayRecovery({ + isDistroRunning: probe, + warn: vi.fn(), + isDisposed: () => false, + isCurrent: () => current, + restart, + dropState + }) + const state = makeState() + recovery.scheduleRestart(state) + await waitFor(() => probe.mock.calls.length === 1) + // A fresh ensure() replaces this state while the probe is in flight. + current = false + resolveProbe?.(false) + await new Promise((resolve) => setTimeout(resolve, 100)) + expect(dropState).not.toHaveBeenCalled() + expect(restart).not.toHaveBeenCalled() + }) + + it('does not restart when the state was replaced mid-probe (probe true)', async () => { + let current = true + let resolveProbe: ((running: boolean) => void) | undefined + const probe = vi.fn(() => new Promise((resolve) => (resolveProbe = resolve))) + const restart = vi.fn() + const recovery = new WslRelayRecovery({ + isDistroRunning: probe, + warn: vi.fn(), + isDisposed: () => false, + isCurrent: () => current, + restart, + dropState: vi.fn() + }) + const state = makeState() + recovery.scheduleRestart(state) + await waitFor(() => probe.mock.calls.length === 1) + current = false + resolveProbe?.(true) + await new Promise((resolve) => setTimeout(resolve, 100)) + expect(restart).not.toHaveBeenCalled() + }) + + it('scheduleOneShotReinstall is a no-op once disposed', async () => { + const run = vi.fn() + const recovery = new WslRelayRecovery({ + isDistroRunning: async () => true, + warn: vi.fn(), + isDisposed: () => true, + isCurrent: () => true, + restart: vi.fn(), + dropState: vi.fn() + }) + const state = makeState() + recovery.scheduleOneShotReinstall(state, 10, run) + await new Promise((resolve) => setTimeout(resolve, 100)) + expect(run).not.toHaveBeenCalled() + expect(state.reinstallTimer).toBeUndefined() + }) + + it('clearTimers cancels both pending timers', async () => { + const restart = vi.fn() + const recovery = new WslRelayRecovery({ + isDistroRunning: async () => true, + warn: vi.fn(), + isDisposed: () => false, + isCurrent: () => true, + restart, + dropState: vi.fn() + }) + const state = makeState() + const reinstall = vi.fn() + recovery.scheduleRestart(state) + recovery.scheduleOneShotReinstall(state, 100, reinstall) + recovery.clearTimers(state) + await new Promise((resolve) => setTimeout(resolve, 500)) + expect(restart).not.toHaveBeenCalled() + expect(reinstall).not.toHaveBeenCalled() + expect(state.restartTimer).toBeUndefined() + expect(state.reinstallTimer).toBeUndefined() + }) +}) diff --git a/src/main/agent-hooks/wsl-hook-relay-recovery.ts b/src/main/agent-hooks/wsl-hook-relay-recovery.ts new file mode 100644 index 000000000000..71c8b4a22d59 --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-relay-recovery.ts @@ -0,0 +1,81 @@ +// Restart/reinstall timer policy for WSL hook relay states. Owns the two +// self-recovery timers so the manager's state machine stays declarative: +// WHEN to retry lives here, WHAT retrying means stays in the manager. +export type WslRelayRecoveryState = { + distro: string + cooldownUntil: number + restartTimer?: ReturnType + reinstallTimer?: ReturnType +} + +export type WslRelayRecoveryIo = { + isDistroRunning: (distro: string) => Promise + warn: (message: string) => void + isDisposed: () => boolean + /** True while this state object is still the one in the manager's map. */ + isCurrent: (state: WslRelayRecoveryState) => boolean + restart: (distro: string) => void + dropState: (state: WslRelayRecoveryState) => void +} + +export class WslRelayRecovery { + constructor(private io: WslRelayRecoveryIo) {} + + /** Arms the restart timer for the state's cooldown. The probe gate matters: + * `wsl -d` BOOTS a stopped distro, so recovery must never resurrect a VM + * the user shut down — a stopped distro has no live agents anyway. */ + scheduleRestart(state: WslRelayRecoveryState): void { + if (this.io.isDisposed() || state.restartTimer) { + return + } + const delayMs = Math.max(state.cooldownUntil - Date.now(), 0) + 250 + state.restartTimer = setTimeout(() => { + state.restartTimer = undefined + void this.restartIfDistroRunning(state) + }, delayMs) + state.restartTimer.unref?.() + } + + scheduleOneShotReinstall(state: WslRelayRecoveryState, delayMs: number, run: () => void): void { + if (this.io.isDisposed()) { + return + } + state.reinstallTimer = setTimeout(() => { + state.reinstallTimer = undefined + run() + }, delayMs) + state.reinstallTimer.unref?.() + } + + clearTimers(state: WslRelayRecoveryState): void { + if (state.restartTimer) { + clearTimeout(state.restartTimer) + state.restartTimer = undefined + } + if (state.reinstallTimer) { + clearTimeout(state.reinstallTimer) + state.reinstallTimer = undefined + } + } + + private async restartIfDistroRunning(state: WslRelayRecoveryState): Promise { + if (this.io.isDisposed() || !this.io.isCurrent(state)) { + return + } + const running = await this.io.isDistroRunning(state.distro) + // Why: a fresh ensure() may have replaced this state during the probe + // await — dropping/restarting here would then act on the replacement, + // orphaning its live relay child outside the manager's map. + if (this.io.isDisposed() || !this.io.isCurrent(state)) { + return + } + if (!running) { + this.io.warn( + `[agent-hooks] WSL hook relay (${state.distro}): distro not running (or probe failed); restart skipped (next WSL terminal re-ensures)` + ) + this.io.dropState(state) + return + } + this.io.restart(state.distro) + } +} diff --git a/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts b/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts new file mode 100644 index 000000000000..a8085485553b --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts @@ -0,0 +1,152 @@ +// Sentinel wait for the WSL relay: consuming stdout until the READY sentinel, +// handing trailing/subsequent bytes to the mux in wire order via the microtask +// flush, and failing (kill + reject) on overflow, close, timeout, and NUL noise. +import { EventEmitter } from 'node:events' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../ssh/relay-protocol' +import { + MAX_STARTUP_BUFFER_BYTES, + waitForWslRelaySentinel, + type WslRelayStartupFailure +} from './wsl-hook-relay-sentinel' + +type FakeChild = ChildProcessWithoutNullStreams & { kill: ReturnType } + +function fakeChild(): FakeChild { + const child = new EventEmitter() as EventEmitter & { + stdout: EventEmitter + stderr: EventEmitter + stdin: { write: ReturnType } + kill: ReturnType + } + child.stdout = new EventEmitter() + child.stderr = new EventEmitter() + child.stdin = { write: vi.fn(() => true) } + child.kill = vi.fn() + return child as unknown as FakeChild +} + +function emitStdout(child: ChildProcessWithoutNullStreams, data: string | Buffer): void { + child.stdout.emit('data', Buffer.isBuffer(data) ? data : Buffer.from(data)) +} + +function emitStderr(child: ChildProcessWithoutNullStreams, data: Buffer): void { + child.stderr.emit('data', data) +} + +function catchStartup( + promise: Promise +): Promise { + return promise.then( + () => { + throw new Error('expected the sentinel wait to reject') + }, + (err: Error & { startup?: WslRelayStartupFailure }) => err + ) +} + +afterEach(() => { + vi.useRealTimers() +}) + +describe('waitForWslRelaySentinel', () => { + it('resolves when the sentinel is split across two chunks', async () => { + const child = fakeChild() + const promise = waitForWslRelaySentinel(child) + const sentinel = Buffer.from(RELAY_SENTINEL) + const mid = Math.floor(sentinel.length / 2) + emitStdout(child, sentinel.subarray(0, mid)) + emitStdout(child, sentinel.subarray(mid)) + const transport = await promise + expect(typeof transport.write).toBe('function') + expect(typeof transport.onData).toBe('function') + }) + + it('resolves past leading garbage and hands trailing bytes to onData', async () => { + const child = fakeChild() + const promise = waitForWslRelaySentinel(child) + emitStdout( + child, + Buffer.concat([Buffer.from('junk noise '), Buffer.from(RELAY_SENTINEL), Buffer.from('TRAIL')]) + ) + const transport = await promise + const received: string[] = [] + transport.onData((d) => received.push(d.toString('utf8'))) + await Promise.resolve() + expect(received).toEqual(['TRAIL']) + }) + + it('delivers a pending trailing chunk before a later direct chunk, in wire order', async () => { + const child = fakeChild() + const promise = waitForWslRelaySentinel(child) + emitStdout(child, Buffer.concat([Buffer.from(RELAY_SENTINEL), Buffer.from('FIRST')])) + const transport = await promise + const received: string[] = [] + transport.onData((d) => received.push(d.toString('utf8'))) + // A real stdout 'data' event is a macrotask; the queued pending flush is a + // microtask and must land ahead of any subsequent direct chunk. + await new Promise((resolve) => { + setImmediate(() => { + emitStdout(child, 'SECOND') + resolve() + }) + }) + expect(received).toEqual(['FIRST', 'SECOND']) + }) + + it('defers the pending flush to a microtask so a caller can finish wiring', async () => { + const child = fakeChild() + const promise = waitForWslRelaySentinel(child) + emitStdout(child, Buffer.concat([Buffer.from(RELAY_SENTINEL), Buffer.from('DEFER')])) + const transport = await promise + const received: string[] = [] + transport.onData((d) => received.push(d.toString('utf8'))) + // Nothing dispatched synchronously at registration — a second handler could + // still be added this tick before the first envelope flushes. + expect(received).toEqual([]) + await Promise.resolve() + expect(received).toEqual(['DEFER']) + }) + + it('kills the child and rejects when startup output exceeds 64 KiB before the sentinel', async () => { + const child = fakeChild() + const settled = catchStartup(waitForWslRelaySentinel(child)) + emitStdout(child, Buffer.alloc(MAX_STARTUP_BUFFER_BYTES + 1, 0x41)) + const err = await settled + expect(err.message).toMatch(/64 KiB/) + expect(child.kill).toHaveBeenCalled() + }) + + it('rejects with an exit failure when the child closes before the sentinel', async () => { + const child = fakeChild() + const settled = catchStartup(waitForWslRelaySentinel(child)) + child.emit('close', 7) + const err = await settled + expect(err.startup).toEqual({ kind: 'exit', code: 7, stderr: '' }) + }) + + it('kills the child and rejects with a timeout after the sentinel deadline', async () => { + vi.useFakeTimers() + const child = fakeChild() + const settled = catchStartup(waitForWslRelaySentinel(child)) + await vi.advanceTimersByTimeAsync(RELAY_SENTINEL_TIMEOUT_MS + 1) + const err = await settled + expect(child.kill).toHaveBeenCalled() + expect(err.startup?.kind).toBe('timeout') + }) + + it('strips NUL bytes from the stderr failure detail', async () => { + const child = fakeChild() + const settled = catchStartup(waitForWslRelaySentinel(child)) + // wsl.exe without WSL_UTF8 emits UTF-16LE — "E_FAIL" as NUL-interleaved ASCII. + const nulLaden = Buffer.from('E_FAIL'.split('').flatMap((c) => [c.charCodeAt(0), 0])) + emitStderr(child, nulLaden) + child.emit('close', 1) + const err = await settled + expect(err.startup?.stderr).toBe('E_FAIL') + expect(err.message).toContain('E_FAIL') + expect(err.message).not.toContain(String.fromCharCode(0)) + }) +}) diff --git a/src/main/agent-hooks/wsl-hook-relay-sentinel.ts b/src/main/agent-hooks/wsl-hook-relay-sentinel.ts new file mode 100644 index 000000000000..fdabf70fe152 --- /dev/null +++ b/src/main/agent-hooks/wsl-hook-relay-sentinel.ts @@ -0,0 +1,159 @@ +// Sentinel wait for the WSL agent-hook relay: consume the guest child's +// stdout until the READY sentinel, then hand the remaining stdio over as a +// MultiplexerTransport. WSL twin of the SSH deploy's waitForSentinel, over a +// ChildProcess instead of a ClientChannel. +import type { ChildProcessWithoutNullStreams } from 'node:child_process' + +import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../ssh/relay-protocol' +import type { MultiplexerTransport } from '../ssh/ssh-channel-multiplexer' + +export const MAX_STARTUP_BUFFER_BYTES = 64 * 1024 + +// Why: without WSL_UTF8, wsl.exe's own messages arrive UTF-16LE; NUL bytes +// in breadcrumbs and the catastrophic-failure matcher must not depend on the +// env var having taken effect (older wsl.exe ignores it). +export function decodeWslText(value: string): string { + return value.split(String.fromCharCode(0)).join('') +} + +export type WslRelayStartupFailure = { + kind: 'exit' | 'timeout' + code: number | null + stderr: string +} + +/** Wait for the relay's ready sentinel on the child's stdout, then hand the + * remaining stdio over as a MultiplexerTransport. WSL twin of the SSH + * deploy's waitForSentinel, over a ChildProcess instead of a ClientChannel. */ +export function waitForWslRelaySentinel( + child: ChildProcessWithoutNullStreams +): Promise { + return new Promise((resolve, reject) => { + let settled = false + let sentinelSeen = false + let stdoutBuffer: Buffer = Buffer.alloc(0) + let stderrOutput = '' + let exitCode: number | null = null + const sentinel = Buffer.from(RELAY_SENTINEL, 'utf8') + const dataCallbacks: ((data: Buffer) => void)[] = [] + const closeCallbacks: (() => void)[] = [] + // Why: post-sentinel chunks queue until the mux registers onData, then + // flush as a microtask — after the caller's synchronous wiring (the mux + // constructor registers onData before the manager can add notification + // handlers, so a synchronous flush could dispatch an early envelope to + // zero handlers) yet before any subsequent stdout IO event, so the frame + // decoder never sees chunks out of order. A setImmediate handoff would + // NOT preserve that: it is a macrotask the next 'data' event can beat. + const pendingChunks: Buffer[] = [] + let closedNotified = false + + const fail = (failure: WslRelayStartupFailure): void => { + if (settled) { + return + } + settled = true + clearTimeout(timeout) + reject(Object.assign(new Error(formatStartupFailure(failure)), { startup: failure })) + } + + const timeout = setTimeout(() => { + child.kill() + fail({ kind: 'timeout', code: null, stderr: stderrOutput }) + }, RELAY_SENTINEL_TIMEOUT_MS) + + const notifyClosed = (): void => { + if (!closedNotified) { + closedNotified = true + for (const cb of closeCallbacks) { + cb() + } + } + } + + const dispatch = (chunk: Buffer): void => { + if (dataCallbacks.length === 0) { + pendingChunks.push(chunk) + return + } + for (const cb of dataCallbacks) { + cb(chunk) + } + } + + child.stderr.on('data', (d: Buffer) => { + stderrOutput = (stderrOutput + decodeWslText(d.toString('utf8'))).slice( + -MAX_STARTUP_BUFFER_BYTES + ) + }) + child.on('error', (err) => + fail({ kind: 'exit', code: null, stderr: `${stderrOutput}\n${err.message}` }) + ) + child.on('exit', (code) => { + exitCode = code + }) + child.on('close', (code) => { + if (sentinelSeen) { + notifyClosed() + return + } + fail({ kind: 'exit', code: code ?? exitCode, stderr: stderrOutput }) + }) + + child.stdout.on('data', (chunk: Buffer) => { + if (sentinelSeen) { + dispatch(chunk) + return + } + stdoutBuffer = Buffer.concat([stdoutBuffer, chunk]) + const idx = stdoutBuffer.indexOf(sentinel) + if (idx === -1) { + // Why: pre-sentinel stdout is untrusted startup noise; cap it so a + // broken guest cannot grow memory until the timeout fires. + if (stdoutBuffer.length > MAX_STARTUP_BUFFER_BYTES) { + child.kill() + fail({ kind: 'exit', code: null, stderr: 'startup output exceeded 64 KiB' }) + } + return + } + sentinelSeen = true + settled = true + clearTimeout(timeout) + const trailing = stdoutBuffer.subarray(idx + sentinel.length) + if (trailing.length > 0) { + pendingChunks.push(trailing) + } + const transport: MultiplexerTransport = { + write: (data) => { + try { + child.stdin.write(data) + } catch { + // Channel already closing — mux close handling takes over. + } + }, + onData: (cb) => { + dataCallbacks.push(cb) + if (dataCallbacks.length === 1 && pendingChunks.length > 0) { + queueMicrotask(() => { + for (const pending of pendingChunks.splice(0)) { + for (const dataCb of dataCallbacks) { + dataCb(pending) + } + } + }) + } + }, + onClose: (cb) => closeCallbacks.push(cb), + close: () => child.kill() + } + resolve(transport) + }) + }) +} + +function formatStartupFailure(failure: WslRelayStartupFailure): string { + const detail = failure.stderr.trim() + if (failure.kind === 'timeout') { + return `WSL hook relay did not become ready within ${RELAY_SENTINEL_TIMEOUT_MS / 1000}s${detail ? `: ${detail}` : ''}` + } + return `WSL hook relay exited (code ${failure.code ?? 'unknown'})${detail ? `: ${detail}` : ''}` +} diff --git a/src/main/ai-vault/cached-session-list.ts b/src/main/ai-vault/cached-session-list.ts new file mode 100644 index 000000000000..4b39e75eb728 --- /dev/null +++ b/src/main/ai-vault/cached-session-list.ts @@ -0,0 +1,101 @@ +import { join } from 'node:path' +import { scanAiVaultSessions } from './session-scanner' +import { getWslHomeAsync, listWslDistrosAsync } from '../wsl' +import type { AiVaultListArgs, AiVaultListResult } from '../../shared/ai-vault-types' +import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' + +// Why: ONE module owns the scan cache so the desktop IPC handler AND the runtime +// RPC method share a single cache instance — opening the desktop panel and the +// mobile screen for the same scope must not double-scan hundreds of transcripts. +const AI_VAULT_CACHE_TTL_MS = 15_000 + +// Why: codex-home + WSL home dirs must be sourced from a serve-mode-reachable +// seam (the OrcaRuntimeService deps), NOT the window-only registerCoreHandlers +// path — `orca serve` never runs that path, so sourcing it there would silently +// drop managed-Codex sessions from remote/SSH results. +export type AiVaultSessionSources = { + getAdditionalCodexHomePaths?: () => readonly string[] +} + +type CachedAiVaultList = { + key: string + result: AiVaultListResult + expiresAt: number +} + +let cachedList: CachedAiVaultList | null = null +let inflightList: Promise | null = null +let inflightKey: string | null = null +let sources: AiVaultSessionSources = {} + +export function configureAiVaultSessionSources(next: AiVaultSessionSources): void { + sources = next +} + +export async function listAiVaultSessions(args?: AiVaultListArgs): Promise { + // Scope paths change the result set, so they must be part of the cache key. + const key = JSON.stringify({ + limit: args?.limit ?? 'default', + scopePaths: args?.scopePaths ?? [] + }) + const now = Date.now() + // Why: opening this panel repeatedly should not re-parse hundreds of JSONL + // transcripts; explicit refreshes bypass the cache but not an active scan. + if (args?.force !== true && cachedList?.key === key && cachedList.expiresAt > now) { + return cachedList.result + } + if (inflightList && inflightKey === key) { + return inflightList + } + + inflightKey = key + const additionalCodexSessionsDirs = + sources.getAdditionalCodexHomePaths?.().map((homePath) => join(homePath, 'sessions')) ?? [] + inflightList = (async () => + scanAiVaultSessions({ + limit: args?.limit, + scopePaths: args?.scopePaths, + additionalCodexSessionsDirs, + wslHomeDirs: await getAiVaultWslHomeDirs(), + // Why: this scan is always host-local; callers addressing this host by a + // runtime id get the result restamped at the RPC edge, never rescanned. + executionHostId: LOCAL_EXECUTION_HOST_ID + }))() + .then((result) => { + cachedList = { + key, + result, + expiresAt: Date.now() + AI_VAULT_CACHE_TTL_MS + } + return result + }) + .finally(() => { + // Only clear tracking if it still refers to this request: a concurrent + // different-key scan may have replaced it and must stay dedupable. + if (inflightKey === key) { + inflightKey = null + inflightList = null + } + }) + return inflightList +} + +// Exported for the subagent-transcript IPC path, which validates +// renderer-supplied paths against the same WSL-aware Claude roots the scan uses. +export async function getAiVaultWslHomeDirs(): Promise { + if (process.platform !== 'win32') { + return [] + } + const homes = await Promise.all( + (await listWslDistrosAsync()).map((distro) => getWslHomeAsync(distro)) + ) + return homes.filter((homeDir): homeDir is string => Boolean(homeDir)) +} + +// Why: tests reset module-level cache/source state between cases. +export function resetAiVaultSessionListCacheForTests(): void { + cachedList = null + inflightList = null + inflightKey = null + sources = {} +} diff --git a/src/main/ai-vault/remote-session-scanner-sources.ts b/src/main/ai-vault/remote-session-scanner-sources.ts index e8d43ae1f085..c05261de31dc 100644 --- a/src/main/ai-vault/remote-session-scanner-sources.ts +++ b/src/main/ai-vault/remote-session-scanner-sources.ts @@ -5,10 +5,8 @@ import { parseCodexSessionContent } from './session-scanner-codex-parser' import { parseDevinSessionContent } from './session-scanner-devin-parser' import { parseDroidSessionContent } from './session-scanner-droid-parser' import { parseMessageGraphSessionContent } from './session-scanner-graph-parsers' -import { - parseClaudeSessionContent, - parseGeminiSessionContent -} from './session-scanner-primary-parsers' +import { parseClaudeSessionContent } from './session-scanner-primary-parsers' +import { parseGeminiSessionContent } from './session-scanner-gemini-parsers' import { parseCopilotSessionContent, parseCursorSessionContent, @@ -36,13 +34,21 @@ export function remoteSessionSources( ): RemoteSessionSource[] { return [ ...remoteCodexSources(remoteHome, hostPlatform), - jsonlSource( - 'claude', - remoteHome, - hostPlatform, - ['.claude', 'projects'], - parseClaudeSessionContent - ), + { + ...jsonlSource( + 'claude', + remoteHome, + hostPlatform, + ['.claude', 'projects'], + parseClaudeSessionContent + ), + // The remote host owns the transcript disk, so the local readdir in the + // Claude parser is skipped; the walked listing supplies the sibling + // subagent counts instead. Partitioning also prunes the subagent + // transcripts themselves, which would otherwise list as phantom + // top-level sessions carrying the parent's sessionId. + collectSubagentSiblingCounts: true + }, source( 'gemini', remoteHome, diff --git a/src/main/ai-vault/remote-session-scanner-types.ts b/src/main/ai-vault/remote-session-scanner-types.ts index d5a4b2f1acfe..c65ef99aded8 100644 --- a/src/main/ai-vault/remote-session-scanner-types.ts +++ b/src/main/ai-vault/remote-session-scanner-types.ts @@ -21,6 +21,9 @@ export type RemoteSessionSource = { rootDir: string extensions: readonly string[] filePredicate?: (path: string) => boolean + // Claude layout: count `/subagents/*.jsonl` siblings from the walked + // listing and drop them from candidates instead of indexing them as sessions. + collectSubagentSiblingCounts?: boolean parse: ( file: FileWithMtime, content: string, @@ -31,4 +34,5 @@ export type RemoteSessionSource = { export type RemoteSessionCandidate = { source: RemoteSessionSource file: FileWithMtime + subagentTranscriptCount?: number } diff --git a/src/main/ai-vault/remote-session-scanner.test.ts b/src/main/ai-vault/remote-session-scanner.test.ts index 16173f7b7361..a2280b291650 100644 --- a/src/main/ai-vault/remote-session-scanner.test.ts +++ b/src/main/ai-vault/remote-session-scanner.test.ts @@ -201,6 +201,125 @@ describe('scanRemoteAiVaultSessions', () => { }) }) + it('excludes Claude subagent transcripts from remote scans', async () => { + const provider = new MemoryRemoteProvider() + provider.addFile( + '/home/ada/.claude/projects/repo/claude-session.jsonl', + jsonLines([ + { + sessionId: 'claude-session', + timestamp: '2026-07-04T04:00:00.000Z', + type: 'user', + message: { content: [{ type: 'text', text: 'Spawn a Task' }] } + } + ]), + 40 + ) + provider.addFile( + '/home/ada/.claude/projects/repo/claude-session/subagents/agent-abc123.jsonl', + jsonLines([ + { + sessionId: 'claude-session', + isSidechain: true, + agentId: 'abc123', + timestamp: '2026-07-04T04:01:00.000Z', + type: 'user', + message: { content: [{ type: 'text', text: 'Subagent task prompt' }] } + } + ]), + 41 + ) + + const result = await scanRemoteAiVaultSessions({ + provider, + executionHostId: 'ssh:dev-box', + remoteHome: '/home/ada', + hostPlatform: getRemoteHostPlatform('linux-x64') + }) + + expect(result.issues).toEqual([]) + // Only the parent session surfaces; the subagent transcript would carry + // the parent's sessionId and list as a phantom top-level row. + expect(result.sessions.map((session) => session.filePath)).toEqual([ + '/home/ada/.claude/projects/repo/claude-session.jsonl' + ]) + }) + + it('counts remote sibling subagent transcripts for zero-turn Claude sessions', async () => { + const provider = new MemoryRemoteProvider() + provider.addFile( + '/home/ada/.claude/projects/repo/lost-session.jsonl', + jsonLines([{ type: 'mode', mode: 'default', sessionId: 'lost-session' }]), + 50 + ) + provider.addFile( + '/home/ada/.claude/projects/repo/lost-session/subagents/agent-a.jsonl', + jsonLines([{ type: 'user', message: { role: 'user', content: 'Subtask A' } }]), + 51 + ) + provider.addFile( + '/home/ada/.claude/projects/repo/lost-session/subagents/agent-b.jsonl', + jsonLines([{ type: 'user', message: { role: 'user', content: 'Subtask B' } }]), + 52 + ) + + const result = await scanRemoteAiVaultSessions({ + provider, + executionHostId: 'ssh:dev-box', + remoteHome: '/home/ada', + hostPlatform: getRemoteHostPlatform('linux-x64') + }) + + expect(result.issues).toEqual([]) + // Subagent transcripts must not surface as standalone sessions; they only + // contribute recoverable signal to their zero-turn parent. + expect(result.sessions).toHaveLength(1) + expect(result.sessions[0]).toMatchObject({ + agent: 'claude', + sessionId: 'lost-session', + messageCount: 0, + subagentTranscriptCount: 2, + filePath: '/home/ada/.claude/projects/repo/lost-session.jsonl' + }) + }) + + it('counts remote subagent siblings for Claude sessions with real turns', async () => { + const provider = new MemoryRemoteProvider() + provider.addFile( + '/home/ada/.claude/projects/repo/live-session.jsonl', + jsonLines([ + { + sessionId: 'live-session', + type: 'user', + message: { content: [{ type: 'text', text: 'Do the thing' }] } + } + ]), + 60 + ) + provider.addFile( + '/home/ada/.claude/projects/repo/live-session/subagents/agent-a.jsonl', + jsonLines([{ type: 'user', message: { role: 'user', content: 'Subtask' } }]), + 61 + ) + + const result = await scanRemoteAiVaultSessions({ + provider, + executionHostId: 'ssh:dev-box', + remoteHome: '/home/ada', + hostPlatform: getRemoteHostPlatform('linux-x64') + }) + + expect(result.issues).toEqual([]) + expect(result.sessions).toHaveLength(1) + // The walk listing supplies the count for every session (the row badge), + // not only zero-turn recoverable ones. + expect(result.sessions[0]).toMatchObject({ + sessionId: 'live-session', + messageCount: 1, + subagentTranscriptCount: 1 + }) + }) + it('builds resume commands with the remote host platform', async () => { const provider = new MemoryRemoteProvider() provider.addFile( diff --git a/src/main/ai-vault/remote-session-scanner.ts b/src/main/ai-vault/remote-session-scanner.ts index 1b7d66cb7b0c..cc5ae37dad3f 100644 --- a/src/main/ai-vault/remote-session-scanner.ts +++ b/src/main/ai-vault/remote-session-scanner.ts @@ -11,6 +11,7 @@ import type { FileStat, IFilesystemProvider } from '../providers/types' import type { RemoteHostPlatform } from '../ssh/ssh-remote-platform' import { joinRemotePath } from '../ssh/ssh-remote-platform' import { sessionSortTime } from './session-scanner-accumulator' +import { partitionSubagentTranscriptPaths } from './session-scanner-subagent-transcripts' import type { FileWithMtime } from './session-scanner-types' import { errorMessage } from './session-scanner-values' import { remoteSessionSources } from './remote-session-scanner-sources' @@ -77,11 +78,15 @@ async function discoverRemoteSourceCandidates(args: { context: RemoteScannerContext issues: AiVaultScanIssue[] }): Promise { - const paths = await walkRemoteSessionFiles( + const walked = await walkRemoteSessionFiles( args.source, args.context.provider, args.context.hostPlatform ) + const partition = args.source.collectSubagentSiblingCounts + ? partitionSubagentTranscriptPaths(walked) + : null + const paths = partition ? partition.sessionFilePaths : walked const files = await mapRemoteScanConcurrently(paths, (path) => statRemoteFile( args.context.provider, @@ -93,7 +98,11 @@ async function discoverRemoteSourceCandidates(args: { ) return files .filter((file): file is FileWithMtime => Boolean(file)) - .map((file) => ({ source: args.source, file })) + .map((file) => ({ + source: args.source, + file, + subagentTranscriptCount: partition?.subagentTranscriptCounts.get(file.path) ?? 0 + })) } async function walkRemoteSessionFiles( @@ -199,7 +208,15 @@ async function parseRemoteSessionCandidate( if (read.isBinary) { return null } - return candidate.source.parse(candidate.file, read.content, context) + const session = await candidate.source.parse(candidate.file, read.content, context) + // Mirror the local rule: every session carries its sibling subagent + // transcript count (row badge; recoverable signal at zero turns). The + // walk listing supplies it — the parser can't readdir a remote disk. + const subagentTranscriptCount = candidate.subagentTranscriptCount ?? 0 + if (session && subagentTranscriptCount > 0) { + return { ...session, subagentTranscriptCount } + } + return session } catch (err) { issues.push({ executionHostId: context.executionHostId, diff --git a/src/main/ai-vault/runtime-session-scanner.test.ts b/src/main/ai-vault/runtime-session-scanner.test.ts new file mode 100644 index 000000000000..07ed14298ed9 --- /dev/null +++ b/src/main/ai-vault/runtime-session-scanner.test.ts @@ -0,0 +1,147 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AiVaultListResult, AiVaultSession } from '../../shared/ai-vault-types' + +const mocks = vi.hoisted(() => ({ + callRuntimeEnvironment: vi.fn(), + listEnvironments: vi.fn() +})) + +vi.mock('../../shared/runtime-environment-store', () => ({ + listEnvironments: mocks.listEnvironments +})) + +vi.mock('../ipc/runtime-environment-transport-routing', () => ({ + callRuntimeEnvironment: mocks.callRuntimeEnvironment +})) + +const { getSavedRuntimeAiVaultHostInfos, scanRuntimeAiVaultSessions } = + await import('./runtime-session-scanner') + +beforeEach(() => { + vi.clearAllMocks() + mocks.listEnvironments.mockReturnValue([]) + mocks.callRuntimeEnvironment.mockResolvedValue({ + ok: true, + result: result([session('runtime:env-1', 'session-1')]) + }) +}) + +describe('runtime AI Vault session scanner', () => { + it('lists saved runtime environments as runtime execution hosts', () => { + mocks.listEnvironments.mockReturnValue([ + { id: 'env-1', name: 'Server 1' }, + { id: 'env-2', name: 'Server 2' } + ]) + + expect(getSavedRuntimeAiVaultHostInfos('/user-data')).toEqual([ + { environmentId: 'env-1', executionHostId: 'runtime:env-1' }, + { environmentId: 'env-2', executionHostId: 'runtime:env-2' } + ]) + }) + + it('forwards scan options to the runtime transport', async () => { + await scanRuntimeAiVaultSessions( + '/user-data', + 'env-1', + { + limit: 25, + force: true, + scopePaths: ['/srv/app'] + }, + { timeoutMs: 3000 } + ) + + expect(mocks.callRuntimeEnvironment).toHaveBeenCalledWith( + '/user-data', + 'env-1', + 'aiVault.listSessions', + { + limit: 25, + force: true, + scopePaths: ['/srv/app'], + executionHostId: 'runtime:env-1' + }, + 3000 + ) + }) + + it('stamps sessions and issues returned for a different execution host', async () => { + mocks.callRuntimeEnvironment.mockResolvedValueOnce({ + ok: true, + result: result( + [session('local', 'session-1')], + [ + { + executionHostId: 'ssh:dev-box', + agent: 'codex', + path: '/sessions/session-1.jsonl', + message: 'could not parse session' + } + ] + ) + }) + + const scanResult = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {}) + + expect(scanResult.sessions).toEqual([ + expect.objectContaining({ + id: 'runtime:env-1:codex:session-1:/sessions/session-1.jsonl', + executionHostId: 'runtime:env-1' + }) + ]) + expect(scanResult.issues).toEqual([ + expect.objectContaining({ + executionHostId: 'runtime:env-1', + agent: 'codex', + path: '/sessions/session-1.jsonl' + }) + ]) + }) + + it('stamps accepted sessions with the requested runtime host', async () => { + const scanResult = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {}) + + expect(scanResult.sessions).toEqual([ + expect.objectContaining({ + id: 'runtime:env-1:codex:session-1:/sessions/session-1.jsonl', + executionHostId: 'runtime:env-1' + }) + ]) + }) +}) + +function result( + sessions: AiVaultSession[], + issues: AiVaultListResult['issues'] = [] +): AiVaultListResult { + return { sessions, issues, scannedAt: '2026-07-04T00:00:00.000Z' } +} + +function session( + executionHostId: AiVaultSession['executionHostId'], + sessionId: string +): AiVaultSession { + return { + id: `${executionHostId}:codex:${sessionId}:/sessions/${sessionId}.jsonl`, + executionHostId, + executionHostPlatform: 'linux', + agent: 'codex', + sessionId, + title: sessionId, + cwd: '/srv/app', + branch: null, + model: null, + filePath: `/sessions/${sessionId}.jsonl`, + codexHome: null, + createdAt: null, + updatedAt: '2026-07-04T03:00:00.000Z', + modifiedAt: '2026-07-04T00:00:00.000Z', + messageCount: 1, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: `codex resume ${sessionId}`, + subagent: null + } +} diff --git a/src/main/ai-vault/runtime-session-scanner.ts b/src/main/ai-vault/runtime-session-scanner.ts new file mode 100644 index 000000000000..b2f318d8e40a --- /dev/null +++ b/src/main/ai-vault/runtime-session-scanner.ts @@ -0,0 +1,195 @@ +import { z } from 'zod' +import { + AI_VAULT_AGENTS, + AI_VAULT_SCOPE_PATHS_MAX_COUNT, + type AiVaultListArgs, + type AiVaultListResult, + type AiVaultSession +} from '../../shared/ai-vault-types' +import { normalizeExecutionHostId, toRuntimeExecutionHostId } from '../../shared/execution-host' +import { listEnvironments } from '../../shared/runtime-environment-store' +import { callRuntimeEnvironment } from '../ipc/runtime-environment-transport-routing' + +export type RuntimeAiVaultHostInfo = { + environmentId: string + executionHostId: `runtime:${string}` +} + +export type RuntimeAiVaultScanOptions = { + timeoutMs?: number +} + +const nodePlatformSchema = z.enum([ + 'aix', + 'android', + 'darwin', + 'freebsd', + 'haiku', + 'linux', + 'openbsd', + 'sunos', + 'win32', + 'cygwin', + 'netbsd' +] satisfies NodeJS.Platform[]) + +const aiVaultSessionPreviewMessageSchema = z.object({ + role: z.enum(['user', 'assistant', 'system', 'tool', 'unknown']), + text: z.string(), + timestamp: z.string().nullable() +}) + +const executionHostIdSchema = z.string().transform((value, ctx) => { + const normalized = normalizeExecutionHostId(value) + if (normalized) { + return normalized + } + ctx.addIssue({ + code: 'custom', + message: 'Invalid execution host id' + }) + return z.NEVER +}) + +const aiVaultListResultSchema = z.object({ + sessions: z.array( + z.object({ + id: z.string(), + executionHostId: executionHostIdSchema, + executionHostPlatform: nodePlatformSchema.nullable().optional(), + agent: z.enum(AI_VAULT_AGENTS), + sessionId: z.string(), + title: z.string(), + cwd: z.string().nullable(), + branch: z.string().nullable(), + model: z.string().nullable(), + filePath: z.string(), + codexHome: z.string().nullable(), + createdAt: z.string().nullable(), + updatedAt: z.string().nullable(), + modifiedAt: z.string(), + messageCount: z.number(), + totalTokens: z.number(), + previewMessages: z.array(aiVaultSessionPreviewMessageSchema), + // Default keeps remote hosts running an older build (no recoverable-signal + // fields) parseable; they simply report no recoverable-empty sessions. + queuedMessageCount: z.number().default(0), + subagentTranscriptCount: z.number().default(0), + resumeCommand: z.string(), + // The default keeps remote hosts running an older build (no subagent + // field) parseable; scanned top-level sessions carry null anyway. + subagent: z + .object({ + parentSessionId: z.string(), + agentType: z.string().nullable(), + status: z.enum(['running', 'completed', 'failed', 'stopped']).nullable() + }) + .nullable() + .default(null) + }) + ), + issues: z.array( + z.object({ + executionHostId: executionHostIdSchema.optional(), + agent: z.enum(AI_VAULT_AGENTS), + path: z.string(), + message: z.string() + }) + ), + scannedAt: z.string() +}) + +export function getSavedRuntimeAiVaultHostInfos( + userDataPath: string +): readonly RuntimeAiVaultHostInfo[] { + return listEnvironments(userDataPath).map((environment) => ({ + environmentId: environment.id, + executionHostId: toRuntimeExecutionHostId(environment.id) + })) +} + +export async function scanRuntimeAiVaultSessions( + userDataPath: string, + environmentId: string, + args: AiVaultListArgs, + options: RuntimeAiVaultScanOptions = {} +): Promise { + const executionHostId = toRuntimeExecutionHostId(environmentId) + const response = await callRuntimeEnvironment( + userDataPath, + environmentId, + 'aiVault.listSessions', + { + limit: args.limit, + force: args.force, + // Why: cap here so the set of scanned paths is explicit on this side — + // the RPC schema CLAMPS to the same bound anyway (older hosts had no + // cap). Dropped paths only lose the older-than-recency-cap guarantee, + // never the recent sessions themselves. + scopePaths: args.scopePaths?.slice(0, AI_VAULT_SCOPE_PATHS_MAX_COUNT), + executionHostId + }, + options.timeoutMs + ) + if (response.ok === true) { + const parsed = aiVaultListResultSchema.safeParse(response.result) + if (parsed.success) { + return withRuntimeExecutionHost(parsed.data, executionHostId) + } + return runtimeScanIssueResult({ + executionHostId, + environmentId, + message: `Invalid aiVault.listSessions response: ${ + parsed.error.issues[0]?.message ?? 'unexpected result shape' + }` + }) + } + return runtimeScanIssueResult({ + executionHostId, + environmentId, + message: response.error.message + }) +} + +function withRuntimeExecutionHost( + result: AiVaultListResult, + executionHostId: `runtime:${string}` +): AiVaultListResult { + return { + sessions: result.sessions.map((session) => retagRuntimeSession(session, executionHostId)), + issues: result.issues.map((issue) => ({ ...issue, executionHostId })), + scannedAt: result.scannedAt + } +} + +function retagRuntimeSession( + session: AiVaultSession, + executionHostId: `runtime:${string}` +): AiVaultSession { + // The paired server is the transport, but the parent owns which concrete + // runtime host was scanned; never trust returned host ids across the boundary. + return { + ...session, + executionHostId, + id: `${executionHostId}:${session.agent}:${session.sessionId}:${session.filePath}` + } +} + +function runtimeScanIssueResult(args: { + executionHostId: `runtime:${string}` + environmentId: string + message: string +}): AiVaultListResult { + return { + sessions: [], + issues: [ + { + executionHostId: args.executionHostId, + agent: 'codex', + path: args.environmentId, + message: args.message + } + ], + scannedAt: new Date().toISOString() + } +} diff --git a/src/main/ai-vault/session-list-results.ts b/src/main/ai-vault/session-list-results.ts new file mode 100644 index 000000000000..06f8df9c39a9 --- /dev/null +++ b/src/main/ai-vault/session-list-results.ts @@ -0,0 +1,71 @@ +import type { + AiVaultListResult, + AiVaultScanIssue, + AiVaultSession +} from '../../shared/ai-vault-types' +import type { ExecutionHostId } from '../../shared/execution-host' +import { sessionSortTime } from './session-scanner-accumulator' + +export function aiVaultScanIssueResult(args: { + executionHostId?: ExecutionHostId + path: string + message: string +}): AiVaultListResult { + return { + sessions: [], + issues: [ + { + ...(args.executionHostId ? { executionHostId: args.executionHostId } : {}), + agent: 'codex', + path: args.path, + message: args.message + } + ], + scannedAt: new Date().toISOString() + } +} + +// Why: the serving-side scan is host-local and cached once for every caller +// (desktop parent, web, mobile), so callers that address this host by a runtime +// id get the cached result restamped on the way out instead of a per-host scan. +// Mirrors the scanner's stamp recipe so ids stay stable across both paths. +export function restampAiVaultListResult( + result: AiVaultListResult, + executionHostId: ExecutionHostId +): AiVaultListResult { + return { + sessions: result.sessions.map((session) => + session.executionHostId === executionHostId + ? session + : { + ...session, + executionHostId, + id: `${executionHostId}:${session.agent}:${session.sessionId}:${session.filePath}` + } + ), + issues: result.issues.map((issue) => ({ ...issue, executionHostId })), + scannedAt: result.scannedAt + } +} + +export function mergeAiVaultListResults( + results: readonly AiVaultListResult[], + rawLimit: number | undefined +): AiVaultListResult { + const limit = rawLimit && rawLimit > 0 ? Math.floor(rawLimit) : 1000 + const byId = new Map() + const issues: AiVaultScanIssue[] = [] + for (const result of results) { + for (const session of result.sessions) { + byId.set(session.id, session) + } + issues.push(...result.issues) + } + return { + sessions: [...byId.values()] + .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)) + .slice(0, limit), + issues, + scannedAt: new Date().toISOString() + } +} diff --git a/src/main/ai-vault/session-scanner-accumulator.ts b/src/main/ai-vault/session-scanner-accumulator.ts index 8e44e30c60b7..e88e7d9fc2e4 100644 --- a/src/main/ai-vault/session-scanner-accumulator.ts +++ b/src/main/ai-vault/session-scanner-accumulator.ts @@ -41,6 +41,8 @@ export function createAccumulator(args: { messageCount: 0, totalTokens: 0, previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, latestTimestampMs: 0 } } @@ -110,6 +112,8 @@ export function finalizeSession( messageCount: accumulator.messageCount, totalTokens: accumulator.totalTokens, previewMessages: accumulator.previewMessages, + queuedMessageCount: accumulator.queuedMessageCount, + subagentTranscriptCount: accumulator.subagentTranscriptCount, resumeCommand: buildAiVaultResumeCommand({ agent: accumulator.agent, sessionId, @@ -117,7 +121,8 @@ export function finalizeSession( cwd: accumulator.cwd, platform, codexHome: options.codexHome - }) + }), + subagent: null } } diff --git a/src/main/ai-vault/session-scanner-agent-parser.ts b/src/main/ai-vault/session-scanner-agent-parser.ts index 5a81ff260d01..22c6cd46abc0 100644 --- a/src/main/ai-vault/session-scanner-agent-parser.ts +++ b/src/main/ai-vault/session-scanner-agent-parser.ts @@ -6,7 +6,8 @@ import { parseMessageGraphSessionFile, parseRovoSessionFile } from './session-sc import { parseKimiSessionFile } from './session-scanner-kimi-parser' import { splitOpenCodeSqliteCandidate } from './session-scanner-opencode-sqlite-paths' import { parseOpenCodeSqliteSession } from './session-scanner-opencode-sqlite' -import { parseClaudeSessionFile, parseGeminiSessionFile } from './session-scanner-primary-parsers' +import { parseClaudeSessionFile } from './session-scanner-primary-parsers' +import { parseGeminiSessionFile } from './session-scanner-gemini-parsers' import { parseCodexSessionFile } from './session-scanner-codex-parser' import { parseCopilotSessionFile, diff --git a/src/main/ai-vault/session-scanner-claude-subagent-prune.test.ts b/src/main/ai-vault/session-scanner-claude-subagent-prune.test.ts new file mode 100644 index 000000000000..2f0fa7c389c1 --- /dev/null +++ b/src/main/ai-vault/session-scanner-claude-subagent-prune.test.ts @@ -0,0 +1,61 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { scanAiVaultSessions } from './session-scanner' +import { isolatedScanRoots, jsonLines } from './session-scanner-test-fixtures' + +let tempRoots: string[] = [] + +afterEach(async () => { + await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) + tempRoots = [] +}) + +describe('scanAiVaultSessions Claude subagent pruning', () => { + it('prunes subagents/ transcripts instead of listing them as sessions', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-prune-')) + tempRoots.push(root) + const roots = isolatedScanRoots(root) + const subagentsDir = join(roots.claudeProjectsDir, 'project', 'claude-session', 'subagents') + await mkdir(subagentsDir, { recursive: true }) + + await writeFile( + join(roots.claudeProjectsDir, 'project', 'claude-session.jsonl'), + jsonLines([ + { + type: 'user', + sessionId: 'claude-session', + timestamp: '2026-05-01T10:00:00.000Z', + cwd: '/repo/app', + message: { role: 'user', content: 'Spawn a Task' } + } + ]) + ) + await writeFile( + join(subagentsDir, 'agent-abc123.jsonl'), + jsonLines([ + { + type: 'user', + sessionId: 'claude-session', + isSidechain: true, + agentId: 'abc123', + timestamp: '2026-05-01T10:01:00.000Z', + cwd: '/repo/app', + message: { role: 'user', content: 'Subagent task prompt' } + } + ]) + ) + + const result = await scanAiVaultSessions({ ...roots, platform: 'darwin' }) + + expect(result.issues).toEqual([]) + // Only the parent session surfaces; the subagent transcript is not a row, + // but it is still counted for the row's "N subagents" affordance. + expect(result.sessions).toHaveLength(1) + expect(result.sessions[0]).toMatchObject({ + sessionId: 'claude-session', + subagentTranscriptCount: 1 + }) + }) +}) diff --git a/src/main/ai-vault/session-scanner-claude-subagents.test.ts b/src/main/ai-vault/session-scanner-claude-subagents.test.ts new file mode 100644 index 000000000000..eb0f90d9bc93 --- /dev/null +++ b/src/main/ai-vault/session-scanner-claude-subagents.test.ts @@ -0,0 +1,396 @@ +import { mkdir, mkdtemp, rm, utimes, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { listClaudeSubagentSessions } from './session-scanner-claude-subagents' +import { countSubagentTranscripts } from './session-scanner-subagent-transcripts' + +let tempRoots: string[] = [] + +async function writeJsonlFile(filePath: string, records: unknown[]): Promise { + await mkdir(dirname(filePath), { recursive: true }) + await writeFile(filePath, `${records.map((record) => JSON.stringify(record)).join('\n')}\n`) +} + +afterEach(async () => { + await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) + tempRoots = [] +}) + +async function writeSubagentTranscript(args: { + subagentsDir: string + agentId: string + taskPrompt: string + timestamp: string +}): Promise { + await writeJsonlFile(join(args.subagentsDir, `agent-${args.agentId}.jsonl`), [ + { + type: 'user', + sessionId: 'parent-session', + isSidechain: true, + agentId: args.agentId, + timestamp: args.timestamp, + cwd: '/tmp/claude', + message: { role: 'user', content: args.taskPrompt } + } + ]) +} + +describe('listClaudeSubagentSessions', () => { + it('lists subagents titled by the spawn description, newest first, linked to the parent', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-list-')) + tempRoots.push(root) + const parentFilePath = join(root, 'project', 'parent-session.jsonl') + const subagentsDir = join(root, 'project', 'parent-session', 'subagents') + + await writeJsonlFile(parentFilePath, [ + { + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:00:00.000Z', + cwd: '/tmp/claude', + message: { role: 'user', content: 'Parent prompt' } + } + ]) + await writeSubagentTranscript({ + subagentsDir, + agentId: 'older', + taskPrompt: 'Task prompt for the older subagent', + timestamp: '2026-07-05T10:01:00.000Z' + }) + await writeFile( + join(subagentsDir, 'agent-older.meta.json'), + JSON.stringify({ + agentType: 'Explore', + description: 'Map the scanner internals', + toolUseId: 'toolu_older' + }) + ) + await writeSubagentTranscript({ + subagentsDir, + agentId: 'newer', + taskPrompt: 'Task prompt for the newer subagent', + timestamp: '2026-07-05T10:02:00.000Z' + }) + await writeFile( + join(subagentsDir, 'agent-newer.meta.json'), + JSON.stringify({ + agentType: 'general-purpose', + description: 'Check latest news', + toolUseId: 'toolu_newer' + }) + ) + + const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' }) + + expect(result.issues).toEqual([]) + expect(result.sessions.map((session) => session.title)).toEqual([ + 'Check latest news', + 'Map the scanner internals' + ]) + // No task notifications in the parent and freshly written transcripts: + // both count as still running. + expect(result.sessions.map((session) => session.subagent)).toEqual([ + { parentSessionId: 'parent-session', agentType: 'general-purpose', status: 'running' }, + { parentSessionId: 'parent-session', agentType: 'Explore', status: 'running' } + ]) + expect(result.sessions.map((session) => session.messageCount)).toEqual([1, 1]) + }) + + it('falls back to the Task prompt title when the meta sidecar is missing or corrupt', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-meta-')) + tempRoots.push(root) + const parentFilePath = join(root, 'project', 'parent-session.jsonl') + const subagentsDir = join(root, 'project', 'parent-session', 'subagents') + + await writeSubagentTranscript({ + subagentsDir, + agentId: 'nometa', + taskPrompt: 'Sidecarless task prompt', + timestamp: '2026-07-05T10:01:00.000Z' + }) + await writeSubagentTranscript({ + subagentsDir, + agentId: 'badmeta', + taskPrompt: 'Corrupt sidecar task prompt', + timestamp: '2026-07-05T10:02:00.000Z' + }) + await writeFile(join(subagentsDir, 'agent-badmeta.meta.json'), '{not json') + + const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' }) + + expect(result.issues).toEqual([]) + expect(result.sessions.map((session) => session.title)).toEqual([ + 'Corrupt sidecar task prompt', + 'Sidecarless task prompt' + ]) + expect(result.sessions.map((session) => session.subagent?.agentType)).toEqual([null, null]) + }) + + it('resolves statuses from parent task notifications, falling back to transcript recency', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-status-')) + tempRoots.push(root) + const parentFilePath = join(root, 'project', 'parent-session.jsonl') + const subagentsDir = join(root, 'project', 'parent-session', 'subagents') + + await writeJsonlFile(parentFilePath, [ + { + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:00:00.000Z', + cwd: '/tmp/claude', + message: { role: 'user', content: 'Parent prompt' } + }, + { + // Interim notification: superseded by the terminal one below. + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:00:30.000Z', + message: { + role: 'user', + content: + '\nfinished\nrunning\n' + } + }, + { + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:01:00.000Z', + message: { + role: 'user', + content: + '\nfinished\ncompleted\n' + } + }, + { + // queue-operation records carry the notification as a plain string. + type: 'queue-operation', + operation: 'enqueue', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:02:00.000Z', + content: + '\ncrashed\nfailed\n' + }, + { + // Synchronous Tasks finish with a toolUseResult record, no notification. + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:03:00.000Z', + message: { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: 'toolu_sync', content: 'done' }] + }, + toolUseResult: { status: 'completed', agentId: 'syncdone', agentType: 'Explore' } + } + ]) + for (const agentId of ['finished', 'crashed', 'active', 'stale', 'syncdone']) { + await writeSubagentTranscript({ + subagentsDir, + agentId, + taskPrompt: `Task for ${agentId}`, + timestamp: '2026-07-05T10:00:10.000Z' + }) + } + // A transcript silent for an hour with no terminal notification has no + // trustworthy status. + const staleTime = new Date(Date.now() - 60 * 60_000) + await utimes(join(subagentsDir, 'agent-stale.jsonl'), staleTime, staleTime) + + const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' }) + + expect(result.issues).toEqual([]) + const statusByTitle = Object.fromEntries( + result.sessions.map((session) => [session.title, session.subagent?.status ?? null]) + ) + expect(statusByTitle).toEqual({ + 'Task for finished': 'completed', + 'Task for crashed': 'failed', + 'Task for active': 'running', + 'Task for stale': null, + 'Task for syncdone': 'completed' + }) + expect(await countSubagentTranscripts(parentFilePath)).toBe(5) + }) + + it('reads a terminal status whose sits past the title truncation limit', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-longnote-')) + tempRoots.push(root) + const parentFilePath = join(root, 'project', 'parent-session.jsonl') + const subagentsDir = join(root, 'project', 'parent-session', 'subagents') + + // A real notification carries / before , + // pushing well past the 96-char title cap; delivered as a user + // message it must still be read untruncated so the terminal status wins + // over the transcript-recency fallback. + const notification = + '\nbigtask\n' + + 'toolu_01HB57dwUE6hQVK6Mh8jVFHA\n' + + '/private/tmp/claude-501/-Users-me-orca-workspaces-project/' + + 'parent-session/tasks/bigtask.output\n' + + 'completed\nAgent finished\n' + expect(notification.indexOf('')).toBeGreaterThan(96) + + await writeJsonlFile(parentFilePath, [ + { + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:00:00.000Z', + cwd: '/tmp/claude', + message: { role: 'user', content: 'Parent prompt' } + }, + { + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:01:00.000Z', + message: { role: 'user', content: notification } + } + ]) + // Freshly written, so a dropped status would fall back to 'running' — the + // assertion below only holds when the notification is parsed untruncated. + await writeSubagentTranscript({ + subagentsDir, + agentId: 'bigtask', + taskPrompt: 'Task for bigtask', + timestamp: '2026-07-05T10:00:10.000Z' + }) + + const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' }) + + expect(result.issues).toEqual([]) + expect(result.sessions.map((session) => session.subagent?.status)).toEqual(['completed']) + }) + + it('ignores a quoted notification in a user prompt so it cannot overwrite a real status', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-quoted-')) + tempRoots.push(root) + const parentFilePath = join(root, 'project', 'parent-session.jsonl') + const subagentsDir = join(root, 'project', 'parent-session', 'subagents') + + await writeJsonlFile(parentFilePath, [ + { + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:00:00.000Z', + message: { + role: 'user', + content: + '\nquoted\ncompleted\n' + } + }, + { + // A user prompt that merely quotes an earlier notification must not + // supersede the real terminal status recorded above. + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:01:00.000Z', + message: { + role: 'user', + content: + 'Re-run: \nquoted\nfailed\n' + } + } + ]) + const staleTime = new Date(Date.now() - 60 * 60_000) + await writeSubagentTranscript({ + subagentsDir, + agentId: 'quoted', + taskPrompt: 'Task for quoted', + timestamp: '2026-07-05T10:00:10.000Z' + }) + await utimes(join(subagentsDir, 'agent-quoted.jsonl'), staleTime, staleTime) + + const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' }) + + expect(result.issues).toEqual([]) + expect(result.sessions.map((session) => session.subagent?.status)).toEqual(['completed']) + }) + + it('reads a sync-Task toolUseResult status even when its report quotes a notification', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-turmarker-')) + tempRoots.push(root) + const parentFilePath = join(root, 'project', 'parent-session.jsonl') + const subagentsDir = join(root, 'project', 'parent-session', 'subagents') + + await writeJsonlFile(parentFilePath, [ + { + // A sync-Task completion: the terminal status lives in toolUseResult, + // but the subagent's own report text quotes , so the + // raw-line prefilter must not misroute it into the notification branch. + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:03:00.000Z', + message: { + role: 'user', + content: [ + { + type: 'tool_result', + tool_use_id: 'toolu_report', + content: 'The subagent explained how records work.' + } + ] + }, + toolUseResult: { status: 'completed', agentId: 'reporter', agentType: 'Explore' } + } + ]) + // Stale, so a dropped status would fall back to null, not 'completed'. + const staleTime = new Date(Date.now() - 60 * 60_000) + await writeSubagentTranscript({ + subagentsDir, + agentId: 'reporter', + taskPrompt: 'Task for reporter', + timestamp: '2026-07-05T10:00:10.000Z' + }) + await utimes(join(subagentsDir, 'agent-reporter.jsonl'), staleTime, staleTime) + + const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' }) + + expect(result.issues).toEqual([]) + expect(result.sessions.map((session) => session.subagent?.status)).toEqual(['completed']) + }) + + it('links to the parent derived from its file path even when the transcript has no sessionId', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-parent-')) + tempRoots.push(root) + const parentFilePath = join(root, 'project', 'parent-session.jsonl') + const subagentsDir = join(root, 'project', 'parent-session', 'subagents') + + // A transcript with no sessionId record: the parser falls back to the + // subagent's own filename-derived id, so parentSessionId must not use it. + await writeJsonlFile(join(subagentsDir, 'agent-nosession.jsonl'), [ + { + type: 'user', + isSidechain: true, + agentId: 'nosession', + timestamp: '2026-07-05T10:01:00.000Z', + cwd: '/tmp/claude', + message: { role: 'user', content: 'Orphan subagent prompt' } + } + ]) + + const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' }) + + expect(result.issues).toEqual([]) + expect(result.sessions.map((session) => session.subagent?.parentSessionId)).toEqual([ + 'parent-session' + ]) + }) + + it('returns an empty list when the session never spawned subagents', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-subagent-none-')) + tempRoots.push(root) + const parentFilePath = join(root, 'project', 'parent-session.jsonl') + await writeJsonlFile(parentFilePath, [ + { + type: 'user', + sessionId: 'parent-session', + timestamp: '2026-07-05T10:00:00.000Z', + cwd: '/tmp/claude', + message: { role: 'user', content: 'Parent prompt' } + } + ]) + + const result = await listClaudeSubagentSessions({ parentFilePath, platform: 'darwin' }) + + expect(result).toEqual({ sessions: [], issues: [] }) + }) +}) diff --git a/src/main/ai-vault/session-scanner-claude-subagents.ts b/src/main/ai-vault/session-scanner-claude-subagents.ts new file mode 100644 index 000000000000..5c269d91cf3b --- /dev/null +++ b/src/main/ai-vault/session-scanner-claude-subagents.ts @@ -0,0 +1,281 @@ +import { createReadStream } from 'node:fs' +import { readdir, readFile, stat } from 'node:fs/promises' +import { basename, extname, join } from 'node:path' +import { createInterface } from 'node:readline' +import type { + AiVaultScanIssue, + AiVaultSession, + AiVaultSubagentListResult, + AiVaultSubagentRunStatus +} from '../../shared/ai-vault-types' +import { sessionIdFromFileName, sessionSortTime } from './session-scanner-accumulator' +import { parseClaudeSessionFile } from './session-scanner-primary-parsers' +import { + isSubagentTranscriptFileName, + subagentTranscriptsDirFor, + SUBAGENT_TRANSCRIPT_PREFIX +} from './session-scanner-subagent-transcripts' +import { + asRecord, + errorMessage, + extractString, + normalizeTitleText, + parseJsonObject +} from './session-scanner-values' + +// A subagent writing nothing for this long without a terminal notification is +// treated as no longer running (its status stays unknown rather than stale). +const SUBAGENT_RUNNING_RECENCY_MS = 5 * 60_000 +// Match the main scanner's deliberate parse batching (SESSION_PARSE_CONCURRENCY): +// opening every subagent read stream at once stalls over SSH/WSL UNC paths. +const SUBAGENT_PARSE_CONCURRENCY = 8 + +const TASK_NOTIFICATION_MARKER = '' +const TOOL_USE_RESULT_MARKER = '"toolUseResult"' +// A sync-Task toolUseResult sets a status only when it carries an agentId. Tool +// output records (Read/Bash) also carry "toolUseResult" and are the largest lines +// in a transcript, so gating on this second marker keeps the status pass from +// JSON-parsing ~all of the file's bytes on every on-demand fetch. +const TOOL_USE_RESULT_AGENT_ID_MARKER = '"agentId"' +const TASK_ID_PATTERN = /([^<]+)<\/task-id>/ +const TASK_STATUS_PATTERN = /([a-z_]+)<\/status>/ + +// Statuses reported by parent-transcript records +// (background Tasks) and toolUseResult records (synchronous Tasks). +const TERMINAL_TASK_STATUSES: Record = { + completed: 'completed', + failed: 'failed', + killed: 'stopped', + stopped: 'stopped' +} + +type ClaudeSubagentMeta = { + description: string | null + agentType: string | null +} + +/** + * List the Task subagent transcripts of one Claude session, on demand. The + * main scan prunes `subagents/` subtrees for speed, so this is the only path + * that reads them — and only when the user expands a session's details. + */ +export async function listClaudeSubagentSessions(args: { + parentFilePath: string + platform?: NodeJS.Platform + now?: number +}): Promise { + const platform = args.platform ?? process.platform + const now = args.now ?? Date.now() + const issues: AiVaultScanIssue[] = [] + const subagentsDir = subagentTranscriptsDirFor(args.parentFilePath) + + let entries + try { + entries = await readdir(subagentsDir, { withFileTypes: true }) + } catch { + return { sessions: [], issues } + } + + const transcriptNames = entries + .filter((entry) => isSubagentTranscriptFileName(entry.name, entry.isFile())) + .map((entry) => entry.name) + if (transcriptNames.length === 0) { + return { sessions: [], issues } + } + + // One pass over the parent transcript resolves every subagent's status. + const statusByAgentId = await collectSubagentTaskStatuses(args.parentFilePath) + // Why: the layout fixes the parent's sessionId (.jsonl -> subagents/); + // deriving it here avoids a subagent transcript with no sessionId records + // linking to its own filename-derived id instead of the parent. + const parentSessionId = sessionIdFromFileName(args.parentFilePath) + const parsed: (AiVaultSession | null)[] = [] + for (let index = 0; index < transcriptNames.length; index += SUBAGENT_PARSE_CONCURRENCY) { + const batch = transcriptNames.slice(index, index + SUBAGENT_PARSE_CONCURRENCY) + const batchResults = await Promise.all( + batch.map((name) => + parseSubagentTranscript({ + filePath: join(subagentsDir, name), + agentId: subagentIdFromFileName(name), + parentSessionId, + statusByAgentId, + now, + platform, + issues + }) + ) + ) + parsed.push(...batchResults) + } + + return { + sessions: parsed + .filter((session): session is AiVaultSession => session !== null) + .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)), + issues + } +} + +function subagentIdFromFileName(name: string): string { + return basename(name, extname(name)).slice(SUBAGENT_TRANSCRIPT_PREFIX.length) +} + +async function parseSubagentTranscript(args: { + filePath: string + agentId: string + parentSessionId: string + statusByAgentId: ReadonlyMap + now: number + platform: NodeJS.Platform + issues: AiVaultScanIssue[] +}): Promise { + try { + const fileStat = await stat(args.filePath) + const session = await parseClaudeSessionFile( + { + path: args.filePath, + mtimeMs: fileStat.mtimeMs, + modifiedAt: fileStat.mtime.toISOString() + }, + args.platform + ) + if (!session) { + return null + } + const meta = await readSubagentMeta(args.filePath) + return { + ...session, + // Why: the spawn description is the name the main agent gave this Task; + // it beats the transcript-derived fallback (the raw Task prompt). + title: meta.description ?? session.title, + subagent: { + // The parent's sessionId is derived from its file path, not the + // subagent transcript, so it survives transcripts with no sessionId. + parentSessionId: args.parentSessionId, + agentType: meta.agentType, + status: resolveSubagentStatus({ + reportedStatus: args.statusByAgentId.get(args.agentId), + mtimeMs: fileStat.mtimeMs, + now: args.now + }) + } + } + } catch (err) { + args.issues.push({ agent: 'claude', path: args.filePath, message: errorMessage(err) }) + return null + } +} + +function resolveSubagentStatus(args: { + reportedStatus: string | undefined + mtimeMs: number + now: number +}): AiVaultSubagentRunStatus | null { + const terminal = args.reportedStatus ? TERMINAL_TASK_STATUSES[args.reportedStatus] : undefined + if (terminal) { + return terminal + } + // No terminal notification yet: a recently-written transcript is running; + // a stale one has no trustworthy status (e.g. the parent was interrupted). + return args.now - args.mtimeMs <= SUBAGENT_RUNNING_RECENCY_MS ? 'running' : null +} + +// The parent transcript reports subagent completion in two shapes: sync Tasks +// finish with a toolUseResult record ({ agentId, status }); background Tasks +// launch with status 'async_launched' and finish with a +// whose is the agentId. Last record wins, so interim statuses (e.g. +// 'async_launched', notification 'running') are superseded by terminal ones. +async function collectSubagentTaskStatuses(parentFilePath: string): Promise> { + const statuses = new Map() + try { + const lines = createInterface({ + input: createReadStream(parentFilePath, { encoding: 'utf-8' }), + crlfDelay: Infinity + }) + for await (const line of lines) { + const hasNotification = line.includes(TASK_NOTIFICATION_MARKER) + const hasTaskResult = + line.includes(TOOL_USE_RESULT_MARKER) && line.includes(TOOL_USE_RESULT_AGENT_ID_MARKER) + if (!hasNotification && !hasTaskResult) { + continue + } + const record = parseJsonObject(line) + if (!record) { + continue + } + // Only records whose text IS the notification set a status; a user prompt + // (or a sync-Task toolUseResult report) that merely quotes one also trips + // the raw-line prefilter, so it must not consume the record — fall through + // to the toolUseResult branch below rather than dropping a real status. + // Accepted limitation: a user message that BEGINS with a verbatim + // notification is indistinguishable from a real delivery (records carry no + // provenance marker), so it can set a bogus status. The impact is a wrong + // dot on a view-only row, so we don't gate on user-type markers here (that + // would risk dropping genuine harness-delivered statuses). + if (hasNotification) { + const text = taskNotificationText(record) + if (text.startsWith(TASK_NOTIFICATION_MARKER)) { + const taskId = TASK_ID_PATTERN.exec(text)?.[1]?.trim() + const status = TASK_STATUS_PATTERN.exec(text)?.[1] + if (taskId && status) { + statuses.set(taskId, status) + } + continue + } + } + const result = asRecord(record.toolUseResult) + const agentId = extractString(result?.agentId) + const status = extractString(result?.status) + if (agentId && status) { + statuses.set(agentId, status) + } + } + } catch { + // A missing/unreadable parent transcript degrades to recency-only status. + } + return statuses +} + +// The marker follows / lines in real +// notifications, so it sits well past the 96-char title cap — the notification +// text must be read untruncated (unlike titles/previews). Both delivery shapes +// appear: queue-operation records carry it as top-level `content`; user-message +// records under `message.content` (a string, or text content blocks). +function taskNotificationText(record: Record): string { + const direct = extractString(record.content) + if (direct) { + return direct + } + const content = asRecord(record.message)?.content + if (typeof content === 'string') { + return content.trim() + } + if (Array.isArray(content)) { + return content.map(taskNotificationBlockText).filter(Boolean).join(' ').trim() + } + return '' +} + +function taskNotificationBlockText(block: unknown): string { + if (typeof block === 'string') { + return block + } + const record = asRecord(block) + return extractString(record?.text) ?? extractString(record?.content) ?? '' +} + +// Claude writes an `agent-.meta.json` sidecar for every subagent transcript, +// carrying the Task tool's spawn `description` and its resolved `agentType`. +async function readSubagentMeta(transcriptPath: string): Promise { + const metaPath = `${transcriptPath.slice(0, -extname(transcriptPath).length)}.meta.json` + try { + const record = asRecord(JSON.parse(await readFile(metaPath, 'utf-8')) as unknown) + return { + description: normalizeTitleText(extractString(record?.description) ?? ''), + agentType: extractString(record?.agentType) + } + } catch { + // The sidecar is optional; the transcript still yields a usable title. + return { description: null, agentType: null } + } +} diff --git a/src/main/ai-vault/session-scanner-codex-parser.test.ts b/src/main/ai-vault/session-scanner-codex-parser.test.ts index 592ac2e9d72d..f48d58f495aa 100644 --- a/src/main/ai-vault/session-scanner-codex-parser.test.ts +++ b/src/main/ai-vault/session-scanner-codex-parser.test.ts @@ -85,4 +85,55 @@ describe('parseCodexSessionFile', () => { expect(session?.totalTokens).toBe(150) }) + + it('extracts the model from turn context, latest turn winning', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-codex-model-')) + tempRoots.push(root) + const sessionPath = join(root, 'sessions', '2026', '07', '05', 'rollout-model.jsonl') + await mkdir(dirname(sessionPath), { recursive: true }) + + await writeFile( + sessionPath, + jsonLines([ + { + timestamp: '2026-07-05T10:00:00.000Z', + type: 'session_meta', + payload: { id: 'model-session', cwd: '/repo/app' } + }, + { + timestamp: '2026-07-05T10:00:01.000Z', + type: 'turn_context', + payload: { cwd: '/repo/app', model: 'gpt-5.1' } + }, + { + timestamp: '2026-07-05T10:00:02.000Z', + type: 'response_item', + payload: { + type: 'message', + role: 'user', + content: [{ type: 'text', text: 'Switch the model' }] + } + }, + { + // A /model switch mid-session writes a later turn_context. + timestamp: '2026-07-05T10:00:03.000Z', + type: 'turn_context', + payload: { cwd: '/repo/app', model: 'gpt-5.5' } + } + ]) + ) + + const sessionStat = await stat(sessionPath) + const session = await parseCodexSessionFile( + { + path: sessionPath, + mtimeMs: sessionStat.mtimeMs, + modifiedAt: sessionStat.mtime.toISOString() + }, + 'darwin', + root + ) + + expect(session?.model).toBe('gpt-5.5') + }) }) diff --git a/src/main/ai-vault/session-scanner-discovery.ts b/src/main/ai-vault/session-scanner-discovery.ts index 9bfade6e6656..c176fb3c6e5a 100644 --- a/src/main/ai-vault/session-scanner-discovery.ts +++ b/src/main/ai-vault/session-scanner-discovery.ts @@ -70,6 +70,8 @@ export async function walkSessionFiles( options: { extensions: Set filePredicate?: (path: string) => boolean + // Return false to skip descending into a directory (matched by its name), + // so pruned subtrees are never stat'd or parsed. directoryPredicate?: (name: string) => boolean } ): Promise { diff --git a/src/main/ai-vault/session-scanner-gemini-parsers.ts b/src/main/ai-vault/session-scanner-gemini-parsers.ts new file mode 100644 index 000000000000..6f0b9fdc7c13 --- /dev/null +++ b/src/main/ai-vault/session-scanner-gemini-parsers.ts @@ -0,0 +1,156 @@ +import { createReadStream } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { createInterface } from 'node:readline' +import type { AiVaultSession } from '../../shared/ai-vault-types' +import type { + FileWithMtime, + ResumableParseFinalizeOptions, + ResumableSessionParseState, + SessionAccumulator +} from './session-scanner-types' +import { + accumulatorFoldResumeState, + addPreviewContent, + createAccumulator, + finalizeSession, + sessionIdFromFileName, + updateTimeline +} from './session-scanner-accumulator' +import { + arrayValue, + asRecord, + extractContentText, + extractString, + parseJsonObject, + tokenTotal +} from './session-scanner-values' + +export async function parseGeminiSessionFile( + file: FileWithMtime, + platform: NodeJS.Platform = process.platform +): Promise { + if (file.path.endsWith('.jsonl')) { + return parseGeminiJsonlSessionFile(file, platform) + } + + return parseGeminiJsonSessionContent(file, await readFile(file.path, 'utf-8'), platform) +} + +export async function parseGeminiSessionContent( + file: FileWithMtime, + content: string, + platform: NodeJS.Platform = process.platform, + options: ResumableParseFinalizeOptions = {} +): Promise { + if (file.path.endsWith('.jsonl')) { + return parseGeminiJsonlSessionLines({ + file, + lines: content.split(/\r?\n/), + platform, + options + }) + } + return parseGeminiJsonSessionContent(file, content, platform, options) +} + +function parseGeminiJsonSessionContent( + file: FileWithMtime, + content: string, + platform: NodeJS.Platform, + options: ResumableParseFinalizeOptions = {} +): AiVaultSession | null { + const record = asRecord(JSON.parse(content) as unknown) + if (!record) { + return null + } + const accumulator = createAccumulator({ + agent: 'gemini', + file, + sessionId: extractString(record.sessionId) ?? sessionIdFromFileName(file.path) + }) + updateTimeline(accumulator, extractString(record.startTime)) + updateTimeline(accumulator, extractString(record.lastUpdated)) + for (const message of arrayValue(record.messages)) { + consumeGeminiMessage(accumulator, asRecord(message)) + } + return finalizeSession(accumulator, platform, options) +} + +export async function parseGeminiJsonlSessionFile( + file: FileWithMtime, + platform: NodeJS.Platform +): Promise { + const lines = createInterface({ + input: createReadStream(file.path, { encoding: 'utf-8' }), + crlfDelay: Infinity + }) + return parseGeminiJsonlSessionLines({ file, lines, platform }) +} + +function consumeGeminiJsonlRecordLine(accumulator: SessionAccumulator, line: string): void { + const record = parseJsonObject(line) + if (!record) { + return + } + const setRecord = asRecord(record.$set) + if (setRecord) { + updateTimeline(accumulator, extractString(setRecord.lastUpdated)) + return + } + const sessionId = extractString(record.sessionId) + if (sessionId) { + accumulator.sessionId = sessionId + } + updateTimeline(accumulator, extractString(record.startTime)) + updateTimeline(accumulator, extractString(record.lastUpdated)) + consumeGeminiMessage(accumulator, record) +} + +// Resumable only for the JSONL log format; Gemini's legacy single-JSON +// session documents are rewritten in place and must be re-read whole. +export function createGeminiJsonlSessionResumeState( + file: FileWithMtime +): ResumableSessionParseState { + return accumulatorFoldResumeState( + createAccumulator({ agent: 'gemini', file, sessionId: sessionIdFromFileName(file.path) }), + consumeGeminiJsonlRecordLine + ) +} + +async function parseGeminiJsonlSessionLines(args: { + file: FileWithMtime + lines: AsyncIterable | Iterable + platform: NodeJS.Platform + options?: ResumableParseFinalizeOptions +}): Promise { + const state = createGeminiJsonlSessionResumeState(args.file) + for await (const line of args.lines) { + state.consumeLine(line) + } + return state.finalize(args.platform, args.options) +} + +export function consumeGeminiMessage( + accumulator: SessionAccumulator, + record: Record | null +): void { + if (!record) { + return + } + updateTimeline(accumulator, extractString(record.timestamp)) + if (record.type === 'user') { + accumulator.messageCount++ + accumulator.title ??= extractContentText(record.content) + addPreviewContent(accumulator, 'user', record.content, record.timestamp) + return + } + if (record.type === 'gemini') { + accumulator.messageCount++ + addPreviewContent(accumulator, 'assistant', record.content, record.timestamp) + const model = extractString(record.model) + if (model) { + accumulator.model = model + } + accumulator.totalTokens += tokenTotal(record.tokens) + } +} diff --git a/src/main/ai-vault/session-scanner-injected-title.test.ts b/src/main/ai-vault/session-scanner-injected-title.test.ts new file mode 100644 index 000000000000..a42296f95367 --- /dev/null +++ b/src/main/ai-vault/session-scanner-injected-title.test.ts @@ -0,0 +1,56 @@ +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { scanAiVaultSessions } from './session-scanner' +import { isolatedScanRoots, jsonLines } from './session-scanner-test-fixtures' + +let tempRoots: string[] = [] + +afterEach(async () => { + vi.restoreAllMocks() + await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) + tempRoots = [] +}) + +describe('scanAiVaultSessions harness-injected title seeding', () => { + it('keeps harness-injected Claude turns without isMeta out of session titles', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-claude-injected-title-')) + tempRoots.push(root) + const roots = isolatedScanRoots(root) + await mkdir(join(roots.claudeProjectsDir, 'project'), { recursive: true }) + + await writeFile( + join(roots.claudeProjectsDir, 'project', 'injected-first.jsonl'), + jsonLines([ + { + type: 'user', + sessionId: 'injected-first', + timestamp: '2026-06-11T10:00:00.000Z', + cwd: '/repo/app', + // Task notifications carry no isMeta — only their text marks them. + message: { + role: 'user', + content: ' abc completed' + } + }, + { + type: 'user', + sessionId: 'injected-first', + timestamp: '2026-06-11T10:00:01.000Z', + cwd: '/repo/app', + message: { role: 'user', content: 'Fix the sidebar label bug' } + } + ]) + ) + + const result = await scanAiVaultSessions({ + ...roots, + platform: 'darwin' + }) + + expect(result.issues).toEqual([]) + expect(result.sessions).toHaveLength(1) + expect(result.sessions[0]?.title).toBe('Fix the sidebar label bug') + }) +}) diff --git a/src/main/ai-vault/session-scanner-parse-cache.ts b/src/main/ai-vault/session-scanner-parse-cache.ts index 20650f105a91..70d0d311d6b8 100644 --- a/src/main/ai-vault/session-scanner-parse-cache.ts +++ b/src/main/ai-vault/session-scanner-parse-cache.ts @@ -5,14 +5,13 @@ import { parseAgentSessionFile } from './session-scanner-agent-parser' import { createCodexSessionResumeState } from './session-scanner-codex-parser' import { createDroidSessionResumeState } from './session-scanner-droid-parser' import { createMessageGraphSessionResumeState } from './session-scanner-graph-parsers' -import { - createClaudeSessionResumeState, - createGeminiJsonlSessionResumeState -} from './session-scanner-primary-parsers' +import { createClaudeSessionResumeState } from './session-scanner-primary-parsers' +import { createGeminiJsonlSessionResumeState } from './session-scanner-gemini-parsers' import { createCopilotSessionResumeState, createCursorSessionResumeState } from './session-scanner-secondary-parsers' +import { countSubagentTranscripts } from './session-scanner-subagent-transcripts' import type { ResumableSessionParseState, SessionFileCandidate } from './session-scanner-types' // Sized past the default recency cap (1000) plus the in-scope cap (2000) so a @@ -132,6 +131,16 @@ export async function parseAgentSessionFileCached( if (stats) { stats.reused++ } + // A zero-turn transcript usually never changes again, but its sibling + // subagents/ dir can gain files after the parent's last write (a + // still-running subagent finishing). The mtime+size key can't see that, + // so refresh the cheap directory count on reuse. + if (entry.session && candidate.agent === 'claude' && entry.session.messageCount === 0) { + const subagentTranscriptCount = await countSubagentTranscripts(file.path) + if (subagentTranscriptCount !== entry.session.subagentTranscriptCount) { + entry.session = { ...entry.session, subagentTranscriptCount } + } + } storeEntry(file.path, entry) return entry.session } diff --git a/src/main/ai-vault/session-scanner-primary-parsers.ts b/src/main/ai-vault/session-scanner-primary-parsers.ts index e07329a30032..9e2701947129 100644 --- a/src/main/ai-vault/session-scanner-primary-parsers.ts +++ b/src/main/ai-vault/session-scanner-primary-parsers.ts @@ -1,15 +1,14 @@ import { createReadStream } from 'node:fs' -import { readFile } from 'node:fs/promises' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' -import type { ExecutionHostId } from '../../shared/execution-host' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../shared/execution-host' +import { isHarnessInjectedUserTurnText } from '../../shared/harness-injected-user-turns' import type { FileWithMtime, ResumableSessionParseState, SessionAccumulator } from './session-scanner-types' import { - accumulatorFoldResumeState, addPreviewContent, createAccumulator, finalizeSession, @@ -17,16 +16,14 @@ import { updateLatestLocation, updateTimeline } from './session-scanner-accumulator' +import { countSubagentTranscripts } from './session-scanner-subagent-transcripts' import { - arrayValue, asRecord, claudeUsageTotal, - extractContentText, extractMessageText, extractString, normalizeTitleText, - parseJsonObject, - tokenTotal + parseJsonObject } from './session-scanner-values' type ParserSessionOptions = { @@ -102,13 +99,31 @@ export function consumeClaudeSessionLine(state: ClaudeSessionParseState, line: s return } + if (record.type === 'queue-operation') { + // Enqueued prompts hold real content (e.g. queued subagent messages) that + // survives even when the conversation was never persisted — recoverable + // signal for an otherwise-empty session, but not a conversation turn. + // Count net of remove/dequeue: consumed or user-removed prompts are written + // as later queue-operation records and are no longer queued. Accepted gap: + // a dequeue/remove of an uncounted empty-content enqueue can undercount, + // which only hides the recoverable badge — it never fabricates one. + if (record.operation === 'enqueue' && (extractString(record.content)?.trim().length ?? 0) > 0) { + accumulator.queuedMessageCount++ + } else if (record.operation === 'remove' || record.operation === 'dequeue') { + accumulator.queuedMessageCount = Math.max(0, accumulator.queuedMessageCount - 1) + } + return + } + if (record.type === 'user') { accumulator.messageCount++ const title = extractMessageText(record.message) addPreviewContent(accumulator, 'user', asRecord(record.message)?.content, record.timestamp) if (title) { - // Meta prompts (injected context) only seed the last-resort title. - if (record.isMeta === true) { + // Meta prompts (injected context) only seed the last-resort title. Some + // injected turns (task notifications) carry no isMeta, so also gate on + // the shared machinery-text classifier. + if (record.isMeta === true || isHarnessInjectedUserTurnText(title)) { state.metaTitle ??= title } else { state.firstUserTitle ??= title @@ -129,11 +144,11 @@ export function consumeClaudeSessionLine(state: ClaudeSessionParseState, line: s } } -export function finalizeClaudeSessionParseState( +export async function finalizeClaudeSessionParseState( state: ClaudeSessionParseState, platform: NodeJS.Platform, options: ParserSessionOptions = {} -): AiVaultSession | null { +): Promise { // Finalize a snapshot: the live state (and its preview array) may keep // accumulating appended lines after this session object is handed out. const snapshot = cloneClaudeSessionParseState(state) @@ -141,6 +156,20 @@ export function finalizeClaudeSessionParseState( // session name (ai-title) should outrank the raw first prompt when present. snapshot.accumulator.fallbackTitle = snapshot.generatedTitle ?? snapshot.firstUserTitle ?? snapshot.metaTitle + // Every session's sibling subagent transcripts are counted (one readdir): + // the row UI shows the count without expanding details, and for zero-turn + // transcripts it doubles as the recoverable-content signal. The sibling dir + // lives on the host that owns the transcript, so content fetched from a + // remote (SSH) host must not readdir this machine's disk. Runtime hosts scan + // their own local disk (their host id is stamped after parse), so they are + // already covered by the undefined-executionHostId branch. + const ownsTranscriptDisk = + !options.executionHostId || options.executionHostId === LOCAL_EXECUTION_HOST_ID + if (ownsTranscriptDisk) { + snapshot.accumulator.subagentTranscriptCount = await countSubagentTranscripts( + snapshot.accumulator.filePath + ) + } return finalizeSession(snapshot.accumulator, platform, options) } @@ -198,133 +227,3 @@ async function parseClaudeSessionLines(args: { } return finalizeClaudeSessionParseState(state, args.platform, args.options) } - -export async function parseGeminiSessionFile( - file: FileWithMtime, - platform: NodeJS.Platform = process.platform -): Promise { - if (file.path.endsWith('.jsonl')) { - return parseGeminiJsonlSessionFile(file, platform) - } - - return parseGeminiJsonSessionContent(file, await readFile(file.path, 'utf-8'), platform) -} - -export async function parseGeminiSessionContent( - file: FileWithMtime, - content: string, - platform: NodeJS.Platform = process.platform, - options: ParserSessionOptions = {} -): Promise { - if (file.path.endsWith('.jsonl')) { - return parseGeminiJsonlSessionLines({ - file, - lines: content.split(/\r?\n/), - platform, - options - }) - } - return parseGeminiJsonSessionContent(file, content, platform, options) -} - -function parseGeminiJsonSessionContent( - file: FileWithMtime, - content: string, - platform: NodeJS.Platform, - options: ParserSessionOptions = {} -): AiVaultSession | null { - const record = asRecord(JSON.parse(content) as unknown) - if (!record) { - return null - } - const accumulator = createAccumulator({ - agent: 'gemini', - file, - sessionId: extractString(record.sessionId) ?? sessionIdFromFileName(file.path) - }) - updateTimeline(accumulator, extractString(record.startTime)) - updateTimeline(accumulator, extractString(record.lastUpdated)) - for (const message of arrayValue(record.messages)) { - consumeGeminiMessage(accumulator, asRecord(message)) - } - return finalizeSession(accumulator, platform, options) -} - -export async function parseGeminiJsonlSessionFile( - file: FileWithMtime, - platform: NodeJS.Platform -): Promise { - const lines = createInterface({ - input: createReadStream(file.path, { encoding: 'utf-8' }), - crlfDelay: Infinity - }) - return parseGeminiJsonlSessionLines({ file, lines, platform }) -} - -function consumeGeminiJsonlRecordLine(accumulator: SessionAccumulator, line: string): void { - const record = parseJsonObject(line) - if (!record) { - return - } - const setRecord = asRecord(record.$set) - if (setRecord) { - updateTimeline(accumulator, extractString(setRecord.lastUpdated)) - return - } - const sessionId = extractString(record.sessionId) - if (sessionId) { - accumulator.sessionId = sessionId - } - updateTimeline(accumulator, extractString(record.startTime)) - updateTimeline(accumulator, extractString(record.lastUpdated)) - consumeGeminiMessage(accumulator, record) -} - -// Resumable only for the JSONL log format; Gemini's legacy single-JSON -// session documents are rewritten in place and must be re-read whole. -export function createGeminiJsonlSessionResumeState( - file: FileWithMtime -): ResumableSessionParseState { - return accumulatorFoldResumeState( - createAccumulator({ agent: 'gemini', file, sessionId: sessionIdFromFileName(file.path) }), - consumeGeminiJsonlRecordLine - ) -} - -async function parseGeminiJsonlSessionLines(args: { - file: FileWithMtime - lines: AsyncIterable | Iterable - platform: NodeJS.Platform - options?: ParserSessionOptions -}): Promise { - const state = createGeminiJsonlSessionResumeState(args.file) - for await (const line of args.lines) { - state.consumeLine(line) - } - return state.finalize(args.platform, args.options) -} - -export function consumeGeminiMessage( - accumulator: SessionAccumulator, - record: Record | null -): void { - if (!record) { - return - } - updateTimeline(accumulator, extractString(record.timestamp)) - if (record.type === 'user') { - accumulator.messageCount++ - accumulator.title ??= extractContentText(record.content) - addPreviewContent(accumulator, 'user', record.content, record.timestamp) - return - } - if (record.type === 'gemini') { - accumulator.messageCount++ - addPreviewContent(accumulator, 'assistant', record.content, record.timestamp) - const model = extractString(record.model) - if (model) { - accumulator.model = model - } - accumulator.totalTokens += tokenTotal(record.tokens) - } -} diff --git a/src/main/ai-vault/session-scanner-recoverable-empty.test.ts b/src/main/ai-vault/session-scanner-recoverable-empty.test.ts new file mode 100644 index 000000000000..17c093a064c1 --- /dev/null +++ b/src/main/ai-vault/session-scanner-recoverable-empty.test.ts @@ -0,0 +1,261 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { isAiVaultSessionRecoverableEmpty } from '../../shared/ai-vault-types' +import { scanAiVaultSessions } from './session-scanner' +import { parseClaudeSessionContent } from './session-scanner-primary-parsers' +import { countSubagentTranscripts } from './session-scanner-subagent-transcripts' +import { isolatedScanRoots, writeJsonlFile } from './session-scanner-test-fixtures' + +let tempRoots: string[] = [] + +afterEach(async () => { + await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) + tempRoots = [] +}) + +// Shape of the real ~/.claude/.../9176163a-*.jsonl artifact: CLI metadata plus +// four queued subagent messages, and zero user/assistant conversation turns. +function metadataOnlyTranscript(sessionId: string): unknown[] { + return [ + { + type: 'last-prompt', + lastPrompt: 'Run the review', + leafUuid: 'leaf-1', + sessionId + }, + { type: 'ai-title', aiTitle: 'Push failure recovery review', sessionId }, + { type: 'mode', mode: 'default', sessionId }, + { type: 'permission-mode', permissionMode: 'acceptEdits', sessionId }, + ...['contracts', 'environment', 'correctness', 'perf'].map((lens, index) => ({ + type: 'queue-operation', + operation: 'enqueue', + timestamp: `2026-07-08T16:3${index}:00.000Z`, + sessionId, + content: `Review complete` + })) + ] +} + +describe('recoverable-but-empty Claude sessions', () => { + it('surfaces a zero-turn session with queued messages and subagent transcripts', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-recoverable-')) + tempRoots.push(root) + const roots = isolatedScanRoots(root) + const sessionId = '9176163a-2f89-431f-b202-32f04d61f124' + + await writeJsonlFile( + join(roots.claudeProjectsDir, 'project', `${sessionId}.jsonl`), + metadataOnlyTranscript(sessionId) + ) + // Sibling subagent transcripts survive even though the parent conversation + // was never persisted; a .meta.json sidecar is not a transcript. + const subagentsDir = join(roots.claudeProjectsDir, 'project', sessionId, 'subagents') + await writeJsonlFile(join(subagentsDir, 'agent-arev-contracts-1.jsonl'), [ + { + type: 'user', + sessionId, + message: { role: 'user', content: 'Contracts review' } + } + ]) + await writeJsonlFile(join(subagentsDir, 'agent-arev-perf-2.jsonl'), [ + { + type: 'user', + sessionId, + message: { role: 'user', content: 'Perf review' } + } + ]) + await writeFile(join(subagentsDir, 'agent-arev-contracts-1.meta.json'), '{}') + + const result = await scanAiVaultSessions({ ...roots, platform: 'darwin' }) + const session = result.sessions.find((entry) => entry.sessionId === sessionId) + + expect(session).toBeDefined() + expect(session?.messageCount).toBe(0) + expect(session?.queuedMessageCount).toBe(4) + expect(session?.subagentTranscriptCount).toBe(2) + expect(isAiVaultSessionRecoverableEmpty(session!)).toBe(true) + }) + + it('reports no recoverable signal for a plain metadata-only session', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-plain-empty-')) + tempRoots.push(root) + const roots = isolatedScanRoots(root) + const sessionId = 'plain-empty-session' + + await writeJsonlFile(join(roots.claudeProjectsDir, 'project', `${sessionId}.jsonl`), [ + { type: 'mode', mode: 'default', sessionId }, + { type: 'permission-mode', permissionMode: 'default', sessionId } + ]) + + const result = await scanAiVaultSessions({ ...roots, platform: 'darwin' }) + const session = result.sessions.find((entry) => entry.sessionId === sessionId) + + expect(session).toBeDefined() + expect(session?.messageCount).toBe(0) + expect(session?.queuedMessageCount).toBe(0) + expect(session?.subagentTranscriptCount).toBe(0) + expect(isAiVaultSessionRecoverableEmpty(session!)).toBe(false) + }) + + it('counts subagent transcripts for a session that has real turns without flagging it recoverable', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-nonempty-')) + tempRoots.push(root) + const roots = isolatedScanRoots(root) + const sessionId = 'conversation-session' + + await writeJsonlFile(join(roots.claudeProjectsDir, 'project', `${sessionId}.jsonl`), [ + { + type: 'user', + sessionId, + message: { role: 'user', content: 'Do the thing' } + } + ]) + await writeJsonlFile( + join(roots.claudeProjectsDir, 'project', sessionId, 'subagents', 'agent-x.jsonl'), + [ + { + type: 'user', + sessionId, + message: { role: 'user', content: 'Subtask' } + } + ] + ) + + const result = await scanAiVaultSessions({ ...roots, platform: 'darwin' }) + const session = result.sessions.find((entry) => entry.sessionId === sessionId) + + expect(session?.messageCount).toBe(1) + // Counted for every local session (the row's "N subagents" affordance), + // but a session with real turns is never surfaced as recoverable-empty. + expect(session?.subagentTranscriptCount).toBe(1) + expect(isAiVaultSessionRecoverableEmpty(session!)).toBe(false) + }) + + it('counts queued messages net of remove and dequeue operations', async () => { + const sessionId = 'net-queue-session' + const content = [ + { type: 'mode', mode: 'default', sessionId }, + ...[1, 2, 3].map((n) => ({ + type: 'queue-operation', + operation: 'enqueue', + sessionId, + content: `queued prompt ${n}` + })), + // One prompt consumed, one removed by the user: only one is still queued. + { type: 'queue-operation', operation: 'dequeue', sessionId }, + { + type: 'queue-operation', + operation: 'remove', + sessionId, + content: null + } + ] + .map((line) => JSON.stringify(line)) + .join('\n') + const file = { + path: `/tmp/${sessionId}.jsonl`, + mtimeMs: 0, + modifiedAt: '2026-07-08T16:30:00.000Z' + } + + const session = await parseClaudeSessionContent(file, content, 'darwin', { + executionHostId: 'ssh:host' + }) + expect(session?.queuedMessageCount).toBe(1) + }) + + it('picks up subagent transcripts written after the parent transcript last changed', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-late-sub-')) + tempRoots.push(root) + const roots = isolatedScanRoots(root) + const sessionId = 'late-subagent-session' + + await writeJsonlFile(join(roots.claudeProjectsDir, 'project', `${sessionId}.jsonl`), [ + { type: 'mode', mode: 'default', sessionId } + ]) + const first = await scanAiVaultSessions({ ...roots, platform: 'darwin' }) + expect( + first.sessions.find((entry) => entry.sessionId === sessionId)?.subagentTranscriptCount + ).toBe(0) + + // The parent file never changes again, but a still-running subagent lands + // its transcript afterwards; the cached parse must still surface it. + await writeJsonlFile( + join(roots.claudeProjectsDir, 'project', sessionId, 'subagents', 'agent-late.jsonl'), + [ + { + type: 'user', + sessionId, + message: { role: 'user', content: 'Late subtask' } + } + ] + ) + const second = await scanAiVaultSessions({ ...roots, platform: 'darwin' }) + expect( + second.sessions.find((entry) => entry.sessionId === sessionId)?.subagentTranscriptCount + ).toBe(1) + }) + + it('never counts local subagent transcripts for a remote-host transcript', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-remote-')) + tempRoots.push(root) + const sessionId = 'remote-session' + const transcriptPath = join(root, `${sessionId}.jsonl`) + // A local sibling dir exists, but the transcript content came from an SSH + // host — its real subagents live on that host, not on this disk. + await writeJsonlFile(join(root, sessionId, 'subagents', 'agent-x.jsonl'), [{ type: 'user' }]) + const content = metadataOnlyTranscript(sessionId) + .map((line) => JSON.stringify(line)) + .join('\n') + const file = { + path: transcriptPath, + mtimeMs: 0, + modifiedAt: '2026-07-08T16:30:00.000Z' + } + + const remote = await parseClaudeSessionContent(file, content, 'linux', { + executionHostId: 'ssh:host' + }) + expect(remote?.subagentTranscriptCount).toBe(0) + expect(remote?.queuedMessageCount).toBe(4) + + const local = await parseClaudeSessionContent(file, content, 'darwin') + expect(local?.subagentTranscriptCount).toBe(1) + }) +}) + +describe('countSubagentTranscripts', () => { + it('returns 0 when the sibling subagents directory is absent', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-nosub-')) + tempRoots.push(root) + expect(await countSubagentTranscripts(join(root, 'session.jsonl'))).toBe(0) + }) + + it('counts only .jsonl transcripts, excluding meta sidecars', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-sub-count-')) + tempRoots.push(root) + const transcriptPath = join(root, 'session.jsonl') + const subagentsDir = join(root, 'session', 'subagents') + await writeJsonlFile(join(subagentsDir, 'agent-a.jsonl'), [{ type: 'user' }]) + await writeJsonlFile(join(subagentsDir, 'agent-b.jsonl'), [{ type: 'user' }]) + await writeFile(join(subagentsDir, 'agent-a.meta.json'), '{}') + + expect(await countSubagentTranscripts(transcriptPath)).toBe(2) + }) + + it('excludes non-agent .jsonl files and directories named like transcripts', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-sub-predicate-')) + tempRoots.push(root) + const transcriptPath = join(root, 'session.jsonl') + const subagentsDir = join(root, 'session', 'subagents') + await writeJsonlFile(join(subagentsDir, 'agent-a.jsonl'), [{ type: 'user' }]) + // A stray sibling artifact and a directory would inflate the row badge past + // what the on-demand lister shows; both must fail the shared predicate. + await writeFile(join(subagentsDir, 'notes.jsonl'), '{}') + await mkdir(join(subagentsDir, 'agent-x.jsonl')) + + expect(await countSubagentTranscripts(transcriptPath)).toBe(1) + }) +}) diff --git a/src/main/ai-vault/session-scanner-source-discovery.ts b/src/main/ai-vault/session-scanner-source-discovery.ts index 8c03ec72e427..f77404bfc5af 100644 --- a/src/main/ai-vault/session-scanner-source-discovery.ts +++ b/src/main/ai-vault/session-scanner-source-discovery.ts @@ -2,11 +2,13 @@ import { homedir } from 'node:os' import { basename, join } from 'node:path' import type { AiVaultScanIssue } from '../../shared/ai-vault-types' import { uniqueCodexSessionsDirs } from './session-scanner-codex-paths' +import { SUBAGENT_DIR_NAME } from './session-scanner-subagent-transcripts' import { discoverFiles, discoverOpenClawFiles } from './session-scanner-discovery' import { droidDiscoveries, kimiDiscoveries } from './session-scanner-droid-kimi-sources' import { opencodeDiscoveries } from './session-scanner-opencode-sources' import type { AiVaultScanOptions, SessionFileDiscovery } from './session-scanner-types' import { normalizeAgentSessionsDir } from './session-scanner-values' +import { resolveGrokSessionsDir } from '../../shared/grok-session-paths' const CLAUDE_PROJECTS_DIR = join(homedir(), '.claude', 'projects') export const DEFAULT_CODEX_HOME_DIR = join(homedir(), '.codex') @@ -18,10 +20,7 @@ const COPILOT_SESSIONS_DIR = join( 'session-state' ) const CURSOR_PROJECTS_DIR = join(homedir(), '.cursor', 'projects') -const GROK_SESSIONS_DIR = join( - process.env.GROK_HOME?.trim() || join(homedir(), '.grok'), - 'sessions' -) +const GROK_SESSIONS_DIR = resolveGrokSessionsDir() const HERMES_SESSIONS_DIR = join(homedir(), '.hermes', 'sessions') const ROVO_SESSIONS_DIR = join(homedir(), '.rovodev', 'sessions') const OPENCLAW_STATE_DIR = process.env.OPENCLAW_STATE_DIR?.trim() || join(homedir(), '.openclaw') @@ -39,6 +38,18 @@ const DEVIN_TRANSCRIPTS_DIR = join( 'transcripts' ) +// The local host and each WSL distro's `~/.claude/projects`. Callers reading +// Claude session files by path use these roots to reject arbitrary paths. +export function claudeProjectsRootDirs(args: { + claudeProjectsDir?: string + wslHomeDirs?: readonly string[] +}): string[] { + return [ + args.claudeProjectsDir ?? CLAUDE_PROJECTS_DIR, + ...(args.wslHomeDirs ?? []).map((homeDir) => join(homeDir, '.claude', 'projects')) + ] +} + export async function discoverAiVaultSessionSources(args: { options: AiVaultScanOptions limitPerAgent: number @@ -77,10 +88,10 @@ function claudeDiscoveries( limit: number, issues: AiVaultScanIssue[] ): Promise[] { - return [ - options.claudeProjectsDir ?? CLAUDE_PROJECTS_DIR, - ...wslHomeDirs.map((homeDir) => join(homeDir, '.claude', 'projects')) - ].map((rootDir) => + return claudeProjectsRootDirs({ + claudeProjectsDir: options.claudeProjectsDir, + wslHomeDirs + }).map((rootDir) => discoverFiles({ rootDir, limit, @@ -89,8 +100,9 @@ function claudeDiscoveries( extensions: ['.jsonl'], // Why: Task subagent transcripts under `/subagents/` share the parent // sessionId and aren't independently resumable, so they'd just duplicate the - // parent as untitled rows; prune the subtree instead of indexing it. - directoryPredicate: (name) => name !== 'subagents' + // parent as untitled rows; prune the subtree and read them on demand under + // their parent instead. + directoryPredicate: (name) => name !== SUBAGENT_DIR_NAME }) ) } diff --git a/src/main/ai-vault/session-scanner-subagent-transcripts.ts b/src/main/ai-vault/session-scanner-subagent-transcripts.ts new file mode 100644 index 000000000000..0477f9dc2294 --- /dev/null +++ b/src/main/ai-vault/session-scanner-subagent-transcripts.ts @@ -0,0 +1,85 @@ +import { readdir } from 'node:fs/promises' +import { basename, dirname, extname, join } from 'node:path' + +// Exported so discovery can prune these subtrees using the same literal that +// locates them here — the pruning comment and behavior can't drift. +export const SUBAGENT_DIR_NAME = 'subagents' + +// Claude names every Task subagent transcript `agent-.jsonl`. The row-badge +// count, the recoverable-empty signal, and the on-demand lister all key off this +// one predicate so the "N subagents" badge can never disagree with the expanded +// list (a stray non-transcript `.jsonl` or a dir named `x.jsonl` would otherwise +// inflate the count). +export const SUBAGENT_TRANSCRIPT_PREFIX = 'agent-' + +export function isSubagentTranscriptFileName(name: string, isFile: boolean): boolean { + return ( + isFile && + name.startsWith(SUBAGENT_TRANSCRIPT_PREFIX) && + extname(name).toLowerCase() === '.jsonl' + ) +} + +// Claude writes subagent transcripts to a sibling directory named after the +// parent transcript file (…//.jsonl → …///subagents/). +// These survive intact even when the parent conversation persisted zero turns, +// so they are the recoverable signal that keeps such a session from being hidden. +export function subagentTranscriptsDirFor(transcriptFilePath: string): string { + const stem = basename(transcriptFilePath, extname(transcriptFilePath)) + return join(dirname(transcriptFilePath), stem, SUBAGENT_DIR_NAME) +} + +/** + * Count sibling subagent transcript files for a session's transcript. Returns 0 + * when the directory is absent (the common case), so callers can treat any + * positive count as recoverable content. Meta sidecars (`*.meta.json`) are not + * transcripts and are excluded. + */ +export async function countSubagentTranscripts(transcriptFilePath: string): Promise { + let entries + try { + entries = await readdir(subagentTranscriptsDirFor(transcriptFilePath), { withFileTypes: true }) + } catch { + return 0 + } + return entries.filter((entry) => isSubagentTranscriptFileName(entry.name, entry.isFile())).length +} + +// Direct child of a subagents dir: `//subagents/agent-.jsonl`. +// The `agent-` prefix mirrors the local count/list predicate so remote badges +// can't over-count. Greedy prefix means nested subagent trees attribute to their +// nearest parent, matching the local direct-children-only readdir semantics. +const SUBAGENT_DIRECT_CHILD_PATTERN = /^(.*)[\\/]subagents[\\/]agent-[^\\/]+\.jsonl$/i +const SUBAGENT_SUBTREE_PATTERN = /[\\/]subagents[\\/]/i + +/** + * Partition a recursively walked transcript listing into session candidates and + * per-parent sibling subagent transcript counts. Remote (SSH) scans cannot + * readdir the transcript's sibling directory, but their walk already enumerates + * subagent paths — counting from the listing costs no extra round-trips. + * Subagent transcripts share the parent sessionId and are not independently + * resumable, so they are excluded from candidates (mirrors the local discovery + * pruning in session-scanner-source-discovery.ts). + */ +export function partitionSubagentTranscriptPaths(paths: readonly string[]): { + sessionFilePaths: string[] + subagentTranscriptCounts: Map +} { + const sessionFilePaths: string[] = [] + const subagentTranscriptCounts = new Map() + for (const path of paths) { + if (!SUBAGENT_SUBTREE_PATTERN.test(path)) { + sessionFilePaths.push(path) + continue + } + const directChild = SUBAGENT_DIRECT_CHILD_PATTERN.exec(path) + if (directChild) { + const parentTranscriptPath = `${directChild[1]}.jsonl` + subagentTranscriptCounts.set( + parentTranscriptPath, + (subagentTranscriptCounts.get(parentTranscriptPath) ?? 0) + 1 + ) + } + } + return { sessionFilePaths, subagentTranscriptCounts } +} diff --git a/src/main/ai-vault/session-scanner-types.ts b/src/main/ai-vault/session-scanner-types.ts index 5364e29e21e1..803554316c1c 100644 --- a/src/main/ai-vault/session-scanner-types.ts +++ b/src/main/ai-vault/session-scanner-types.ts @@ -100,6 +100,9 @@ export type SessionAccumulator = { messageCount: number totalTokens: number previewMessages: AiVaultSessionPreviewMessage[] + // Recoverable signal for a zero-turn transcript (see AiVaultSession). + queuedMessageCount: number + subagentTranscriptCount: number latestTimestampMs: number } diff --git a/src/main/automations/service.test.ts b/src/main/automations/service.test.ts index 786ff017bb26..1c9c314b41b9 100644 --- a/src/main/automations/service.test.ts +++ b/src/main/automations/service.test.ts @@ -538,6 +538,62 @@ describe('AutomationService', () => { expect(getAutomationRunUsage).toHaveBeenCalledTimes(1) }) + it('does not throw when retention evicts the run during usage collection', async () => { + vi.setSystemTime(new Date('2026-05-13T10:00:00')) + const store = await createStore() + store.addRepo(makeRepo()) + const automation = store.createAutomation({ + name: 'Costed check', + prompt: 'Check spend', + agentId: 'claude', + projectId: 'r1', + workspaceMode: 'existing', + workspaceId: 'wt1', + timezone: 'UTC', + rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', + dtstart: new Date('2026-05-13T00:00:00Z').getTime() + }) + const base = Date.now() + const run = store.createAutomationRun(automation, base, 'manual') + store.updateAutomationRun({ + runId: run.id, + status: 'dispatched', + workspaceId: 'wt1', + terminalSessionId: 'tab-1', + error: null + }) + // While usage collection is awaited the run is already final, so a + // scheduler tick creating newer runs can prune it away mid-flight. + const getAutomationRunUsage = vi.fn().mockImplementation(async () => { + for (let i = 1; i <= 120; i++) { + const later = store.createAutomationRun(automation, base + i * 60_000) + store.updateAutomationRun({ + runId: later.id, + status: 'completed', + workspaceId: 'wt1', + error: null + }) + } + return null + }) + const service = new AutomationService(store, { + tickMs: 60_000, + claudeUsage: { getAutomationRunUsage } as never + }) + + const updated = await service.markDispatchResult({ + runId: run.id, + status: 'completed', + workspaceId: 'wt1', + terminalSessionId: 'tab-1', + error: null + }) + + expect(updated.id).toBe(run.id) + // The run really was evicted; the usage write was skipped instead of throwing. + expect(store.listAutomationRuns(automation.id).some((entry) => entry.id === run.id)).toBe(false) + }) + it('records unsupported usage cleanly for completed agents without local usage stores', async () => { vi.setSystemTime(new Date('2026-05-13T10:00:00')) const store = await createStore() diff --git a/src/main/automations/service.ts b/src/main/automations/service.ts index dc22550e7ec5..91b70ff60884 100644 --- a/src/main/automations/service.ts +++ b/src/main/automations/service.ts @@ -1,12 +1,12 @@ import type { WebContents } from 'electron' import type { Store } from '../persistence' -import type { - Automation, - AutomationDispatchRequest, - AutomationDispatchResult, - AutomationPrecheckResult, - AutomationRun, - AutomationRunStatus +import { + isFinalAutomationRunStatus, + type Automation, + type AutomationDispatchRequest, + type AutomationDispatchResult, + type AutomationPrecheckResult, + type AutomationRun } from '../../shared/automations-types' import type { ClaudeUsageStore } from '../claude-usage/store' import type { CodexUsageStore } from '../codex-usage/store' @@ -135,7 +135,7 @@ export class AutomationService { async markDispatchResult(result: AutomationDispatchResult): Promise { const run = this.store.updateAutomationRun(result) clearAutomationDispatchTokens(run.automationId, run.id) - if (!isFinalRunStatus(run.status)) { + if (!isFinalAutomationRunStatus(run.status)) { return run } // Why: the renderer's mark-completed effect can re-fire for the same run @@ -151,6 +151,11 @@ export class AutomationService { claudeUsage: this.claudeUsage, codexUsage: this.codexUsage }) + // Why: the run is final during the await above, so a concurrent create-time + // retention prune may have evicted it — the usage write must not throw then. + if (!this.store.listAutomationRuns(run.automationId).some((entry) => entry.id === run.id)) { + return run + } return this.store.updateAutomationRun({ runId: run.id, status: run.status, @@ -309,14 +314,3 @@ export class AutomationService { } } } - -function isFinalRunStatus(status: AutomationRunStatus): boolean { - return ( - status === 'completed' || - status === 'dispatch_failed' || - status === 'skipped_precheck' || - status === 'skipped_missed' || - status === 'skipped_unavailable' || - status === 'skipped_needs_interactive_auth' - ) -} diff --git a/src/main/browser/browser-cookie-import-test-database.ts b/src/main/browser/browser-cookie-import-test-database.ts new file mode 100644 index 000000000000..ead377e5b463 --- /dev/null +++ b/src/main/browser/browser-cookie-import-test-database.ts @@ -0,0 +1,82 @@ +import { createCipheriv, pbkdf2Sync } from 'node:crypto' +import { mkdirSync } from 'node:fs' +import { DatabaseSync } from 'node:sqlite' +import { join } from 'node:path' + +type ChromiumCookieTestRow = { + name: string + value: string + encryptedValue?: Buffer +} + +export function createChromiumCookieTestDatabase( + databasePath: string, + rows: ChromiumCookieTestRow[], + options: { journalMode?: 'wal' } = {} +): DatabaseSync { + mkdirSync(join(databasePath, '..'), { recursive: true }) + const database = new DatabaseSync(databasePath) + if (options.journalMode === 'wal') { + database.exec('PRAGMA journal_mode = WAL; PRAGMA wal_autocheckpoint = 0') + } + database.exec(` + CREATE TABLE cookies ( + creation_utc INTEGER NOT NULL, + host_key TEXT NOT NULL, + top_frame_site_key TEXT NOT NULL DEFAULT '', + name TEXT NOT NULL, + value TEXT NOT NULL, + encrypted_value BLOB NOT NULL DEFAULT X'', + path TEXT NOT NULL, + expires_utc INTEGER NOT NULL, + is_secure INTEGER NOT NULL, + is_httponly INTEGER NOT NULL, + samesite INTEGER NOT NULL, + source_scheme INTEGER NOT NULL DEFAULT 0, + source_port INTEGER NOT NULL DEFAULT -1, + last_update_utc INTEGER NOT NULL DEFAULT 0, + has_cross_site_ancestor INTEGER NOT NULL DEFAULT 0, + UNIQUE(host_key, top_frame_site_key, name, path, source_scheme, source_port) + ) + `) + const insert = database.prepare(` + INSERT INTO cookies ( + creation_utc, + host_key, + top_frame_site_key, + name, + value, + encrypted_value, + path, + expires_utc, + is_secure, + is_httponly, + samesite, + source_scheme, + source_port, + last_update_utc, + has_cross_site_ancestor + ) VALUES (?, ?, '', ?, ?, ?, '/', 0, 0, 0, 0, 0, -1, ?, 0) + `) + rows.forEach((row, index) => { + insert.run( + 133_000_000_000_000 + index, + '.example.com', + row.name, + row.value, + row.encryptedValue ?? Buffer.alloc(0), + 0 + ) + }) + return database +} + +export function encryptMacChromiumCookie(value: string, password: string): Buffer { + const key = pbkdf2Sync(password, 'saltysalt', 1003, 16, 'sha1') + const cipher = createCipheriv('aes-128-cbc', key, Buffer.alloc(16, ' ')) + return Buffer.concat([ + Buffer.from('v10'), + cipher.update(Buffer.from(value, 'latin1')), + cipher.final() + ]) +} diff --git a/src/main/browser/browser-cookie-import.test.ts b/src/main/browser/browser-cookie-import.test.ts index c2965e7f17fe..276630170979 100644 --- a/src/main/browser/browser-cookie-import.test.ts +++ b/src/main/browser/browser-cookie-import.test.ts @@ -1,11 +1,34 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { sessionFromPartitionMock, dialogShowOpenDialogMock } = vi.hoisted(() => ({ +import type * as NodeFs from 'node:fs' + +const { + appGetPathMock, + copyFileSyncMock, + execFileSyncMock, + sessionFromPartitionMock, + dialogShowOpenDialogMock +} = vi.hoisted(() => ({ + appGetPathMock: vi.fn(), + copyFileSyncMock: vi.fn(), + execFileSyncMock: vi.fn(), sessionFromPartitionMock: vi.fn(), dialogShowOpenDialogMock: vi.fn() })) +vi.mock('node:child_process', () => ({ execFileSync: execFileSyncMock })) +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + copyFileSync: (...args: Parameters) => { + copyFileSyncMock(...args) + return actual.copyFileSync(...args) + } + } +}) + vi.mock('electron', () => ({ + app: { getPath: appGetPathMock }, BrowserWindow: { fromWebContents: vi.fn() }, dialog: { showOpenDialog: dialogShowOpenDialogMock }, session: { fromPartition: sessionFromPartitionMock } @@ -20,10 +43,26 @@ import { type ChromiumCookieColumnInfo, type DetectedBrowser } from './browser-cookie-import' -import { writeFileSync, mkdtempSync, rmSync } from 'node:fs' +import { + createChromiumCookieTestDatabase, + encryptMacChromiumCookie +} from './browser-cookie-import-test-database' +import { existsSync, writeFileSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' +function chromeBrowser(cookiesPath: string): DetectedBrowser { + return { + family: 'chrome', + label: 'Google Chrome', + cookiesPath, + keychainService: 'Chrome Safe Storage', + keychainAccount: 'Chrome', + profiles: [{ name: 'Default', directory: 'Default' }], + selectedProfile: 'Default' + } +} + const LARGE_SAFARI_COOKIE_COUNT = 150_000 describe('summarizeCookieImportError', () => { @@ -327,6 +366,172 @@ describe('importCookiesFromBrowser Safari', () => { }) }) +describe('importCookiesFromBrowser Chromium', () => { + let tmpDir: string + let cookiesSetMock: ReturnType + let cookiesRemoveMock: ReturnType + let cookiesFlushStoreMock: ReturnType + let clearStorageDataMock: ReturnType + + beforeEach(() => { + tmpDir = mkdtempSync(join(tmpdir(), 'orca-chromium-cookie-test-')) + cookiesSetMock = vi.fn().mockResolvedValue(undefined) + cookiesRemoveMock = vi.fn().mockResolvedValue(undefined) + cookiesFlushStoreMock = vi.fn().mockResolvedValue(undefined) + clearStorageDataMock = vi.fn().mockResolvedValue(undefined) + appGetPathMock.mockReset() + appGetPathMock.mockReturnValue(join(tmpDir, 'userData')) + copyFileSyncMock.mockClear() + execFileSyncMock.mockReset() + execFileSyncMock.mockImplementation(() => { + throw new Error('OS credential commands are unavailable in this test') + }) + sessionFromPartitionMock.mockReset() + sessionFromPartitionMock.mockReturnValue({ + cookies: { + set: cookiesSetMock, + remove: cookiesRemoveMock, + flushStore: cookiesFlushStoreMock + }, + clearStorageData: clearStorageDataMock + }) + }) + + afterEach(() => { + rmSync(tmpDir, { recursive: true, force: true }) + }) + + it('imports from a live Chromium source DB into a Network/Cookies target profile', async () => { + const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies') + const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies') + // Why: keeping the writer open leaves the committed row in WAL, matching a + // running Chromium profile whose latest auth cookies are not checkpointed. + const sourceDb = createChromiumCookieTestDatabase( + sourceCookiesPath, + [{ name: 'sid', value: 'source-value' }], + { journalMode: 'wal' } + ) + createChromiumCookieTestDatabase(targetCookiesPath, [ + { name: 'old', value: 'target-value' } + ]).close() + + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + try { + expect(existsSync(`${sourceCookiesPath}-wal`)).toBe(true) + const sourceFilesBefore = ['', '-wal', '-shm'].map((suffix) => + readFileSync(sourceCookiesPath + suffix) + ) + + const result = await importCookiesFromBrowser( + chromeBrowser(sourceCookiesPath), + 'persist:test' + ) + + expect(result.ok).toBe(true) + expect(cookiesSetMock).toHaveBeenCalledWith( + expect.objectContaining({ + domain: '.example.com', + name: 'sid', + value: 'source-value' + }) + ) + expect(execFileSyncMock.mock.calls.some(([command]) => command === 'security')).toBe(false) + expect(copyFileSyncMock.mock.calls.some(([source]) => source === sourceCookiesPath)).toBe( + true + ) + expect( + copyFileSyncMock.mock.calls.some(([source]) => source === `${sourceCookiesPath}-wal`) + ).toBe(true) + expect( + ['', '-wal', '-shm'].map((suffix) => readFileSync(sourceCookiesPath + suffix)) + ).toEqual(sourceFilesBefore) + expect(cookiesRemoveMock).not.toHaveBeenCalled() + expect(clearStorageDataMock).toHaveBeenCalledWith({ storages: ['cookies'] }) + } finally { + platformSpy.mockRestore() + sourceDb.close() + } + }) + + it('uses the OS key for encrypted Chromium rows', async () => { + const password = 'test-password' + const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies') + const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies') + createChromiumCookieTestDatabase(sourceCookiesPath, [ + { + name: 'sid', + value: '', + encryptedValue: encryptMacChromiumCookie('encrypted-value', password) + } + ]).close() + createChromiumCookieTestDatabase(targetCookiesPath, []).close() + execFileSyncMock.mockImplementation((command: string) => { + if (command === 'security') { + return `${password}\n` + } + throw new Error(`Unexpected command: ${command}`) + }) + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + + try { + const result = await importCookiesFromBrowser( + chromeBrowser(sourceCookiesPath), + 'persist:test' + ) + + expect(result.ok).toBe(true) + expect(execFileSyncMock).toHaveBeenCalledWith( + 'security', + expect.any(Array), + expect.any(Object) + ) + expect(cookiesSetMock).toHaveBeenCalledWith( + expect.objectContaining({ name: 'sid', value: 'encrypted-value' }) + ) + } finally { + platformSpy.mockRestore() + } + }) + + it('removes staging data when the OS key is unavailable', async () => { + const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies') + const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies') + createChromiumCookieTestDatabase(sourceCookiesPath, [ + { name: 'sid', value: '', encryptedValue: Buffer.from('v10-encrypted') } + ]).close() + createChromiumCookieTestDatabase(targetCookiesPath, []).close() + const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') + + try { + const result = await importCookiesFromBrowser( + chromeBrowser(sourceCookiesPath), + 'persist:test' + ) + + expect(result.ok).toBe(false) + expect(readdirSync(join(tmpDir, 'userData', 'cookie-import-staging'))).toEqual([]) + } finally { + platformSpy.mockRestore() + } + }) + + it('removes partial staging data when the target database copy fails', async () => { + const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies') + const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies') + createChromiumCookieTestDatabase(sourceCookiesPath, []).close() + createChromiumCookieTestDatabase(targetCookiesPath, []).close() + copyFileSyncMock.mockImplementationOnce((_source: string, destination: string) => { + writeFileSync(destination, 'partial cookie database') + throw new Error('simulated copy failure') + }) + + const result = await importCookiesFromBrowser(chromeBrowser(sourceCookiesPath), 'persist:test') + + expect(result).toEqual({ ok: false, reason: 'Could not create staging cookie database.' }) + expect(readdirSync(join(tmpDir, 'userData', 'cookie-import-staging'))).toEqual([]) + }) +}) + describe('detectInstalledBrowsers', () => { it('returns an array of detected browsers', () => { const browsers = detectInstalledBrowsers() diff --git a/src/main/browser/browser-cookie-import.ts b/src/main/browser/browser-cookie-import.ts index bf568abfe792..3191509d30cc 100644 --- a/src/main/browser/browser-cookie-import.ts +++ b/src/main/browser/browser-cookie-import.ts @@ -78,6 +78,11 @@ import type { } from '../../shared/types' import { browserSessionRegistry } from './browser-session-registry' import { setupClientHintsOverride } from './browser-session-ua' +import { + createChromiumCookieSnapshot, + type ChromiumCookieSnapshot +} from './chromium-cookie-snapshot' +import { resolveChromiumCookiesPath } from './chromium-cookie-path' // --------------------------------------------------------------------------- // Browser detection @@ -192,20 +197,6 @@ function browserRootPath(def: ChromiumBrowserDef): string | null { return join(configHome, def.linuxRoot) } -// Why: Chromium 96+ moved the cookies DB from /Cookies to -// /Network/Cookies. Try the newer path first, fall back to legacy. -function resolveCookiesPath(profileDir: string): string | null { - const networkPath = join(profileDir, 'Network', 'Cookies') - if (existsSync(networkPath)) { - return networkPath - } - const legacyPath = join(profileDir, 'Cookies') - if (existsSync(legacyPath)) { - return legacyPath - } - return null -} - function isSafeBrowserProfileDirectory(directory: string): boolean { return ( directory.length > 0 && @@ -373,7 +364,7 @@ export function detectInstalledBrowsers(): DetectedBrowser[] { // Use the first profile with a valid cookies path as the default selection. for (const profile of profiles) { const profileDir = join(root, profile.directory) - const cookiesPath = resolveCookiesPath(profileDir) + const cookiesPath = resolveChromiumCookiesPath(profileDir) if (cookiesPath) { detected.push({ family: browser.family, @@ -434,7 +425,7 @@ export function selectBrowserProfile( return null } const profileDir = join(root, profileDirectory) - const cookiesPath = resolveCookiesPath(profileDir) + const cookiesPath = resolveChromiumCookiesPath(profileDir) if (!cookiesPath) { return null } @@ -1468,37 +1459,6 @@ export async function importCookiesFromBrowser( return importCookiesFromSafari(browser, targetPartition) } - // Why: the browser may hold a lock on the Cookies file. Copying to a temp - // location avoids lock contention and ensures we read a consistent snapshot. - const tmpDir = mkdtempSync(join(tmpdir(), 'orca-cookie-import-')) - const tmpCookiesPath = join(tmpDir, 'Cookies') - - try { - copyFileSync(browser.cookiesPath, tmpCookiesPath) - // Why: when the source browser is running, it uses WAL journal mode. The most - // recently written cookies (including fresh auth tokens) may only exist in the - // WAL sidecar file, not yet flushed to the main DB. Copying WAL + SHM ensures - // our snapshot reflects the browser's current state. - for (const suffix of ['-wal', '-shm'] as const) { - const sidecar = browser.cookiesPath + suffix - if (existsSync(sidecar)) { - try { - copyFileSync(sidecar, tmpCookiesPath + suffix) - } catch { - // Why: sidecar copy is best-effort. The main DB alone may still have - // enough cookies for a usable session; missing the WAL just means - // we might miss the very latest writes. - } - } - } - } catch { - rmSync(tmpDir, { recursive: true, force: true }) - return { - ok: false, - reason: `Could not copy ${browser.label} cookies database. Try closing ${browser.label} first.` - } - } - // Why: Electron's cookies.set() API rejects many valid cookie values (binary // bytes > 0x7F etc). Instead, decrypt from the source browser and write // plaintext directly to the SQLite `value` column. CookieMonster reads @@ -1508,16 +1468,6 @@ export async function importCookiesFromBrowser( // In packaged builds where os_crypt IS active, CookieMonster will re-encrypt // plaintext cookies on its next flush, so this approach is safe in both modes. - // Why: only Chromium browsers reach this point — Firefox/Safari dispatched above. - const sourceKey = getEncryptionKey(browser.keychainService!, browser.keychainAccount!, browser) - if (!sourceKey) { - rmSync(tmpDir, { recursive: true, force: true }) - return { - ok: false, - reason: `Could not access ${browser.label} encryption key. The OS may have denied access.` - } - } - // Why: CookieMonster holds the live DB's data in memory and overwrites it // on flush/shutdown. Writing directly to the live DB is futile. Instead, // copy the live DB to a staging location, populate it there, and let the @@ -1526,13 +1476,14 @@ export async function importCookiesFromBrowser( await targetSession.cookies.flushStore() const partitionName = targetPartition.replace('persist:', '') - const liveCookiesPath = join(app.getPath('userData'), 'Partitions', partitionName, 'Cookies') + const partitionDir = join(app.getPath('userData'), 'Partitions', partitionName) + let liveCookiesPath = resolveChromiumCookiesPath(partitionDir) // Why: Electron only creates the partition's Cookies SQLite file after the // session has actually stored a cookie. For newly created profiles that have // never been used by a webview, the file won't exist yet. Setting and // removing a throwaway cookie forces Electron to initialize the database. - if (!existsSync(liveCookiesPath)) { + if (!liveCookiesPath) { try { await targetSession.cookies.set({ url: 'https://localhost', name: '__init', value: '1' }) await targetSession.cookies.remove('https://localhost', '__init') @@ -1540,10 +1491,10 @@ export async function importCookiesFromBrowser( } catch { // ignore — the set/remove may fail but flushStore should still create the file } + liveCookiesPath = resolveChromiumCookiesPath(partitionDir) } - if (!existsSync(liveCookiesPath)) { - rmSync(tmpDir, { recursive: true, force: true }) + if (!liveCookiesPath) { return { ok: false, reason: 'Target cookie database not found. Open a browser tab first.' } } @@ -1557,17 +1508,44 @@ export async function importCookiesFromBrowser( mkdirSync(stagingDir, { recursive: true }) copyFileSync(liveCookiesPath, stagingCookiesPath) } catch { - rmSync(tmpDir, { recursive: true, force: true }) + // Why: copyFile is not atomic and can leave a partial database after an + // I/O failure, so failed imports must not retain sensitive cookie data. + try { + unlinkSync(stagingCookiesPath) + } catch { + /* best-effort */ + } return { ok: false, reason: 'Could not create staging cookie database.' } } + let sourceSnapshot: ChromiumCookieSnapshot + try { + // Why: the browser can commit cookies only to WAL while it remains open; + // snapshot retries prevent pairing the main DB with a racing WAL generation. + sourceSnapshot = createChromiumCookieSnapshot(browser.cookiesPath) + } catch (err) { + try { + unlinkSync(stagingCookiesPath) + } catch { + /* best-effort */ + } + diag(` Chromium snapshot failed: ${err}`) + return { + ok: false, + reason: `Could not copy ${browser.label} cookies database. Try closing ${browser.label} first.` + } + } + let sourceDb: InstanceType | null = null let stagingDb: InstanceType | null = null try { // Why: Chromium stores timestamps as microseconds since 1601, which can exceed // Number.MAX_SAFE_INTEGER (~9e15). readBigInts ensures no precision loss. - sourceDb = new DatabaseSync(tmpCookiesPath, { readOnly: true, readBigInts: true }) + sourceDb = new DatabaseSync(sourceSnapshot.databasePath, { + readOnly: true, + readBigInts: true + }) stagingDb = new DatabaseSync(stagingCookiesPath) const targetColumnInfo = stagingDb @@ -1590,10 +1568,37 @@ export async function importCookiesFromBrowser( if (sourceRows.length === 0) { stagingDb.close() stagingDb = null - rmSync(tmpDir, { recursive: true, force: true }) + try { + unlinkSync(stagingCookiesPath) + } catch { + /* best-effort */ + } return { ok: false, reason: `No cookies found in ${browser.label}.` } } + const needsSourceKey = sourceRows.some((sourceRow) => { + const encRaw = sourceRow.encrypted_value + return encRaw instanceof Uint8Array && encRaw.length > 0 + }) + const sourceKey = needsSourceKey + ? getEncryptionKey(browser.keychainService!, browser.keychainAccount!, browser) + : null + if (needsSourceKey && !sourceKey) { + stagingDb.close() + stagingDb = null + // Why: key denial happens after staging, so failed retries must not leave + // one full target database copy behind each time. + try { + unlinkSync(stagingCookiesPath) + } catch { + /* best-effort */ + } + return { + ok: false, + reason: `Could not access ${browser.label} encryption key. The OS may have denied access.` + } + } + // Why: Google's integrity cookies (SIDCC, __Secure-*PSIDCC, __Secure-STRP) // are cryptographically bound to the source browser's TLS fingerprint and // environment. Importing them into a different browser causes @@ -1652,7 +1657,7 @@ export async function importCookiesFromBrowser( let decryptedValue: Buffer if (encBuf && encBuf.length > 0) { - const raw = decryptCookieValueRaw(encBuf, sourceKey) + const raw = sourceKey ? decryptCookieValueRaw(encBuf, sourceKey) : null if (!raw) { skipped++ continue @@ -1709,7 +1714,6 @@ export async function importCookiesFromBrowser( stagingDb.close() stagingDb = null - rmSync(tmpDir, { recursive: true, force: true }) diag(` SQLite staging complete: ${imported} cookies, ${domainSet.size} domains`) // Why: clearing the session's in-memory cookie store before loading imported @@ -1795,7 +1799,6 @@ export async function importCookiesFromBrowser( } catch { /* may already be closed */ } - rmSync(tmpDir, { recursive: true, force: true }) // Why: if the import fails after the staging DB was created, clean it up // to avoid a stale staged import being applied on the next cold start. try { @@ -1810,5 +1813,11 @@ export async function importCookiesFromBrowser( `Could not import cookies from ${browser.label}: ${summarizeCookieImportError(err)}.` ) } + } finally { + try { + sourceSnapshot.cleanup() + } catch (err) { + diag(` Chromium snapshot cleanup failed: ${err}`) + } } } diff --git a/src/main/browser/browser-manager.test.ts b/src/main/browser/browser-manager.test.ts index e0c741943c97..c854d1f0acb4 100644 --- a/src/main/browser/browser-manager.test.ts +++ b/src/main/browser/browser-manager.test.ts @@ -1,4 +1,5 @@ /* oxlint-disable max-lines */ +import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -129,7 +130,7 @@ describe('browserManager', () => { expect(shellOpenExternalMock).toHaveBeenCalledWith('http://localhost:3000/') }) - it('routes safe popup URLs into a new Orca browser tab for the owning renderer', () => { + it('allows registered safe popup URLs as Electron child windows', () => { const rendererSendMock = vi.fn() const guest = { id: 103, @@ -160,18 +161,84 @@ describe('browserManager', () => { const handler = guestSetWindowOpenHandlerMock.mock.calls[0][0] as (details: { url: string - }) => { action: 'deny' } - expect(handler({ url: 'https://example.com/login' })).toEqual({ action: 'deny' }) + features?: string + }) => { action: 'allow' | 'deny' } + expect(handler({ url: 'about:blank' })).toMatchObject({ action: 'allow' }) + expect( + handler({ + url: 'https://example.com/login', + features: 'alwaysOnTop=yes,frame=no,fullscreen=yes,kiosk=yes,modal=yes,transparent=yes' + }) + ).toEqual({ + action: 'allow', + overrideBrowserWindowOptions: { + alwaysOnTop: false, + closable: true, + focusable: true, + frame: true, + fullscreen: false, + kiosk: false, + modal: false, + movable: true, + opacity: 1, + show: true, + simpleFullscreen: false, + skipTaskbar: false, + titleBarStyle: 'default', + transparent: false + } + }) expect(shellOpenExternalMock).not.toHaveBeenCalled() - expect(rendererSendMock).toHaveBeenCalledWith('browser:open-link-in-orca-tab', { + expect(rendererSendMock).not.toHaveBeenCalled() + }) + + it('blocks unsafe popup URLs for registered guests', () => { + const rendererSendMock = vi.fn() + const guest = { + id: 106, + isDestroyed: vi.fn(() => false), + getType: vi.fn(() => 'webview'), + setBackgroundThrottling: guestSetBackgroundThrottlingMock, + setWindowOpenHandler: guestSetWindowOpenHandlerMock, + on: guestOnMock, + off: guestOffMock, + openDevTools: guestOpenDevToolsMock + } + webContentsFromIdMock.mockImplementation((id: number) => { + if (id === guest.id) { + return guest + } + if (id === rendererWebContentsId) { + return { isDestroyed: vi.fn(() => false), send: rendererSendMock } + } + return null + }) + + browserManager.attachGuestPolicies(guest as never) + browserManager.registerGuest({ browserPageId: 'browser-1', - url: 'https://example.com/login' + webContentsId: guest.id, + rendererWebContentsId }) + + const handler = guestSetWindowOpenHandlerMock.mock.calls[0][0] as (details: { + url: string + }) => { action: 'allow' | 'deny' } + expect(handler({ url: 'javascript:alert(1)' })).toEqual({ action: 'deny' }) + expect(handler({ url: 'file:///etc/passwd' })).toEqual({ action: 'deny' }) + expect(handler({ url: 'file:///C:/Users/example/.ssh/id_rsa' })).toEqual({ action: 'deny' }) + expect(handler({ url: 'file://server/share/private.txt' })).toEqual({ action: 'deny' }) + + expect(shellOpenExternalMock).not.toHaveBeenCalled() + expect(rendererSendMock).not.toHaveBeenCalledWith( + 'browser:open-link-in-orca-tab', + expect.anything() + ) expect(rendererSendMock).toHaveBeenCalledWith('browser:popup', { browserPageId: 'browser-1', - origin: 'https://example.com', - action: 'opened-in-orca' + origin: 'null', + action: 'blocked' }) }) @@ -855,6 +922,202 @@ describe('browserManager', () => { expect(guestSetWindowOpenHandlerMock).toHaveBeenCalledTimes(1) expect(guestOnMock.mock.calls.filter(([event]) => event === 'will-navigate')).toHaveLength(1) expect(guestOnMock.mock.calls.filter(([event]) => event === 'will-redirect')).toHaveLength(1) + expect(guestOnMock.mock.calls.filter(([event]) => event === 'did-create-window')).toHaveLength( + 1 + ) + }) + + it('attaches guest policies to created popup child windows', () => { + const rendererSendMock = vi.fn() + const childSetBackgroundThrottlingMock = vi.fn() + const childSetWindowOpenHandlerMock = vi.fn() + const childOnMock = vi.fn() + const childOffMock = vi.fn() + const childOpenDevToolsMock = vi.fn() + const childGuest = { + id: 4040, + isDestroyed: vi.fn(() => false), + getType: vi.fn(() => 'webview'), + setBackgroundThrottling: childSetBackgroundThrottlingMock, + setWindowOpenHandler: childSetWindowOpenHandlerMock, + on: childOnMock, + off: childOffMock, + openDevTools: childOpenDevToolsMock + } + const guest = { + id: 404, + isDestroyed: vi.fn(() => false), + getType: vi.fn(() => 'webview'), + setBackgroundThrottling: guestSetBackgroundThrottlingMock, + setWindowOpenHandler: guestSetWindowOpenHandlerMock, + on: guestOnMock, + off: guestOffMock, + openDevTools: guestOpenDevToolsMock + } + webContentsFromIdMock.mockImplementation((id: number) => { + if (id === guest.id) { + return guest + } + if (id === rendererWebContentsId) { + return { isDestroyed: vi.fn(() => false), send: rendererSendMock } + } + return null + }) + + browserManager.attachGuestPolicies(guest as never) + browserManager.registerGuest({ + browserPageId: 'browser-1', + webContentsId: guest.id, + rendererWebContentsId + }) + + const didCreateWindowHandler = guestOnMock.mock.calls.find( + ([event]) => event === 'did-create-window' + )?.[1] as ((window: { webContents: typeof childGuest }) => void) | undefined + expect(didCreateWindowHandler).toBeTypeOf('function') + + didCreateWindowHandler?.({ webContents: childGuest }) + + expect(childSetBackgroundThrottlingMock).toHaveBeenCalledWith(false) + expect(childSetWindowOpenHandlerMock).toHaveBeenCalledTimes(1) + expect(childOnMock.mock.calls.filter(([event]) => event === 'did-create-window')).toHaveLength( + 1 + ) + expect(childOnMock.mock.calls.filter(([event]) => event === 'will-navigate')).toHaveLength(1) + expect(childOnMock.mock.calls.filter(([event]) => event === 'will-redirect')).toHaveLength(1) + + const childWindowOpenHandler = childSetWindowOpenHandlerMock.mock.calls[0][0] as (details: { + url: string + }) => { action: 'allow' | 'deny' } + expect(childWindowOpenHandler({ url: 'https://identity.example.com/login' })).toMatchObject({ + action: 'allow' + }) + expect(childWindowOpenHandler({ url: 'file:///etc/passwd' })).toEqual({ action: 'deny' }) + expect(rendererSendMock).toHaveBeenCalledWith('browser:popup', { + browserPageId: 'browser-1', + origin: 'null', + action: 'blocked' + }) + browserManager.notifyPermissionDenied({ + guestWebContentsId: childGuest.id, + permission: 'notifications', + rawUrl: 'https://identity.example.com/login' + }) + expect(rendererSendMock).toHaveBeenCalledWith('browser:permission-denied', { + browserPageId: 'browser-1', + permission: 'notifications', + origin: 'https://identity.example.com' + }) + + const childDidFailLoadHandler = childOnMock.mock.calls.find( + ([event]) => event === 'did-fail-load' + )?.[1] as + | (( + event: Electron.Event, + errorCode: number, + errorDescription: string, + validatedURL: string, + isMainFrame: boolean + ) => void) + | undefined + childDidFailLoadHandler?.( + {} as Electron.Event, + -105, + 'Name not resolved', + 'https://identity.example.com/unavailable', + true + ) + expect(rendererSendMock).not.toHaveBeenCalledWith( + 'browser:guest-load-failed', + expect.anything() + ) + + const childDownloadItem = createDownloadItem() + browserManager.handleGuestWillDownload({ + guestWebContentsId: childGuest.id, + item: childDownloadItem + }) + expect(rendererSendMock).toHaveBeenCalledWith( + 'browser:download-requested', + expect.objectContaining({ browserPageId: 'browser-1' }) + ) + const childDownloadDoneHandler = getDownloadItemEventHandler(childDownloadItem, 'once', 'done') + childDownloadDoneHandler?.({} as Electron.Event, 'completed') + + const managerState = browserManager as unknown as { + popupOwnerContextByGuestId: Map + } + expect(managerState.popupOwnerContextByGuestId.has(childGuest.id)).toBe(true) + + const cleanupChildOnMock = vi.fn() + const cleanupChildGuest = { + ...childGuest, + id: 4041, + on: cleanupChildOnMock, + off: vi.fn(), + setBackgroundThrottling: vi.fn(), + setWindowOpenHandler: vi.fn() + } + const childDidCreateWindowHandler = childOnMock.mock.calls.find( + ([event]) => event === 'did-create-window' + )?.[1] as ((window: { webContents: typeof cleanupChildGuest }) => void) | undefined + childDidCreateWindowHandler?.({ webContents: cleanupChildGuest }) + expect(managerState.popupOwnerContextByGuestId.has(cleanupChildGuest.id)).toBe(true) + const cleanupChildWindowOpenHandler = cleanupChildGuest.setWindowOpenHandler.mock + .calls[0][0] as (details: { url: string }) => { action: 'allow' | 'deny' } + expect( + cleanupChildWindowOpenHandler({ url: 'https://identity.example.com/continue' }) + ).toMatchObject({ action: 'allow' }) + const cleanupChildDestroyedHandler = cleanupChildOnMock.mock.calls.find( + ([event]) => event === 'destroyed' + )?.[1] as (() => void) | undefined + cleanupChildDestroyedHandler?.() + expect(managerState.popupOwnerContextByGuestId.has(cleanupChildGuest.id)).toBe(false) + + const replacementGuest = { + ...guest, + id: 405, + on: vi.fn(), + off: vi.fn(), + setBackgroundThrottling: vi.fn(), + setWindowOpenHandler: vi.fn() + } + webContentsFromIdMock.mockImplementation((id: number) => { + if (id === guest.id) { + return guest + } + if (id === replacementGuest.id) { + return replacementGuest + } + if (id === rendererWebContentsId) { + return { isDestroyed: vi.fn(() => false), send: rendererSendMock } + } + return null + }) + browserManager.attachGuestPolicies(replacementGuest as never) + browserManager.registerGuest({ + browserPageId: 'browser-1', + webContentsId: replacementGuest.id, + rendererWebContentsId + }) + + expect(childWindowOpenHandler({ url: 'https://identity.example.com/next' })).toEqual({ + action: 'deny' + }) + expect(shellOpenExternalMock).toHaveBeenCalledWith('https://identity.example.com/next') + expect(managerState.popupOwnerContextByGuestId.has(childGuest.id)).toBe(false) + + const childDestroyedHandler = childOnMock.mock.calls.find( + ([event]) => event === 'destroyed' + )?.[1] as (() => void) | undefined + childDestroyedHandler?.() + expect(managerState.popupOwnerContextByGuestId.has(childGuest.id)).toBe(false) + + browserManager.unregisterAll() + + expect(childOffMock).toHaveBeenCalledWith('did-create-window', expect.any(Function)) + expect(childOffMock).toHaveBeenCalledWith('will-navigate', expect.any(Function)) + expect(childOffMock).toHaveBeenCalledWith('will-redirect', expect.any(Function)) }) it('cleans attached guest policy state when a guest is destroyed before registration', () => { @@ -1068,11 +1331,11 @@ describe('browserManager', () => { origin: 'https://example.com', totalBytes: 2048, mimeType: 'text/csv', - savePath: '/downloads/report.csv', + savePath: join('/downloads', 'report.csv'), status: 'downloading' }) ) - expect(item.setSavePath).toHaveBeenCalledWith('/downloads/report.csv') + expect(item.setSavePath).toHaveBeenCalledWith(join('/downloads', 'report.csv')) }) it('sets the download save path immediately and reports progress and completion', () => { @@ -1106,7 +1369,7 @@ describe('browserManager', () => { }) browserManager.handleGuestWillDownload({ guestWebContentsId: guest.id, item }) - expect(item.setSavePath).toHaveBeenCalledWith('/downloads/report.csv') + expect(item.setSavePath).toHaveBeenCalledWith(join('/downloads', 'report.csv')) expect(item.on).toHaveBeenCalledWith('updated', expect.any(Function)) expect(item.once).toHaveBeenCalledWith('done', expect.any(Function)) expect(rendererSendMock).toHaveBeenCalledWith( @@ -1114,7 +1377,7 @@ describe('browserManager', () => { expect.objectContaining({ browserPageId: 'browser-1', filename: 'report.csv', - savePath: '/downloads/report.csv', + savePath: join('/downloads', 'report.csv'), status: 'downloading' }) ) @@ -1139,7 +1402,7 @@ describe('browserManager', () => { expect.objectContaining({ browserPageId: 'browser-1', status: 'completed', - savePath: '/downloads/report.csv', + savePath: join('/downloads', 'report.csv'), error: null }) ) diff --git a/src/main/browser/browser-manager.ts b/src/main/browser/browser-manager.ts index 99c91f29e499..18cddd8c78c7 100644 --- a/src/main/browser/browser-manager.ts +++ b/src/main/browser/browser-manager.ts @@ -5,6 +5,7 @@ in one file avoids scattering the browser security boundary across modules. */ import { randomUUID } from 'node:crypto' import { shell, webContents } from 'electron' +import { ORCA_BROWSER_BLANK_URL } from '../../shared/constants' import { normalizeBrowserNavigationUrl, normalizeExternalBrowserUrl, @@ -140,6 +141,27 @@ export type BrowserGuestRegistration = { type PendingPermissionEvent = Omit type PendingPopupEvent = Omit type BrowserDownloadDoneState = 'completed' | 'cancelled' | 'interrupted' +type PopupOwnerContext = { + browserTabId: string + rootGuestWebContentsId: number +} + +const SAFE_POPUP_WINDOW_OPTIONS = { + alwaysOnTop: false, + closable: true, + focusable: true, + frame: true, + fullscreen: false, + kiosk: false, + modal: false, + movable: true, + opacity: 1, + show: true, + simpleFullscreen: false, + skipTaskbar: false, + titleBarStyle: 'default', + transparent: false +} satisfies Electron.BrowserWindowConstructorOptions type ActiveDownload = { downloadId: string @@ -181,6 +203,7 @@ export class BrowserManager { // Why: reverse map enables O(1) guest→tab lookups instead of O(N) linear // scans on every mouse event, load failure, permission, and popup event. private readonly tabIdByWebContentsId = new Map() + private readonly popupOwnerContextByGuestId = new Map() // Why: guest registration is keyed by browser page id, but renderer // visibility/focus state is keyed by browser workspace id. Screenshot prep // has to bridge that mismatch to activate the right tab before capture. @@ -293,7 +316,23 @@ export class BrowserManager { } private resolveBrowserTabIdForGuestWebContentsId(guestWebContentsId: number): string | null { - return this.tabIdByWebContentsId.get(guestWebContentsId) ?? null + return this.resolvePopupOwnerContext(guestWebContentsId)?.browserTabId ?? null + } + + private resolvePopupOwnerContext(guestWebContentsId: number): PopupOwnerContext | null { + const browserTabId = this.tabIdByWebContentsId.get(guestWebContentsId) + if (browserTabId) { + return { browserTabId, rootGuestWebContentsId: guestWebContentsId } + } + const inherited = this.popupOwnerContextByGuestId.get(guestWebContentsId) + if ( + inherited && + this.webContentsIdByTabId.get(inherited.browserTabId) === inherited.rootGuestWebContentsId + ) { + return inherited + } + this.popupOwnerContextByGuestId.delete(guestWebContentsId) + return null } private resolveRendererForBrowserTab(browserTabId: string): Electron.WebContents | null { @@ -558,11 +597,17 @@ export class BrowserManager { } } - attachGuestPolicies(guest: Electron.WebContents): void { + attachGuestPolicies( + guest: Electron.WebContents, + inheritedOwnerContext: PopupOwnerContext | null = null + ): void { if (this.policyAttachedGuestIds.has(guest.id)) { return } this.policyAttachedGuestIds.add(guest.id) + if (inheritedOwnerContext) { + this.popupOwnerContextByGuestId.set(guest.id, inheritedOwnerContext) + } // Why: Cloudflare Turnstile and similar bot detectors probe browser APIs // (navigator.webdriver, plugins, window.chrome) that differ in Electron @@ -575,22 +620,24 @@ export class BrowserManager { // Orca window is not the focused foreground app. With throttling enabled, // the compositor stops producing frames and capturePage() returns empty. guest.setBackgroundThrottling(false) + const handleDidCreateWindow = (window: Electron.BrowserWindow): void => { + // Why: popup descendants inherit the opener's owner context for routing, + // but must not replace its primary guest registration. + this.attachGuestPolicies(window.webContents, this.resolvePopupOwnerContext(guest.id)) + } + guest.on('did-create-window', handleDidCreateWindow) guest.setWindowOpenHandler(({ url }) => { const browserTabId = this.resolveBrowserTabIdForGuestWebContentsId(guest.id) const browserUrl = normalizeBrowserNavigationUrl(url) const externalUrl = normalizeExternalBrowserUrl(url) - // Why: popup-capable guests are required for OAuth and target=_blank - // flows, but Orca still does not host child windows itself. For normal - // web URLs, route the request into Orca's own browser-tab model first so - // the user stays in the IDE. Only fall back to the system browser when - // Orca cannot safely host the destination or when the guest is not yet - // associated with a trusted browser tab/renderer. - if (browserTabId && browserUrl && this.openLinkInOrcaTab(browserTabId, browserUrl)) { - this.forwardOrQueuePopupEvent(guest.id, { - origin: safeOrigin(browserUrl), - action: 'opened-in-orca' - }) + // Why: file URLs are valid for user-opened in-pane previews, but remote + // content must not create native child windows targeting local paths. + const canOpenAsChild = Boolean(externalUrl || browserUrl === ORCA_BROWSER_BLANK_URL) + if (browserTabId && canOpenAsChild) { + // Why: OAuth may request ordinary size/position features, but browser + // content must not create deceptive or inescapable native chrome. + return { action: 'allow', overrideBrowserWindowOptions: SAFE_POPUP_WINDOW_OPTIONS } } else if (externalUrl) { // Why: a target=_blank click on a Kagi search result page produces a // popup URL that still contains the bearer token; redact before @@ -671,6 +718,7 @@ export class BrowserManager { disposeAntiDetection() try { guest.off('destroyed', handleDestroyed) + guest.off('did-create-window', handleDidCreateWindow) } catch { // guest may already be destroyed } @@ -687,17 +735,28 @@ export class BrowserManager { // swaps renderer processes. Late events from the dead guest must stop // resolving to the live page, or stale download/popup/permission callbacks // can be delivered to the wrong session after the swap. - this.tabIdByWebContentsId.delete(previousWebContentsId) this.cleanupGuestPolicyAttachment(previousWebContentsId) + this.tabIdByWebContentsId.delete(previousWebContentsId) } private cleanupGuestPolicyAttachment(guestWebContentsId: number): void { + const isPrimaryGuest = this.tabIdByWebContentsId.has(guestWebContentsId) const policyCleanup = this.policyCleanupByGuestId.get(guestWebContentsId) if (policyCleanup) { policyCleanup() this.policyCleanupByGuestId.delete(guestWebContentsId) } this.policyAttachedGuestIds.delete(guestWebContentsId) + this.popupOwnerContextByGuestId.delete(guestWebContentsId) + // Why: a popup must stop inheriting authorization as soon as its primary + // owner is retired, even if Chromium has not destroyed the child yet. + if (isPrimaryGuest) { + for (const [popupGuestId, owner] of this.popupOwnerContextByGuestId) { + if (owner.rootGuestWebContentsId === guestWebContentsId) { + this.popupOwnerContextByGuestId.delete(popupGuestId) + } + } + } this.pendingLoadFailuresByGuestId.delete(guestWebContentsId) this.pendingPermissionEventsByGuestId.delete(guestWebContentsId) this.pendingPopupEventsByGuestId.delete(guestWebContentsId) @@ -883,6 +942,7 @@ export class BrowserManager { } this.policyCleanupByGuestId.clear() this.tabIdByWebContentsId.clear() + this.popupOwnerContextByGuestId.clear() this.worktreeIdByTabId.clear() this.sessionProfileIdByPageId.clear() this.pendingLoadFailuresByGuestId.clear() @@ -1773,26 +1833,6 @@ export class BrowserManager { } }) } - - private openLinkInOrcaTab(browserTabId: string, rawUrl: string): boolean { - const renderer = this.resolveRendererForBrowserTab(browserTabId) - if (!renderer) { - return false - } - const normalizedUrl = normalizeBrowserNavigationUrl(rawUrl) - if (!normalizedUrl || normalizedUrl === 'about:blank') { - return false - } - // Why: the guest context menu knows which browser tab the click came from, - // but only the renderer owns the worktree/tab model. Forward the validated - // URL back to that renderer so it can open a sibling Orca browser tab in - // the same worktree without letting the guest process mutate app state. - renderer.send('browser:open-link-in-orca-tab', { - browserPageId: browserTabId, - url: normalizedUrl - }) - return true - } } export const browserManager = new BrowserManager() diff --git a/src/main/browser/browser-session-permission-policy.ts b/src/main/browser/browser-session-permission-policy.ts index a66e27980e35..895161db9e36 100644 --- a/src/main/browser/browser-session-permission-policy.ts +++ b/src/main/browser/browser-session-permission-policy.ts @@ -9,7 +9,10 @@ const AUTO_GRANTED_BROWSER_PERMISSIONS = new Set([ 'notifications', // Chromium can request this at runtime even though Electron's TS union does // not list it; chatgpt.com uses it to keep browser storage from eviction. - 'persistent-storage' + 'persistent-storage', + // Chromium still requires user activation, so this only removes Orca's + // otherwise unactionable denial for immersive browser apps. + 'pointerLock' ]) export function isAutoGrantedBrowserSessionPermission(permission: string): boolean { diff --git a/src/main/browser/browser-session-registry.persistence.test.ts b/src/main/browser/browser-session-registry.persistence.test.ts index 121df82de6da..583afff08155 100644 --- a/src/main/browser/browser-session-registry.persistence.test.ts +++ b/src/main/browser/browser-session-registry.persistence.test.ts @@ -157,6 +157,54 @@ describe('BrowserSessionRegistry persistence', () => { expect(fsState.present.has('/user-data/Partitions/orca-browser/Cookies')).toBe(true) }) + it('replays pending cookies into an existing Network database', async () => { + const stagedPath = '/staged/network-import' + const networkPath = '/user-data/Partitions/orca-browser/Network/Cookies' + const legacyPath = '/user-data/Partitions/orca-browser/Cookies' + const fsState = createFsState() + seedMeta(fsState, { + defaultSource: null, + userAgent: null, + pendingCookieDbPath: stagedPath, + profiles: [] + }) + fsState.files.set(stagedPath, 'imported cookies') + fsState.files.set(networkPath, 'old cookies') + fsState.present.add(stagedPath) + fsState.present.add(networkPath) + + installModuleMocks(fsState) + const { browserSessionRegistry } = await import('./browser-session-registry') + + browserSessionRegistry.applyPendingCookieImport() + + expect(fsState.files.get(networkPath)).toBe('imported cookies') + expect(fsState.present.has(legacyPath)).toBe(false) + }) + + it('persists new browser session profiles under the active Orca profile directory', async () => { + const fsState = createFsState() + const profileMetaPath = '/user-data/profiles/local-work/browser-session-meta.json' + + installModuleMocks(fsState) + const { browserSessionRegistry } = await import('./browser-session-registry') + + browserSessionRegistry.configureForOrcaProfile({ + orcaProfileId: 'local-work', + profileDirectory: '/user-data/profiles/local-work' + }) + const profile = browserSessionRegistry.createProfile('isolated', 'Work Browser') + + expect(profile).not.toBeNull() + expect(fsState.files.has(profileMetaPath)).toBe(true) + expect(fsState.files.has(META_PATH)).toBe(false) + expect(JSON.parse(fsState.files.get(profileMetaPath) ?? '{}').profiles[0]).toMatchObject({ + id: profile!.id, + partition: profile!.partition, + label: 'Work Browser' + }) + }) + it('merges partition-keyed pending entries without clobbering unrelated entries', async () => { const fsState = createFsState() seedMeta(fsState, { diff --git a/src/main/browser/browser-session-registry.test.ts b/src/main/browser/browser-session-registry.test.ts index 363094775c70..8d81590ae5cf 100644 --- a/src/main/browser/browser-session-registry.test.ts +++ b/src/main/browser/browser-session-registry.test.ts @@ -28,6 +28,11 @@ vi.mock('./browser-manager', () => ({ import { browserSessionRegistry } from './browser-session-registry' import { setupClientHintsOverride } from './browser-session-ua' import { ORCA_BROWSER_PARTITION } from '../../shared/constants' +import { + DEFAULT_LOCAL_ORCA_PROFILE_ID, + getOrcaProfileBrowserDefaultPartition, + getOrcaProfileBrowserSessionPartition +} from '../../shared/orca-profiles' describe('BrowserSessionRegistry', () => { beforeEach(() => { @@ -201,6 +206,20 @@ describe('BrowserSessionRegistry', () => { expect(mockSession?.setDevicePermissionHandler).toHaveBeenCalled() }) + it('auto-grants pointer lock for browser partitions', () => { + browserSessionRegistry.createProfile('isolated', 'Pointer Lock Test') + const mockSession = sessionFromPartitionMock.mock.results[0]?.value + const requestHandler = mockSession.setPermissionRequestHandler.mock.calls[0][0] + const checkHandler = mockSession.setPermissionCheckHandler.mock.calls[0][0] + const callback = vi.fn() + const guestWc = { id: 7, getURL: vi.fn(() => 'https://example.com/') } + + requestHandler(guestWc, 'pointerLock', callback, {}) + + expect(callback).toHaveBeenCalledWith(true) + expect(checkHandler(null, 'pointerLock', '', {})).toBe(true) + }) + it('routes media permission requests through macOS TCC for isolated partitions', async () => { // Why: verify the parallel fix to the default partition — isolated/imported // profiles must also defer media permission checks to macOS instead of @@ -280,6 +299,30 @@ describe('BrowserSessionRegistry', () => { expect(webAuthnCallback).toHaveBeenCalledWith('credential-1') }) + it('uses profile-owned partitions for non-default Orca profiles', () => { + const orcaProfileId = 'local-work' + browserSessionRegistry.configureForOrcaProfile({ + orcaProfileId, + profileDirectory: '/profiles/local-work' + }) + + expect(browserSessionRegistry.getDefaultProfile().partition).toBe( + getOrcaProfileBrowserDefaultPartition(orcaProfileId) + ) + expect(browserSessionRegistry.isAllowedPartition(ORCA_BROWSER_PARTITION)).toBe(false) + + const profile = browserSessionRegistry.createProfile('isolated', 'Work Browser') + expect(profile).not.toBeNull() + expect(profile!.partition).toBe( + getOrcaProfileBrowserSessionPartition(orcaProfileId, profile!.id) + ) + + browserSessionRegistry.configureForOrcaProfile({ + orcaProfileId: DEFAULT_LOCAL_ORCA_PROFILE_ID, + profileDirectory: '/profiles/local-default' + }) + }) + describe('setupClientHintsOverride', () => { it('overrides sec-ch-ua headers for Edge UA', () => { const onBeforeSendHeaders = vi.fn() diff --git a/src/main/browser/browser-session-registry.ts b/src/main/browser/browser-session-registry.ts index 98b944de7294..3603de11568f 100644 --- a/src/main/browser/browser-session-registry.ts +++ b/src/main/browser/browser-session-registry.ts @@ -14,12 +14,19 @@ import { unlinkSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import { ORCA_BROWSER_PARTITION } from '../../shared/constants' +import { + DEFAULT_LOCAL_ORCA_PROFILE_ID, + getOrcaProfileBrowserDefaultPartition, + getOrcaProfileBrowserPartitionSegment, + getOrcaProfileBrowserSessionPartition +} from '../../shared/orca-profiles' import type { BrowserSessionProfile, BrowserSessionProfileScope } from '../../shared/types' import { browserManager } from './browser-manager' import { hasSystemMediaAccess, requestSystemMediaAccess } from './browser-media-access' import { cleanElectronUserAgent, setupClientHintsOverride } from './browser-session-ua' +import { resolveChromiumCookiesPath } from './chromium-cookie-path' import { isAutoGrantedBrowserSessionPermission } from './browser-session-permission-policy' import { allowsBrowserWebAuthnPermission, @@ -36,6 +43,15 @@ type BrowserSessionMeta = { profiles: BrowserSessionProfile[] } +export type BrowserSessionRegistryProfileOptions = { + orcaProfileId: string + profileDirectory: string +} + +const BROWSER_SESSION_META_FILE_NAME = 'browser-session-meta.json' +const LEGACY_BROWSER_SESSION_PARTITION_RE = + /^persist:orca-browser-session-[\da-f-]{8}-[\da-f-]{4}-[\da-f-]{4}-[\da-f-]{4}-[\da-f-]{12}$/ + // Why: the registry is the single source of truth for which Electron partitions // are valid. will-attach-webview consults it to decide whether a guest's // requested partition is allowed. This prevents a compromised renderer from @@ -43,13 +59,28 @@ type BrowserSessionMeta = { class BrowserSessionRegistry { private readonly profiles = new Map() + private activeOrcaProfileId = DEFAULT_LOCAL_ORCA_PROFILE_ID + private metadataPathOverride: string | null = null + private defaultPartition = ORCA_BROWSER_PARTITION constructor() { + this.resetDefaultProfile() + } + + configureForOrcaProfile(options: BrowserSessionRegistryProfileOptions): void { + this.activeOrcaProfileId = options.orcaProfileId + this.metadataPathOverride = join(options.profileDirectory, BROWSER_SESSION_META_FILE_NAME) + this.defaultPartition = getOrcaProfileBrowserDefaultPartition(options.orcaProfileId) + this.profiles.clear() + this.resetDefaultProfile() + } + + private resetDefaultProfile(): void { const persisted = this.loadPersistedSource() this.profiles.set('default', { id: 'default', scope: 'default', - partition: ORCA_BROWSER_PARTITION, + partition: this.defaultPartition, label: 'Default', source: persisted }) @@ -60,7 +91,9 @@ class BrowserSessionRegistry { // status. Cookies themselves persist in the Electron partition's SQLite DB, // but the registry is in-memory only. private get metadataPath(): string { - return join(app.getPath('userData'), 'browser-session-meta.json') + return ( + this.metadataPathOverride ?? join(app.getPath('userData'), BROWSER_SESSION_META_FILE_NAME) + ) } private loadPersistedSource(): BrowserSessionProfile['source'] { @@ -69,7 +102,10 @@ class BrowserSessionRegistry { private static partitionCookiesPath(partition: string): string { const partitionName = partition.replace('persist:', '') - return join(app.getPath('userData'), 'Partitions', partitionName, 'Cookies') + const partitionDir = join(app.getPath('userData'), 'Partitions', partitionName) + // Why: replay must overwrite the same modern or legacy database that the + // importing Electron partition already uses. + return resolveChromiumCookiesPath(partitionDir) ?? join(partitionDir, 'Cookies') } // Why: write-to-temp-then-rename is atomic on all supported platforms. @@ -78,6 +114,7 @@ class BrowserSessionRegistry { try { const existing = this.loadPersistedMeta() const tmpPath = `${this.metadataPath}.tmp` + mkdirSync(dirname(this.metadataPath), { recursive: true }) writeFileSync(tmpPath, JSON.stringify({ ...existing, ...updates })) renameSync(tmpPath, this.metadataPath) } catch { @@ -108,8 +145,8 @@ class BrowserSessionRegistry { data && typeof data.userAgentByPartition === 'object' && data.userAgentByPartition ? { ...data.userAgentByPartition } : {} - if (legacyUserAgent && !userAgentByPartition[ORCA_BROWSER_PARTITION]) { - userAgentByPartition[ORCA_BROWSER_PARTITION] = legacyUserAgent + if (legacyUserAgent && !userAgentByPartition[this.defaultPartition]) { + userAgentByPartition[this.defaultPartition] = legacyUserAgent } const legacyPendingCookieDbPath = @@ -118,8 +155,8 @@ class BrowserSessionRegistry { data && typeof data.pendingCookieImports === 'object' && data.pendingCookieImports ? { ...data.pendingCookieImports } : {} - if (legacyPendingCookieDbPath && !pendingCookieImports[ORCA_BROWSER_PARTITION]) { - pendingCookieImports[ORCA_BROWSER_PARTITION] = legacyPendingCookieDbPath + if (legacyPendingCookieDbPath && !pendingCookieImports[this.defaultPartition]) { + pendingCookieImports[this.defaultPartition] = legacyPendingCookieDbPath } return { defaultSource: data?.defaultSource ?? null, @@ -168,10 +205,10 @@ class BrowserSessionRegistry { // hydrateFromPersisted skips the default partition and createProfile never // targets it. Without this, clipboard permissions and other guest policies // are denied by default in the default browser partition. - this.setupSessionPolicies(ORCA_BROWSER_PARTITION) + this.setupSessionPolicies(this.defaultPartition) const partitions = new Set([ - ORCA_BROWSER_PARTITION, + this.defaultPartition, ...this.listProfiles().map((p) => p.partition) ]) for (const partition of partitions) { @@ -208,9 +245,9 @@ class BrowserSessionRegistry { } // Why: replay writes to partition-derived file paths, so corrupted // metadata must pass the same validation as the webview allowlist. - const knownPartitions = new Set([ORCA_BROWSER_PARTITION]) + const knownPartitions = new Set([this.defaultPartition]) for (const profile of meta.profiles) { - if (BrowserSessionRegistry.isValidPersistedProfile(profile)) { + if (this.isValidPersistedProfile(profile)) { knownPartitions.add(profile.partition) } } @@ -270,7 +307,7 @@ class BrowserSessionRegistry { } this.persistMeta({ pendingCookieImports: remainingEntries, - pendingCookieDbPath: remainingEntries[ORCA_BROWSER_PARTITION] ?? null + pendingCookieDbPath: remainingEntries[this.defaultPartition] ?? null }) } catch { // best-effort — if this fails, CookieMonster loads the old DB @@ -282,7 +319,7 @@ class BrowserSessionRegistry { const pendingCookieImports = { ...meta.pendingCookieImports, [partition]: stagingDbPath } this.persistMeta({ pendingCookieImports, - pendingCookieDbPath: pendingCookieImports[ORCA_BROWSER_PARTITION] ?? null + pendingCookieDbPath: pendingCookieImports[this.defaultPartition] ?? null }) } @@ -296,7 +333,7 @@ class BrowserSessionRegistry { } this.persistMeta({ userAgentByPartition, - userAgent: userAgentByPartition[ORCA_BROWSER_PARTITION] ?? null + userAgent: userAgentByPartition[this.defaultPartition] ?? null }) } @@ -313,7 +350,7 @@ class BrowserSessionRegistry { } isAllowedPartition(partition: string): boolean { - if (partition === ORCA_BROWSER_PARTITION) { + if (partition === this.defaultPartition) { return true } return [...this.profiles.values()].some((p) => p.partition === partition) @@ -321,14 +358,17 @@ class BrowserSessionRegistry { resolvePartition(profileId: string | null | undefined): string { if (!profileId) { - return ORCA_BROWSER_PARTITION + return this.defaultPartition } - return this.profiles.get(profileId)?.partition ?? ORCA_BROWSER_PARTITION + return this.profiles.get(profileId)?.partition ?? this.defaultPartition } resolveKnownPartition(profileId: string | null | undefined): string | null { if (!profileId) { - return ORCA_BROWSER_PARTITION + // Why: must track the active Orca profile's default partition, not the + // legacy constant, or non-default profiles would resolve local-default's + // cookie jar. + return this.defaultPartition } return this.profiles.get(profileId)?.partition ?? null } @@ -336,7 +376,7 @@ class BrowserSessionRegistry { createProfile(scope: BrowserSessionProfileScope, label: string): BrowserSessionProfile | null { // Why: only the constructor may create the default profile. Allowing the // renderer to pass scope:'default' would create a second profile sharing - // ORCA_BROWSER_PARTITION, causing confusion on delete (clearing storage + // the active default partition, causing confusion on delete (clearing storage // for the shared partition). if (scope === 'default') { return null @@ -345,7 +385,7 @@ class BrowserSessionRegistry { // Why: partition names are deterministic from the profile id so main can // reconstruct the allowlist on restart from persisted profile metadata // without needing a separate partition→profile mapping. - const partition = `persist:orca-browser-session-${id}` + const partition = getOrcaProfileBrowserSessionPartition(this.activeOrcaProfileId, id) const profile: BrowserSessionProfile = { id, scope, @@ -391,9 +431,9 @@ class BrowserSessionRegistry { delete userAgentByPartition[profile.partition] this.persistMeta({ pendingCookieImports, - pendingCookieDbPath: pendingCookieImports[ORCA_BROWSER_PARTITION] ?? null, + pendingCookieDbPath: pendingCookieImports[this.defaultPartition] ?? null, userAgentByPartition, - userAgent: userAgentByPartition[ORCA_BROWSER_PARTITION] ?? null + userAgent: userAgentByPartition[this.defaultPartition] ?? null }) // Why: clearing the partition's storage prevents orphaned cookies/cache from @@ -423,9 +463,9 @@ class BrowserSessionRegistry { } const meta = this.loadPersistedMeta() const pendingCookieImports = { ...meta.pendingCookieImports } - delete pendingCookieImports[ORCA_BROWSER_PARTITION] + delete pendingCookieImports[this.defaultPartition] const userAgentByPartition = { ...meta.userAgentByPartition } - delete userAgentByPartition[ORCA_BROWSER_PARTITION] + delete userAgentByPartition[this.defaultPartition] this.persistMeta({ defaultSource: null, userAgent: null, @@ -434,7 +474,7 @@ class BrowserSessionRegistry { pendingCookieImports }) - const sess = session.fromPartition(ORCA_BROWSER_PARTITION) + const sess = session.fromPartition(this.defaultPartition) await sess.clearStorageData({ storages: ['cookies'] }) return true } catch { @@ -449,9 +489,7 @@ class BrowserSessionRegistry { // tampered file could inject an arbitrary partition into the allowlist that // will-attach-webview trusts, so we validate the expected shape before // registering anything. - private static readonly PARTITION_RE = /^persist:orca-browser-session-[\da-f-]{36}$/ - - private static isValidPersistedProfile(profile: unknown): profile is BrowserSessionProfile { + private isValidPersistedProfile(profile: unknown): profile is BrowserSessionProfile { if (!profile || typeof profile !== 'object') { return false } @@ -462,17 +500,34 @@ class BrowserSessionRegistry { typeof candidate.id === 'string' && typeof candidate.partition === 'string' && typeof candidate.label === 'string' && - BrowserSessionRegistry.PARTITION_RE.test(candidate.partition) + this.isProfileOwnedSessionPartition(candidate.partition) ) } + private isProfileOwnedSessionPartition(partition: string): boolean { + if ( + this.activeOrcaProfileId === DEFAULT_LOCAL_ORCA_PROFILE_ID && + LEGACY_BROWSER_SESSION_PARTITION_RE.test(partition) + ) { + return true + } + + const segment = getOrcaProfileBrowserPartitionSegment(this.activeOrcaProfileId) + const prefix = `persist:orca-profile-${segment}-browser-session-` + if (!partition.startsWith(prefix)) { + return false + } + const profileId = partition.slice(prefix.length) + return /^[\da-f-]{8}-[\da-f-]{4}-[\da-f-]{4}-[\da-f-]{4}-[\da-f-]{12}$/.test(profileId) + } + hydrateFromPersisted(profiles: BrowserSessionProfile[]): void { for (const profile of profiles) { - if (!BrowserSessionRegistry.isValidPersistedProfile(profile)) { + if (!this.isValidPersistedProfile(profile)) { continue } this.profiles.set(profile.id, profile) - if (profile.partition !== ORCA_BROWSER_PARTITION) { + if (profile.partition !== this.defaultPartition) { this.setupSessionPolicies(profile.partition) } } diff --git a/src/main/browser/browser-session-startup.test.ts b/src/main/browser/browser-session-startup.test.ts index e6f7860e3253..720b0935fc93 100644 --- a/src/main/browser/browser-session-startup.test.ts +++ b/src/main/browser/browser-session-startup.test.ts @@ -1,20 +1,24 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' function installRegistryMock(): { + configureForOrcaProfileMock: ReturnType applyPendingCookieImportMock: ReturnType initializeBrowserSessionsFromPersistedStateMock: ReturnType } { + const configureForOrcaProfileMock = vi.fn() const applyPendingCookieImportMock = vi.fn() const initializeBrowserSessionsFromPersistedStateMock = vi.fn() vi.doMock('./browser-session-registry', () => ({ browserSessionRegistry: { + configureForOrcaProfile: configureForOrcaProfileMock, applyPendingCookieImport: applyPendingCookieImportMock, initializeBrowserSessionsFromPersistedState: initializeBrowserSessionsFromPersistedStateMock } })) return { + configureForOrcaProfileMock, applyPendingCookieImportMock, initializeBrowserSessionsFromPersistedStateMock } @@ -40,6 +44,31 @@ describe('initializeBrowserSessionsForApp', () => { ) }) + it('configures the active Orca profile before replaying browser sessions', async () => { + const { + configureForOrcaProfileMock, + applyPendingCookieImportMock, + initializeBrowserSessionsFromPersistedStateMock + } = installRegistryMock() + const { initializeBrowserSessionsForApp } = await import('./browser-session-startup') + + initializeBrowserSessionsForApp({ + orcaProfileId: 'local-work', + profileDirectory: '/profiles/local-work' + }) + + expect(configureForOrcaProfileMock).toHaveBeenCalledWith({ + orcaProfileId: 'local-work', + profileDirectory: '/profiles/local-work' + }) + expect(configureForOrcaProfileMock.mock.invocationCallOrder[0]).toBeLessThan( + applyPendingCookieImportMock.mock.invocationCallOrder[0] + ) + expect(applyPendingCookieImportMock.mock.invocationCallOrder[0]).toBeLessThan( + initializeBrowserSessionsFromPersistedStateMock.mock.invocationCallOrder[0] + ) + }) + it('initializes browser sessions once per app process', async () => { const { applyPendingCookieImportMock, initializeBrowserSessionsFromPersistedStateMock } = installRegistryMock() diff --git a/src/main/browser/browser-session-startup.ts b/src/main/browser/browser-session-startup.ts index c23867c08c1f..949b3173f708 100644 --- a/src/main/browser/browser-session-startup.ts +++ b/src/main/browser/browser-session-startup.ts @@ -1,12 +1,19 @@ import { browserSessionRegistry } from './browser-session-registry' +import type { BrowserSessionRegistryProfileOptions } from './browser-session-registry' let initialized = false -export function initializeBrowserSessionsForApp(): void { +export function initializeBrowserSessionsForApp( + activeProfile?: BrowserSessionRegistryProfileOptions +): void { if (initialized) { return } + if (activeProfile) { + browserSessionRegistry.configureForOrcaProfile(activeProfile) + } + // Why: cookie replay must happen before the first session.fromPartition() // call, otherwise Chromium opens the stale live cookie DB before import. browserSessionRegistry.applyPendingCookieImport() diff --git a/src/main/browser/cdp-ws-proxy.test.ts b/src/main/browser/cdp-ws-proxy.test.ts index 60248d21b15c..5c366eda7278 100644 --- a/src/main/browser/cdp-ws-proxy.test.ts +++ b/src/main/browser/cdp-ws-proxy.test.ts @@ -89,6 +89,148 @@ describe('CdpWsProxy', () => { client.close() }) + it('routes Playwright nested browser and page sessions on the proxy path', async () => { + const client = await connect(endpoint) + + const primaryPageAttachResponse = await sendAndReceive(client, { + id: 31, + method: 'Target.attachToTarget', + params: { targetId: 'orca-proxy-target', flatten: true } + }) + + expect(primaryPageAttachResponse).toEqual({ + id: 31, + result: { sessionId: 'orca-proxy-session' } + }) + + const attachResponse = await sendAndReceive(client, { + id: 32, + method: 'Target.attachToBrowserTarget', + params: {} + }) + + expect(attachResponse).toEqual({ + id: 32, + result: { sessionId: 'orca-proxy-browser-session' } + }) + expect(getSendCommandMethods(mock)).not.toContain('Target.attachToBrowserTarget') + + const pageAttachResponse = await sendAndReceive(client, { + id: 33, + method: 'Target.attachToTarget', + params: { targetId: 'orca-proxy-target', flatten: true }, + sessionId: 'orca-proxy-browser-session' + }) + + expect(pageAttachResponse).toEqual({ + id: 33, + result: { sessionId: 'orca-proxy-session-2' }, + sessionId: 'orca-proxy-browser-session' + }) + + const sessionResponse = await sendAndReceive(client, { + id: 34, + method: 'Runtime.evaluate', + params: { expression: 'document.title' }, + sessionId: 'orca-proxy-session-2' + }) + + expect(sessionResponse).toEqual({ + id: 34, + result: {}, + sessionId: 'orca-proxy-session-2' + }) + expect(getSendCommandCalls(mock)).toContainEqual([ + 'Runtime.evaluate', + { expression: 'document.title' } + ]) + + const detachResponse = await sendAndReceive(client, { + id: 35, + method: 'Target.detachFromTarget', + params: { sessionId: 'orca-proxy-session-2' }, + sessionId: 'orca-proxy-browser-session' + }) + + expect(detachResponse).toEqual({ + id: 35, + result: {}, + sessionId: 'orca-proxy-browser-session' + }) + + const primaryPageResponse = await sendAndReceive(client, { + id: 36, + method: 'Runtime.evaluate', + params: { expression: 'document.URL' }, + sessionId: 'orca-proxy-session' + }) + + expect(primaryPageResponse).toEqual({ + id: 36, + result: {}, + sessionId: 'orca-proxy-session' + }) + + const browserSessionResponse = await sendAndReceive(client, { + id: 37, + method: 'Target.getTargets', + params: {}, + sessionId: 'orca-proxy-browser-session' + }) + + expect(browserSessionResponse).toMatchObject({ + id: 37, + sessionId: 'orca-proxy-browser-session' + }) + client.close() + }) + + it('preserves Target.attachToTarget and clears the synthetic session on Target.detachFromTarget', async () => { + const client = await connect(endpoint) + + const attachResponse = await sendAndReceive(client, { + id: 33, + method: 'Target.attachToTarget', + params: { targetId: 'orca-proxy-target', flatten: true } + }) + + expect(attachResponse).toEqual({ + id: 33, + result: { sessionId: 'orca-proxy-session' } + }) + + const detachResponse = await sendAndReceive(client, { + id: 34, + method: 'Target.detachFromTarget', + params: { sessionId: 'orca-proxy-session' } + }) + + expect(detachResponse).toEqual({ id: 34, result: {} }) + + const rootEventPromise = new Promise>((resolve) => { + client.once('message', (data) => resolve(JSON.parse(data.toString()))) + }) + mock.emit('message', {}, 'Runtime.executionContextCreated', { context: { id: 1 } }) + + const rootEvent = await rootEventPromise + expect(rootEvent).toEqual({ + method: 'Runtime.executionContextCreated', + params: { context: { id: 1 } } + }) + + const reattachResponse = await sendAndReceive(client, { + id: 35, + method: 'Target.attachToTarget', + params: { targetId: 'orca-proxy-target', flatten: true } + }) + + expect(reattachResponse).toEqual({ + id: 35, + result: { sessionId: 'orca-proxy-session-2' } + }) + client.close() + }) + it('returns an error instead of crashing when a command arrives after tab destruction', async () => { const client = await connect(endpoint) mock.destroy() diff --git a/src/main/browser/cdp-ws-proxy.ts b/src/main/browser/cdp-ws-proxy.ts index 62e51342d265..99c1d5546545 100644 --- a/src/main/browser/cdp-ws-proxy.ts +++ b/src/main/browser/cdp-ws-proxy.ts @@ -19,6 +19,7 @@ export class CdpWsProxy { private httpServer: Server | null = null private wss: WebSocketServer | null = null private client: WebSocket | null = null + private readonly responseSessionIdsByClient = new WeakMap>() private detachClientListeners: (() => void) | null = null private port = 0 private debuggerMessageHandler: ((...args: unknown[]) => void) | null = null @@ -27,6 +28,10 @@ export class CdpWsProxy { private attached = false // Why: agent-browser filters events by sessionId from Target.attachToTarget. private clientSessionId: string | undefined = undefined + private readonly clientSessionIds = new Set() + private readonly clientBrowserSessionIds = new Set() + private nextClientSessionOrdinal = 0 + private nextClientBrowserSessionOrdinal = 0 private readonly pdfStreams = new CdpPdfStreamStore() constructor(private readonly webContents: WebContents) {} @@ -59,7 +64,7 @@ export class CdpWsProxy { const onClose = (): void => { detach() if (this.client === ws) { - this.pdfStreams.clear() + this.clearClientState() this.client = null } } @@ -110,16 +115,43 @@ export class CdpWsProxy { this.detachClientListeners?.() this.detachClientListeners = null this.client = null - // Why: a pending focus belongs to the departing client; never replay it for the next one. + this.clearClientState() + if (client) { + this.responseSessionIdsByClient.delete(client) + } + client?.close() + } + + private clearClientState(): void { + // Why: session and focus state belongs to one websocket and must not cross client replacement. this.pendingDomFocusBySession.clear() this.pdfStreams.clear() - client?.close() + this.clientSessionId = undefined + this.clientSessionIds.clear() + this.clientBrowserSessionIds.clear() + this.nextClientSessionOrdinal = 0 + this.nextClientBrowserSessionOrdinal = 0 } private send(payload: unknown, client = this.client): void { + const responsePayload = client ? this.addResponseSessionId(payload, client) : payload if (client?.readyState === WebSocket.OPEN) { - client.send(JSON.stringify(payload)) + client.send(JSON.stringify(responsePayload)) + } + } + + private addResponseSessionId(payload: unknown, client: WebSocket): unknown { + if (typeof payload !== 'object' || payload === null) { + return payload + } + const clientId = (payload as { id?: unknown }).id + if (typeof clientId !== 'number') { + return payload } + const responseSessionIds = this.responseSessionIdsByClient.get(client) + const sessionId = responseSessionIds?.get(clientId) + responseSessionIds?.delete(clientId) + return sessionId ? { ...payload, sessionId } : payload } private sendResult(clientId: number, result: unknown, client = this.client): void { @@ -253,6 +285,13 @@ export class CdpWsProxy { return } const clientId = msg.id + const responseSessionIds = this.responseSessionIdsByClient.get(client) ?? new Map() + if (msg.sessionId) { + responseSessionIds.set(clientId, msg.sessionId) + } else { + responseSessionIds.delete(clientId) + } + this.responseSessionIdsByClient.set(client, responseSessionIds) if (msg.method === 'Target.getTargets') { this.sendResult(clientId, { targetInfos: [this.buildTargetInfo()] }, client) @@ -264,14 +303,30 @@ export class CdpWsProxy { } if (msg.method === 'Target.setDiscoverTargets' || msg.method === 'Target.detachFromTarget') { if (msg.method === 'Target.detachFromTarget') { - this.clientSessionId = undefined + const detachedSessionId = msg.params?.sessionId + if (typeof detachedSessionId === 'string') { + this.clientSessionIds.delete(detachedSessionId) + this.clientBrowserSessionIds.delete(detachedSessionId) + if (detachedSessionId === this.clientSessionId) { + this.clientSessionId = this.clientSessionIds.values().next().value + } + } } this.sendResult(clientId, {}, client) return } + if (msg.method === 'Target.attachToBrowserTarget') { + // Why: Playwright needs a distinct browser session before it attaches to the selected page. + const sessionId = this.nextSyntheticBrowserSessionId() + this.clientBrowserSessionIds.add(sessionId) + this.sendResult(clientId, { sessionId }, client) + return + } if (msg.method === 'Target.attachToTarget') { - this.clientSessionId = 'orca-proxy-session' - this.sendResult(clientId, { sessionId: this.clientSessionId }, client) + const sessionId = this.nextSyntheticPageSessionId() + this.clientSessionIds.add(sessionId) + this.clientSessionId ??= sessionId + this.sendResult(clientId, { sessionId }, client) return } if (msg.method === 'Browser.getVersion') { @@ -363,7 +418,24 @@ export class CdpWsProxy { } private resolveDebuggerSessionId(msgSessionId?: string): string | undefined { - return msgSessionId && msgSessionId !== this.clientSessionId ? msgSessionId : undefined + const syntheticSession = + (msgSessionId && this.clientSessionIds.has(msgSessionId)) || + (msgSessionId && this.clientBrowserSessionIds.has(msgSessionId)) + return msgSessionId && !syntheticSession ? msgSessionId : undefined + } + + private nextSyntheticPageSessionId(): string { + this.nextClientSessionOrdinal += 1 + return this.nextClientSessionOrdinal === 1 + ? 'orca-proxy-session' + : `orca-proxy-session-${this.nextClientSessionOrdinal}` + } + + private nextSyntheticBrowserSessionId(): string { + this.nextClientBrowserSessionOrdinal += 1 + return this.nextClientBrowserSessionOrdinal === 1 + ? 'orca-proxy-browser-session' + : `orca-proxy-browser-session-${this.nextClientBrowserSessionOrdinal}` } private isActiveClient(client: WebSocket): boolean { diff --git a/src/main/browser/chromium-cookie-path.ts b/src/main/browser/chromium-cookie-path.ts new file mode 100644 index 000000000000..ed6b2c4a8c6d --- /dev/null +++ b/src/main/browser/chromium-cookie-path.ts @@ -0,0 +1,13 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' + +// Why: Chromium 96+ moved the cookie DB under Network, while older profiles +// still use the profile root. Every reader and replay writer must agree. +export function resolveChromiumCookiesPath(profileDir: string): string | null { + const networkPath = join(profileDir, 'Network', 'Cookies') + if (existsSync(networkPath)) { + return networkPath + } + const legacyPath = join(profileDir, 'Cookies') + return existsSync(legacyPath) ? legacyPath : null +} diff --git a/src/main/browser/chromium-cookie-snapshot.test.ts b/src/main/browser/chromium-cookie-snapshot.test.ts new file mode 100644 index 000000000000..16fbd50a63ff --- /dev/null +++ b/src/main/browser/chromium-cookie-snapshot.test.ts @@ -0,0 +1,170 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as NodeFs from 'node:fs' + +const { beforeCopyMock } = vi.hoisted(() => ({ beforeCopyMock: vi.fn() })) + +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + copyFileSync: (...args: Parameters) => { + beforeCopyMock(...args) + return actual.copyFileSync(...args) + } + } +}) + +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { DatabaseSync } from 'node:sqlite' +import { createChromiumCookieTestDatabase } from './browser-cookie-import-test-database' +import { createChromiumCookieSnapshot } from './chromium-cookie-snapshot' + +function sourceFiles(databasePath: string): Map { + const files = new Map() + for (const suffix of ['', '-wal', '-shm'] as const) { + const path = databasePath + suffix + if (existsSync(path)) { + files.set(suffix, readFileSync(path)) + } + } + return files +} + +function expectSourceFilesUnchanged(databasePath: string, before: Map): void { + expect(sourceFiles(databasePath)).toEqual(before) +} + +describe('createChromiumCookieSnapshot', () => { + let root: string + let writer: DatabaseSync | null + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-chromium-snapshot-test-')) + writer = null + beforeCopyMock.mockReset() + }) + + afterEach(() => { + writer?.close() + rmSync(root, { recursive: true, force: true }) + }) + + it('reads committed WAL-only rows without changing any live source file', () => { + const sourcePath = join(root, 'Chrome', 'Default', 'Network', 'Cookies') + writer = createChromiumCookieTestDatabase( + sourcePath, + [{ name: 'wal-session', value: 'fresh-value' }], + { journalMode: 'wal' } + ) + const before = sourceFiles(sourcePath) + + const snapshot = createChromiumCookieSnapshot(sourcePath, { tempRoot: root }) + const snapshotDir = dirname(snapshot.databasePath) + const database = new DatabaseSync(snapshot.databasePath, { readOnly: true }) + const rows = database.prepare('SELECT name, value FROM cookies').all() + database.close() + + expect(rows).toEqual([expect.objectContaining({ name: 'wal-session', value: 'fresh-value' })]) + expect(existsSync(`${snapshot.databasePath}-wal`)).toBe(true) + expect(existsSync(`${snapshot.databasePath}-shm`)).toBe(true) + expectSourceFilesUnchanged(sourcePath, before) + + snapshot.cleanup() + expect(existsSync(snapshotDir)).toBe(false) + }) + + it('snapshots a database when WAL and SHM sidecars are absent', () => { + const sourcePath = join(root, 'Chrome', 'Default', 'Cookies') + createChromiumCookieTestDatabase(sourcePath, [ + { name: 'main-session', value: 'persisted-value' } + ]).close() + + const snapshot = createChromiumCookieSnapshot(sourcePath, { tempRoot: root }) + const database = new DatabaseSync(snapshot.databasePath, { readOnly: true }) + const row = database.prepare('SELECT name, value FROM cookies').get() + database.close() + + expect(row).toEqual(expect.objectContaining({ name: 'main-session', value: 'persisted-value' })) + expect(existsSync(`${snapshot.databasePath}-wal`)).toBe(false) + snapshot.cleanup() + }) + + it('retries when a WAL appears while the main database is being copied', () => { + const sourcePath = join(root, 'Chrome', 'Default', 'Cookies') + createChromiumCookieTestDatabase(sourcePath, []).close() + beforeCopyMock.mockImplementationOnce((source: string) => { + if (source === sourcePath) { + writer = new DatabaseSync(sourcePath) + writer.exec( + "PRAGMA journal_mode = WAL; PRAGMA wal_autocheckpoint = 0; INSERT INTO cookies (creation_utc, host_key, name, value, path, expires_utc, is_secure, is_httponly, samesite) VALUES (1, '.example.com', 'raced-in', 'wal-value', '/', 0, 0, 0, 0)" + ) + } + }) + + const snapshot = createChromiumCookieSnapshot(sourcePath, { tempRoot: root }) + const database = new DatabaseSync(snapshot.databasePath, { readOnly: true }) + const row = database.prepare("SELECT value FROM cookies WHERE name = 'raced-in'").get() + database.close() + + expect(row).toEqual(expect.objectContaining({ value: 'wal-value' })) + expect(beforeCopyMock.mock.calls.filter(([source]) => source === sourcePath)).toHaveLength(2) + snapshot.cleanup() + }) + + it('retries when sidecars disappear after Chromium checkpoints on close', () => { + const sourcePath = join(root, 'Chrome', 'Default', 'Cookies') + writer = createChromiumCookieTestDatabase( + sourcePath, + [{ name: 'checkpointed', value: 'main-value' }], + { journalMode: 'wal' } + ) + beforeCopyMock.mockImplementationOnce((source: string) => { + if (source === sourcePath) { + writer?.close() + writer = null + } + }) + + const snapshot = createChromiumCookieSnapshot(sourcePath, { tempRoot: root }) + const database = new DatabaseSync(snapshot.databasePath, { readOnly: true }) + const row = database.prepare("SELECT value FROM cookies WHERE name = 'checkpointed'").get() + database.close() + + expect(row).toEqual(expect.objectContaining({ value: 'main-value' })) + expect(beforeCopyMock.mock.calls.filter(([source]) => source === sourcePath)).toHaveLength(2) + snapshot.cleanup() + }) + + it('removes a partial snapshot when a WAL copy fails', () => { + const sourcePath = join(root, 'Chrome', 'Default', 'Cookies') + const snapshotsRoot = join(root, 'snapshots') + mkdirSync(snapshotsRoot) + writer = createChromiumCookieTestDatabase(sourcePath, [{ name: 'session', value: 'value' }], { + journalMode: 'wal' + }) + beforeCopyMock.mockImplementation((source: string) => { + if (source === `${sourcePath}-wal`) { + throw Object.assign(new Error('permission denied'), { code: 'EACCES' }) + } + }) + + expect(() => createChromiumCookieSnapshot(sourcePath, { tempRoot: snapshotsRoot })).toThrow( + 'permission denied' + ) + expect(readdirSync(snapshotsRoot)).toEqual([]) + }) + + it('removes its temporary directory when the source database is missing', () => { + const snapshotsRoot = join(root, 'snapshots') + mkdirSync(snapshotsRoot) + + expect(() => + createChromiumCookieSnapshot(join(root, 'missing', 'Cookies'), { + tempRoot: snapshotsRoot + }) + ).toThrow('does not exist') + expect(readdirSync(snapshotsRoot)).toEqual([]) + }) +}) diff --git a/src/main/browser/chromium-cookie-snapshot.ts b/src/main/browser/chromium-cookie-snapshot.ts new file mode 100644 index 000000000000..4b54e98be8d4 --- /dev/null +++ b/src/main/browser/chromium-cookie-snapshot.ts @@ -0,0 +1,140 @@ +import { copyFileSync, mkdtempSync, rmSync, statSync, unlinkSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +const SNAPSHOT_ATTEMPTS = 5 + +type FileState = { + device: bigint + inode: bigint + size: bigint + modifiedAt: bigint + changedAt: bigint +} + +export type ChromiumCookieSnapshot = { + databasePath: string + cleanup: () => void +} + +type ChromiumCookieSnapshotOptions = { + tempRoot?: string +} + +function removeSnapshotDirectory(path: string): void { + // Why: Windows can briefly retain SQLite handles after close; bounded retries + // keep cleanup reliable without ever touching the live browser directory. + rmSync(path, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }) +} + +function isMissingFileError(error: unknown): boolean { + return ( + error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT' + ) +} + +function readFileState(path: string): FileState | null { + try { + const stats = statSync(path, { bigint: true }) + return { + device: stats.dev, + inode: stats.ino, + size: stats.size, + modifiedAt: stats.mtimeNs, + changedAt: stats.ctimeNs + } + } catch (error) { + if (isMissingFileError(error)) { + return null + } + throw error + } +} + +function sameFileState(left: FileState | null, right: FileState | null): boolean { + if (!left || !right) { + return left === right + } + return ( + left.device === right.device && + left.inode === right.inode && + left.size === right.size && + left.modifiedAt === right.modifiedAt && + left.changedAt === right.changedAt + ) +} + +function removeAttemptFiles(databasePath: string): void { + for (const suffix of ['', '-wal', '-shm'] as const) { + try { + unlinkSync(databasePath + suffix) + } catch { + /* best-effort between snapshot attempts */ + } + } +} + +function copyStableAttempt(sourcePath: string, databasePath: string): boolean { + const sourceWalPath = `${sourcePath}-wal` + const databaseBefore = readFileState(sourcePath) + const walBefore = readFileState(sourceWalPath) + if (!databaseBefore) { + throw new Error('Chromium cookies database does not exist') + } + + removeAttemptFiles(databasePath) + copyFileSync(sourcePath, databasePath) + + if (walBefore) { + try { + // Why: SQLite only discovers a WAL whose basename exactly matches the DB. + copyFileSync(sourceWalPath, `${databasePath}-wal`) + } catch (error) { + if (isMissingFileError(error)) { + return false + } + throw error + } + } + // Why: SHM is a transient mmap WAL index that may be locked or mid-update. + // SQLite safely rebuilds a matching Cookies-shm beside the private WAL copy. + + const databaseAfter = readFileState(sourcePath) + const walAfter = readFileState(sourceWalPath) + if (!sameFileState(databaseBefore, databaseAfter) || !sameFileState(walBefore, walAfter)) { + return false + } + + const copiedDatabase = readFileState(databasePath) + const copiedWal = readFileState(`${databasePath}-wal`) + return ( + copiedDatabase?.size === databaseBefore.size && + (walBefore ? copiedWal?.size === walBefore.size : copiedWal === null) + ) +} + +export function createChromiumCookieSnapshot( + sourcePath: string, + options: ChromiumCookieSnapshotOptions = {} +): ChromiumCookieSnapshot { + const snapshotDir = mkdtempSync(join(options.tempRoot ?? tmpdir(), 'orca-cookie-import-')) + const databasePath = join(snapshotDir, 'Cookies') + let keepSnapshot = false + + try { + for (let attempt = 0; attempt < SNAPSHOT_ATTEMPTS; attempt += 1) { + if (copyStableAttempt(sourcePath, databasePath)) { + keepSnapshot = true + return { + databasePath, + cleanup: () => removeSnapshotDirectory(snapshotDir) + } + } + } + throw new Error('Chromium cookies database changed while creating a snapshot') + } finally { + if (!keepSnapshot) { + removeSnapshotDirectory(snapshotDir) + } + } +} diff --git a/src/main/claude-usage/scanner-scan.test.ts b/src/main/claude-usage/scanner-scan.test.ts index eb657636cde0..83fd6356d46a 100644 --- a/src/main/claude-usage/scanner-scan.test.ts +++ b/src/main/claude-usage/scanner-scan.test.ts @@ -165,6 +165,319 @@ describe('scanClaudeUsageFiles', () => { expect(second.dailyAggregates[0]?.inputTokens).toBe(999) }) + it('dedupes fork copies when only message.id is present (no requestId)', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'bbbb-fork.jsonl') + + const turn = (sessionId: string, messageId: string, inputTokens: number): string => + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: '2026-04-09T10:00:00.000Z', + cwd: '/workspace/repo-a', + message: { + id: messageId, + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile(originalFile, turn('session-1', 'msg_1', 100)) + await writeFile( + forkFile, + [turn('session-2', 'msg_1', 100), turn('session-2', 'msg_2', 50)].join('\n') + ) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const result = await scanClaudeUsageFiles([]) + expect(result.dailyAggregates.reduce((sum, row) => sum + row.inputTokens, 0)).toBe(150) + expect(result.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg:msg_1']) + expect(result.processedFiles[1]?.ownedDedupeKeys).toEqual(['msg:msg_2']) + }) + + it('dedupes fork copies via uuid when message ids are absent', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'bbbb-fork.jsonl') + + const turn = (sessionId: string, uuid: string, inputTokens: number): string => + JSON.stringify({ + type: 'assistant', + sessionId, + uuid, + timestamp: '2026-04-09T10:00:00.000Z', + cwd: '/workspace/repo-a', + message: { + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile(originalFile, turn('session-1', 'uuid-1', 100)) + await writeFile( + forkFile, + [turn('session-2', 'uuid-1', 100), turn('session-2', 'uuid-2', 40)].join('\n') + ) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const result = await scanClaudeUsageFiles([]) + expect(result.dailyAggregates.reduce((sum, row) => sum + row.inputTokens, 0)).toBe(140) + expect(result.processedFiles[0]?.ownedDedupeKeys).toEqual(['uuid:uuid-1']) + expect(result.processedFiles[1]?.ownedDedupeKeys).toEqual(['uuid:uuid-2']) + }) + + it('counts turns copied into forked session files exactly once', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'bbbb-fork.jsonl') + + const turn = ( + sessionId: string, + messageId: string, + requestId: string, + inputTokens: number + ): string => + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: '2026-04-09T10:00:00.000Z', + requestId, + cwd: '/workspace/repo-a', + message: { + id: messageId, + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile( + originalFile, + [turn('session-1', 'msg_1', 'req_1', 100), turn('session-1', 'msg_2', 'req_2', 200)].join( + '\n' + ) + ) + // Fork copies the original history with preserved message/request IDs but a + // rewritten sessionId, then appends its own new turn. + await writeFile( + forkFile, + [ + turn('session-2', 'msg_1', 'req_1', 100), + turn('session-2', 'msg_2', 'req_2', 200), + turn('session-2', 'msg_3', 'req_3', 400) + ].join('\n') + ) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const result = await scanClaudeUsageFiles([]) + const totalInput = result.dailyAggregates.reduce( + (sum, aggregate) => sum + aggregate.inputTokens, + 0 + ) + + expect(totalInput).toBe(700) + expect(result.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg_1:req_1', 'msg_2:req_2']) + expect(result.processedFiles[0]?.hasDeferredClaims).toBe(false) + expect(result.processedFiles[1]?.ownedDedupeKeys).toEqual(['msg_3:req_3']) + expect(result.processedFiles[1]?.hasDeferredClaims).toBe(true) + }) + + it('keeps fork dedupe stable when the original file projection is reused from cache', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'zzzz-fork.jsonl') + + const turn = ( + sessionId: string, + messageId: string, + requestId: string, + inputTokens: number + ): string => + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: '2026-04-09T10:00:00.000Z', + requestId, + cwd: '/workspace/repo-a', + message: { + id: messageId, + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile(originalFile, turn('session-1', 'msg_1', 'req_1', 100)) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const first = await scanClaudeUsageFiles([]) + expect(first.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg_1:req_1']) + + // A fork appears later while the original stays unchanged (cache reuse). + await writeFile( + forkFile, + [turn('session-2', 'msg_1', 'req_1', 100), turn('session-2', 'msg_9', 'req_9', 50)].join('\n') + ) + + const second = await scanClaudeUsageFiles([], first.processedFiles) + const totalInput = second.dailyAggregates.reduce( + (sum, aggregate) => sum + aggregate.inputTokens, + 0 + ) + + expect(totalInput).toBe(150) + expect(second.processedFiles.map((file) => file.ownedDedupeKeys)).toEqual([ + ['msg_1:req_1'], + ['msg_9:req_9'] + ]) + + // Rescanning with the full cache stays stable. + const third = await scanClaudeUsageFiles([], second.processedFiles) + expect(third.dailyAggregates.reduce((sum, aggregate) => sum + aggregate.inputTokens, 0)).toBe( + 150 + ) + }) + + it('reclaims fork-copied turns when the owning original file is deleted', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'bbbb-fork.jsonl') + + const turn = ( + sessionId: string, + messageId: string, + requestId: string, + inputTokens: number + ): string => + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: '2026-04-09T10:00:00.000Z', + requestId, + cwd: '/workspace/repo-a', + message: { + id: messageId, + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile(originalFile, turn('session-1', 'msg_1', 'req_1', 100)) + await writeFile( + forkFile, + [turn('session-2', 'msg_1', 'req_1', 100), turn('session-2', 'msg_9', 'req_9', 50)].join('\n') + ) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const first = await scanClaudeUsageFiles([]) + expect(first.dailyAggregates.reduce((sum, aggregate) => sum + aggregate.inputTokens, 0)).toBe( + 150 + ) + expect(first.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg_1:req_1']) + expect(first.processedFiles[1]?.ownedDedupeKeys).toEqual(['msg_9:req_9']) + + // Deleting the owner must reparse deferred forks so they can re-claim the + // copied turn instead of permanently under-counting. + await rm(originalFile) + + const second = await scanClaudeUsageFiles([], first.processedFiles) + expect(second.dailyAggregates.reduce((sum, aggregate) => sum + aggregate.inputTokens, 0)).toBe( + 150 + ) + expect(second.processedFiles).toHaveLength(1) + expect(second.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg_1:req_1', 'msg_9:req_9']) + }) + + it('keeps unrelated cached transcripts when a different owner file is deleted', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'bbbb-fork.jsonl') + const unrelatedFile = join(projectDir, 'cccc-unrelated.jsonl') + + const turn = ( + sessionId: string, + messageId: string, + requestId: string, + inputTokens: number + ): string => + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: '2026-04-09T10:00:00.000Z', + requestId, + cwd: '/workspace/repo-a', + message: { + id: messageId, + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile(originalFile, turn('session-1', 'msg_1', 'req_1', 100)) + await writeFile( + forkFile, + [turn('session-2', 'msg_1', 'req_1', 100), turn('session-2', 'msg_9', 'req_9', 50)].join('\n') + ) + await writeFile(unrelatedFile, turn('session-3', 'msg_u', 'req_u', 25)) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const first = await scanClaudeUsageFiles([]) + const unrelatedBefore = first.processedFiles.find((file) => file.path === unrelatedFile) + expect(unrelatedBefore?.hasDeferredClaims).toBe(false) + expect(unrelatedBefore?.ownedDedupeKeys).toEqual(['msg_u:req_u']) + + await rm(originalFile) + + const second = await scanClaudeUsageFiles([], first.processedFiles) + const unrelatedAfter = second.processedFiles.find((file) => file.path === unrelatedFile) + // Unrelated files must keep their cached projection identity (stat-only path). + expect(unrelatedAfter).toBe(unrelatedBefore) + expect(second.dailyAggregates.reduce((sum, aggregate) => sum + aggregate.inputTokens, 0)).toBe( + 175 + ) + }) + it('canonicalizes repeated cwd paths once per scan file', async () => { const root = await makeClaudeProjectsRoot() const projectDir = join(root, '.claude', 'projects', 'project-a') diff --git a/src/main/claude-usage/scanner.ts b/src/main/claude-usage/scanner.ts index bac5d5cac5f7..db1c1f21f7cd 100644 --- a/src/main/claude-usage/scanner.ts +++ b/src/main/claude-usage/scanner.ts @@ -29,6 +29,8 @@ type ClaudeUsageSourceRecord = { cwd?: string gitBranch?: string requestId?: string + /** Stable row id when present; preserved across fork-copied history. */ + uuid?: string isSidechain?: boolean agentId?: string message?: { @@ -209,9 +211,11 @@ function stripClaudeSourceMetadata(turn: ClaudeUsageParsedSourceTurn): ClaudeUsa } } -function dedupeClaudeUsageTurns(turns: ClaudeUsageParsedSourceTurn[]): ClaudeUsageParsedTurn[] { +function dedupeClaudeUsageTurns( + turns: ClaudeUsageParsedSourceTurn[] +): ClaudeUsageParsedSourceTurn[] { const dedupeIndexByKey = new Map() - const deduped: ClaudeUsageParsedTurn[] = [] + const deduped: ClaudeUsageParsedSourceTurn[] = [] for (const turn of turns) { if (turn.dedupeKey) { @@ -228,8 +232,7 @@ function dedupeClaudeUsageTurns(turns: ClaudeUsageParsedSourceTurn[]): ClaudeUsa } } - const stripped = stripClaudeSourceMetadata(turn) - deduped.push(stripped) + deduped.push({ ...turn }) if (turn.dedupeKey) { dedupeIndexByKey.set(turn.dedupeKey, deduped.length - 1) } @@ -273,8 +276,10 @@ function parseClaudeUsageSourceRecord( model: parsed.message?.model ?? null, cwd: parsed.cwd ?? null, gitBranch: parsed.gitBranch ?? null, - dedupeKey: - parsed.message?.id && parsed.requestId ? `${parsed.message.id}:${parsed.requestId}` : null, + // Why: forks rewrite sessionId but keep message/request ids (and usually + // uuid). Prefer the strongest stable identity available so ownership still + // works when requestId is missing on older or partial rows. + dedupeKey: buildClaudeUsageDedupeKey(parsed), inputTokens, outputTokens, cacheReadTokens, @@ -282,6 +287,22 @@ function parseClaudeUsageSourceRecord( } } +function buildClaudeUsageDedupeKey(parsed: ClaudeUsageSourceRecord): string | null { + const messageId = parsed.message?.id?.trim() + const requestId = parsed.requestId?.trim() + if (messageId && requestId) { + return `${messageId}:${requestId}` + } + if (messageId) { + return `msg:${messageId}` + } + const uuid = parsed.uuid?.trim() + if (uuid) { + return `uuid:${uuid}` + } + return null +} + export function parseClaudeUsageRecord(line: string): ClaudeUsageParsedTurn | null { const parsed = parseClaudeUsageSourceRecord(line) return parsed ? stripClaudeSourceMetadata(parsed) : null @@ -302,12 +323,12 @@ export async function parseClaudeUsageFile(filePath: string): Promise { const fileStat = await stat(filePath) let lineCount = 0 @@ -597,18 +618,6 @@ export function aggregateClaudeUsage(turns: ClaudeUsageAttributedTurn[]): { } } -async function parseClaudeUsagePersistedFile( - filePath: string, - worktreeLookup: Map -): Promise { - const { processedFile, turns } = await readClaudeUsageScanFile(filePath) - const attributed = await attributeClaudeUsageTurns(turns, worktreeLookup) - return { - ...processedFile, - ...aggregateClaudeUsage(attributed) - } -} - export async function scanClaudeUsageFiles( worktrees: ClaudeUsageWorktreeRef[], previousProcessedFiles: ClaudeUsagePersistedFile[] = [] @@ -619,41 +628,122 @@ export async function scanClaudeUsageFiles( }> { const files = await listClaudeTranscriptFiles() const previousByPath = new Map(previousProcessedFiles.map((file) => [file.path, file])) - const processedFiles: ClaudeUsagePersistedFile[] = [] const worktreeLookup = await buildWorktreeLookup(worktrees) - const sessionsById = new Map() - const dailyByKey = new Map() + const currentPaths = new Set(files) + // Why: when a file that owned dedupe keys is deleted, remaining forks still + // contain those turns but their caches record them as unowned. Only files + // that previously deferred claims can reclaim, so invalidate those — not the + // entire transcript corpus (histories can be gigabytes). + const lostOwnerPath = previousProcessedFiles.some( + (file) => + !currentPaths.has(file.path) && + Array.isArray(file.ownedDedupeKeys) && + file.ownedDedupeKeys.length > 0 + ) + + const reusedByPath = new Map() + const pathsToParse: string[] = [] for (let index = 0; index < files.length; index += FILE_SCAN_BATCH_SIZE) { const batch = files.slice(index, index + FILE_SCAN_BATCH_SIZE) - const results = await Promise.all( + const reusable = await Promise.all( batch.map(async (filePath) => { const fileInfo = await getProcessedFileStat(filePath) const previous = previousByPath.get(filePath) // Why: Claude histories can be gigabytes. Unchanged files should pay // only stat cost on refresh while preserving exactly the old projection. + // When an owner disappears, only deferred-claim files need reparse. + const mustReclaimDeferred = lostOwnerPath && previous?.hasDeferredClaims !== false const canReuse = + !mustReclaimDeferred && previous && previous.mtimeMs === fileInfo.mtimeMs && previous.size === fileInfo.size && Array.isArray(previous.sessions) && - Array.isArray(previous.dailyAggregates) - - return canReuse ? previous : parseClaudeUsagePersistedFile(filePath, worktreeLookup) + Array.isArray(previous.dailyAggregates) && + Array.isArray(previous.ownedDedupeKeys) && + typeof previous.hasDeferredClaims === 'boolean' + return canReuse ? previous : null }) ) - for (const processed of results) { - processedFiles.push(processed) - mergeClaudeSessions(sessionsById, processed.sessions) - mergeClaudeDailyAggregates(dailyByKey, processed.dailyAggregates) + for (const [batchIndex, previous] of reusable.entries()) { + if (previous) { + reusedByPath.set(batch[batchIndex], previous) + } else { + pathsToParse.push(batch[batchIndex]) + } } + if (index + batch.length < files.length) { + await yieldToEventLoop() + } + } + + // Why: resuming or forking a Claude session copies earlier turns — with their + // original message/request IDs — into a new transcript file under a new + // session id. Per-file dedupe cannot see those copies, so long-lived sessions + // get re-counted on every fork (issue #8006). Cross-file ownership counts each + // turn for exactly one file; cached files keep the claims they persisted. + const turnOwnerByDedupeKey = new Map() + for (const [filePath, previous] of reusedByPath) { + for (const dedupeKey of previous.ownedDedupeKeys) { + // First cached claim wins so conflicting projections stay deterministic. + if (!turnOwnerByDedupeKey.has(dedupeKey)) { + turnOwnerByDedupeKey.set(dedupeKey, filePath) + } + } + } + + const parsedByPath = new Map() + for (let index = 0; index < pathsToParse.length; index += FILE_SCAN_BATCH_SIZE) { + const batch = pathsToParse.slice(index, index + FILE_SCAN_BATCH_SIZE) // Why: transcript scans run in Electron's main process. Small parallel // batches cut independent file I/O without letting Settings stay blocked. - if (index + batch.length < files.length) { + const reads = await Promise.all(batch.map((filePath) => readClaudeUsageScanFile(filePath))) + for (const [batchIndex, filePath] of batch.entries()) { + const { processedFile, turns } = reads[batchIndex] + // Why: ownership claims must be sequential in sorted-path order so + // rescans assign duplicated turns to the same file deterministically. + const ownedTurns: ClaudeUsageParsedTurn[] = [] + const ownedDedupeKeys: string[] = [] + let hasDeferredClaims = false + for (const turn of turns) { + if (turn.dedupeKey) { + const owner = turnOwnerByDedupeKey.get(turn.dedupeKey) + if (owner !== undefined && owner !== filePath) { + hasDeferredClaims = true + continue + } + turnOwnerByDedupeKey.set(turn.dedupeKey, filePath) + ownedDedupeKeys.push(turn.dedupeKey) + } + ownedTurns.push(stripClaudeSourceMetadata(turn)) + } + const attributed = await attributeClaudeUsageTurns(ownedTurns, worktreeLookup) + parsedByPath.set(filePath, { + ...processedFile, + ...aggregateClaudeUsage(attributed), + ownedDedupeKeys, + hasDeferredClaims + }) + } + if (index + batch.length < pathsToParse.length) { await yieldToEventLoop() } } + const processedFiles: ClaudeUsagePersistedFile[] = [] + const sessionsById = new Map() + const dailyByKey = new Map() + for (const filePath of files) { + const processed = reusedByPath.get(filePath) ?? parsedByPath.get(filePath) + if (!processed) { + continue + } + processedFiles.push(processed) + mergeClaudeSessions(sessionsById, processed.sessions) + mergeClaudeDailyAggregates(dailyByKey, processed.dailyAggregates) + } + return { processedFiles, sessions: finalizeClaudeSessions(sessionsById), diff --git a/src/main/claude-usage/store.ts b/src/main/claude-usage/store.ts index 092ee6aa208e..a020186ee90d 100644 --- a/src/main/claude-usage/store.ts +++ b/src/main/claude-usage/store.ts @@ -19,7 +19,10 @@ import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-w import type { ClaudeUsagePersistedState } from './types' import { createWorktreeRefs, getSessionProjectLabel, scanClaudeUsageFiles } from './scanner' -const SCHEMA_VERSION = 3 +// Why: v5 widens Claude ownership keys (message-id / uuid fallbacks). Older +// caches either lack ownership or used narrower keys and can under/over-count +// after fork reclaim (#8006). +const SCHEMA_VERSION = 5 const STALE_MS = 5 * 60_000 const AUTOMATION_ATTRIBUTION_WINDOW_MS = 5 * 60_000 diff --git a/src/main/claude-usage/types.ts b/src/main/claude-usage/types.ts index 8760621d7547..ec497e5e098a 100644 --- a/src/main/claude-usage/types.ts +++ b/src/main/claude-usage/types.ts @@ -66,6 +66,14 @@ export type ClaudeUsagePersistedState = { export type ClaudeUsagePersistedFile = ClaudeUsageProcessedFile & { sessions: ClaudeUsageSession[] dailyAggregates: ClaudeUsageDailyAggregate[] + /** Dedupe keys (message.id:requestId) this file counted. Forked/resumed + * sessions copy earlier turns into new files; ownership keeps each turn + * counted by exactly one cached file across incremental scans. */ + ownedDedupeKeys: string[] + /** True when this file saw turns already claimed by another file. When that + * owner disappears, only deferred files need reparse to reclaim — not the + * entire transcript corpus. */ + hasDeferredClaims: boolean } export type ClaudeUsageParsedTurn = { diff --git a/src/main/codex-accounts/runtime-home-service.test.ts b/src/main/codex-accounts/runtime-home-service.test.ts index 9a6b8566f577..9958e0fe867d 100644 --- a/src/main/codex-accounts/runtime-home-service.test.ts +++ b/src/main/codex-accounts/runtime-home-service.test.ts @@ -79,7 +79,7 @@ function createSettings(overrides: Partial = {}): GlobalSettings terminalRightClickToPaste: false, terminalFocusFollowsMouse: false, terminalClipboardOnSelect: false, - terminalAllowOsc52Clipboard: false, + terminalAllowOsc52Clipboard: true, setupScriptLaunchMode: 'split-vertical', terminalScrollbackRows: 5_000, localAccountRuntime: 'host', @@ -533,6 +533,124 @@ describe('CodexRuntimeHomeService', () => { } }) + it('promotes WSL in-Codex setting changes on the next Codex launch', async () => { + const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + vi.doMock('../codex/wsl-codex-session-bridge', () => ({ + startWslCodexSessionBridgeInBackground: vi.fn(() => Promise.resolve()) + })) + const wslHome = join(testState.userDataDir, 'wsl-home') + vi.doMock('../wsl', () => ({ + getDefaultWslDistro: () => 'Ubuntu', + getWslHome: () => wslHome + })) + const store = createStore( + createSettings({ + activeCodexManagedAccountId: null, + activeCodexManagedAccountIdsByRuntime: { host: null, wsl: { Ubuntu: null } } + }) + ) + const wslSystemConfigPath = join(wslHome, '.codex', 'config.toml') + mkdirSync(join(wslHome, '.codex'), { recursive: true }) + writeFileSync(wslSystemConfigPath, 'model = "gpt-5"\n', 'utf-8') + + try { + const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + const wslRuntimeHomePath = join( + wslHome, + '.local', + 'share', + 'orca', + 'codex-runtime-home', + 'home' + ) + + // First launch seeds the runtime config and records the per-distro baseline. + expect(service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe( + wslRuntimeHomePath + ) + const baselinePath = join(wslRuntimeHomePath, '.orca-config-settings-baseline.json') + expect(existsSync(baselinePath)).toBe(true) + + // A direct WSL Codex edit wins and is mirrored into Orca's runtime before + // the baseline advances, so later in-Orca changes remain promotable. + const runtimeConfigPath = join(wslRuntimeHomePath, 'config.toml') + writeFileSync(wslSystemConfigPath, 'model = "outside-edit"\n', 'utf-8') + service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) + expect(readFileSync(runtimeConfigPath, 'utf-8')).toBe('model = "outside-edit"\n') + expect(readFileSync(baselinePath, 'utf-8')).toContain('"model": "\\"outside-edit\\""') + + // Codex now persists a /model change inside Orca's reconciled runtime. + writeFileSync( + runtimeConfigPath, + readFileSync(runtimeConfigPath, 'utf-8').replace('model = "outside-edit"', 'model = "o4"'), + 'utf-8' + ) + + service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) + expect(readFileSync(wslSystemConfigPath, 'utf-8')).toBe('model = "o4"\n') + // Baseline advances so the promoted value is not re-promoted forever. + expect(readFileSync(baselinePath, 'utf-8')).toContain('"model": "\\"o4\\""') + } finally { + vi.doUnmock('../codex/wsl-codex-session-bridge') + vi.doUnmock('../wsl') + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + } + }) + + it('bridges WSL history from a configured per-distro source-home override', async () => { + const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + const startWslCodexSessionBridgeInBackground = vi.fn(() => Promise.resolve()) + vi.doMock('../codex/wsl-codex-session-bridge', () => ({ + startWslCodexSessionBridgeInBackground + })) + const wslHome = join(testState.userDataDir, 'wsl-home') + vi.doMock('../wsl', () => ({ + getDefaultWslDistro: () => 'Ubuntu', + getWslHome: () => wslHome + })) + const store = createStore( + createSettings({ + activeCodexManagedAccountId: null, + activeCodexManagedAccountIdsByRuntime: { host: null, wsl: { Ubuntu: null } }, + // Why: the override is a Linux path inside the distro, not /.codex. + codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } } + }) + ) + + try { + const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + const wslRuntimeHomePath = join( + wslHome, + '.local', + 'share', + 'orca', + 'codex-runtime-home', + 'home' + ) + + service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' }) + + expect(startWslCodexSessionBridgeInBackground).toHaveBeenCalledTimes(1) + expect(startWslCodexSessionBridgeInBackground).toHaveBeenCalledWith({ + distro: 'Ubuntu', + systemCodexHomePath: '/home/me/.config/codex', + managedCodexHomePath: wslRuntimeHomePath + }) + } finally { + vi.doUnmock('../codex/wsl-codex-session-bridge') + vi.doUnmock('../wsl') + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + } + }) + it('starts WSL session bridging for the distro used by the materialized runtime home', async () => { const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) @@ -1842,7 +1960,7 @@ describe('CodexRuntimeHomeService', () => { } }) - it('uses the stable WSL runtime home for WSL system-default rate-limit fetches', async () => { + it('reads WSL system-default rate limits from the live system home without materializing', async () => { const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) const wslHome = join(testState.userDataDir, 'wsl-home') @@ -1860,10 +1978,21 @@ describe('CodexRuntimeHomeService', () => { try { const { CodexRuntimeHomeService } = await import('./runtime-home-service') const service = new CodexRuntimeHomeService(store as never) - - expect(service.prepareForRateLimitFetch({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe( - join(wslHome, '.local', 'share', 'orca', 'codex-runtime-home', 'home') + const syncWslRuntime = vi.spyOn( + service as unknown as { + syncWslRuntimeForCurrentSelection: (target: { + runtime: 'wsl' + wslDistro?: string | null + }) => string | null + }, + 'syncWslRuntimeForCurrentSelection' ) + const target = { runtime: 'wsl' as const, wslDistro: 'Ubuntu' } + const expectedHome = join(wslHome, '.codex') + + expect(service.prepareForRateLimitFetch(target)).toBe(expectedHome) + expect(service.prepareForRateLimitFetch(target)).toBe(expectedHome) + expect(syncWslRuntime).not.toHaveBeenCalled() } finally { if (originalPlatform) { Object.defineProperty(process, 'platform', originalPlatform) @@ -1991,20 +2120,23 @@ describe('CodexRuntimeHomeService', () => { try { const { CodexRuntimeHomeService } = await import('./runtime-home-service') const service = new CodexRuntimeHomeService(store as never) - const wslRuntimeHomePath = join( - wslHome, - '.local', - 'share', - 'orca', - 'codex-runtime-home', - 'home' - ) - expect(service.prepareForRateLimitFetch({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe( - wslRuntimeHomePath + systemCodexHomePath ) expect(readFileSync(join(managedHomePath, 'auth.json'), 'utf-8')).toBe(managedAuth) - expect(readFileSync(join(wslRuntimeHomePath, 'auth.json'), 'utf-8')).toBe(systemDefaultAuth) + const externallyRefreshedAuth = createCodexAuthJson( + 'wsl@example.com', + 'acct-wsl', + 'system-refreshed', + 3_000 + ) + writeFileSync(join(systemCodexHomePath, 'auth.json'), externallyRefreshedAuth, 'utf-8') + expect(service.prepareForRateLimitFetch({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe( + systemCodexHomePath + ) + expect(readFileSync(join(systemCodexHomePath, 'auth.json'), 'utf-8')).toBe( + externallyRefreshedAuth + ) } finally { if (originalPlatform) { Object.defineProperty(process, 'platform', originalPlatform) diff --git a/src/main/codex-accounts/runtime-home-service.ts b/src/main/codex-accounts/runtime-home-service.ts index 3d2b0670354c..2c6259dd98eb 100644 --- a/src/main/codex-accounts/runtime-home-service.ts +++ b/src/main/codex-accounts/runtime-home-service.ts @@ -33,6 +33,7 @@ import { import { app } from 'electron' import type { CodexManagedAccount } from '../../shared/types' import type { Store } from '../persistence' +import { WSL_CODEX_RUNTIME_HOME_SEGMENTS } from '../pty/codex-home-wsl-env' import { writeFileAtomically } from './fs-utils' import { getOrcaManagedCodexHomePath, @@ -40,6 +41,10 @@ import { syncSystemCodexResourcesIntoManagedHome } from '../codex/codex-home-paths' import { startSystemCodexSessionBridgeInBackground } from '../codex/codex-session-bridge' +import { + resolveHostCodexSessionSourceHome, + resolveWslCodexSessionSourceHome +} from '../codex/codex-session-source-home' import { startWslCodexSessionBridgeInBackground } from '../codex/wsl-codex-session-bridge' import { prepareSystemConfigForFreshRuntimeMirror, @@ -135,9 +140,9 @@ export class CodexRuntimeHomeService { prepareForCodexLaunch(target?: CodexAccountSelectionTarget): string | null { if (target?.runtime === 'wsl') { const wslTarget = this.resolveWslDefaultTarget(target) - const runtimeHomePath = - this.syncWslRuntimeForCurrentSelection(wslTarget) ?? - this.getWslSystemCodexHomePath(wslTarget) + const syncedRuntimeHomePath = this.syncWslRuntimeForCurrentSelection(wslTarget) + this.syncWslConfigSettingsForLaunch(wslTarget, syncedRuntimeHomePath) + const runtimeHomePath = syncedRuntimeHomePath ?? this.getWslSystemCodexHomePath(wslTarget) this.startWslSessionBridgeForLaunch(wslTarget, runtimeHomePath) return runtimeHomePath } @@ -146,7 +151,10 @@ export class CodexRuntimeHomeService { syncSystemConfigIntoManagedCodexHome() // Why: historical Codex sessions can be large; bridge them after launch // setup so starting a fresh Codex TUI never waits on a full tree walk. - void startSystemCodexSessionBridgeInBackground() + void startSystemCodexSessionBridgeInBackground( + {}, + resolveHostCodexSessionSourceHome(this.store.getSettings()) + ) return this.getRuntimeHomePath() } @@ -162,10 +170,11 @@ export class CodexRuntimeHomeService { if (!distro) { return } - const systemCodexHomePath = this.getWslSystemCodexHomePath({ - runtime: 'wsl', - wslDistro: distro - }) + // Why: history-only override lets custom-CODEX_HOME users bridge from their + // real home; falls back to /.codex, which auth/config still use. + const systemCodexHomePath = + resolveWslCodexSessionSourceHome(this.store.getSettings(), distro) ?? + this.getWslSystemCodexHomePath({ runtime: 'wsl', wslDistro: distro }) if (!systemCodexHomePath || systemCodexHomePath === runtimeHomePath) { return } @@ -214,13 +223,33 @@ export class CodexRuntimeHomeService { return home ? this.joinWslPath(home, '.codex') : null } + // Why: WSL needs the same promote-then-mirror transaction as host. It keeps + // in-Orca changes while reconciling a newer external ~/.codex edit before + // advancing the per-distro baseline. Only runs on a materialized runtime. + private syncWslConfigSettingsForLaunch( + target: CodexAccountSelectionTarget, + runtimeHomePath: string | null + ): void { + if (!runtimeHomePath) { + return + } + const distro = + parseWslUncPath(runtimeHomePath)?.distro || target.wslDistro?.trim() || getDefaultWslDistro() + if (!distro) { + return + } + const systemHomePath = this.getWslSystemCodexHomePath({ runtime: 'wsl', wslDistro: distro }) + if (!systemHomePath || systemHomePath === runtimeHomePath) { + return + } + syncSystemConfigIntoManagedCodexHome({ runtimeHomePath, systemHomePath }) + } + prepareForRateLimitFetch(target?: CodexAccountSelectionTarget): string | null { if (target?.runtime === 'wsl') { const wslTarget = this.resolveWslDefaultTarget(target) - return ( - this.syncWslRuntimeForCurrentSelection(wslTarget) ?? - this.getWslSystemCodexHomePath(wslTarget) - ) + const syncedRuntimeHomePath = this.getPreparedWslRateLimitHomePath(wslTarget) + return syncedRuntimeHomePath ?? this.getWslSystemCodexHomePath(wslTarget) } this.syncForCurrentSelection() syncSystemCodexResourcesIntoManagedHome() @@ -495,6 +524,32 @@ export class CodexRuntimeHomeService { return parseWslUncPath(account.managedHomePath) ? account.managedHomePath : null } + private getPreparedWslRateLimitHomePath(target: CodexAccountSelectionTarget): string | null { + const distro = target.wslDistro?.trim() + if (distro) { + const settings = this.store.getSettings() + const selectedAccountId = getSelectedCodexAccountIdForTarget(settings, target) + if (selectedAccountId === null) { + // Why: the system-default account changes outside Orca (login, logout, + // token refresh). Read its real home directly so a cached runtime copy + // cannot stay stale; filesystem probing in the fetcher is asynchronous. + return this.getWslSystemCodexHomePath(target) + } + const cachedRuntimeHomePath = this.wslRuntimeHomePathByDistro.get(distro) + if ( + cachedRuntimeHomePath && + this.lastSyncedWslAccountIdByDistro.has(distro) && + this.lastSyncedWslAccountIdByDistro.get(distro) === selectedAccountId + ) { + // Why: RateLimitService resolves provenance twice per poll. Account + // changes sync explicitly, so repeated resolution must stay path-only + // instead of blocking main on UNC reads and a wsl.exe migration probe. + return cachedRuntimeHomePath + } + } + return this.syncWslRuntimeForCurrentSelection(target) + } + private syncWslRuntimeForCurrentSelection(target: CodexAccountSelectionTarget): string | null { if (process.platform !== 'win32') { return null @@ -603,9 +658,7 @@ export class CodexRuntimeHomeService { private getWslRuntimeHomePath(distro: string): string | null { const home = getWslHome(distro) - return home - ? this.joinWslPath(home, '.local', 'share', 'orca', 'codex-runtime-home', 'home') - : null + return home ? this.joinWslPath(home, ...WSL_CODEX_RUNTIME_HOME_SEGMENTS) : null } private safeReadBackActiveWslAccountBeforeRestart( diff --git a/src/main/codex-accounts/service.test.ts b/src/main/codex-accounts/service.test.ts index 69fed98ea8db..a7cf0d033e28 100644 --- a/src/main/codex-accounts/service.test.ts +++ b/src/main/codex-accounts/service.test.ts @@ -15,6 +15,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { PassThrough } from 'node:stream' import type { GlobalSettings } from '../../shared/types' +import { buildWslCodexAvailabilityArgs, buildWslCodexLoginArgs } from './wsl-codex-command' const testState = { userDataDir: '', @@ -83,7 +84,7 @@ function createSettings(overrides: Partial = {}): GlobalSettings terminalRightClickToPaste: false, terminalFocusFollowsMouse: false, terminalClipboardOnSelect: false, - terminalAllowOsc52Clipboard: false, + terminalAllowOsc52Clipboard: true, setupScriptLaunchMode: 'split-vertical', terminalScrollbackRows: 5_000, localAccountRuntime: 'host', @@ -766,20 +767,20 @@ describe('CodexAccountService config sync', () => { if (script.includes('readlink -f')) { return `${wslLinuxHomePath}\n` } + if (script.includes('command -v codex')) { + throw new Error('bash -ic does not inherit the distro login-shell PATH') + } + if (args.slice(2, 5).join(' ') === '-- sh -c') { + expect(args).toEqual(buildWslCodexAvailabilityArgs('Debian')) + return '' + } mkdirSync(wslManagedHomePath, { recursive: true }) writeFileSync(join(wslManagedHomePath, '.orca-managed-home'), 'account-id-for-test\n') return '' }) const spawnMock = vi.fn((command: string, args: string[]) => { expect(command).toBe('wsl.exe') - expect(args).toEqual([ - '-d', - 'Debian', - '--exec', - 'bash', - '-ic', - `export CODEX_HOME='${wslLinuxHomePath}'; exec codex login` - ]) + expect(args).toEqual(buildWslCodexLoginArgs('Debian', wslLinuxHomePath)) // Why: codex login runs inside WSL, so the rewritten path must be the // Linux-side ~/.codex, not a Windows UNC path. expect(readFileSync(join(wslManagedHomePath, 'config.toml'), 'utf-8')).toBe( @@ -876,8 +877,8 @@ describe('CodexAccountService config sync', () => { if (script.includes('readlink -f')) { return `${wslLinuxHomePath}\n` } - if (script.includes('command -v codex')) { - expect(args.slice(0, 5)).toEqual(['-d', 'Debian', '--exec', 'bash', '-ic']) + if (args.slice(2, 5).join(' ') === '-- sh -c') { + expect(args).toEqual(buildWslCodexAvailabilityArgs('Debian')) throw new Error('codex missing') } mkdirSync(wslManagedHomePath, { recursive: true }) @@ -960,14 +961,7 @@ describe('CodexAccountService config sync', () => { }) const spawnMock = vi.fn((command: string, args: string[]) => { expect(command).toBe('wsl.exe') - expect(args).toEqual([ - '-d', - 'Ubuntu', - '--exec', - 'bash', - '-ic', - `export CODEX_HOME='${wslLinuxHomePath}'; exec codex login` - ]) + expect(args).toEqual(buildWslCodexLoginArgs('Ubuntu', wslLinuxHomePath)) const child = new EventEmitter() as EventEmitter & { stdout: PassThrough stderr: PassThrough @@ -1075,14 +1069,7 @@ describe('CodexAccountService config sync', () => { }) const spawnMock = vi.fn((command: string, args: string[]) => { expect(command).toBe('wsl.exe') - expect(args).toEqual([ - '-d', - 'Ubuntu', - '--exec', - 'bash', - '-ic', - `export CODEX_HOME='${wslLinuxHomePath}'; exec codex login` - ]) + expect(args).toEqual(buildWslCodexLoginArgs('Ubuntu', wslLinuxHomePath)) expect(readFileSync(join(wslManagedHomePath, '.orca-managed-home'), 'utf-8')).toBe( 'account-1\n' ) diff --git a/src/main/codex-accounts/service.ts b/src/main/codex-accounts/service.ts index c979725633b2..2a0fb54bdc40 100644 --- a/src/main/codex-accounts/service.ts +++ b/src/main/codex-accounts/service.ts @@ -22,6 +22,11 @@ import type { RateLimitService } from '../rate-limits/service' import { parseWslUncPath } from '../../shared/wsl-paths' import { toWindowsWslPath } from '../wsl' import { buildEncodedWslBashCommand } from '../wsl-bash-command' +import { + buildWslCodexAvailabilityArgs, + buildWslCodexLoginArgs, + WSL_CODEX_AVAILABILITY_TIMEOUT_MS +} from './wsl-codex-command' import { getCodexSelectionTargetForAccount, getSelectedCodexAccountIdForTarget, @@ -805,15 +810,7 @@ export class CodexAccountService { const spawnConfig = wslInfo ? { command: 'wsl.exe', - // Why: nvm and similar WSL installs often initialize PATH from interactive shell config. - args: [ - '-d', - wslInfo.distro, - '--exec', - 'bash', - '-ic', - `export CODEX_HOME=${shellQuote(wslInfo.linuxPath)}; exec codex login` - ], + args: buildWslCodexLoginArgs(wslInfo.distro, wslInfo.linuxPath), env: process.env, codexCommand: 'codex' } @@ -923,18 +920,10 @@ export class CodexAccountService { private assertWslCodexCliAvailable(wslInfo: { distro: string; linuxPath: string }): void { try { - execFileSync( - 'wsl.exe', - [ - '-d', - wslInfo.distro, - '--exec', - 'bash', - '-ic', - buildEncodedWslBashCommand('command -v codex >/dev/null 2>&1') - ], - { encoding: 'utf-8', timeout: 5000 } - ) + execFileSync('wsl.exe', buildWslCodexAvailabilityArgs(wslInfo.distro), { + encoding: 'utf-8', + timeout: WSL_CODEX_AVAILABILITY_TIMEOUT_MS + }) } catch (error) { throw new Error( `Codex CLI is not available in WSL ${wslInfo.distro}. Install Codex in that distro or switch Account location to Windows.`, diff --git a/src/main/codex-accounts/wsl-codex-command.test.ts b/src/main/codex-accounts/wsl-codex-command.test.ts new file mode 100644 index 000000000000..f696ddcde4ff --- /dev/null +++ b/src/main/codex-accounts/wsl-codex-command.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { buildWslCodexAvailabilityArgs, buildWslCodexLoginArgs } from './wsl-codex-command' + +describe('WSL Codex commands', () => { + it('checks the alias-neutral PATH from the distro login shell', () => { + const args = buildWslCodexAvailabilityArgs('Ubuntu24-Dev') + + expect(args.slice(0, 5)).toEqual(['-d', 'Ubuntu24-Dev', '--', 'sh', '-c']) + expect(args.at(-1)).toContain('getent passwd') + expect(args.at(-1)).toContain('_orca_lookup_command=') + expect(args.at(-1)).toContain('codex') + expect(args.at(-1)).not.toContain('bash -ic') + }) + + it('launches the resolved Codex executable with its quoted managed home', () => { + const args = buildWslCodexLoginArgs('Ubuntu', '/home/alice/managed-home') + const command = args.at(-1) + + expect(command).toContain('export CODEX_HOME=') + expect(command).toContain('/home/alice/managed-home') + expect(command).toContain('exec "\\$resolved" login') + }) +}) diff --git a/src/main/codex-accounts/wsl-codex-command.ts b/src/main/codex-accounts/wsl-codex-command.ts new file mode 100644 index 000000000000..02527c8ed23a --- /dev/null +++ b/src/main/codex-accounts/wsl-codex-command.ts @@ -0,0 +1,43 @@ +import { buildPosixCommandPathLookupScript } from '../../shared/posix-command-path-lookup' +import { + buildWslLoginShellCommand, + escapeWslShCommandForWindows, + quotePosixShell +} from '../../shared/wsl-login-shell-command' + +export const WSL_CODEX_AVAILABILITY_TIMEOUT_MS = 5_000 + +export function buildWslCodexAvailabilityArgs(distro: string): string[] { + const command = [buildCodexPathLookup(), '[ -n "$resolved" ]'].join('\n') + return buildWslCodexShellArgs(distro, command) +} + +export function buildWslCodexLoginArgs(distro: string, linuxHomePath: string): string[] { + const command = [ + buildCodexPathLookup(), + 'if [ -z "$resolved" ]; then', + " printf '%s\\n' 'Codex CLI not found in the WSL login-shell PATH.' >&2", + ' exit 127', + 'fi', + `export CODEX_HOME=${quotePosixShell(linuxHomePath)}`, + 'exec "$resolved" login' + ].join('\n') + return buildWslCodexShellArgs(distro, command) +} + +function buildCodexPathLookup(): string { + return buildPosixCommandPathLookupScript({ kind: 'literal', value: 'codex' }) +} + +function buildWslCodexShellArgs(distro: string, command: string): string[] { + // Why: Codex must use the distro user's configured login shell, whose PATH + // can differ from a hard-coded non-login bash invocation. + return [ + '-d', + distro, + '--', + 'sh', + '-c', + escapeWslShCommandForWindows(buildWslLoginShellCommand(command)) + ] +} diff --git a/src/main/codex-usage/scanner-paths.test.ts b/src/main/codex-usage/scanner-paths.test.ts index 46c10be0c8fe..ecdc03e139f3 100644 --- a/src/main/codex-usage/scanner-paths.test.ts +++ b/src/main/codex-usage/scanner-paths.test.ts @@ -1,5 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { linkSync, lstatSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { + linkSync, + lstatSync, + mkdirSync, + mkdtempSync, + rmSync, + unlinkSync, + writeFileSync +} from 'node:fs' import { tmpdir } from 'node:os' import type * as NodeOs from 'node:os' import { join } from 'node:path' @@ -300,6 +308,216 @@ describe('listCodexSessionFiles', () => { ).toBe(3) }) + it('counts token events copied into forked rollout files exactly once', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'bbbb-fork.jsonl') + const copiedPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15) + ].join('') + writeFileSync(originalPath, copiedPrefix, 'utf-8') + writeFileSync(forkPath, `${copiedPrefix}${usageRecord('2026-05-26T12:02:00.000Z', 7, 22)}`) + + const result = await scanCodexUsageFiles([], []) + + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.eventCount, 0) + ).toBe(3) + expect(result.sessions).toHaveLength(1) + expect(result.sessions[0]?.totalTokens).toBe(22) + }) + + it('dedupes fork copies even when session_meta id is rewritten', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'bbbb-fork.jsonl') + const originalPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-original', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15) + ].join('') + // Same token_count records, different session_meta id (real resume/fork shape). + const forkBody = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-fork', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15), + usageRecord('2026-05-26T12:02:00.000Z', 7, 22) + ].join('') + writeFileSync(originalPath, originalPrefix, 'utf-8') + writeFileSync(forkPath, forkBody) + + const result = await scanCodexUsageFiles([], []) + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect(result.processedFiles[0]?.ownedEventKeys).toHaveLength(2) + expect(result.processedFiles[1]?.ownedEventKeys).toHaveLength(1) + expect(result.processedFiles[1]?.hasDeferredClaims).toBe(true) + }) + + it('does not re-count the cumulative session for copied total-only records', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'bbbb-fork.jsonl') + const copiedPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + totalOnlyUsageRecord('2026-05-26T12:00:00.000Z', 10), + totalOnlyUsageRecord('2026-05-26T12:01:00.000Z', 15) + ].join('') + writeFileSync(originalPath, copiedPrefix, 'utf-8') + // Without cross-file ownership the fork's first copied total-only record + // re-counts the entire cumulative session (10) as a fresh delta. + writeFileSync( + forkPath, + `${copiedPrefix}${totalOnlyUsageRecord('2026-05-26T12:02:00.000Z', 22)}` + ) + + const result = await scanCodexUsageFiles([], []) + + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.eventCount, 0) + ).toBe(3) + }) + + it('keeps fork dedupe stable when the original file is reused from cache', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'zzzz-fork.jsonl') + const copiedPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15) + ].join('') + writeFileSync(originalPath, copiedPrefix, 'utf-8') + + const first = await scanCodexUsageFiles([], []) + expect( + first.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(15) + expect(first.processedFiles[0]?.ownedEventKeys).toHaveLength(2) + + // A fork appears later while the original stays unchanged (cache reuse). + writeFileSync(forkPath, `${copiedPrefix}${usageRecord('2026-05-26T12:02:00.000Z', 7, 22)}`) + + const second = await scanCodexUsageFiles([], first.processedFiles) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect(second.processedFiles.map((file) => file.ownedEventKeys.length)).toEqual([2, 1]) + + // Rescanning with the full cache stays stable. + const third = await scanCodexUsageFiles([], second.processedFiles) + expect( + third.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + }) + + it('reclaims copied token events when the owning original file is deleted', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'bbbb-fork.jsonl') + const copiedPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15) + ].join('') + writeFileSync(originalPath, copiedPrefix, 'utf-8') + writeFileSync(forkPath, `${copiedPrefix}${usageRecord('2026-05-26T12:02:00.000Z', 7, 22)}`) + + const first = await scanCodexUsageFiles([], []) + expect( + first.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect(first.processedFiles[0]?.ownedEventKeys).toHaveLength(2) + expect(first.processedFiles[0]?.hasDeferredClaims).toBe(false) + expect(first.processedFiles[1]?.ownedEventKeys).toHaveLength(1) + expect(first.processedFiles[1]?.hasDeferredClaims).toBe(true) + + // Deleting the owner must reparse deferred forks so they can re-claim the + // copied prefix instead of permanently under-counting. + unlinkSync(originalPath) + + const second = await scanCodexUsageFiles([], first.processedFiles) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect(second.processedFiles).toHaveLength(1) + expect(second.processedFiles[0]?.ownedEventKeys).toHaveLength(3) + }) + + it('keeps unrelated cached rollouts when a different owner file is deleted', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'bbbb-fork.jsonl') + const unrelatedPath = join(sessionsDir, 'cccc-unrelated.jsonl') + const copiedPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15) + ].join('') + writeFileSync(originalPath, copiedPrefix, 'utf-8') + writeFileSync(forkPath, `${copiedPrefix}${usageRecord('2026-05-26T12:02:00.000Z', 7, 22)}`) + writeFileSync( + unrelatedPath, + [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-9', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T13:00:00.000Z', 3) + ].join('') + ) + + const first = await scanCodexUsageFiles([], []) + const unrelatedBefore = first.processedFiles.find((file) => file.path === unrelatedPath) + expect(unrelatedBefore?.hasDeferredClaims).toBe(false) + expect(unrelatedBefore?.ownedEventKeys).toHaveLength(1) + + unlinkSync(originalPath) + + const second = await scanCodexUsageFiles([], first.processedFiles) + const unrelatedAfter = second.processedFiles.find((file) => file.path === unrelatedPath) + expect(unrelatedAfter).toBe(unrelatedBefore) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(25) + }) + it('treats a leading total-only source suffix record as baseline', async () => { const runtimeSessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') const runtimeBridgeMarkerDir = join( diff --git a/src/main/codex-usage/scanner.test.ts b/src/main/codex-usage/scanner.test.ts index 62777257b067..6426222461f6 100644 --- a/src/main/codex-usage/scanner.test.ts +++ b/src/main/codex-usage/scanner.test.ts @@ -99,6 +99,7 @@ describe('parseCodexUsageRecord', () => { expect(first).toEqual({ sessionId: 'session-1', timestamp: '2026-04-09T10:00:00.000Z', + eventKey: expect.any(String), cwd: '/workspace/repo/packages/app', model: 'gpt-5.2-codex', hasInferredPricing: false, @@ -196,6 +197,7 @@ describe('attributeCodexUsageEvent', () => { { sessionId: 'session-1', timestamp: '2026-04-09T10:00:00.000Z', + eventKey: 'event-1', cwd: '/workspace/repo/app2/subdir', model: 'gpt-5.2-codex', hasInferredPricing: false, @@ -233,6 +235,7 @@ describe('attributeCodexUsageEvent', () => { { sessionId: 'session-1', timestamp: '2026-04-09T10:00:00.000Z', + eventKey: 'event-1', cwd: '/workspace/repo/..fixtures/session', model: 'gpt-5.2-codex', hasInferredPricing: false, @@ -263,6 +266,7 @@ describe('attributeCodexUsageEvent', () => { { sessionId: 'session-1', timestamp: '2026-04-09T10:00:00.000Z', + eventKey: 'event-1', cwd: '/workspace/repo/../other/session', model: 'gpt-5.2-codex', hasInferredPricing: false, @@ -292,6 +296,7 @@ describe('attributeCodexUsageEvent', () => { { sessionId: 'session-1', timestamp: '2026-04-09T10:00:00.000Z', + eventKey: 'event-1', cwd: 'D:\\other\\repo', model: 'gpt-5.2-codex', hasInferredPricing: false, diff --git a/src/main/codex-usage/scanner.ts b/src/main/codex-usage/scanner.ts index a9764b53bb75..97e8f6f7b093 100644 --- a/src/main/codex-usage/scanner.ts +++ b/src/main/codex-usage/scanner.ts @@ -388,6 +388,28 @@ function resolveCodexUsageDelta( return null } +function buildCodexUsageEventKey( + timestamp: string, + totalUsage: CodexUsageRawUsage | null, + lastUsage: CodexUsageRawUsage | null +): string { + // Why: fork/resume copies token_count records byte-for-byte into a new + // rollout file, but session_meta.id is often rewritten to the new session. + // Key only on the raw record fields (timestamp + usage tuples) so the copy + // matches the original regardless of surrounding parse context / session id. + const tupleOf = (usage: CodexUsageRawUsage | null): string => + usage + ? [ + usage.inputTokens, + usage.cachedInputTokens, + usage.outputTokens, + usage.reasoningOutputTokens, + usage.totalTokens + ].join(',') + : '' + return [timestamp, tupleOf(totalUsage), tupleOf(lastUsage)].join('|') +} + function extractString(value: unknown): string | null { if (typeof value !== 'string') { return null @@ -956,6 +978,7 @@ export function parseCodexUsageRecord( return { sessionId: context.sessionId, timestamp: parsed.timestamp, + eventKey: buildCodexUsageEventKey(parsed.timestamp, totalUsage, lastUsage), cwd: context.currentCwd ?? context.sessionCwd, model: resolvedModel, hasInferredPricing, @@ -970,7 +993,7 @@ export function parseCodexUsageRecord( export async function parseCodexUsageFile( filePath: string, worktrees: (CodexUsageWorktreeRef & { canonicalPath: string })[], - options: { skipInitialBytes?: number } = {} + options: { skipInitialBytes?: number; claimEventKey?: (eventKey: string) => boolean } = {} ): Promise { const processedFile = await getProcessedFileInfo(filePath) const lines = createInterface({ @@ -992,11 +1015,21 @@ export async function parseCodexUsageFile( totalOnlyBaselinePending: (options.skipInitialBytes ?? 0) > 0 } + const ownedEventKeys = new Set() + let hasDeferredClaims = false for await (const line of lines) { const parsed = parseCodexUsageRecord(line, context) if (!parsed) { continue } + // Why: fork/resume rollouts start with a copied prefix of the parent file. + // Events another file already owns are dropped here, but the record still + // advanced context.previousTotals above, so later deltas stay correct. + if (options.claimEventKey && !options.claimEventKey(parsed.eventKey)) { + hasDeferredClaims = true + continue + } + ownedEventKeys.add(parsed.eventKey) const attributed = await attributeCodexUsageEvent(parsed, worktrees) if (attributed) { events.push(attributed) @@ -1005,7 +1038,9 @@ export async function parseCodexUsageFile( return { ...processedFile, - ...aggregateCodexUsage(events) + ...aggregateCodexUsage(events), + ownedEventKeys: [...ownedEventKeys], + hasDeferredClaims } } @@ -1019,31 +1054,77 @@ export async function scanCodexUsageFiles( }> { const files = await listCodexSessionFiles() const previousByPath = new Map(previousProcessedFiles.map((file) => [file.path, file])) - const processedFiles: CodexUsagePersistedFile[] = [] const worktreesWithCanonicalPaths = await buildWorktreesWithCanonicalPaths(worktrees) const legacySourceSkipBytesByPath = getLegacySourceSkipBytesByPath(files) - const sessionsById = new Map() - const dailyByKey = new Map() + const currentPaths = new Set(files) + // Why: when a rollout that owned event keys is deleted, remaining forks still + // contain those records but their caches record them as unowned. Only files + // that previously deferred claims can reclaim, so invalidate those — not the + // entire rollout corpus. + const lostOwnerPath = previousProcessedFiles.some( + (file) => + !currentPaths.has(file.path) && + Array.isArray(file.ownedEventKeys) && + file.ownedEventKeys.length > 0 + ) + + const reusedByPath = new Map() + const pathsToParse: string[] = [] for (const [index, filePath] of files.entries()) { const legacySourceSkipBytes = legacySourceSkipBytesByPath.get(filePath) ?? 0 const fileInfo = await getProcessedFileInfo(filePath) const previous = previousByPath.get(filePath) + // When an owner disappears, only deferred-claim files need reparse. + const mustReclaimDeferred = lostOwnerPath && previous?.hasDeferredClaims !== false const canReuse = + !mustReclaimDeferred && legacySourceSkipBytes === 0 && previous && previous.mtimeMs === fileInfo.mtimeMs && - previous.size === fileInfo.size + previous.size === fileInfo.size && + Array.isArray(previous.ownedEventKeys) && + typeof previous.hasDeferredClaims === 'boolean' + if (canReuse) { + reusedByPath.set(filePath, previous) + } else { + pathsToParse.push(filePath) + } + if ((index + 1) % YIELD_EVERY_FILES === 0) { + await yieldToEventLoop() + } + } - const processed = canReuse - ? previous - : await parseCodexUsageFile(filePath, worktreesWithCanonicalPaths, { - skipInitialBytes: legacySourceSkipBytes - }) + // Why: resuming or forking a Codex session copies the parent rollout's + // token_count records into a new file, so per-file parsing re-counts the + // whole copied history once per descendant (#8006). Cross-file ownership + // counts each record for exactly one file; cached files keep the claims + // they persisted, and new files claim in sorted-path order so rescans stay + // deterministic. + const eventOwnerByKey = new Map() + for (const [filePath, previous] of reusedByPath) { + for (const eventKey of previous.ownedEventKeys) { + // First cached claim wins so conflicting projections stay deterministic. + if (!eventOwnerByKey.has(eventKey)) { + eventOwnerByKey.set(eventKey, filePath) + } + } + } - processedFiles.push(processed) - mergeSessions(sessionsById, processed.sessions) - mergeDailyAggregates(dailyByKey, processed.dailyAggregates) + const parsedByPath = new Map() + for (const [index, filePath] of pathsToParse.entries()) { + const processed = await parseCodexUsageFile(filePath, worktreesWithCanonicalPaths, { + skipInitialBytes: legacySourceSkipBytesByPath.get(filePath) ?? 0, + claimEventKey: (eventKey) => { + const owner = eventOwnerByKey.get(eventKey) + if (owner !== undefined && owner !== filePath) { + return false + } + eventOwnerByKey.set(eventKey, filePath) + return true + } + }) + parsedByPath.set(filePath, processed) // Why: Codex session history can grow large, and scans run on the Electron // main process. Yield regularly so opening Settings does not stall while @@ -1053,6 +1134,19 @@ export async function scanCodexUsageFiles( } } + const processedFiles: CodexUsagePersistedFile[] = [] + const sessionsById = new Map() + const dailyByKey = new Map() + for (const filePath of files) { + const processed = reusedByPath.get(filePath) ?? parsedByPath.get(filePath) + if (!processed) { + continue + } + processedFiles.push(processed) + mergeSessions(sessionsById, processed.sessions) + mergeDailyAggregates(dailyByKey, processed.dailyAggregates) + } + return { processedFiles, sessions: finalizeSessions(sessionsById), diff --git a/src/main/codex-usage/store.test.ts b/src/main/codex-usage/store.test.ts index 1bb3732373b4..055af8f3a23c 100644 --- a/src/main/codex-usage/store.test.ts +++ b/src/main/codex-usage/store.test.ts @@ -111,7 +111,7 @@ describe('CodexUsageStore', () => { it('persists a successful refresh with one compact disk write', async () => { const store = createStoreWithState({ - schemaVersion: 3, + schemaVersion: 5, scanState: { enabled: true, lastScanStartedAt: null, @@ -138,7 +138,7 @@ describe('CodexUsageStore', () => { const pendingScan = createDeferred() vi.mocked(scanCodexUsageFiles).mockReturnValueOnce(pendingScan.promise) const store = createStoreWithState({ - schemaVersion: 3, + schemaVersion: 5, scanState: { enabled: true, lastScanStartedAt: null, @@ -768,7 +768,7 @@ describe('CodexUsageStore', () => { } as unknown as CodexUsagePersistedState) expect(normalized).toEqual({ - schemaVersion: 3, + schemaVersion: 5, worktreeFingerprint: null, processedFiles: [], sessions: [], diff --git a/src/main/codex-usage/store.ts b/src/main/codex-usage/store.ts index e2963245ca93..ca42ba340614 100644 --- a/src/main/codex-usage/store.ts +++ b/src/main/codex-usage/store.ts @@ -19,7 +19,10 @@ import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-w import type { CodexUsagePersistedState } from './types' import { createWorktreeRefs, scanCodexUsageFiles } from './scanner' -const SCHEMA_VERSION = 3 +// Why: v5 keys Codex ownership on raw token_count identity without session id +// so forks that rewrite session_meta still match. Older caches used session- +// scoped keys and can double-count after fork/resume (#8006). +const SCHEMA_VERSION = 5 const STALE_MS = 5 * 60_000 const AUTOMATION_ATTRIBUTION_WINDOW_MS = 5 * 60_000 diff --git a/src/main/codex-usage/types.ts b/src/main/codex-usage/types.ts index 4b54c6f6cee4..d7e6f058b456 100644 --- a/src/main/codex-usage/types.ts +++ b/src/main/codex-usage/types.ts @@ -86,6 +86,14 @@ export type CodexUsageDailyAggregate = { export type CodexUsagePersistedFile = CodexUsageProcessedFile & { sessions: CodexUsageSession[] dailyAggregates: CodexUsageDailyAggregate[] + /** Event keys this file counted. Resumed/forked rollouts copy earlier + * token_count records into new files; ownership keeps each record counted + * by exactly one cached file across incremental scans. */ + ownedEventKeys: string[] + /** True when this file saw events already claimed by another file. When that + * owner disappears, only deferred files need reparse to reclaim — not the + * entire rollout corpus. */ + hasDeferredClaims: boolean } export type CodexUsagePersistedState = { @@ -105,6 +113,10 @@ export type CodexUsagePersistedState = { export type CodexUsageParsedEvent = { sessionId: string timestamp: string + /** Raw-record identity (timestamp + token tuples) used to dedupe the same + * token_count record copied across fork/resume rollout files. Session id is + * omitted because forks rewrite session_meta while copying the record. */ + eventKey: string model: string | null cwd: string | null hasInferredPricing: boolean diff --git a/src/main/codex/codex-config-mirror.test.ts b/src/main/codex/codex-config-mirror.test.ts index 416ce9af78b8..1ef1f61dd0b2 100644 --- a/src/main/codex/codex-config-mirror.test.ts +++ b/src/main/codex/codex-config-mirror.test.ts @@ -25,6 +25,7 @@ vi.mock('node:os', async () => { import { prepareSystemConfigForFreshRuntimeMirror, + resolveCodexConfigMirrorSourceDirectory, syncSystemConfigIntoManagedCodexHome } from './codex-config-mirror' @@ -313,6 +314,236 @@ describe('syncSystemConfigIntoManagedCodexHome', () => { expect(runtimeConfig.match(/\[projects\."\/repo"\]/g)?.length).toBe(1) }) + it('deduplicates basic and literal project headers by decoded Windows path', () => { + mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true }) + writeFileSync( + getRuntimeConfigPath(), + ["[projects.'c:\\gemini_etl']", 'trust_level = "trusted"', ''].join('\n'), + 'utf-8' + ) + writeFileSync( + getSystemConfigPath(), + ['[projects."c:\\\\gemini_etl"]', 'trust_level = "trusted"', ''].join('\n'), + 'utf-8' + ) + + syncSystemConfigIntoManagedCodexHome() + + const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8') + expect(runtimeConfig.match(/\[projects\./g)).toHaveLength(1) + expect(runtimeConfig).toContain("[projects.'c:\\gemini_etl']") + }) + + it('deduplicates a CRLF system project header against an LF runtime header', () => { + mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true }) + const projectHeader = '[projects."C:/Users/jinwo/orca/workspaces/orca/repo"]' + writeFileSync( + getRuntimeConfigPath(), + [projectHeader, 'trust_level = "trusted"', ''].join('\n'), + 'utf-8' + ) + writeFileSync( + getSystemConfigPath(), + [projectHeader, 'trust_level = "trusted"', ''].join('\r\n'), + 'utf-8' + ) + + syncSystemConfigIntoManagedCodexHome() + + const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8') + expect(runtimeConfig.match(/\[projects\./g)).toHaveLength(1) + expect(runtimeConfig).toContain(`${projectHeader}\ntrust_level = "trusted"`) + }) + + it('self-heals duplicate project tables in a CRLF runtime config', () => { + mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true }) + const projectHeader = '[projects."C:/Users/jinwo/orca/workspaces/orca/repo"]' + writeFileSync( + getRuntimeConfigPath(), + [ + projectHeader, + 'trust_level = "trusted"', + '', + projectHeader, + 'trust_level = "trusted"', + '' + ].join('\r\n'), + 'utf-8' + ) + writeFileSync(getSystemConfigPath(), 'model = "gpt-5"\n', 'utf-8') + + syncSystemConfigIntoManagedCodexHome() + + const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8') + expect(runtimeConfig.match(/\[projects\./g)).toHaveLength(1) + expect(runtimeConfig).toContain('trust_level = "trusted"') + }) + + it('applies a CRLF system revocation to an LF runtime project', () => { + mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true }) + writeFileSync( + getRuntimeConfigPath(), + ["[projects.'c:\\repo']", 'trust_level = "trusted"', ''].join('\n'), + 'utf-8' + ) + writeFileSync( + getSystemConfigPath(), + ['[projects."C:/repo"]', 'trust_level = "untrusted"', ''].join('\r\n'), + 'utf-8' + ) + + syncSystemConfigIntoManagedCodexHome() + + const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8') + expect(runtimeConfig.match(/\[projects\./g)).toHaveLength(1) + expect(runtimeConfig).toContain('trust_level = "untrusted"') + expect(runtimeConfig).not.toContain('trust_level = "trusted"') + }) + + it('lets a semantically matching system revocation replace runtime trust', () => { + mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true }) + writeFileSync( + getRuntimeConfigPath(), + ["[projects.'c:\\gemini_etl']", 'trust_level = "trusted"', ''].join('\n'), + 'utf-8' + ) + writeFileSync( + getSystemConfigPath(), + ['[projects."C:/gemini_etl"]', 'trust_level = "untrusted"', ''].join('\n'), + 'utf-8' + ) + + syncSystemConfigIntoManagedCodexHome() + + const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8') + expect(runtimeConfig.match(/\[projects\./g)).toHaveLength(1) + expect(runtimeConfig).toContain('[projects."C:/gemini_etl"]') + expect(runtimeConfig).toContain('trust_level = "untrusted"') + expect(runtimeConfig).not.toContain('trust_level = "trusted"') + }) + + it.each([ + { + name: 'drive-letter casing and separators', + runtimePath: 'c:\\work\\repo', + systemPath: 'C:/work/repo' + }, + { + name: 'WSL UNC path', + runtimePath: '\\\\wsl$\\Ubuntu\\home\\u\\proj', + systemPath: '//WSL$/ubuntu/home/u/proj' + }, + { + name: 'server UNC path', + runtimePath: '\\\\server\\share\\proj', + systemPath: '//SERVER/share/proj' + } + ])('deduplicates $name across mirror inputs', ({ runtimePath, systemPath }) => { + mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true }) + writeFileSync( + getRuntimeConfigPath(), + [`[projects.'${runtimePath}']`, 'trust_level = "trusted"', ''].join('\n'), + 'utf-8' + ) + writeFileSync( + getSystemConfigPath(), + [`[projects."${systemPath}"]`, 'trust_level = "trusted"', ''].join('\n'), + 'utf-8' + ) + + syncSystemConfigIntoManagedCodexHome() + + expect(readFileSync(getRuntimeConfigPath(), 'utf-8').match(/\[projects\./g)).toHaveLength(1) + }) + + it('self-heals duplicate project tables already present in the runtime config', () => { + mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true }) + writeFileSync( + getRuntimeConfigPath(), + [ + '[projects."c:\\\\gemini_etl"]', + 'trust_level = "trusted"', + '', + "[projects.'c:\\gemini_etl']", + 'trust_level = "trusted"', + '' + ].join('\n'), + 'utf-8' + ) + writeFileSync(getSystemConfigPath(), 'model = "gpt-5"\n', 'utf-8') + + syncSystemConfigIntoManagedCodexHome() + + const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8') + expect(runtimeConfig.match(/\[projects\./g)).toHaveLength(1) + expect(runtimeConfig).toContain('[projects."c:\\\\gemini_etl"]') + }) + + it('keeps untrusted when self-healing duplicate project tables', () => { + mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true }) + writeFileSync( + getRuntimeConfigPath(), + [ + '[projects."c:\\\\gemini_etl"]', + 'trust_level = "trusted"', + '', + "[projects.'C:\\gemini_etl']", + 'trust_level = "untrusted"', + '' + ].join('\n'), + 'utf-8' + ) + writeFileSync(getSystemConfigPath(), 'model = "gpt-5"\n', 'utf-8') + + syncSystemConfigIntoManagedCodexHome() + + const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8') + expect(runtimeConfig.match(/\[projects\./g)).toHaveLength(1) + expect(runtimeConfig).toContain('trust_level = "untrusted"') + expect(runtimeConfig).not.toContain('trust_level = "trusted"') + }) + + it('keeps untrusted when self-healing duplicate system project tables', () => { + writeFileSync( + getSystemConfigPath(), + [ + '[projects."c:\\\\gemini_etl"]', + 'trust_level = "trusted"', + '', + "[projects.'C:\\gemini_etl']", + 'trust_level = "untrusted"', + '' + ].join('\n'), + 'utf-8' + ) + + syncSystemConfigIntoManagedCodexHome() + + const runtimeConfig = readFileSync(getRuntimeConfigPath(), 'utf-8') + expect(runtimeConfig.match(/\[projects\./g)).toHaveLength(1) + expect(runtimeConfig).toContain('trust_level = "untrusted"') + expect(runtimeConfig).not.toContain('trust_level = "trusted"') + }) + + it('deduplicates a POSIX project path containing a quote and backslash', () => { + const projectPath = '/tmp/with"quote\\and-backslash' + mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true }) + writeFileSync( + getRuntimeConfigPath(), + [`[projects.'${projectPath}']`, 'trust_level = "trusted"', ''].join('\n'), + 'utf-8' + ) + writeFileSync( + getSystemConfigPath(), + [`[projects."/tmp/with\\"quote\\\\and-backslash"]`, 'trust_level = "trusted"', ''].join('\n'), + 'utf-8' + ) + + syncSystemConfigIntoManagedCodexHome() + + expect(readFileSync(getRuntimeConfigPath(), 'utf-8').match(/\[projects\./g)).toHaveLength(1) + }) + it('does not treat TOML table headers inside multiline strings as sections', () => { mkdirSync(join(userDataDir, 'codex-runtime-home', 'home'), { recursive: true }) writeFileSync( @@ -402,6 +633,20 @@ describe('syncSystemConfigIntoManagedCodexHome', () => { }) describe('prepareSystemConfigForFreshRuntimeMirror', () => { + it('uses the Linux-side directory for WSL UNC source homes', () => { + const sourceDir = resolveCodexConfigMirrorSourceDirectory( + '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex' + ) + + expect(sourceDir).toBe('/home/alice/.codex') + expect( + prepareSystemConfigForFreshRuntimeMirror( + 'model_instructions_file = "instructions.md"\n', + sourceDir + ) + ).toContain("model_instructions_file = '/home/alice/.codex/instructions.md'") + }) + it('rewrites relative paths against a Linux-side home and strips hook trust', () => { const prepared = prepareSystemConfigForFreshRuntimeMirror( [ diff --git a/src/main/codex/codex-config-mirror.ts b/src/main/codex/codex-config-mirror.ts index ce9208e9b059..1949a703d414 100644 --- a/src/main/codex/codex-config-mirror.ts +++ b/src/main/codex/codex-config-mirror.ts @@ -3,32 +3,54 @@ import { dirname, join } from 'node:path' import { writeFileAtomically } from '../codex-accounts/fs-utils' import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from './codex-home-paths' import { rewriteRelativePathConfigValues } from './codex-config-path-reference-rewrite' +import { parseWslUncPath } from '../../shared/wsl-paths' +import { + promoteCodexRuntimeSettingsToSystem, + snapshotCodexRuntimeSettingsBaseline, + type CodexSettingsPromotionHomes +} from './config-settings-promotion' import { createTomlLineScanState, getTomlTableHeader, isTomlStructuralLine, updateTomlLineScanState } from './config-toml-line-scan' +import { + normalizeCodexProjectPathForLookup, + parseCodexProjectHeaderPath +} from './config-toml-trust' -function getRuntimeCodexConfigTomlPath(): string { - return join(getOrcaManagedCodexHomePath(), 'config.toml') -} - -function getSystemCodexConfigTomlPath(): string { - return join(getSystemCodexHomePath(), 'config.toml') -} - -export function syncSystemConfigIntoManagedCodexHome(): void { +export function syncSystemConfigIntoManagedCodexHome( + homes: CodexSettingsPromotionHomes = { + runtimeHomePath: getOrcaManagedCodexHomePath(), + systemHomePath: getSystemCodexHomePath() + } +): void { + // Why: the mirror overwrites runtime settings from ~/.codex, so changes the + // user made inside Orca-launched Codex (/model, /approvals) must be written + // back to ~/.codex first or this very pass silently reverts them. + if (!promoteCodexRuntimeSettingsToSystem(homes)) { + // Why: mirroring after a failed write-back would erase the runtime change; + // leave both runtime and its old baseline intact so the next launch retries. + return + } try { - syncSystemConfigIntoManagedCodexHomeUnsafe() + syncSystemConfigIntoManagedCodexHomeUnsafe(homes) } catch (error) { console.warn('[codex-config] Failed to mirror system Codex config:', error) + return } + // Why: the baseline advances only after a successful mirror; recording an + // unpromoted runtime change as Orca-written would strand it forever. + snapshotCodexRuntimeSettingsBaseline(homes.runtimeHomePath) } -function syncSystemConfigIntoManagedCodexHomeUnsafe(): void { - const systemConfigPath = getSystemCodexConfigTomlPath() - const runtimeConfigPath = getRuntimeCodexConfigTomlPath() +function syncSystemConfigIntoManagedCodexHomeUnsafe({ + runtimeHomePath, + systemHomePath +}: CodexSettingsPromotionHomes): void { + const systemConfigPath = join(systemHomePath, 'config.toml') + const runtimeConfigPath = join(runtimeHomePath, 'config.toml') const systemConfigExists = existsSync(systemConfigPath) const runtimeConfigExists = existsSync(runtimeConfigPath) if (!systemConfigExists && !runtimeConfigExists) { @@ -36,18 +58,16 @@ function syncSystemConfigIntoManagedCodexHomeUnsafe(): void { } const rawSystemConfig = systemConfigExists ? readFileSync(systemConfigPath, 'utf-8') : '' + const sourceConfigDir = resolveCodexConfigMirrorSourceDirectory(systemHomePath) if (!runtimeConfigExists) { writeFileAtomically( runtimeConfigPath, - prepareSystemConfigForFreshRuntimeMirror(rawSystemConfig, dirname(systemConfigPath)) + prepareSystemConfigForFreshRuntimeMirror(rawSystemConfig, sourceConfigDir) ) return } - const systemConfig = prepareSystemConfigForRuntimeMirror( - rawSystemConfig, - dirname(systemConfigPath) - ) + const systemConfig = prepareSystemConfigForRuntimeMirror(rawSystemConfig, sourceConfigDir) const runtimeConfig = readFileSync(runtimeConfigPath, 'utf-8') const mergedConfig = mergeSystemCodexConfigIntoRuntime(runtimeConfig, systemConfig) if (mergedConfig !== runtimeConfig) { @@ -55,6 +75,10 @@ function syncSystemConfigIntoManagedCodexHomeUnsafe(): void { } } +export function resolveCodexConfigMirrorSourceDirectory(systemHomePath: string): string { + return parseWslUncPath(systemHomePath)?.linuxPath ?? dirname(join(systemHomePath, 'config.toml')) +} + function prepareSystemConfigForRuntimeMirror(config: string, systemConfigDir: string): string { return rewriteRelativePathConfigValues( normalizeDeprecatedCodexHookFeatureFlag(config), @@ -140,14 +164,14 @@ function normalizeFeatureSectionLines(lines: string[], start: number, end: numbe } function mergeSystemCodexConfigIntoRuntime(runtimeConfig: string, systemConfig: string): string { - const runtimeSections = getTomlSections(runtimeConfig) + const runtimeSections = deduplicateProjectTomlSections(getTomlSections(runtimeConfig)) const runtimeProjectHeaders = new Set( runtimeSections .filter((section) => isRuntimeProjectTomlSection(section.header)) .map((section) => getTomlSectionHeaderKey(section.header)) ) const systemUntrustedProjectHeaders = new Set( - getTomlSections(systemConfig) + deduplicateProjectTomlSections(getTomlSections(systemConfig)) .filter((section) => isRuntimeProjectTomlSection(section.header)) .filter((section) => getProjectTrustLevel(section.block) === 'untrusted') .map((section) => getTomlSectionHeaderKey(section.header)) @@ -180,8 +204,9 @@ function stripRuntimeOwnedTomlSections( runtimeProjectHeaders = new Set() ): string { const lines = config.split('\n') - const sections = getTomlSections(config) - const firstSectionIndex = sections[0]?.start ?? -1 + const sourceSections = getTomlSections(config) + const sections = deduplicateProjectTomlSections(sourceSections) + const firstSectionIndex = sourceSections[0]?.start ?? -1 const preamble = firstSectionIndex === -1 ? config : lines.slice(0, firstSectionIndex).join('\n') return joinTomlBlocks([ preamble, @@ -242,11 +267,44 @@ function isRuntimeHookTrustTomlSection(header: string): boolean { } function isRuntimeProjectTomlSection(header: string): boolean { - return header.trimStart().startsWith('[projects.') + return parseCodexProjectHeaderPath(header) !== null } function getTomlSectionHeaderKey(header: string): string { - return header.trim() + const projectPath = parseCodexProjectHeaderPath(header) + return projectPath === null + ? header.trim() + : `project:${normalizeCodexProjectPathForLookup(projectPath)}` +} + +// Why: hook upsert already removes both quote representations, while its paired +// Windows slash variants are required for Codex 0.140 and must remain distinct. +function deduplicateProjectTomlSections(sections: TomlSection[]): TomlSection[] { + const deduplicated: TomlSection[] = [] + const projectIndexes = new Map() + for (const section of sections) { + if (!isRuntimeProjectTomlSection(section.header)) { + deduplicated.push(section) + continue + } + const key = getTomlSectionHeaderKey(section.header) + const existingIndex = projectIndexes.get(key) + if (existingIndex === undefined) { + projectIndexes.set(key, deduplicated.length) + deduplicated.push(section) + continue + } + const existing = deduplicated[existingIndex] + if ( + existing && + getProjectTrustLevel(existing.block) !== 'untrusted' && + getProjectTrustLevel(section.block) === 'untrusted' + ) { + // Why: revocation must survive self-healing regardless of duplicate order. + deduplicated[existingIndex] = section + } + } + return deduplicated } function getProjectTrustLevel(block: string): 'trusted' | 'untrusted' | null { diff --git a/src/main/codex/codex-hook-identity.ts b/src/main/codex/codex-hook-identity.ts new file mode 100644 index 000000000000..cc78a9acb76f --- /dev/null +++ b/src/main/codex/codex-hook-identity.ts @@ -0,0 +1,72 @@ +import type { HookCommandConfig, HookDefinition } from '../agent-hooks/installer-utils' +import type { CodexEventLabel, CodexTrustEntry } from './config-toml-trust' + +// Why: Codex's trust hash key uses the snake_case event label (see +// codex-rs/hooks/src/lib.rs::hook_event_key_label) while hooks.json uses the +// PascalCase serde-rename. Keep the mapping in one shared module so the +// install, status, and write-back promotion paths cannot drift. +export const CODEX_HOOK_EVENT_LABEL: Record = { + SessionStart: 'session_start', + UserPromptSubmit: 'user_prompt_submit', + PreToolUse: 'pre_tool_use', + PermissionRequest: 'permission_request', + PostToolUse: 'post_tool_use', + Stop: 'stop', + PreCompact: 'pre_compact', + PostCompact: 'post_compact' +} + +export const CODEX_EVENT_NAME_BY_LABEL: Record = { + session_start: 'SessionStart', + user_prompt_submit: 'UserPromptSubmit', + pre_tool_use: 'PreToolUse', + permission_request: 'PermissionRequest', + post_tool_use: 'PostToolUse', + stop: 'Stop', + pre_compact: 'PreCompact', + post_compact: 'PostCompact' +} + +export function getCodexManagedScriptFileName(): string { + return process.platform === 'win32' ? 'codex-hook.cmd' : 'codex-hook.sh' +} + +export function createCodexHookTrustEntry( + sourcePath: string, + eventName: string, + groupIndex: number, + handlerIndex: number, + definition: HookDefinition, + hook: HookCommandConfig +): CodexTrustEntry | null { + const eventLabel = CODEX_HOOK_EVENT_LABEL[eventName] + if (!eventLabel || !hook.command) { + return null + } + + return { + sourcePath, + eventLabel, + groupIndex, + handlerIndex, + command: hook.command, + ...(typeof hook.timeout === 'number' ? { timeoutSec: hook.timeout } : {}), + ...(typeof hook.async === 'boolean' ? { async: hook.async } : {}), + ...(typeof definition.matcher === 'string' ? { matcher: definition.matcher } : {}), + ...(typeof hook.statusMessage === 'string' ? { statusMessage: hook.statusMessage } : {}) + } +} + +// Why: identity of a hook's content independent of file position, used to +// match the same hook across the system and runtime hooks.json layouts +// (dedupe and the prepended managed hook shift positions between them). +export function getCodexHookTrustSignature(entry: CodexTrustEntry): string { + return JSON.stringify({ + eventLabel: entry.eventLabel, + command: entry.command, + timeoutSec: Math.max(1, entry.timeoutSec ?? 600), + async: entry.async ?? false, + matcher: entry.matcher ?? null, + statusMessage: entry.statusMessage ?? null + }) +} diff --git a/src/main/codex/codex-session-bridge.test.ts b/src/main/codex/codex-session-bridge.test.ts index ae4e17be6937..ed3c838ea7c2 100644 --- a/src/main/codex/codex-session-bridge.test.ts +++ b/src/main/codex/codex-session-bridge.test.ts @@ -215,6 +215,51 @@ describe('syncSystemCodexSessionsIntoManagedHome', () => { ).toBe(false) }) + it('bridges from a custom source home override instead of ~/.codex', () => { + // Why: users with a custom CODEX_HOME point history discovery at that + // folder; the default ~/.codex must be ignored when an override is given. + const customSourceHome = join(fakeHomeDir, 'custom-codex') + const customSessionPath = join( + customSourceHome, + 'sessions', + '2026', + '05', + '26', + 'rollout-custom.jsonl' + ) + mkdirSync(dirname(customSessionPath), { recursive: true }) + writeFileSync(customSessionPath, '{"id":"custom"}\n', 'utf-8') + + // A session under the default ~/.codex should NOT be bridged when overridden. + const defaultSessionPath = join( + getSystemCodexHomePath(), + 'sessions', + '2026', + '05', + '26', + 'rollout-default.jsonl' + ) + mkdirSync(dirname(defaultSessionPath), { recursive: true }) + writeFileSync(defaultSessionPath, '{"id":"default"}\n', 'utf-8') + + syncSystemCodexSessionsIntoManagedHome(customSourceHome) + + const bridgedCustomPath = join( + getRuntimeCodexHomePath(), + 'sessions', + '2026', + '05', + '26', + 'rollout-custom.jsonl' + ) + expect(readFileSync(bridgedCustomPath, 'utf-8')).toBe('{"id":"custom"}\n') + expect( + existsSync( + join(getRuntimeCodexHomePath(), 'sessions', '2026', '05', '26', 'rollout-default.jsonl') + ) + ).toBe(false) + }) + it('falls back to symlinks when hardlinks are unavailable', () => { fsMockState.failLink = true const systemSessionPath = join( diff --git a/src/main/codex/codex-session-bridge.ts b/src/main/codex/codex-session-bridge.ts index a574228953eb..e546ce9d8f84 100644 --- a/src/main/codex/codex-session-bridge.ts +++ b/src/main/codex/codex-session-bridge.ts @@ -42,9 +42,12 @@ let backgroundSessionBridgeTask: Promise | null = null /** * Synchronously mirrors system session files into the managed runtime home. + * + * `sourceCodexHomePath` overrides the default ~/.codex history source for users + * who run Codex with a custom CODEX_HOME; it only affects history discovery. */ -export function syncSystemCodexSessionsIntoManagedHome(): void { - const systemSessionsRoot = join(getSystemCodexHomePath(), 'sessions') +export function syncSystemCodexSessionsIntoManagedHome(sourceCodexHomePath?: string): void { + const systemSessionsRoot = join(sourceCodexHomePath || getSystemCodexHomePath(), 'sessions') if (!existsSync(systemSessionsRoot)) { return } @@ -62,12 +65,13 @@ export function syncSystemCodexSessionsIntoManagedHome(): void { * background bridging without starting duplicate directory walks. */ export function startSystemCodexSessionBridgeInBackground( - options: CodexSessionBridgeIncrementalOptions = {} + options: CodexSessionBridgeIncrementalOptions = {}, + sourceCodexHomePath?: string ): Promise { if (backgroundSessionBridgeTask) { return backgroundSessionBridgeTask } - const task = syncSystemCodexSessionsIntoManagedHomeIncrementally(options) + const task = syncSystemCodexSessionsIntoManagedHomeIncrementally(options, sourceCodexHomePath) .catch((error: unknown) => { console.warn('[codex-session-bridge] Background session bridge failed:', error) }) @@ -88,9 +92,10 @@ export function startSystemCodexSessionBridgeInBackground( * bridge operation equivalent to the synchronous path. */ export async function syncSystemCodexSessionsIntoManagedHomeIncrementally( - options: CodexSessionBridgeIncrementalOptions = {} + options: CodexSessionBridgeIncrementalOptions = {}, + sourceCodexHomePath?: string ): Promise { - const systemSessionsRoot = join(getSystemCodexHomePath(), 'sessions') + const systemSessionsRoot = join(sourceCodexHomePath || getSystemCodexHomePath(), 'sessions') if (!existsSync(systemSessionsRoot)) { return { scannedFiles: 0, linkedFiles: 0 } } diff --git a/src/main/codex/codex-session-source-home.test.ts b/src/main/codex/codex-session-source-home.test.ts new file mode 100644 index 000000000000..fa29650c4951 --- /dev/null +++ b/src/main/codex/codex-session-source-home.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' +import { + resolveHostCodexSessionSourceHome, + resolveWslCodexSessionSourceHome +} from './codex-session-source-home' + +describe('resolveHostCodexSessionSourceHome', () => { + it('returns undefined when no override is configured', () => { + expect(resolveHostCodexSessionSourceHome({})).toBeUndefined() + expect(resolveHostCodexSessionSourceHome({ codexSessionSourceHome: {} })).toBeUndefined() + }) + + it('returns undefined for blank/whitespace overrides so the default is kept', () => { + expect( + resolveHostCodexSessionSourceHome({ codexSessionSourceHome: { host: ' ' } }) + ).toBeUndefined() + }) + + it('returns the trimmed host override path', () => { + expect( + resolveHostCodexSessionSourceHome({ codexSessionSourceHome: { host: ' /custom/codex ' } }) + ).toBe('/custom/codex') + }) +}) + +describe('resolveWslCodexSessionSourceHome', () => { + it('returns undefined when no per-distro override exists', () => { + expect(resolveWslCodexSessionSourceHome({}, 'Ubuntu')).toBeUndefined() + expect( + resolveWslCodexSessionSourceHome( + { codexSessionSourceHome: { wsl: { Debian: '/home/me/.codex' } } }, + 'Ubuntu' + ) + ).toBeUndefined() + }) + + it('resolves a per-distro override for the matching distro', () => { + expect( + resolveWslCodexSessionSourceHome( + { codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } } }, + 'Ubuntu' + ) + ).toBe('/home/me/.config/codex') + }) + + it('matches distro names case-insensitively, mirroring WSL', () => { + expect( + resolveWslCodexSessionSourceHome( + { codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } } }, + 'ubuntu' + ) + ).toBe('/home/me/.config/codex') + }) + + it('ignores blank per-distro overrides so the default is kept', () => { + expect( + resolveWslCodexSessionSourceHome( + { codexSessionSourceHome: { wsl: { Ubuntu: ' ' } } }, + 'Ubuntu' + ) + ).toBeUndefined() + }) + + it('does not leak the host override into WSL resolution', () => { + expect( + resolveWslCodexSessionSourceHome( + { codexSessionSourceHome: { host: '/custom/codex' } }, + 'Ubuntu' + ) + ).toBeUndefined() + }) +}) diff --git a/src/main/codex/codex-session-source-home.ts b/src/main/codex/codex-session-source-home.ts new file mode 100644 index 000000000000..0060051e9240 --- /dev/null +++ b/src/main/codex/codex-session-source-home.ts @@ -0,0 +1,43 @@ +import type { GlobalSettings } from '../../shared/types' + +/** + * Resolves the user-configured Codex *session history* source home, if any. + * + * Why: Orca relocates CODEX_HOME to a managed home, then bridges history from + * the user's real Codex home so /resume finds it. That source defaults to + * ~/.codex, but users who run Codex with a custom CODEX_HOME need to point + * history discovery at that folder. This override affects history only; auth, + * config, and hooks continue to read from ~/.codex. + */ + +/** Host override; returns undefined to keep the default ~/.codex source. */ +export function resolveHostCodexSessionSourceHome( + settings: Pick +): string | undefined { + return normalizeSourceHome(settings.codexSessionSourceHome?.host) +} + +/** Per-distro WSL override; returns undefined to keep the default /.codex source. */ +export function resolveWslCodexSessionSourceHome( + settings: Pick, + distro: string +): string | undefined { + const perDistro = settings.codexSessionSourceHome?.wsl + if (!perDistro) { + return undefined + } + // Why: distro keys are matched case-insensitively so "Ubuntu" and "ubuntu" + // resolve the same override, mirroring how WSL treats distro names. + const normalizedDistro = distro.trim().toLowerCase() + for (const [key, value] of Object.entries(perDistro)) { + if (key.trim().toLowerCase() === normalizedDistro) { + return normalizeSourceHome(value) + } + } + return undefined +} + +function normalizeSourceHome(value: string | undefined): string | undefined { + const trimmed = value?.trim() + return trimmed ? trimmed : undefined +} diff --git a/src/main/codex/codex-wsl-hook-install-plan.test.ts b/src/main/codex/codex-wsl-hook-install-plan.test.ts new file mode 100644 index 000000000000..1c485abf9345 --- /dev/null +++ b/src/main/codex/codex-wsl-hook-install-plan.test.ts @@ -0,0 +1,200 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const execFileMock = vi.hoisted(() => vi.fn()) + +vi.mock('node:child_process', () => ({ + execFile: execFileMock +})) + +import { _internals } from './codex-wsl-hook-install-plan' + +const originalPlatform = process.platform + +function setPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { value: platform, configurable: true }) +} + +beforeEach(() => { + execFileMock.mockReset() + _internals.resetWslCanonicalPathCache() +}) + +afterEach(() => { + setPlatform(originalPlatform) +}) + +describe('canonicalizeWslLinuxPath', () => { + it('returns the path unchanged off Windows without spawning wsl.exe', () => { + setPlatform('linux') + expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alice')).toBe('/home/alice') + expect(execFileMock).not.toHaveBeenCalled() + }) + + it('never blocks: returns null and schedules an async resolution on first call', () => { + setPlatform('win32') + const result = _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias') + + expect(result).toBeNull() + expect(execFileMock).toHaveBeenCalledTimes(1) + const [file, args] = execFileMock.mock.calls[0] + expect(file).toBe('wsl.exe') + expect(args).toEqual([ + '-d', + 'Ubuntu', + '--', + 'sh', + '-c', + `if [ ! -d "$1" ]; then printf '%s\\n' '__ORCA_WSL_PATH_MISSING__'; exit 0; fi; readlink -f -- "$1"`, + 'sh', + '/home/alias' + ]) + }) + + it('returns the cached path while revalidating it asynchronously', () => { + setPlatform('win32') + expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBeNull() + + const callback = execFileMock.mock.calls[0][3] as (error: Error | null, stdout: string) => void + callback(null, '/home/alice\n') + + expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBe('/home/alice') + expect(execFileMock).toHaveBeenCalledTimes(2) + }) + + it('resolves a custom automount root and notifies the first launch', () => { + setPlatform('win32') + const settled = vi.fn() + const windowsPath = 'D:\\orca\\codex-runtime-home\\home' + + expect( + _internals.canonicalizeWslLinuxPath( + 'Ubuntu', + '/mnt/d/orca/codex-runtime-home/home', + windowsPath, + settled + ) + ).toBeNull() + + const [file, args, options, callback] = execFileMock.mock.calls[0] + expect(file).toBe('wsl.exe') + expect(args).toEqual([ + '-d', + 'Ubuntu', + '--', + 'sh', + '-c', + `resolved=$(wslpath -a -u "$1") || exit; if [ ! -d "$resolved" ]; then printf '%s\\n' '__ORCA_WSL_PATH_MISSING__'; exit 0; fi; readlink -f -- "$resolved"`, + 'sh', + windowsPath + ]) + expect(options).toMatchObject({ timeout: 5000, windowsHide: true }) + + callback(null, '/windows/d/orca/codex-runtime-home/home\n') + expect(settled).toHaveBeenCalledWith({ + status: 'resolved', + canonicalPath: '/windows/d/orca/codex-runtime-home/home' + }) + }) + + it('does not spawn a second subprocess while one is in flight', () => { + setPlatform('win32') + _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias') + _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias') + + expect(execFileMock).toHaveBeenCalledTimes(1) + }) + + it('retries after a failed resolution rather than caching the failure', () => { + setPlatform('win32') + _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias') + const callback = execFileMock.mock.calls[0][3] as (error: Error | null, stdout: string) => void + callback(new Error('wsl unreachable'), '') + + expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBeNull() + expect(execFileMock).toHaveBeenCalledTimes(2) + }) + + it('keeps the last known-good cache when revalidation later fails', () => { + setPlatform('win32') + _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias') + const firstCallback = execFileMock.mock.calls[0][3] as ( + error: Error | null, + stdout: string + ) => void + firstCallback(null, '/home/alice\n') + + const settled = vi.fn() + expect( + _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias', '/home/alias', settled) + ).toBe('/home/alice') + const secondCallback = execFileMock.mock.calls[1][3] as ( + error: Error | null, + stdout: string + ) => void + secondCallback(new Error('path disappeared'), '') + + // Why: a cold or wedged distro times out without proving the path changed. + // Dropping the cache would force the next launch onto /mnt/... and rewrite + // trust under a path Codex will not use when automount is customized. + expect(settled).toHaveBeenCalledWith({ status: 'unavailable' }) + expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBe('/home/alice') + }) + + it('drops the cached identity when WSL confirms the path is missing', () => { + setPlatform('win32') + _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias') + const firstCallback = execFileMock.mock.calls[0][3] as ( + error: Error | null, + stdout: string + ) => void + firstCallback(null, '/home/alice\n') + + const settled = vi.fn() + expect( + _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias', '/home/alias', settled) + ).toBe('/home/alice') + const secondCallback = execFileMock.mock.calls[1][3] as ( + error: Error | null, + stdout: string + ) => void + secondCallback(null, '__ORCA_WSL_PATH_MISSING__\n') + + expect(settled).toHaveBeenCalledWith({ status: 'missing' }) + expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBeNull() + }) + + it('replaces a cached path when its canonical identity changes', () => { + setPlatform('win32') + _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias') + const firstCallback = execFileMock.mock.calls[0][3] as ( + error: Error | null, + stdout: string + ) => void + firstCallback(null, '/home/alice-old\n') + + const settled = vi.fn() + expect( + _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias', '/home/alias', settled) + ).toBe('/home/alice-old') + const secondCallback = execFileMock.mock.calls[1][3] as ( + error: Error | null, + stdout: string + ) => void + secondCallback(null, '/home/alice-new\n') + + expect(settled).toHaveBeenCalledWith({ + status: 'resolved', + canonicalPath: '/home/alice-new' + }) + expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBe('/home/alice-new') + }) + + it('ignores non-absolute readlink output', () => { + setPlatform('win32') + _internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias') + const callback = execFileMock.mock.calls[0][3] as (error: Error | null, stdout: string) => void + callback(null, 'readlink: missing operand\n') + + expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBeNull() + }) +}) diff --git a/src/main/codex/codex-wsl-hook-install-plan.ts b/src/main/codex/codex-wsl-hook-install-plan.ts new file mode 100644 index 000000000000..6edc4aed660b --- /dev/null +++ b/src/main/codex/codex-wsl-hook-install-plan.ts @@ -0,0 +1,197 @@ +import { execFile } from 'node:child_process' +import { win32 as pathWin32 } from 'node:path' +import { parseWslUncPath } from '../../shared/wsl-paths' + +export type CodexWslRuntimeHookTarget = { + runtime?: 'host' | 'wsl' + wslDistro?: string | null +} + +export type CodexWslRuntimeHookInstallPlan = { + configPath: string + tomlPath: string + scriptPath: string + commandScriptPath: string + trustConfigPath: string +} + +export type WslCanonicalPathSettlement = + | { status: 'resolved'; canonicalPath: string } + | { status: 'missing' } + | { status: 'unavailable' } + +export type WslCanonicalPathSettled = (settlement: WslCanonicalPathSettlement) => void + +export type CanonicalizeWslLinuxPath = ( + distro: string, + linuxPath: string, + windowsPath?: string, + onSettled?: WslCanonicalPathSettled +) => string | null + +function trimTrailingSlash(value: string): string { + return value.length > 1 ? value.replace(/\/+$/, '') : value +} + +function toDefaultWslLinuxPath(windowsPath: string): string { + const driveMatch = windowsPath.match(/^([A-Za-z]):[/\\](.*)$/) + if (!driveMatch) { + return windowsPath + } + return `/mnt/${driveMatch[1].toLowerCase()}/${driveMatch[2].replace(/\\/g, '/')}` +} + +const WSL_CANONICALIZE_TIMEOUT_MS = 5000 +const WSL_PATH_MISSING_OUTPUT = '__ORCA_WSL_PATH_MISSING__' + +// Why: `readlink -f` over wsl.exe stalls up to the timeout on a cold or wedged +// distro. Running it synchronously on the Electron main process froze the UI on +// every Codex WSL launch, so resolve it off-thread and cache the latest result. +const canonicalWslPathCache = new Map() +const inFlightWslCanonicalizations = new Map>() + +function wslCanonicalizeCacheKey(distro: string, linuxPath: string): string { + return `${distro}\x00${linuxPath}` +} + +function scheduleWslLinuxPathCanonicalization( + distro: string, + linuxPath: string, + windowsPath: string, + onSettled?: WslCanonicalPathSettled +): void { + const key = wslCanonicalizeCacheKey(distro, linuxPath) + const listeners = inFlightWslCanonicalizations.get(key) + if (listeners) { + if (onSettled) { + listeners.add(onSettled) + } + return + } + const nextListeners = new Set() + if (onSettled) { + nextListeners.add(onSettled) + } + inFlightWslCanonicalizations.set(key, nextListeners) + const drivePath = /^[A-Za-z]:[/\\]/.test(windowsPath) + // Why: wslpath reads each distro's automount root, so a custom root such as + // /windows is discovered without synchronously starting WSL on Electron main. + const args = drivePath + ? [ + '-d', + distro, + '--', + 'sh', + '-c', + `resolved=$(wslpath -a -u "$1") || exit; if [ ! -d "$resolved" ]; then printf '%s\\n' '${WSL_PATH_MISSING_OUTPUT}'; exit 0; fi; readlink -f -- "$resolved"`, + 'sh', + windowsPath + ] + : [ + '-d', + distro, + '--', + 'sh', + '-c', + `if [ ! -d "$1" ]; then printf '%s\\n' '${WSL_PATH_MISSING_OUTPUT}'; exit 0; fi; readlink -f -- "$1"`, + 'sh', + linuxPath + ] + execFile( + 'wsl.exe', + args, + { encoding: 'utf-8', timeout: WSL_CANONICALIZE_TIMEOUT_MS, windowsHide: true }, + (error, stdout) => { + const canonicalPath = stdout.trim() + const resolvedPath = !error && canonicalPath.startsWith('/') ? canonicalPath : null + const pathMissing = !error && canonicalPath === WSL_PATH_MISSING_OUTPUT + const settlement: WslCanonicalPathSettlement = resolvedPath + ? { status: 'resolved', canonicalPath: resolvedPath } + : pathMissing + ? { status: 'missing' } + : { status: 'unavailable' } + if (settlement.status === 'resolved') { + canonicalWslPathCache.set(key, canonicalPath) + } else if (settlement.status === 'missing') { + // Why: a successful directory probe is stronger than a transport error; + // clear the identity so stale trust can be revoked and later rediscovered. + canonicalWslPathCache.delete(key) + } + // Why: keep the last known-good cache on timeout/transient WSL failures. + // Dropping it forces the next launch onto the logical `/mnt/...` guess, + // which is wrong under custom automount roots and rewrites trust keys. + const settledListeners = inFlightWslCanonicalizations.get(key) ?? new Set() + inFlightWslCanonicalizations.delete(key) + for (const listener of settledListeners) { + try { + listener(settlement) + } catch (listenerError) { + console.warn('[codex-wsl-hook-path] failed to reconcile canonical path', listenerError) + } + } + } + ) +} + +function canonicalizeWslLinuxPath( + distro: string, + linuxPath: string, + windowsPath = linuxPath, + onSettled?: WslCanonicalPathSettled +): string | null { + if (process.platform !== 'win32') { + return linuxPath + } + const cached = canonicalWslPathCache.get(wslCanonicalizeCacheKey(distro, linuxPath)) + // Why: every launch revalidates asynchronously. Returning the cache keeps + // launch prep synchronous while settlement repairs or revokes trust in-place. + scheduleWslLinuxPathCanonicalization(distro, linuxPath, windowsPath, onSettled) + return cached ?? null +} + +export function createCodexWslRuntimeHookInstallPlan( + runtimeHomePath: string | null | undefined, + target?: CodexWslRuntimeHookTarget, + canonicalize: CanonicalizeWslLinuxPath = canonicalizeWslLinuxPath, + onCanonicalPathSettled?: WslCanonicalPathSettled +): CodexWslRuntimeHookInstallPlan | null { + if (!runtimeHomePath) { + return null + } + + const wslInfo = parseWslUncPath(runtimeHomePath) + if (!wslInfo && target?.runtime !== 'wsl') { + return null + } + const distro = wslInfo?.distro || (target?.runtime === 'wsl' ? target.wslDistro?.trim() : null) + if (!distro) { + return null + } + + const logicalLinuxRuntimeHome = wslInfo?.linuxPath ?? toDefaultWslLinuxPath(runtimeHomePath) + if (!logicalLinuxRuntimeHome.startsWith('/')) { + return null + } + // Why: Codex canonicalizes hook sources inside WSL; resolving there keeps + // trust keys valid when HOME or the runtime directory crosses a symlink. + const linuxRuntimeHome = trimTrailingSlash( + canonicalize(distro, logicalLinuxRuntimeHome, runtimeHomePath, onCanonicalPathSettled) ?? + logicalLinuxRuntimeHome + ) + + return { + configPath: pathWin32.join(runtimeHomePath, 'hooks.json'), + tomlPath: pathWin32.join(runtimeHomePath, 'config.toml'), + scriptPath: pathWin32.join(runtimeHomePath, '.orca', 'agent-hooks', 'codex-hook.sh'), + commandScriptPath: `${linuxRuntimeHome}/.orca/agent-hooks/codex-hook.sh`, + trustConfigPath: `${linuxRuntimeHome}/hooks.json` + } +} + +export const _internals = { + canonicalizeWslLinuxPath, + resetWslCanonicalPathCache(): void { + canonicalWslPathCache.clear() + inFlightWslCanonicalizations.clear() + } +} diff --git a/src/main/codex/config-settings-promotion.test.ts b/src/main/codex/config-settings-promotion.test.ts new file mode 100644 index 000000000000..f6ceabc362f0 --- /dev/null +++ b/src/main/codex/config-settings-promotion.test.ts @@ -0,0 +1,442 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + chmodSync, + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + utimesSync, + writeFileSync +} from 'node:fs' +import { homedir, tmpdir } from 'node:os' +import type * as Os from 'node:os' +import { join } from 'node:path' +import type * as CodexFsUtils from '../codex-accounts/fs-utils' + +const { homedirMock, promotionTestState } = vi.hoisted(() => ({ + homedirMock: vi.fn<() => string>(), + promotionTestState: { failAtomicWrite: false } +})) + +vi.mock('node:os', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + homedir: homedirMock + } +}) + +vi.mock('../codex-accounts/fs-utils', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + writeFileAtomically: (...args: Parameters) => { + if (promotionTestState.failAtomicWrite) { + throw new Error('injected atomic write failure') + } + return actual.writeFileAtomically(...args) + } + } +}) + +import { syncSystemConfigIntoManagedCodexHome } from './codex-config-mirror' +import { upsertTopLevelSettingsInContent } from './config-settings-promotion' + +let tmpHome: string +let userDataDir: string +let previousUserDataPath: string | undefined + +beforeEach(() => { + tmpHome = mkdtempSync(join(tmpdir(), 'orca-codex-settings-home-')) + userDataDir = mkdtempSync(join(tmpdir(), 'orca-codex-settings-user-data-')) + previousUserDataPath = process.env.ORCA_USER_DATA_PATH + process.env.ORCA_USER_DATA_PATH = userDataDir + homedirMock.mockReturnValue(tmpHome) + promotionTestState.failAtomicWrite = false + // Why: promotion writes into homedir()/.codex — if the mock ever fails to + // intercept, these tests would rewrite the developer's real Codex config. + if (homedir() !== tmpHome) { + throw new Error('node:os homedir mock is not active; refusing to touch the real ~/.codex') + } +}) + +afterEach(() => { + rmSync(tmpHome, { recursive: true, force: true }) + rmSync(userDataDir, { recursive: true, force: true }) + if (previousUserDataPath === undefined) { + delete process.env.ORCA_USER_DATA_PATH + } else { + process.env.ORCA_USER_DATA_PATH = previousUserDataPath + } + vi.clearAllMocks() +}) + +function systemConfigPath(): string { + return join(tmpHome, '.codex', 'config.toml') +} + +function runtimeHomeDir(): string { + return join(userDataDir, 'codex-runtime-home', 'home') +} + +function runtimeConfigPath(): string { + return join(runtimeHomeDir(), 'config.toml') +} + +function baselinePath(): string { + return join(runtimeHomeDir(), '.orca-config-settings-baseline.json') +} + +function writeSystemConfig(content: string): void { + mkdirSync(join(tmpHome, '.codex'), { recursive: true }) + writeFileSync(systemConfigPath(), content, 'utf-8') +} + +function readSystemConfig(): string { + return readFileSync(systemConfigPath(), 'utf-8') +} + +function readRuntimeConfig(): string { + return readFileSync(runtimeConfigPath(), 'utf-8') +} + +// Mimics how Codex (toml_edit) persists a /model or /approvals change: the +// top-level key line is rewritten in place, or created when absent. +function simulateCodexSettingWrite(key: string, rawValue: string): void { + mkdirSync(runtimeHomeDir(), { recursive: true }) + const existing = existsSync(runtimeConfigPath()) ? readFileSync(runtimeConfigPath(), 'utf-8') : '' + const linePattern = new RegExp(`^${key}[ \\t]*=.*$`, 'm') + const rendered = `${key} = ${rawValue}` + const next = linePattern.test(existing) + ? existing.replace(linePattern, rendered) + : `${rendered}\n${existing}` + writeFileSync(runtimeConfigPath(), next, 'utf-8') +} + +function simulateCodexSettingRemoval(key: string): void { + const existing = readFileSync(runtimeConfigPath(), 'utf-8') + const linePattern = new RegExp(`^${key}[ \\t]*=.*\\n?`, 'm') + writeFileSync(runtimeConfigPath(), existing.replace(linePattern, ''), 'utf-8') +} + +describe('codex settings write-back promotion', () => { + it('promotes an in-Codex model change to ~/.codex and reaches a steady state', () => { + writeSystemConfig( + 'model = "gpt-5"\napproval_policy = "on-request"\n\n[features]\nhooks = true\n' + ) + syncSystemConfigIntoManagedCodexHome() + expect(existsSync(baselinePath())).toBe(true) + + simulateCodexSettingWrite('model', '"gpt-5.5-codex"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe( + 'model = "gpt-5.5-codex"\napproval_policy = "on-request"\n\n[features]\nhooks = true\n' + ) + expect(readRuntimeConfig()).toContain('model = "gpt-5.5-codex"') + + const settledSystem = readSystemConfig() + const settledRuntime = readRuntimeConfig() + syncSystemConfigIntoManagedCodexHome() + expect(readSystemConfig()).toBe(settledSystem) + expect(readRuntimeConfig()).toBe(settledRuntime) + }) + + it('promotes multiple approvals keys in one pass', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('approval_policy', '"never"') + simulateCodexSettingWrite('sandbox_mode', '"danger-full-access"') + syncSystemConfigIntoManagedCodexHome() + + const system = readSystemConfig() + expect(system).toContain('approval_policy = "never"') + expect(system).toContain('sandbox_mode = "danger-full-access"') + expect(system).toContain('model = "gpt-5"') + }) + + it('does not promote on the first pass without a baseline, then promotes after one', () => { + writeSystemConfig('model = "gpt-5"\n') + mkdirSync(runtimeHomeDir(), { recursive: true }) + // Pre-upgrade state: runtime already diverged, but no baseline exists. + writeFileSync(runtimeConfigPath(), 'model = "user-changed-before-upgrade"\n', 'utf-8') + + syncSystemConfigIntoManagedCodexHome() + expect(readSystemConfig()).toBe('model = "gpt-5"\n') + expect(readRuntimeConfig()).toContain('model = "gpt-5"') + expect(existsSync(baselinePath())).toBe(true) + + simulateCodexSettingWrite('model', '"o4"') + syncSystemConfigIntoManagedCodexHome() + expect(readSystemConfig()).toBe('model = "o4"\n') + }) + + it('treats a corrupt baseline as missing and rewrites it', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + writeFileSync(baselinePath(), 'not json', 'utf-8') + + simulateCodexSettingWrite('model', '"o4"') + syncSystemConfigIntoManagedCodexHome() + expect(readSystemConfig()).toBe('model = "gpt-5"\n') + expect(JSON.parse(readFileSync(baselinePath(), 'utf-8'))).toMatchObject({ version: 1 }) + + simulateCodexSettingWrite('model', '"o4"') + syncSystemConfigIntoManagedCodexHome() + expect(readSystemConfig()).toBe('model = "o4"\n') + }) + + it('lets an outside ~/.codex edit win over a conflicting in-Codex change', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('model', '"in-codex-choice"') + writeSystemConfig('model = "outside-edit"\n') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe('model = "outside-edit"\n') + expect(readRuntimeConfig()).toContain('model = "outside-edit"') + }) + + it('inserts a key ~/.codex lacks into the preamble without disturbing the rest', () => { + writeSystemConfig('# my codex config\nmodel = "gpt-5"\n\n[features]\nhooks = true\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('approval_policy', '"on-request"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe( + '# my codex config\nmodel = "gpt-5"\napproval_policy = "on-request"\n\n[features]\nhooks = true\n' + ) + }) + + it('creates ~/.codex/config.toml when a user without one changes a setting', () => { + // Why: no mkdir of ~/.codex here — a genuinely fresh host has neither the + // config nor its directory, and promotion must create both. + expect(existsSync(join(tmpHome, '.codex'))).toBe(false) + syncSystemConfigIntoManagedCodexHome() + expect(existsSync(baselinePath())).toBe(true) + + // Codex itself creates the runtime config.toml on the first /model write. + simulateCodexSettingWrite('model', '"gpt-5.5-codex"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe('model = "gpt-5.5-codex"\n') + expect(readRuntimeConfig()).toContain('model = "gpt-5.5-codex"') + }) + + it('does not promote a key deletion', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingRemoval('model') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe('model = "gpt-5"\n') + expect(readRuntimeConfig()).toContain('model = "gpt-5"') + }) + + it('ignores keys outside the allowlist', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('notify', '["custom-notifier"]') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe('model = "gpt-5"\n') + }) + + it('ignores allowlisted keys inside tables such as [profiles.*]', () => { + writeSystemConfig('model = "gpt-5"\n\n[profiles.dev]\nmodel = "profile-model"\n') + syncSystemConfigIntoManagedCodexHome() + + const runtime = readRuntimeConfig() + writeFileSync( + runtimeConfigPath(), + runtime.replace('model = "profile-model"', 'model = "profile-changed"'), + 'utf-8' + ) + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe('model = "gpt-5"\n\n[profiles.dev]\nmodel = "profile-model"\n') + }) + + it('never rewrites a multiline system value', () => { + writeSystemConfig('model = """\nodd\nmultiline\n"""\n') + syncSystemConfigIntoManagedCodexHome() + + writeFileSync(runtimeConfigPath(), 'model = "single"\n', 'utf-8') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe('model = """\nodd\nmultiline\n"""\n') + }) + + it('preserves CRLF line endings when replacing a value', () => { + writeSystemConfig('model = "gpt-5"\r\napproval_policy = "on-request"\r\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('model', '"o4"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toContain('model = "o4"\r\n') + expect(readSystemConfig()).toContain('approval_policy = "on-request"\r\n') + }) + + it('promotes over a value that carried an inline comment', () => { + writeSystemConfig('model = "gpt-5" # my favorite\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('model', '"o4"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe('model = "o4"\n') + }) + + it.skipIf(process.platform === 'win32')( + 'preserves a restrictive mode on the existing ~/.codex/config.toml', + () => { + writeSystemConfig('model = "gpt-5"\n') + chmodSync(systemConfigPath(), 0o600) + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('model', '"o4"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe('model = "o4"\n') + expect(statSync(systemConfigPath()).mode & 0o777).toBe(0o600) + } + ) + + it.skipIf(process.platform === 'win32')( + 'creates a new ~/.codex/config.toml with owner-only permissions', + () => { + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('model', '"o4"') + syncSystemConfigIntoManagedCodexHome() + + expect(statSync(systemConfigPath()).mode & 0o777).toBe(0o600) + // The created ~/.codex itself is owner-only — it will also hold + // auth.json once the user signs in. + expect(statSync(join(tmpHome, '.codex')).mode & 0o777).toBe(0o700) + } + ) + + it.skipIf(process.platform === 'win32')( + 'writes through a symlinked config.toml without replacing the link', + () => { + mkdirSync(join(tmpHome, '.codex'), { recursive: true }) + const realConfigPath = join(tmpHome, 'dotfiles-config.toml') + writeFileSync(realConfigPath, 'model = "gpt-5"\n', 'utf-8') + symlinkSync(realConfigPath, systemConfigPath()) + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('model', '"o4"') + syncSystemConfigIntoManagedCodexHome() + + expect(lstatSync(systemConfigPath()).isSymbolicLink()).toBe(true) + expect(readFileSync(realConfigPath, 'utf-8')).toBe('model = "o4"\n') + } + ) + + it.skipIf(process.platform === 'win32')( + 'preserves a dangling config.toml symlink and creates its target', + () => { + mkdirSync(join(tmpHome, '.codex'), { recursive: true }) + const realConfigPath = join(tmpHome, 'dotfiles', 'config.toml') + symlinkSync(realConfigPath, systemConfigPath()) + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('model', '"o4"') + syncSystemConfigIntoManagedCodexHome() + + expect(lstatSync(systemConfigPath()).isSymbolicLink()).toBe(true) + expect(readFileSync(realConfigPath, 'utf-8')).toBe('model = "o4"\n') + } + ) + + it('inserts a missing key into a CRLF config with CRLF endings', () => { + writeSystemConfig('model = "gpt-5"\r\n\r\n[features]\r\nhooks = true\r\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexSettingWrite('approval_policy', '"never"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe( + 'model = "gpt-5"\r\napproval_policy = "never"\r\n\r\n[features]\r\nhooks = true\r\n' + ) + }) + + it('does not rewrite an unchanged settings baseline', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + + const past = new Date(Date.now() - 120_000) + utimesSync(baselinePath(), past, past) + syncSystemConfigIntoManagedCodexHome() + + expect(statSync(baselinePath()).mtimeMs).toBeLessThan(Date.now() - 60_000) + }) + + it('keeps the old baseline and retries after a transient promotion failure', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + const baselineBeforeFailure = readFileSync(baselinePath(), 'utf-8') + simulateCodexSettingWrite('model', '"o4"') + + promotionTestState.failAtomicWrite = true + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe('model = "gpt-5"\n') + expect(readRuntimeConfig()).toBe('model = "o4"\n') + expect(readFileSync(baselinePath(), 'utf-8')).toBe(baselineBeforeFailure) + + promotionTestState.failAtomicWrite = false + syncSystemConfigIntoManagedCodexHome() + expect(readSystemConfig()).toBe('model = "o4"\n') + }) +}) + +describe('upsertTopLevelSettingsInContent', () => { + it('writes into empty content', () => { + expect(upsertTopLevelSettingsInContent('', new Map([['model', '"x"']]))).toBe('model = "x"\n') + }) + + it('inserts before the first table with a separating blank line', () => { + expect( + upsertTopLevelSettingsInContent('[features]\nhooks = true\n', new Map([['model', '"x"']])) + ).toBe('model = "x"\n\n[features]\nhooks = true\n') + }) + + it('appends to a preamble-only file without a trailing newline', () => { + expect( + upsertTopLevelSettingsInContent('approval_policy = "never"', new Map([['model', '"x"']])) + ).toBe('approval_policy = "never"\nmodel = "x"\n') + }) + + it('replaces the existing line in place', () => { + expect( + upsertTopLevelSettingsInContent( + '# keep\nmodel = "old"\n\n[t]\nk = 1\n', + new Map([['model', '"new"']]) + ) + ).toBe('# keep\nmodel = "new"\n\n[t]\nk = 1\n') + }) + + it('inserts with CRLF endings into CRLF content', () => { + expect( + upsertTopLevelSettingsInContent('[features]\r\nhooks = true\r\n', new Map([['model', '"x"']])) + ).toBe('model = "x"\r\n\r\n[features]\r\nhooks = true\r\n') + }) + + it('appends with CRLF to a CRLF preamble-only file', () => { + expect( + upsertTopLevelSettingsInContent('approval_policy = "never"\r\n', new Map([['model', '"x"']])) + ).toBe('approval_policy = "never"\r\nmodel = "x"\r\n') + }) +}) diff --git a/src/main/codex/config-settings-promotion.ts b/src/main/codex/config-settings-promotion.ts new file mode 100644 index 000000000000..7e8552bb9b66 --- /dev/null +++ b/src/main/codex/config-settings-promotion.ts @@ -0,0 +1,341 @@ +import { + existsSync, + lstatSync, + mkdirSync, + readFileSync, + readlinkSync, + realpathSync, + statSync, + writeFileSync +} from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { writeFileAtomically } from '../codex-accounts/fs-utils' +import { parseWslUncPath } from '../../shared/wsl-paths' +import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from './codex-home-paths' +import { + createTomlLineScanState, + getTomlTableHeader, + isTomlStructuralLine, + updateTomlLineScanState +} from './config-toml-line-scan' + +// Why: the config mirror rewrites the runtime config.toml from ~/.codex on +// every launch (and on background rate-limit fetches), so settings the user +// changes inside Orca-launched Codex silently revert. Promotion diffs the +// runtime file against a baseline of what Orca last wrote — anything that +// differs is a change Codex persisted for the user and belongs in ~/.codex. + +// Why: only the user-preference scalars the Codex TUI itself persists +// (/model writes model + model_reasoning_effort, /approvals writes +// approval_policy + sandbox_mode). Every key added here gets written into the +// user's real ~/.codex/config.toml, so grow this list deliberately. +export const PROMOTED_CODEX_SETTING_KEYS = [ + 'model', + 'model_reasoning_effort', + 'approval_policy', + 'sandbox_mode' +] as const + +type TopLevelSettingValue = { + raw: string + // Why: a value that opens a multiline string/array cannot be replaced or + // copied line-by-line safely, so it is excluded from promotion entirely. + multiline: boolean +} + +type SettingsBaselineFile = { + version: 1 + settings: Record +} + +function getSettingsBaselinePath(runtimeHomePath: string): string { + return join(runtimeHomePath, '.orca-config-settings-baseline.json') +} + +function readSettingsBaseline(runtimeHomePath: string): Map | null { + const baselinePath = getSettingsBaselinePath(runtimeHomePath) + if (!existsSync(baselinePath)) { + return null + } + try { + const parsed: unknown = JSON.parse(readFileSync(baselinePath, 'utf-8')) + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return null + } + const settings = (parsed as SettingsBaselineFile).settings + if (!settings || typeof settings !== 'object' || Array.isArray(settings)) { + return null + } + const result = new Map() + for (const [key, value] of Object.entries(settings)) { + if (typeof value === 'string') { + result.set(key, value) + } + } + return result + } catch { + return null + } +} + +// Why: only keys in the top-level preamble are scanned — Codex writes profile +// overrides into [profiles.*] tables, and rewriting nested tables surgically +// is not worth the risk for stage-1 promotion. +function readTopLevelSettingValues(configPath: string): Map { + const result = new Map() + if (!existsSync(configPath)) { + return result + } + const lines = readFileSync(configPath, 'utf-8').split('\n') + let state = createTomlLineScanState() + for (const line of lines) { + if (isTomlStructuralLine(state)) { + if (getTomlTableHeader(line)) { + break + } + const match = /^[ \t]*([A-Za-z0-9_-]+)[ \t]*=[ \t]*(.*?)[ \t\r]*$/.exec(line) + const key = match?.[1] + if (key && (PROMOTED_CODEX_SETTING_KEYS as readonly string[]).includes(key)) { + const nextState = updateTomlLineScanState(state, line) + result.set(key, { raw: match?.[2] ?? '', multiline: !isTomlStructuralLine(nextState) }) + state = nextState + continue + } + } + state = updateTomlLineScanState(state, line) + } + return result +} + +/** + * Records the promotable top-level settings the runtime config.toml holds + * after a mirror, so the next promotion can tell "value Orca mirrored" apart + * from "value Codex wrote for the user". Call after a successful mirror only — + * advancing the baseline past an unpromoted change would strand it forever. + */ +export function snapshotCodexRuntimeSettingsBaseline( + runtimeHomePath = getOrcaManagedCodexHomePath() +): void { + try { + const runtimeTomlPath = join(runtimeHomePath, 'config.toml') + // Why: a missing runtime config still records an empty baseline — when + // Codex later creates the file for a user with no ~/.codex/config.toml, + // that first change must diff against "Orca left nothing" and promote. + const settings: Record = {} + for (const [key, value] of readTopLevelSettingValues(runtimeTomlPath)) { + if (!value.multiline) { + settings[key] = value.raw + } + } + const file: SettingsBaselineFile = { version: 1, settings } + const baselinePath = getSettingsBaselinePath(runtimeHomePath) + const serialized = `${JSON.stringify(file, null, 2)}\n` + // Why: launch preparation can run repeatedly; skip byte-identical rewrites + // so an unchanged pass does no disk writes. + if (existsSync(baselinePath) && readFileSync(baselinePath, 'utf-8') === serialized) { + return + } + writeFileSync(baselinePath, serialized, { + encoding: 'utf-8', + mode: 0o600 + }) + } catch (error) { + console.warn('[codex-settings-promotion] failed to snapshot settings baseline', error) + } +} + +export type CodexSettingsPromotionHomes = { + runtimeHomePath: string + systemHomePath: string +} + +function getHostPromotionHomes(): CodexSettingsPromotionHomes { + return { + runtimeHomePath: getOrcaManagedCodexHomePath(), + systemHomePath: getSystemCodexHomePath() + } +} + +/** + * Promotes setting changes the user made inside Orca-launched Codex (written + * by Codex into the runtime config.toml) into ~/.codex/config.toml. Runs + * before the config mirror so the promoted values survive the same mirror + * pass instead of reverting. WSL callers pass explicit per-distro homes; the + * default is the host runtime home and host ~/.codex. + */ +export function promoteCodexRuntimeSettingsToSystem(homes?: CodexSettingsPromotionHomes): boolean { + try { + promoteCodexRuntimeSettingsToSystemUnsafe(homes ?? getHostPromotionHomes()) + return true + } catch (error) { + // Why: promotion is best-effort launch prep; callers preserve the runtime + // for retry, while a malformed file must not block Codex launch itself. + console.warn('[codex-settings-promotion] failed to promote runtime settings', error) + return false + } +} + +function promoteCodexRuntimeSettingsToSystemUnsafe(homes: CodexSettingsPromotionHomes): void { + const { runtimeHomePath, systemHomePath } = homes + const runtimeTomlPath = join(runtimeHomePath, 'config.toml') + const systemTomlPath = join(systemHomePath, 'config.toml') + if (resolve(runtimeTomlPath) === resolve(systemTomlPath)) { + return + } + if (!existsSync(runtimeTomlPath)) { + return + } + // Why: without a baseline of what Orca last mirrored (first launch after + // upgrading to a build with promotion, or a corrupted snapshot), a stale + // runtime value is indistinguishable from a fresh in-Codex change. Skip + // this pass — the mirror writes the first baseline and promotion starts on + // the next one. + const baseline = readSettingsBaseline(runtimeHomePath) + if (!baseline) { + return + } + const runtimeValues = readTopLevelSettingValues(runtimeTomlPath) + const systemValues = readTopLevelSettingValues(systemTomlPath) + const updates = new Map() + for (const key of PROMOTED_CODEX_SETTING_KEYS) { + const runtime = runtimeValues.get(key) + if (!runtime || runtime.multiline) { + continue + } + if (runtime.raw === baseline.get(key)) { + // Orca mirrored this value and nothing touched it since — not a change. + continue + } + const system = systemValues.get(key) + if (system?.multiline) { + continue + } + // Why: ~/.codex stays source of truth — if the user also edited it there + // since the baseline, the outside edit wins over the in-Codex change. + if (system?.raw !== baseline.get(key)) { + continue + } + updates.set(key, runtime.raw) + } + if (updates.size === 0) { + return + } + // Why: a genuinely fresh host has no ~/.codex yet; without the directory + // the atomic write ENOENTs and the following mirror wipes the setting. + // Owner-only: the directory holds auth.json and the full user config. + mkdirSync(systemHomePath, { recursive: true, mode: 0o700 }) + const writeTarget = resolvePromotionWriteTarget(systemTomlPath) + // Why: a dangling dotfile-manager symlink can point into a directory tree + // that has not been materialized yet; preserve the link and create its real + // parent so the atomic temp file can be written beside the target. + mkdirSync(dirname(writeTarget.path), { recursive: true, mode: 0o700 }) + const targetExists = existsSync(writeTarget.path) + const systemContent = targetExists ? readFileSync(writeTarget.path, 'utf-8') : '' + const nextContent = upsertTopLevelSettingsInContent(systemContent, updates) + if (targetExists && parseWslUncPath(writeTarget.path)) { + // Why: symlink metadata through the \\wsl$ 9P provider is not reliable + // enough for realpath/lstat detection, and an atomic rename would replace + // a WSL-side dotfile symlink with a plain file. Writing through the + // existing file preserves the Linux-side inode (and its mode). + writeFileSync(writeTarget.path, nextContent, 'utf-8') + return + } + writeFileAtomically(writeTarget.path, nextContent, { + mode: writeTarget.mode + }) +} + +// Why: promotion rewrites the user's real config.toml. Follow an existing +// symlink (dotfile managers) instead of replacing the link with a plain file, +// and carry the real file's mode forward — an atomic write without a mode +// would widen a user-restricted 0600 config to the process umask default. +// A new or unreadable target is created owner-only. +function resolvePromotionWriteTarget(systemTomlPath: string): { path: string; mode: number } { + try { + const realPath = realpathSync(systemTomlPath) + return { path: realPath, mode: statSync(realPath).mode & 0o777 } + } catch { + // Continue below: realpath also fails for a valid dangling dotfile link. + } + try { + if (lstatSync(systemTomlPath).isSymbolicLink()) { + const targetPath = resolveDanglingSymlinkTarget(systemTomlPath) + return { path: targetPath, mode: 0o600 } + } + } catch { + // Missing non-link targets are created owner-only at the requested path. + } + return { path: systemTomlPath, mode: 0o600 } +} + +function resolveDanglingSymlinkTarget(linkPath: string): string { + let currentPath = linkPath + const visited = new Set() + while (!visited.has(currentPath)) { + visited.add(currentPath) + try { + if (!lstatSync(currentPath).isSymbolicLink()) { + return currentPath + } + currentPath = resolve(dirname(currentPath), readlinkSync(currentPath)) + } catch { + return currentPath + } + } + // Why: replacing any link in a cycle would destroy dotfile-manager state; + // abort promotion and leave the runtime/baseline intact for manual repair. + throw new Error(`Codex config symlink cycle at ${linkPath}`) +} + +export function upsertTopLevelSettingsInContent( + content: string, + updates: Map +): string { + const lines = content.split('\n') + let state = createTomlLineScanState() + let preambleEnd = lines.length + const keyLineIndexes = new Map() + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index] ?? '' + if (isTomlStructuralLine(state)) { + if (getTomlTableHeader(line)) { + preambleEnd = index + break + } + const match = /^[ \t]*([A-Za-z0-9_-]+)[ \t]*=/.exec(line) + if (match?.[1] && updates.has(match[1])) { + keyLineIndexes.set(match[1], index) + } + } + state = updateTomlLineScanState(state, line) + } + + // Why: CRLF configs keep a trailing \r after the split; new lines must use + // the file's existing endings or a Windows-owned config becomes mixed-EOL. + const usesCrlf = content.includes('\r\n') + const insertions: string[] = [] + for (const [key, raw] of updates) { + const existingIndex = keyLineIndexes.get(key) + const rendered = `${key} = ${raw}` + if (existingIndex !== undefined) { + lines[existingIndex] = lines[existingIndex]?.endsWith('\r') ? `${rendered}\r` : rendered + } else { + insertions.push(usesCrlf ? `${rendered}\r` : rendered) + } + } + if (insertions.length > 0) { + let insertAt = preambleEnd + while (insertAt > 0 && (lines[insertAt - 1] ?? '').trim() === '') { + insertAt -= 1 + } + if (insertAt === preambleEnd && preambleEnd < lines.length) { + insertions.push(usesCrlf ? '\r' : '') + } + lines.splice(insertAt, 0, ...insertions) + } + const result = lines.join('\n') + if (result.endsWith('\n') || result.length === 0) { + return result + } + return result.endsWith('\r') ? `${result}\n` : `${result}${usesCrlf ? '\r\n' : '\n'}` +} diff --git a/src/main/codex/config-toml-trust.test.ts b/src/main/codex/config-toml-trust.test.ts index 8be83c8f340e..4f4dcf4861fc 100644 --- a/src/main/codex/config-toml-trust.test.ts +++ b/src/main/codex/config-toml-trust.test.ts @@ -1108,6 +1108,60 @@ describe('upsertProjectTrustLevel', () => { expect(updated).not.toContain('trust_level = "untrusted"') }) + it('updates a Codex literal-string Windows project block without duplicating it', () => { + const original = ["[projects.'c:\\gemini_etl']", 'trust_level = "untrusted"', ''].join('\n') + + const updated = upsertProjectTrustLevelInContent(original, 'c:\\gemini_etl', 'trusted', { + alreadyCanonical: true + }) + + expect(updated.match(/\[projects\./g)).toHaveLength(1) + expect(updated).toContain("[projects.'c:\\gemini_etl']") + expect(updated).toContain('trust_level = "trusted"') + expect(updated).not.toContain('[projects."c:\\\\gemini_etl"]') + }) + + it.each([ + { + name: 'drive-letter casing and separators', + existingPath: 'c:\\work\\repo', + incomingPath: 'C:/work/repo' + }, + { + name: 'WSL UNC path casing and separators', + existingPath: '\\\\wsl$\\Ubuntu\\home\\u\\proj', + incomingPath: '//WSL$/ubuntu/home/u/proj' + }, + { + name: 'server UNC path casing and separators', + existingPath: '\\\\server\\share\\proj', + incomingPath: '//SERVER/share/proj' + } + ])('matches $name by decoded Windows path value', ({ existingPath, incomingPath }) => { + const original = [`[projects.'${existingPath}']`, 'trust_level = "untrusted"', ''].join('\n') + + const updated = upsertProjectTrustLevelInContent(original, incomingPath, 'trusted', { + alreadyCanonical: true + }) + + expect(updated.match(/\[projects\./g)).toHaveLength(1) + expect(updated).toContain(`[projects.'${existingPath}']`) + expect(updated).toContain('trust_level = "trusted"') + }) + + it('matches a literal-string POSIX project path containing a quote and backslash', () => { + const projectPath = '/tmp/with"quote\\and-backslash' + const original = [`[projects.'${projectPath}']`, 'trust_level = "untrusted"', ''].join('\n') + + const updated = upsertProjectTrustLevelInContent(original, projectPath, 'trusted', { + alreadyCanonical: true + }) + + expect(updated.match(/\[projects\./g)).toHaveLength(1) + expect(updated).toContain(`[projects.'${projectPath}']`) + expect(updated).toContain('trust_level = "trusted"') + }) + it('preserves an already-canonical remote Windows project path', () => { // Why: SSH project paths are resolved on the remote; local realpath would // canonicalize the wrong machine if the same path happens to exist locally. @@ -1461,6 +1515,34 @@ describe('readHookTrustEntries', () => { } ) + it.skipIf(process.platform !== 'win32')( + 'keeps WSL hook trust paths case-sensitive on a Windows host', + () => { + const upperKey = '/windows/d/Repo/hooks.json:session_start:0:0' + const lowerKey = '/windows/d/repo/hooks.json:session_start:0:0' + writeFileSync( + configPath, + [ + `[hooks.state."${upperKey}"]`, + 'enabled = true', + 'trusted_hash = "sha256:UPPER"', + '', + `[hooks.state."${lowerKey}"]`, + 'enabled = true', + 'trusted_hash = "sha256:LOWER"', + '' + ].join('\n'), + 'utf-8' + ) + + const result = readHookTrustEntries(configPath) + + expect(result.get(upperKey)?.trustedHash).toBe('sha256:UPPER') + expect(result.get(lowerKey)?.trustedHash).toBe('sha256:LOWER') + expect(result.size).toBe(2) + } + ) + it('reads entries from a CRLF-terminated config', () => { const key = '/x/hooks.json:pre_tool_use:0:0' const original = [ diff --git a/src/main/codex/config-toml-trust.ts b/src/main/codex/config-toml-trust.ts index cdf44768135a..02cd03728370 100644 --- a/src/main/codex/config-toml-trust.ts +++ b/src/main/codex/config-toml-trust.ts @@ -9,7 +9,6 @@ import { } from 'node:fs' import { dirname, join } from 'node:path' import { createHash, randomUUID } from 'node:crypto' -import { escapeRegex } from '../../shared/string-utils' import { copyFileWithWindowsRetry, renameFileWithWindowsRetry } from '../codex-accounts/fs-utils' import { createTomlLineScanState, @@ -55,6 +54,13 @@ export type CodexTrustEntry = { matcher?: string /** Optional statusMessage field. */ statusMessage?: string + /** Verbatim hash to write instead of computing one. Used when carrying a + * Codex-written approval across files, so trust survives even if Codex's + * hash algorithm drifts from computeTrustedHash. Never fed into hashing. */ + trustedHash?: string + /** Explicit enabled state to write. When absent, a pre-existing + * `enabled = false` on the target block is preserved. */ + enabled?: boolean } export type CodexHookTrustState = { @@ -195,7 +201,19 @@ function normalizeWindowsPathSeparators(sourcePath: string): string { } function usesWindowsPathSeparators(sourcePath: string): boolean { - return /^[A-Za-z]:[\\/]/.test(sourcePath) || sourcePath.startsWith('\\\\') + return ( + /^[A-Za-z]:[\\/]/.test(sourcePath) || + sourcePath.startsWith('\\\\') || + sourcePath.startsWith('//') + ) +} + +// Why: Codex and Orca can disagree on quote style, separators, and casing for +// the same Windows project, including when the caller targets a remote host. +export function normalizeCodexProjectPathForLookup(projectPath: string): string { + return usesWindowsPathSeparators(projectPath) + ? normalizeWindowsPathSeparators(projectPath).toLowerCase() + : projectPath } export function parseTrustKey(key: string): { @@ -308,7 +326,8 @@ export function upsertHookTrustEntriesInContent( updated = upsertTrustBlocks( updated, getTrustKeyWriteVariants(computeTrustKey(entry)), - computeTrustedHash(entry) + entry.trustedHash ?? computeTrustedHash(entry), + entry.enabled ) } return updated @@ -338,12 +357,11 @@ export function upsertProjectTrustLevelInContent( const trustedProjectPath = options?.alreadyCanonical ? projectPath : getCodexCanonicalProjectPath(projectPath) - const headerPattern = buildProjectHeaderPattern(trustedProjectPath) - const match = headerPattern.exec(existing) + const headerLineEnd = findProjectHeaderLineEnd(existing, trustedProjectPath) const eol = existing.includes('\r\n') ? '\r\n' : '\n' const trustLine = `trust_level = "${trustLevel}"` - if (!match) { + if (headerLineEnd === null) { const block = [`[projects."${escapeTomlString(trustedProjectPath)}"]`, trustLine].join(eol) if (existing.length === 0) { return `${block}${eol}` @@ -356,7 +374,6 @@ export function upsertProjectTrustLevelInContent( return `${existing}${separator}${block}${eol}` } - const headerLineEnd = match.index + match[0].length const after = existing.slice(headerLineEnd) const nextHeaderRel = findNextTableHeader(after) const blockEnd = nextHeaderRel === -1 ? existing.length : headerLineEnd + nextHeaderRel @@ -420,7 +437,12 @@ export function escapeTomlString(value: string): string { .replaceAll('\t', '\\t') } -function upsertTrustBlocks(content: string, keys: readonly string[], hash: string): string { +function upsertTrustBlocks( + content: string, + keys: readonly string[], + hash: string, + explicitEnabled?: boolean +): string { const ranges = keys .flatMap((key) => findTrustBlockRanges(content, key)) .filter( @@ -431,7 +453,7 @@ function upsertTrustBlocks(content: string, keys: readonly string[], hash: strin ) .sort((a, b) => a.start - b.start) if (ranges.length === 0) { - const block = buildTrustBlocks(keys, hash, true) + const block = buildTrustBlocks(keys, hash, explicitEnabled ?? true) if (content.length === 0) { return `${block}\n` } @@ -446,13 +468,17 @@ function upsertTrustBlocks(content: string, keys: readonly string[], hash: strin // silently re-enabled by the next auto-install on app start. // If duplicate blocks already exist, treat any disabled copy as authoritative // while collapsing the malformed TOML back to one table. - const enabled = !ranges.some((range) => { - const existingBlock = content.slice(range.headerLineEnd, range.end) - const enabledMatch = /^[ \t]*enabled[ \t]*=[ \t]*(true|false)[ \t\r]*(?:#.*)?$/m.exec( - existingBlock - ) - return enabledMatch?.[1] === 'false' - }) + // An explicit enabled state (write-back promotion of an in-Orca /hooks + // toggle) overrides that preservation: it IS the user's latest decision. + const enabled = + explicitEnabled ?? + !ranges.some((range) => { + const existingBlock = content.slice(range.headerLineEnd, range.end) + const enabledMatch = /^[ \t]*enabled[ \t]*=[ \t]*(true|false)[ \t\r]*(?:#.*)?$/m.exec( + existingBlock + ) + return enabledMatch?.[1] === 'false' + }) const block = buildTrustBlocks(keys, hash, enabled) let cursor = 0 let deduped = '' @@ -503,7 +529,11 @@ export function normalizeHookTrustKeyForLookup(key: string): string { const separated = parsed ? `${normalizeWindowsPathSeparators(parsed.sourcePath)}:${parsed.eventLabel}:${parsed.groupIndex}:${parsed.handlerIndex}` : normalizeWindowsPathSeparators(key) - return process.platform === 'win32' ? separated.toLowerCase() : separated + // Why: Windows-native paths are case-insensitive, but WSL and SSH trust + // sources remain case-sensitive even when Orca's host process is Windows. + const caseInsensitiveWindowsPath = + process.platform === 'win32' && usesWindowsPathSeparators(parsed?.sourcePath ?? key) + return caseInsensitiveWindowsPath ? separated.toLowerCase() : separated } function findTrustBlockRanges(content: string, key: string): TrustBlockRange[] { @@ -535,20 +565,6 @@ function findTrustBlockRanges(content: string, key: string): TrustBlockRange[] { return ranges } -function buildProjectHeaderPattern(projectPath: string): RegExp { - const headerPathValues = [projectPath] - if (usesWindowsPathSeparators(projectPath)) { - headerPathValues.push(projectPath.replace(/\//g, '\\'), projectPath.replace(/\\/g, '/')) - } - const headerPaths = [...new Set(headerPathValues)].map((path) => - escapeRegex(escapeTomlString(path)) - ) - return new RegExp( - `(^|\\r?\\n)[ \\t]*\\[projects\\."(?:${headerPaths.join('|')})"\\][ \\t]*(?:#[^\\r\\n]*)?(?=\\r?\\n|$)`, - process.platform === 'win32' ? 'i' : undefined - ) -} - type ParsedTomlString = { value: string endIndex: number @@ -574,6 +590,48 @@ function parseHookStateHeaderKey(line: string): string | null { return index === trimmed.length || trimmed[index] === '#' ? parsedKey.value : null } +export function parseCodexProjectHeaderPath(line: string): string | null { + // Why: mirror section headers come from split CRLF files and retain the + // terminal carriage return, while direct upserts scan CR-stripped lines. + const trimmed = line.replace(/\r$/, '').trimStart() + const prefixMatch = /^\[[ \t]*projects[ \t]*\.[ \t]*/.exec(trimmed) + if (!prefixMatch) { + return null + } + const parsedPath = parseTomlSingleLineString(trimmed, prefixMatch[0].length) + if (!parsedPath) { + return null + } + let index = skipTomlInlineWhitespace(trimmed, parsedPath.endIndex) + if (trimmed[index] !== ']') { + return null + } + index = skipTomlInlineWhitespace(trimmed, index + 1) + return index === trimmed.length || trimmed[index] === '#' ? parsedPath.value : null +} + +function findProjectHeaderLineEnd(content: string, projectPath: string): number | null { + const lookupPath = normalizeCodexProjectPathForLookup(projectPath) + let cursor = 0 + let scanState = createTomlLineScanState() + while (cursor < content.length) { + const newlineIndex = content.indexOf('\n', cursor) + const lineEnd = newlineIndex === -1 ? content.length : newlineIndex + const rawLine = content.slice(cursor, lineEnd) + const line = rawLine.replace(/\r$/, '') + const existingPath = isTomlStructuralLine(scanState) ? parseCodexProjectHeaderPath(line) : null + if (existingPath !== null && normalizeCodexProjectPathForLookup(existingPath) === lookupPath) { + return rawLine.endsWith('\r') ? lineEnd - 1 : lineEnd + } + scanState = updateTomlLineScanState(scanState, line) + if (newlineIndex === -1) { + return null + } + cursor = newlineIndex + 1 + } + return null +} + function parseTomlSingleLineString(line: string, startIndex: number): ParsedTomlString | null { if (line[startIndex] === '"') { return parseTomlBasicSingleLineString(line, startIndex + 1) diff --git a/src/main/codex/hook-service-wsl-runtime.test.ts b/src/main/codex/hook-service-wsl-runtime.test.ts new file mode 100644 index 000000000000..232725e5f66d --- /dev/null +++ b/src/main/codex/hook-service-wsl-runtime.test.ts @@ -0,0 +1,384 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { spawnSync } from 'node:child_process' +import { tmpdir } from 'node:os' +import { dirname, join, win32 as pathWin32 } from 'node:path' + +import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../agent-hooks/installer-utils' +import { + computeTrustKey, + computeTrustedHash, + readHookTrustEntries, + type CodexTrustEntry +} from './config-toml-trust' +import { + _internals, + createCodexWslRuntimeHookInstallPlan, + type CodexWslRuntimeHookInstallPlan +} from './hook-service' + +type HooksConfig = { + hooks: Record +} + +const managedEvents = [ + 'SessionStart', + 'UserPromptSubmit', + 'PreToolUse', + 'PermissionRequest', + 'PostToolUse', + 'Stop' +] as const + +let tempRoots: string[] = [] + +afterEach(() => { + for (const root of tempRoots) { + rmSync(root, { recursive: true, force: true }) + } + tempRoots = [] +}) + +function createTestPlan(): CodexWslRuntimeHookInstallPlan { + const root = mkdtempSync(join(tmpdir(), 'orca-codex-wsl-hooks-')) + tempRoots.push(root) + const linuxHome = '/home/alice/.local/share/orca/codex-runtime-home/home' + return { + configPath: join(root, 'hooks.json'), + tomlPath: join(root, 'config.toml'), + scriptPath: join(root, '.orca', 'agent-hooks', 'codex-hook.sh'), + commandScriptPath: `${linuxHome}/.orca/agent-hooks/codex-hook.sh`, + trustConfigPath: `${linuxHome}/hooks.json` + } +} + +function getManagedTrustEntry( + plan: CodexWslRuntimeHookInstallPlan, + command: string +): CodexTrustEntry { + return { + sourcePath: plan.trustConfigPath, + eventLabel: 'user_prompt_submit', + groupIndex: 0, + handlerIndex: 0, + command, + timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS + } +} + +describe('Codex WSL runtime hook install', () => { + it('plans WSL hook files with Linux command and trust paths', () => { + const runtimeHome = + '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.local\\share\\orca\\codex-runtime-home\\home' + + expect( + createCodexWslRuntimeHookInstallPlan(runtimeHome, undefined, (_distro, path) => path) + ).toEqual({ + configPath: pathWin32.join(runtimeHome, 'hooks.json'), + tomlPath: pathWin32.join(runtimeHome, 'config.toml'), + scriptPath: pathWin32.join(runtimeHome, '.orca', 'agent-hooks', 'codex-hook.sh'), + commandScriptPath: + '/home/alice/.local/share/orca/codex-runtime-home/home/.orca/agent-hooks/codex-hook.sh', + trustConfigPath: '/home/alice/.local/share/orca/codex-runtime-home/home/hooks.json' + }) + }) + + it('plans WSL hooks when the distro home is mounted on a Windows drive', () => { + const runtimeHome = 'D:\\wsl-home\\.local\\share\\orca\\codex-runtime-home\\home' + + expect( + createCodexWslRuntimeHookInstallPlan( + runtimeHome, + { runtime: 'wsl', wslDistro: 'Ubuntu' }, + (_distro, path) => path + ) + ).toEqual({ + configPath: pathWin32.join(runtimeHome, 'hooks.json'), + tomlPath: pathWin32.join(runtimeHome, 'config.toml'), + scriptPath: pathWin32.join(runtimeHome, '.orca', 'agent-hooks', 'codex-hook.sh'), + commandScriptPath: + '/mnt/d/wsl-home/.local/share/orca/codex-runtime-home/home/.orca/agent-hooks/codex-hook.sh', + trustConfigPath: '/mnt/d/wsl-home/.local/share/orca/codex-runtime-home/home/hooks.json' + }) + }) + + it('uses WSL-canonical paths for hook commands and trust keys', () => { + const runtimeHome = + '\\\\wsl.localhost\\Ubuntu\\home\\alias\\.local\\share\\orca\\codex-runtime-home\\home' + const canonicalHome = '/home/alice/.local/share/orca/codex-runtime-home/home' + + const plan = createCodexWslRuntimeHookInstallPlan( + runtimeHome, + { runtime: 'wsl', wslDistro: 'Ubuntu' }, + (distro, linuxPath) => { + expect(distro).toBe('Ubuntu') + expect(linuxPath).toBe('/home/alias/.local/share/orca/codex-runtime-home/home') + return canonicalHome + } + ) + + expect(plan?.commandScriptPath).toBe(`${canonicalHome}/.orca/agent-hooks/codex-hook.sh`) + expect(plan?.trustConfigPath).toBe(`${canonicalHome}/hooks.json`) + expect(plan?.configPath).toBe(pathWin32.join(runtimeHome, 'hooks.json')) + }) + + it('removes managed trust when the WSL canonical path changes', () => { + const plan = createTestPlan() + writeFileSync(plan.configPath, '{"hooks":{}}\n', 'utf-8') + writeFileSync(plan.tomlPath, '', 'utf-8') + + const oldPlan = { + ...plan, + commandScriptPath: '/old/home/.orca/agent-hooks/codex-hook.sh', + trustConfigPath: '/old/home/hooks.json' + } + expect(_internals.installManagedHooksIntoWslRuntime(oldPlan).state).toBe('installed') + const oldCommand = `if [ -r '${oldPlan.commandScriptPath}' ]; then /bin/sh '${oldPlan.commandScriptPath}'; fi` + const oldKey = computeTrustKey(getManagedTrustEntry(oldPlan, oldCommand)) + + const newPlan = { + ...plan, + commandScriptPath: '/new/home/.orca/agent-hooks/codex-hook.sh', + trustConfigPath: '/new/home/hooks.json' + } + expect(_internals.installManagedHooksIntoWslRuntime(newPlan).state).toBe('installed') + const newCommand = `if [ -r '${newPlan.commandScriptPath}' ]; then /bin/sh '${newPlan.commandScriptPath}'; fi` + const newKey = computeTrustKey(getManagedTrustEntry(newPlan, newCommand)) + const trustEntries = readHookTrustEntries(plan.tomlPath) + + expect(trustEntries.has(oldKey)).toBe(false) + expect(trustEntries.has(newKey)).toBe(true) + }) + + it('sweeps all managed WSL trust for disable or confirmed absence', () => { + // Why: disable and confirmed absence intentionally pass []. Transient + // unavailability must NOT use this path — last known-good trust remains. + const plan = createTestPlan() + writeFileSync(plan.configPath, '{"hooks":{}}\n', 'utf-8') + writeFileSync(plan.tomlPath, '', 'utf-8') + expect(_internals.installManagedHooksIntoWslRuntime(plan).state).toBe('installed') + + _internals.removeStaleWslRuntimeManagedHookTrustEntries(plan.tomlPath, []) + + expect(readHookTrustEntries(plan.tomlPath).size).toBe(0) + }) + + it('reconciles only current, conclusive WSL path settlements', () => { + expect( + _internals.getWslHookReconciliationAction({ + settlement: { status: 'unavailable' }, + isCurrentGeneration: true, + installedTrustConfigPath: '/mnt/d/home/hooks.json', + resolvedTrustConfigPath: null + }) + ).toBe('none') + + expect( + _internals.getWslHookReconciliationAction({ + settlement: { status: 'missing' }, + isCurrentGeneration: false, + installedTrustConfigPath: '/mnt/d/home/hooks.json', + resolvedTrustConfigPath: null + }) + ).toBe('none') + + expect( + _internals.getWslHookReconciliationAction({ + settlement: { status: 'missing' }, + isCurrentGeneration: true, + installedTrustConfigPath: '/mnt/d/home/hooks.json', + resolvedTrustConfigPath: null + }) + ).toBe('remove') + + expect( + _internals.getWslHookReconciliationAction({ + settlement: { status: 'resolved', canonicalPath: '/windows/d/home' }, + isCurrentGeneration: true, + installedTrustConfigPath: '/windows/d/home/hooks.json', + resolvedTrustConfigPath: '/windows/d/home/hooks.json' + }) + ).toBe('none') + + expect( + _internals.getWslHookReconciliationAction({ + settlement: { status: 'resolved', canonicalPath: '/windows/d/home' }, + isCurrentGeneration: true, + installedTrustConfigPath: '/mnt/d/home/hooks.json', + resolvedTrustConfigPath: '/windows/d/home/hooks.json' + }) + ).toBe('reinstall') + }) + + it('generates a POSIX hook that bridges WSL loopback failures through Windows curl', () => { + const script = _internals.getManagedScript('posix') + expect(script).toContain('load_hook_endpoint()') + expect(script).toContain('"set ORCA_AGENT_HOOK_TOKEN="*)') + expect(script).toContain('post_codex_hook()') + expect(script).toContain('is_wsl_runtime()') + expect(script).toContain('WSL_DISTRO_NAME') + expect(script).toContain('windows_curl=$(command -v curl.exe 2>/dev/null || true)') + expect(script).toContain('--data-urlencode "payload@-"') + expect(script).toContain('if post_codex_hook curl >/dev/null 2>&1; then') + expect(script).toContain('post_codex_hook "$windows_curl" 3 5 >/dev/null 2>&1 || true') + }) + + it.skipIf(process.platform === 'win32')( + 'refreshes stale hook coordinates from a Windows endpoint file', + () => { + const plan = createTestPlan() + const root = dirname(plan.configPath) + const endpointPath = join(root, 'endpoint.cmd') + const binDir = join(root, 'bin') + const curlPath = join(binDir, 'curl') + const capturePath = join(root, 'curl-args.txt') + mkdirSync(binDir, { recursive: true }) + writeFileSync( + endpointPath, + [ + 'set ORCA_AGENT_HOOK_PORT=43210', + 'set ORCA_AGENT_HOOK_TOKEN=fresh-token', + 'set ORCA_AGENT_HOOK_ENV=development', + 'set ORCA_AGENT_HOOK_VERSION=1', + '' + ].join('\r\n'), + 'utf-8' + ) + writeFileSync( + curlPath, + '#!/bin/sh\nprintf \'%s\\n\' "$@" > "$ORCA_TEST_CAPTURE"\ncat >> "$ORCA_TEST_CAPTURE"\n', + 'utf-8' + ) + chmodSync(curlPath, 0o755) + mkdirSync(dirname(plan.scriptPath), { recursive: true }) + writeFileSync(plan.scriptPath, _internals.getManagedScript('posix'), 'utf-8') + + const result = spawnSync('/bin/sh', [plan.scriptPath], { + encoding: 'utf-8', + input: '{"hook_event_name":"UserPromptSubmit","prompt":"restart"}', + env: { + ...process.env, + PATH: `${binDir}:${process.env.PATH ?? ''}`, + ORCA_AGENT_HOOK_ENDPOINT: endpointPath, + ORCA_AGENT_HOOK_PORT: '1', + ORCA_AGENT_HOOK_TOKEN: 'stale-token', + ORCA_PANE_KEY: 'pane-1', + ORCA_TEST_CAPTURE: capturePath + } + }) + + expect(result.status).toBe(0) + const posted = readFileSync(capturePath, 'utf-8') + expect(posted).toContain('http://127.0.0.1:43210/hook/codex') + expect(posted).toContain('X-Orca-Agent-Hook-Token: fresh-token') + expect(posted).not.toContain('stale-token') + } + ) + + it.skipIf(process.platform === 'win32')( + 'uses the Windows curl discovered from the WSL PATH after loopback fails', + () => { + const plan = createTestPlan() + const root = dirname(plan.configPath) + const binDir = join(root, 'bin') + const capturePath = join(root, 'windows-curl-args.txt') + mkdirSync(binDir, { recursive: true }) + writeFileSync(join(binDir, 'curl'), '#!/bin/sh\nexit 7\n', 'utf-8') + writeFileSync( + join(binDir, 'curl.exe'), + '#!/bin/sh\nprintf \'%s\\n\' "$@" > "$ORCA_TEST_CAPTURE"\ncat >> "$ORCA_TEST_CAPTURE"\n', + 'utf-8' + ) + chmodSync(join(binDir, 'curl'), 0o755) + chmodSync(join(binDir, 'curl.exe'), 0o755) + mkdirSync(dirname(plan.scriptPath), { recursive: true }) + writeFileSync(plan.scriptPath, _internals.getManagedScript('posix'), 'utf-8') + + const result = spawnSync('/bin/sh', [plan.scriptPath], { + encoding: 'utf-8', + input: '{"hook_event_name":"Stop"}', + env: { + ...process.env, + PATH: `${binDir}:${process.env.PATH ?? ''}`, + WSL_DISTRO_NAME: 'Ubuntu', + ORCA_AGENT_HOOK_ENDPOINT: '', + ORCA_AGENT_HOOK_PORT: '43210', + ORCA_AGENT_HOOK_TOKEN: 'token', + ORCA_PANE_KEY: 'pane-1', + ORCA_TEST_CAPTURE: capturePath + } + }) + + expect(result.status).toBe(0) + const posted = readFileSync(capturePath, 'utf-8') + expect(posted).toContain('http://127.0.0.1:43210/hook/codex') + expect(posted).toContain('X-Orca-Agent-Hook-Token: token') + } + ) + + it('installs trusted WSL hooks and removes only Orca entries when disabled', () => { + const plan = createTestPlan() + const userCommand = '/bin/sh /home/alice/user-hook.sh' + writeFileSync( + plan.configPath, + `${JSON.stringify({ + hooks: { + UserPromptSubmit: [{ hooks: [{ type: 'command', command: userCommand }] }], + PreCompact: [ + { + hooks: [ + { + type: 'command', + command: + "if [ -x '/old/.orca/agent-hooks/codex-hook.sh' ]; then /bin/sh '/old/.orca/agent-hooks/codex-hook.sh'; fi" + } + ] + } + ] + } + })}\n`, + 'utf-8' + ) + const unrelatedTrustKey = '/home/alice/custom/hooks.json:stop:0:0' + writeFileSync( + plan.tomlPath, + `[hooks.state."${unrelatedTrustKey}"]\nenabled = false\ntrusted_hash = "sha256:user"\n`, + 'utf-8' + ) + + expect(_internals.installManagedHooksIntoWslRuntime(plan).state).toBe('installed') + + const installed = JSON.parse(readFileSync(plan.configPath, 'utf-8')) as HooksConfig + expect(Object.keys(installed.hooks).sort()).toEqual([...managedEvents].sort()) + const managedCommand = installed.hooks.UserPromptSubmit[0]?.hooks?.[0]?.command + expect(managedCommand).toBe( + `if [ -r '${plan.commandScriptPath}' ]; then /bin/sh '${plan.commandScriptPath}'; fi` + ) + expect(installed.hooks.UserPromptSubmit[1]?.hooks?.[0]?.command).toBe(userCommand) + expect(readFileSync(plan.scriptPath, 'utf-8')).toContain('command -v curl.exe') + + const managedTrustEntry = getManagedTrustEntry(plan, managedCommand!) + const trustEntries = readHookTrustEntries(plan.tomlPath) + expect(trustEntries.get(computeTrustKey(managedTrustEntry))).toEqual({ + enabled: true, + trustedHash: computeTrustedHash(managedTrustEntry) + }) + expect(trustEntries.get(unrelatedTrustKey)).toEqual({ + enabled: false, + trustedHash: 'sha256:user' + }) + + expect(_internals.refreshWslRuntimeUserHooks(plan).state).toBe('not_installed') + + const refreshed = JSON.parse(readFileSync(plan.configPath, 'utf-8')) as HooksConfig + expect(refreshed.hooks).toEqual({ + UserPromptSubmit: [{ hooks: [{ type: 'command', command: userCommand }] }] + }) + const refreshedTrustEntries = readHookTrustEntries(plan.tomlPath) + expect(refreshedTrustEntries.has(computeTrustKey(managedTrustEntry))).toBe(false) + expect(refreshedTrustEntries.get(unrelatedTrustKey)).toEqual({ + enabled: false, + trustedHash: 'sha256:user' + }) + }) +}) diff --git a/src/main/codex/hook-service.ts b/src/main/codex/hook-service.ts index 0b01d65554f0..97142a4a2423 100644 --- a/src/main/codex/hook-service.ts +++ b/src/main/codex/hook-service.ts @@ -1,6 +1,6 @@ /* eslint-disable max-lines -- Why: getStatus + install + remove all share the managed-command and trust-key derivation. Splitting would hide that the three operations must agree on group index, event label, and command bytes. */ import { existsSync, readFileSync, unlinkSync } from 'node:fs' -import { join } from 'node:path' +import { join, win32 as pathWin32 } from 'node:path' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { @@ -16,7 +16,6 @@ import { wrapWindowsCmdHookCommand, writeHooksJson, writeManagedScript, - type HookCommandConfig, type HookDefinition } from '../agent-hooks/installer-utils' import { @@ -44,6 +43,22 @@ import { } from './config-toml-trust' import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from './codex-home-paths' import { syncSystemConfigIntoManagedCodexHome } from './codex-config-mirror' +import { + createCodexWslRuntimeHookInstallPlan, + type CodexWslRuntimeHookInstallPlan, + type CodexWslRuntimeHookTarget, + type WslCanonicalPathSettlement +} from './codex-wsl-hook-install-plan' +import { + CODEX_HOOK_EVENT_LABEL, + createCodexHookTrustEntry, + getCodexHookTrustSignature, + getCodexManagedScriptFileName +} from './codex-hook-identity' +import { + promoteCodexRuntimeHookApprovalsToSystem, + snapshotCodexRuntimeHookTrustProvenance +} from './hook-trust-promotion' // Why: PreToolUse/PostToolUse give the dashboard a live readout of the // in-flight tool (name + input preview) between UserPromptSubmit and Stop. @@ -73,29 +88,21 @@ function getCodexConfigTomlPath(): string { return join(getOrcaManagedCodexHomePath(), 'config.toml') } -// Why: Codex's hash key uses the snake_case event label (see -// codex-rs/hooks/src/lib.rs::hook_event_key_label). Our hooks.json uses the -// PascalCase serde-rename. Map between them at one place so the trust-write -// path can't drift from the install path. +// Why: the managed-event subset of the shared PascalCase→label map; the +// full mapping lives in codex-hook-identity.ts so promotion can't drift. const CODEX_EVENT_LABEL: Record<(typeof CODEX_EVENTS)[number], CodexEventLabel> = { - SessionStart: 'session_start', - UserPromptSubmit: 'user_prompt_submit', - PreToolUse: 'pre_tool_use', - PermissionRequest: 'permission_request', - PostToolUse: 'post_tool_use', - Stop: 'stop' + SessionStart: CODEX_HOOK_EVENT_LABEL.SessionStart!, + UserPromptSubmit: CODEX_HOOK_EVENT_LABEL.UserPromptSubmit!, + PreToolUse: CODEX_HOOK_EVENT_LABEL.PreToolUse!, + PermissionRequest: CODEX_HOOK_EVENT_LABEL.PermissionRequest!, + PostToolUse: CODEX_HOOK_EVENT_LABEL.PostToolUse!, + Stop: CODEX_HOOK_EVENT_LABEL.Stop! } const CODEX_MANAGED_EVENT_LABELS = new Set( CODEX_EVENTS.map((eventName) => CODEX_EVENT_LABEL[eventName]) ) -const CODEX_HOOK_EVENT_LABEL: Record = { - ...CODEX_EVENT_LABEL, - PreCompact: 'pre_compact', - PostCompact: 'post_compact' -} - const CODEX_PLUGIN_ONLY_HOOK_PLACEHOLDERS = [ '${CLAUDE_PLUGIN_ROOT}', '${CLAUDE_PLUGIN_DATA}', @@ -112,12 +119,8 @@ type MirroredRuntimeUserHookTrustEntry = { enabled: boolean } -function getManagedScriptFileName(): string { - return process.platform === 'win32' ? 'codex-hook.cmd' : 'codex-hook.sh' -} - function getManagedScriptPath(): string { - return getSharedManagedScriptPath(getManagedScriptFileName()) + return getSharedManagedScriptPath(getCodexManagedScriptFileName()) } function getManagedCommand(scriptPath: string): string { @@ -126,6 +129,16 @@ function getManagedCommand(scriptPath: string): string { : wrapPosixHookCommand(scriptPath) } +export { createCodexWslRuntimeHookInstallPlan } +export type { CodexWslRuntimeHookInstallPlan } + +function wrapReadablePosixHookCommand(scriptPath: string): string { + const quoted = `'${scriptPath.replaceAll("'", "'\\''")}'` + // Why: WSL runtime hooks are written from Windows through UNC, where the + // executable bit is not reliable. /bin/sh only needs the script to be readable. + return `if [ -r ${quoted} ]; then /bin/sh ${quoted}; fi` +} + function getSystemConfigPath(): string { return join(getSystemCodexHomePath(), 'hooks.json') } @@ -151,7 +164,7 @@ function collectManagedTrustEntries( if (!isManagedCommand(hook.command)) { return } - const entry = createHookTrustEntry( + const entry = createCodexHookTrustEntry( sourcePath, eventName, groupIndex, @@ -167,32 +180,6 @@ function collectManagedTrustEntries( return entries } -function createHookTrustEntry( - sourcePath: string, - eventName: string, - groupIndex: number, - handlerIndex: number, - definition: HookDefinition, - hook: HookCommandConfig -): CodexTrustEntry | null { - const eventLabel = CODEX_HOOK_EVENT_LABEL[eventName] - if (!eventLabel || !hook.command) { - return null - } - - return { - sourcePath, - eventLabel, - groupIndex, - handlerIndex, - command: hook.command, - ...(typeof hook.timeout === 'number' ? { timeoutSec: hook.timeout } : {}), - ...(typeof hook.async === 'boolean' ? { async: hook.async } : {}), - ...(typeof definition.matcher === 'string' ? { matcher: definition.matcher } : {}), - ...(typeof hook.statusMessage === 'string' ? { statusMessage: hook.statusMessage } : {}) - } -} - function removeMatchingTrustEntries(configPath: string, entries: readonly CodexTrustEntry[]): void { if (entries.length === 0) { return @@ -218,7 +205,7 @@ function removeStaleRuntimeHookTrustEntries( const expectedHashes = new Map( expectedEntries.map((entry) => [ normalizeHookTrustKeyForLookup(computeTrustKey(entry)), - computeTrustedHash(entry) + entry.trustedHash ?? computeTrustedHash(entry) ]) ) const canonicalRuntimeHooksPath = getCodexCanonicalTrustPath(runtimeHooksPath) @@ -238,17 +225,6 @@ function removeStaleRuntimeHookTrustEntries( } } -function getTrustSignature(entry: CodexTrustEntry): string { - return JSON.stringify({ - eventLabel: entry.eventLabel, - command: entry.command, - timeoutSec: Math.max(1, entry.timeoutSec ?? 600), - async: entry.async ?? false, - matcher: entry.matcher ?? null, - statusMessage: entry.statusMessage ?? null - }) -} - function commandUsesCodexPluginOnlyPlaceholder(command: string | undefined): boolean { return ( typeof command === 'string' && @@ -316,12 +292,17 @@ function getRuntimeHooksWithSystemUserHooks( } } +type TrustedSystemHookSignatureState = { + enabled: boolean + trustedHash: string +} + function getTrustedSystemUserHookSignatures( systemConfigPath: string, systemHooks: Record, isManagedCommand: (command: string | undefined) => boolean -): Map { - const signatures = new Map() +): Map { + const signatures = new Map() let trustEntries: Map try { trustEntries = readHookTrustEntries(getSystemCodexConfigTomlPath()) @@ -342,7 +323,7 @@ function getTrustedSystemUserHookSignatures( if (isManagedCommand(hook.command)) { return } - const entry = createHookTrustEntry( + const entry = createCodexHookTrustEntry( systemConfigPath, eventName, groupIndex, @@ -353,20 +334,15 @@ function getTrustedSystemUserHookSignatures( if (!entry) { return } - const expectedHash = computeTrustedHash(entry) - const state = trustEntries.get(computeTrustKey(entry)) - const enabled = - state?.trustedHash === expectedHash - ? state.enabled !== false - : trustedHashesByEvent.get(entry.eventLabel)?.get(expectedHash) - if (enabled === undefined) { + const state = resolveTrustedSystemHookState(entry, trustEntries, trustedHashesByEvent) + if (!state) { return } - const signature = getTrustSignature(entry) + const signature = getCodexHookTrustSignature(entry) // Why: runtime deduping collapses identical system hook definitions; // if any duplicate remains enabled, keep the mirrored hook enabled. - if (enabled || !signatures.has(signature)) { - signatures.set(signature, enabled) + if (state.enabled || !signatures.has(signature)) { + signatures.set(signature, state) } }) }) @@ -374,6 +350,31 @@ function getTrustedSystemUserHookSignatures( return signatures } +function resolveTrustedSystemHookState( + entry: CodexTrustEntry, + trustEntries: ReadonlyMap, + trustedHashesByEvent: ReadonlyMap> +): TrustedSystemHookSignatureState | null { + const expectedHash = computeTrustedHash(entry) + const state = trustEntries.get(computeTrustKey(entry)) + if (state?.trustedHash === expectedHash) { + return { enabled: state.enabled !== false, trustedHash: expectedHash } + } + const reorderedEnabled = trustedHashesByEvent.get(entry.eventLabel)?.get(expectedHash) + if (reorderedEnabled !== undefined) { + return { enabled: reorderedEnabled, trustedHash: expectedHash } + } + if (state?.trustedHash) { + // Why: carry a key-matched system hash verbatim instead of dropping it as + // stale. Codex is the authority on its own hash algorithm; recomputing + // here is what turned #7110-style hash drift into an endless re-approval + // loop. If the hash is genuinely stale (edited hook), Codex prompts — + // exactly what a plain ~/.codex session would do. + return { enabled: state.enabled !== false, trustedHash: state.trustedHash } + } + return null +} + function getTrustedSystemHookHashesByEvent( systemConfigPath: string, trustEntries: ReadonlyMap @@ -406,7 +407,7 @@ function getTrustedSystemHookHashesByEvent( function collectMirroredRuntimeUserHookTrustEntries( runtimeConfigPath: string, runtimeHooks: Record, - trustedSystemHookSignatures: ReadonlyMap, + trustedSystemHookSignatures: ReadonlyMap, isManagedCommand: (command: string | undefined) => boolean ): MirroredRuntimeUserHookTrustEntry[] { if (trustedSystemHookSignatures.size === 0) { @@ -424,7 +425,7 @@ function collectMirroredRuntimeUserHookTrustEntries( if (isManagedCommand(hook.command)) { return } - const entry = createHookTrustEntry( + const entry = createCodexHookTrustEntry( runtimeConfigPath, eventName, groupIndex, @@ -435,10 +436,13 @@ function collectMirroredRuntimeUserHookTrustEntries( if (!entry) { return } - const signature = getTrustSignature(entry) - const enabled = trustedSystemHookSignatures.get(signature) - if (enabled !== undefined) { - entries.push({ entry, enabled }) + const signature = getCodexHookTrustSignature(entry) + const state = trustedSystemHookSignatures.get(signature) + if (state !== undefined) { + entries.push({ + entry: { ...entry, trustedHash: state.trustedHash }, + enabled: state.enabled + }) } }) }) @@ -533,7 +537,7 @@ function cleanupLegacySystemManagedHooks(): void { return } - const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName()) + const isManagedCommand = createManagedCommandMatcher(getCodexManagedScriptFileName()) const nextHooks = { ...config.hooks } const trustEntries: CodexTrustEntry[] = [] let removedManagedHook = false @@ -674,6 +678,98 @@ function removeRuntimeManagedHookTrustEntries(configPath: string): void { } } +function removeWslRuntimeManagedHookTrustEntries(plan: CodexWslRuntimeHookInstallPlan): void { + try { + const existingEntries = readHookTrustEntries(plan.tomlPath) + const command = wrapReadablePosixHookCommand(plan.commandScriptPath) + const managedEventLabels = new Set( + CODEX_EVENTS.map((event) => CODEX_EVENT_LABEL[event]) + ) + const canonicalConfigPath = getCodexCanonicalTrustPath(plan.trustConfigPath) + const ourKeys: string[] = [] + for (const [key, state] of existingEntries) { + const parts = parseTrustKey(key) + if (parts === null) { + continue + } + if (getCodexCanonicalTrustPath(parts.sourcePath) !== canonicalConfigPath) { + continue + } + if (!managedEventLabels.has(parts.eventLabel)) { + continue + } + const expectedEntry: CodexTrustEntry = { + sourcePath: plan.trustConfigPath, + eventLabel: parts.eventLabel, + groupIndex: parts.groupIndex, + handlerIndex: parts.handlerIndex, + command, + timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS + } + const recognizedHashes = new Set([ + computeTrustedHash(expectedEntry), + computeTrustedHash({ ...expectedEntry, timeoutSec: undefined }) + ]) + if (state.trustedHash && recognizedHashes.has(state.trustedHash)) { + ourKeys.push(key) + } + } + if (ourKeys.length > 0) { + removeHookTrustEntries(plan.tomlPath, ourKeys) + } + } catch (error) { + // Why: removing disabled WSL status hooks should be best-effort like the + // host cleanup path; stale trust is inert once hooks.json no longer points at us. + console.warn('[codex-hook-service] failed to clean WSL trust entries', error) + } +} + +function removeStaleWslRuntimeManagedHookTrustEntries( + tomlPath: string, + desiredEntries: readonly CodexTrustEntry[] +): void { + const desiredKeys = new Set( + desiredEntries.map((entry) => normalizeHookTrustKeyForLookup(computeTrustKey(entry))) + ) + const existingEntries = readHookTrustEntries(tomlPath) + const ourKeys: string[] = [] + for (const [key, state] of existingEntries) { + if (desiredKeys.has(normalizeHookTrustKeyForLookup(key))) { + continue + } + const parts = parseTrustKey(key) + if (!parts || !CODEX_MANAGED_EVENT_LABELS.has(parts.eventLabel)) { + continue + } + const sourcePath = parts.sourcePath + // Why: this cleanup owns only guest-side WSL trust. A runtime config can + // still contain user Windows/remote hooks, which must remain untouched. + if (!sourcePath.startsWith('/') || !sourcePath.endsWith('/hooks.json')) { + continue + } + const runtimeHome = sourcePath.slice(0, -'/hooks.json'.length) + const command = wrapReadablePosixHookCommand(`${runtimeHome}/.orca/agent-hooks/codex-hook.sh`) + const expectedEntry: CodexTrustEntry = { + sourcePath: parts.sourcePath, + eventLabel: parts.eventLabel, + groupIndex: parts.groupIndex, + handlerIndex: parts.handlerIndex, + command, + timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS + } + const recognizedHashes = new Set([ + computeTrustedHash(expectedEntry), + computeTrustedHash({ ...expectedEntry, timeoutSec: undefined }) + ]) + if (state.trustedHash && recognizedHashes.has(state.trustedHash)) { + ourKeys.push(key) + } + } + if (ourKeys.length > 0) { + removeHookTrustEntries(tomlPath, ourKeys) + } +} + function getManagedScript(target: 'local' | 'posix' = 'local'): string { if (target === 'local' && process.platform === 'win32') { return [ @@ -698,8 +794,30 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string { // Why: see claude/hook-service.ts for rationale. Sourcing refreshes // PORT/TOKEN/ENV/VERSION from the current Orca so a surviving PTY keeps // reporting after a restart. + 'load_hook_endpoint() {', + ' endpoint_path="$1"', + ' case "$endpoint_path" in', + ' *.cmd)', + // Why: Windows passes endpoint.cmd into WSL through WSLENV path translation. + // Parse only Orca's known assignments; cmd.exe `set` lines are not shell syntax. + ' endpoint_cr=$(printf "\\r")', + ' while IFS= read -r endpoint_line || [ -n "$endpoint_line" ]; do', + ' endpoint_line=${endpoint_line%"$endpoint_cr"}', + ' case "$endpoint_line" in', + ' "set ORCA_AGENT_HOOK_PORT="*) ORCA_AGENT_HOOK_PORT=${endpoint_line#*=} ;;', + ' "set ORCA_AGENT_HOOK_TOKEN="*) ORCA_AGENT_HOOK_TOKEN=${endpoint_line#*=} ;;', + ' "set ORCA_AGENT_HOOK_ENV="*) ORCA_AGENT_HOOK_ENV=${endpoint_line#*=} ;;', + ' "set ORCA_AGENT_HOOK_VERSION="*) ORCA_AGENT_HOOK_VERSION=${endpoint_line#*=} ;;', + ' esac', + ' done < "$endpoint_path"', + ' ;;', + ' *)', + ' . "$endpoint_path" 2>/dev/null || :', + ' ;;', + ' esac', + '}', 'if [ -n "$ORCA_AGENT_HOOK_ENDPOINT" ] && [ -r "$ORCA_AGENT_HOOK_ENDPOINT" ]; then', - ' . "$ORCA_AGENT_HOOK_ENDPOINT" 2>/dev/null || :', + ' load_hook_endpoint "$ORCA_AGENT_HOOK_ENDPOINT"', 'fi', 'if [ -z "$ORCA_AGENT_HOOK_PORT" ] || [ -z "$ORCA_AGENT_HOOK_TOKEN" ] || [ -z "$ORCA_PANE_KEY" ]; then', ' exit 0', @@ -708,6 +826,10 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string { 'if [ -z "$payload" ]; then', ' exit 0', 'fi', + 'post_codex_hook() {', + ' curl_bin="$1"', + ' connect_timeout="${2:-0.5}"', + ' max_time="${3:-1.5}"', // Why: worktreeId embeds a filesystem path, so hand-building JSON in POSIX // shell is not safe once a path contains quotes or newlines. Post the raw // hook payload plus metadata as form fields and let the receiver parse it. @@ -715,23 +837,260 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string { // Why: pipe payload to curl's stdin (`payload@-`) instead of an inline // `payload=$VALUE` arg, so tens-of-KB tool output stays off the curl // command line (EDR command-line false positives). Wire body is identical. - 'printf \'%s\' "$payload" | curl -sS -X POST "http://127.0.0.1:${ORCA_AGENT_HOOK_PORT}/hook/codex" \\', - ' --connect-timeout 0.5 --max-time 1.5 \\', - ' -H "Content-Type: application/x-www-form-urlencoded" \\', - ' -H "X-Orca-Agent-Hook-Token: ${ORCA_AGENT_HOOK_TOKEN}" \\', - ' --data-urlencode "paneKey=${ORCA_PANE_KEY}" \\', - ' --data-urlencode "tabId=${ORCA_TAB_ID}" \\', - ' --data-urlencode "launchToken=${ORCA_AGENT_LAUNCH_TOKEN}" \\', - ' --data-urlencode "worktreeId=${ORCA_WORKTREE_ID}" \\', - ' --data-urlencode "env=${ORCA_AGENT_HOOK_ENV}" \\', - ' --data-urlencode "version=${ORCA_AGENT_HOOK_VERSION}" \\', - ' --data-urlencode "payload@-" >/dev/null 2>&1 || true', + ' printf \'%s\' "$payload" | "$curl_bin" -sS -X POST "http://127.0.0.1:${ORCA_AGENT_HOOK_PORT}/hook/codex" \\', + ' --connect-timeout "$connect_timeout" --max-time "$max_time" \\', + ' --noproxy "127.0.0.1" \\', + ' -H "Content-Type: application/x-www-form-urlencoded" \\', + ' -H "X-Orca-Agent-Hook-Token: ${ORCA_AGENT_HOOK_TOKEN}" \\', + ' --data-urlencode "paneKey=${ORCA_PANE_KEY}" \\', + ' --data-urlencode "tabId=${ORCA_TAB_ID}" \\', + ' --data-urlencode "launchToken=${ORCA_AGENT_LAUNCH_TOKEN}" \\', + ' --data-urlencode "worktreeId=${ORCA_WORKTREE_ID}" \\', + ' --data-urlencode "env=${ORCA_AGENT_HOOK_ENV}" \\', + ' --data-urlencode "version=${ORCA_AGENT_HOOK_VERSION}" \\', + ' --data-urlencode "payload@-"', + '}', + 'is_wsl_runtime() {', + ' [ -n "$WSL_DISTRO_NAME" ] && return 0', + ' grep -qiE "microsoft|wsl" /proc/sys/kernel/osrelease /proc/version 2>/dev/null', + '}', + 'if post_codex_hook curl >/dev/null 2>&1; then', + ' exit 0', + 'fi', + 'if is_wsl_runtime; then', + ' windows_curl=$(command -v curl.exe 2>/dev/null || true)', + ' if [ -n "$windows_curl" ] && [ -x "$windows_curl" ]; then', + ' post_codex_hook "$windows_curl" 3 5 >/dev/null 2>&1 || true', + ' fi', + 'fi', 'exit 0', '' ].join('\n') } +function installManagedHooksIntoWslRuntime( + plan: CodexWslRuntimeHookInstallPlan +): AgentHookInstallStatus { + const config = readHooksJson(plan.configPath) + if (!config) { + return { + agent: 'codex', + state: 'error', + configPath: plan.configPath, + managedHooksPresent: false, + detail: 'Could not parse Codex hooks.json' + } + } + + const isManagedCommand = createManagedCommandMatcher('codex-hook.sh') + const command = wrapReadablePosixHookCommand(plan.commandScriptPath) + const nextHooks = { ...config.hooks } + const managedEvents = new Set(CODEX_EVENTS) + for (const [eventName, definitions] of Object.entries(nextHooks)) { + if (managedEvents.has(eventName) || !Array.isArray(definitions)) { + continue + } + const cleaned = removeManagedCommands(definitions, isManagedCommand) + if (cleaned.length === 0) { + delete nextHooks[eventName] + } else { + nextHooks[eventName] = cleaned + } + } + + const trustEntries: CodexTrustEntry[] = [] + for (const eventName of CODEX_EVENTS) { + const current = Array.isArray(nextHooks[eventName]) ? nextHooks[eventName] : [] + const cleaned = removeManagedCommands(current, isManagedCommand) + const definition: HookDefinition = { + hooks: [buildManagedCommandHook(command)] + } + nextHooks[eventName] = [definition, ...cleaned] + trustEntries.push({ + sourcePath: plan.trustConfigPath, + eventLabel: CODEX_EVENT_LABEL[eventName], + groupIndex: 0, + handlerIndex: 0, + command, + timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS + }) + } + + config.hooks = nextHooks + writeManagedScript(plan.scriptPath, getManagedScript('posix')) + writeCodexHooksJson(plan.configPath, nextHooks) + try { + // Why: WSL runtime homes may carry user hook approvals we did not rebuild + // here; only upsert Orca's entries instead of sweeping the whole source. + upsertHookTrustEntries(plan.tomlPath, trustEntries) + removeStaleWslRuntimeManagedHookTrustEntries(plan.tomlPath, trustEntries) + } catch (error) { + return { + agent: 'codex', + state: 'error', + configPath: plan.configPath, + managedHooksPresent: true, + detail: `Hooks installed but trust entries could not be written: ${error instanceof Error ? error.message : String(error)}. Run /hooks in Codex to approve.` + } + } + + return { + agent: 'codex', + state: 'installed', + configPath: plan.configPath, + managedHooksPresent: true, + detail: null + } +} + +function refreshWslRuntimeUserHooks(plan: CodexWslRuntimeHookInstallPlan): AgentHookInstallStatus { + const config = readHooksJson(plan.configPath) + if (!config) { + return { + agent: 'codex', + state: 'error', + configPath: plan.configPath, + managedHooksPresent: false, + detail: 'Could not parse Codex hooks.json' + } + } + + const isManagedCommand = createManagedCommandMatcher('codex-hook.sh') + const nextHooks = { ...config.hooks } + for (const [eventName, definitions] of Object.entries(nextHooks)) { + if (!Array.isArray(definitions)) { + continue + } + const cleaned = removeManagedCommands(definitions, isManagedCommand) + if (cleaned.length === 0) { + delete nextHooks[eventName] + } else { + nextHooks[eventName] = cleaned + } + } + writeCodexHooksJson(plan.configPath, nextHooks) + removeWslRuntimeManagedHookTrustEntries(plan) + try { + // Why: the disabled path may be reached after the WSL mount root changed, + // so cleanup cannot be scoped only to the plan's current source path. + removeStaleWslRuntimeManagedHookTrustEntries(plan.tomlPath, []) + } catch (error) { + console.warn('[codex-hook-service] failed to clean stale WSL trust entries', error) + } + return { + agent: 'codex', + state: 'not_installed', + configPath: plan.configPath, + managedHooksPresent: false, + detail: null + } +} + +// Why: transport failures preserve the last known-good identity, while a +// successful absence probe is strong enough to revoke trust immediately. +function getWslHookReconciliationAction(args: { + settlement: WslCanonicalPathSettlement + isCurrentGeneration: boolean + installedTrustConfigPath: string | null + resolvedTrustConfigPath: string | null +}): 'none' | 'remove' | 'reinstall' { + if (!args.isCurrentGeneration) { + return 'none' + } + if (args.settlement.status === 'missing') { + return 'remove' + } + if ( + args.settlement.status !== 'resolved' || + !args.resolvedTrustConfigPath || + args.resolvedTrustConfigPath === args.installedTrustConfigPath + ) { + return 'none' + } + return 'reinstall' +} + export class CodexHookService { + private readonly wslReconciliationGeneration = new Map() + + private supersedeWslReconciliation(runtimeHomePath: string | null | undefined): number { + if (!runtimeHomePath) { + return 0 + } + const key = process.platform === 'win32' ? runtimeHomePath.toLowerCase() : runtimeHomePath + const generation = (this.wslReconciliationGeneration.get(key) ?? 0) + 1 + this.wslReconciliationGeneration.set(key, generation) + return generation + } + + installForRuntimeHome( + runtimeHomePath: string | null | undefined, + target?: CodexWslRuntimeHookTarget + ): AgentHookInstallStatus | null { + const generation = this.supersedeWslReconciliation(runtimeHomePath) + let installedTrustConfigPath: string | null = null + const onCanonicalPathSettled = (settlement: WslCanonicalPathSettlement): void => { + if (!runtimeHomePath) { + return + } + const key = process.platform === 'win32' ? runtimeHomePath.toLowerCase() : runtimeHomePath + const resolvedPlan = + settlement.status === 'resolved' + ? createCodexWslRuntimeHookInstallPlan( + runtimeHomePath, + target, + () => settlement.canonicalPath + ) + : null + const action = getWslHookReconciliationAction({ + settlement, + isCurrentGeneration: this.wslReconciliationGeneration.get(key) === generation, + installedTrustConfigPath, + resolvedTrustConfigPath: resolvedPlan?.trustConfigPath ?? null + }) + if (action === 'none') { + return + } + if (action === 'remove') { + try { + removeStaleWslRuntimeManagedHookTrustEntries( + pathWin32.join(runtimeHomePath, 'config.toml'), + [] + ) + } catch (error) { + console.warn('[codex-hook-service] failed to revoke stale WSL hook trust', error) + } + return + } + if (!resolvedPlan) { + return + } + const status = installManagedHooksIntoWslRuntime(resolvedPlan) + if (status.state === 'error') { + console.warn('[codex-hook-service] failed to reconcile WSL hook path', status.detail) + return + } + installedTrustConfigPath = resolvedPlan.trustConfigPath + } + const wslPlan = createCodexWslRuntimeHookInstallPlan( + runtimeHomePath, + target, + undefined, + onCanonicalPathSettled + ) + installedTrustConfigPath = wslPlan?.trustConfigPath ?? null + return wslPlan ? installManagedHooksIntoWslRuntime(wslPlan) : null + } + + refreshRuntimeUserHooksForRuntimeHome( + runtimeHomePath: string | null | undefined, + target?: CodexWslRuntimeHookTarget + ): AgentHookInstallStatus | null { + this.supersedeWslReconciliation(runtimeHomePath) + const wslPlan = createCodexWslRuntimeHookInstallPlan(runtimeHomePath, target) + return wslPlan ? refreshWslRuntimeUserHooks(wslPlan) : null + } + getStatus(): AgentHookInstallStatus { const configPath = getConfigPath() const scriptPath = getManagedScriptPath() @@ -853,6 +1212,11 @@ export class CodexHookService { install(): AgentHookInstallStatus { const configPath = getConfigPath() const scriptPath = getManagedScriptPath() + // Why: must run before this install rewrites hooks.json/config.toml — + // approvals the user made inside Orca-launched Codex are keyed to the + // previous launch's runtime layout, and stale-trust cleanup below would + // delete them once the system config stops backing them. + promoteCodexRuntimeHookApprovalsToSystem() const config = readHooksJson(configPath) if (!config) { return { @@ -868,7 +1232,7 @@ export class CodexHookService { // install sweeps stale entries left by older builds or a different // Electron userData path (dev vs. prod). Without this, repeated installs // accumulate duplicate hook entries pointing at defunct scripts. - const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName()) + const isManagedCommand = createManagedCommandMatcher(getCodexManagedScriptFileName()) const command = getManagedCommand(scriptPath) const hookPlan = getRuntimeHooksWithSystemUserHooks(config.hooks, isManagedCommand) const nextHooks = hookPlan.hooks @@ -953,6 +1317,7 @@ export class CodexHookService { detail: `Hooks installed but trust entries could not be written: ${error instanceof Error ? error.message : String(error)}. Run /hooks in Codex to approve.` } } + snapshotCodexRuntimeHookTrustProvenance() try { cleanupLegacySystemManagedHooks() cleanupLegacyCodexProfileHooks() @@ -962,9 +1327,25 @@ export class CodexHookService { return this.getStatus() } - async installRemote(sftp: SFTPWrapper, remoteHome: string): Promise { - const remoteConfigPath = `${remoteHome.replace(/\/$/, '')}/.codex/hooks.json` - const remoteTomlPath = `${remoteHome.replace(/\/$/, '')}/.codex/config.toml` + async installRemote( + sftp: SFTPWrapper, + remoteHome: string, + options?: { + /** Explicit CODEX_HOME dir (flat layout: hooks.json/config.toml at its + * root). WSL sessions read Orca's managed runtime home, not ~/.codex — + * installing to the default location leaves those sessions hookless. */ + codexHomeDir?: string + /** Skip the trust write when config.toml doesn't exist yet. The WSL + * runtime home's config.toml is seeded only-if-absent by the launch + * path; creating it here first would silently cancel that seed. A + * later (idempotent) reinstall upserts trust once the seed lands. */ + deferTrustUntilConfigToml?: boolean + } + ): Promise { + const codexHomeBase = + options?.codexHomeDir?.replace(/\/$/, '') ?? `${remoteHome.replace(/\/$/, '')}/.codex` + const remoteConfigPath = `${codexHomeBase}/hooks.json` + const remoteTomlPath = `${codexHomeBase}/config.toml` const remoteScriptPath = `${remoteHome.replace(/\/$/, '')}/.orca/agent-hooks/codex-hook.sh` try { const config = await readHooksJsonRemote(sftp, remoteConfigPath) @@ -1023,7 +1404,17 @@ export class CodexHookService { // Preserve non-Orca top-level metadata while replacing the hooks tree. await writeHooksJsonRemote(sftp, remoteConfigPath, { ...config, hooks: nextHooks }) try { - const existingToml = (await readTextFileRemote(sftp, remoteTomlPath)) ?? '' + const existingTomlRaw = await readTextFileRemote(sftp, remoteTomlPath) + if (existingTomlRaw === null && options?.deferTrustUntilConfigToml === true) { + return { + agent: 'codex', + state: 'installed', + configPath: remoteConfigPath, + managedHooksPresent: true, + detail: 'Trust entries deferred until config.toml is seeded by the launch path' + } + } + const existingToml = existingTomlRaw ?? '' const updatedToml = upsertHookTrustEntriesInContent(existingToml, trustEntries) if (updatedToml !== existingToml) { await writeTextFileRemoteAtomic(sftp, remoteTomlPath, updatedToml) @@ -1060,6 +1451,9 @@ export class CodexHookService { refreshRuntimeUserHooks(): AgentHookInstallStatus { const configPath = getConfigPath() + // Why: same as install() — capture in-Orca approvals before this refresh + // rewrites the runtime files they are keyed against. + promoteCodexRuntimeHookApprovalsToSystem() const config = readHooksJson(configPath) if (!config) { // Why: disabled launch prep used to call remove(); preserve its legacy @@ -1074,7 +1468,7 @@ export class CodexHookService { } } - const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName()) + const isManagedCommand = createManagedCommandMatcher(getCodexManagedScriptFileName()) const hookPlan = getRuntimeHooksWithSystemUserHooks(config.hooks, isManagedCommand) config.hooks = hookPlan.hooks writeCodexHooksJson(configPath, hookPlan.hooks) @@ -1099,6 +1493,7 @@ export class CodexHookService { detail: `User hooks refreshed but trust entries could not be written: ${error instanceof Error ? error.message : String(error)}. Run /hooks in Codex to approve.` } } + snapshotCodexRuntimeHookTrustProvenance() cleanupLegacyManagedHookRepresentations() return this.getStatus() @@ -1124,7 +1519,7 @@ export class CodexHookService { const nextHooks = { ...config.hooks } // Why: same broad matcher as install(), so remove() also cleans up stale // entries from older builds even if the current scriptPath has moved. - const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName()) + const isManagedCommand = createManagedCommandMatcher(getCodexManagedScriptFileName()) for (const [eventName, definitions] of Object.entries(nextHooks)) { if (!Array.isArray(definitions)) { // Why: a malformed hooks.json entry (non-array value for an event name) @@ -1157,3 +1552,11 @@ export class CodexHookService { } export const codexHookService = new CodexHookService() + +export const _internals = { + getManagedScript, + installManagedHooksIntoWslRuntime, + refreshWslRuntimeUserHooks, + removeStaleWslRuntimeManagedHookTrustEntries, + getWslHookReconciliationAction +} diff --git a/src/main/codex/hook-trust-promotion.test.ts b/src/main/codex/hook-trust-promotion.test.ts new file mode 100644 index 000000000000..b497591db638 --- /dev/null +++ b/src/main/codex/hook-trust-promotion.test.ts @@ -0,0 +1,399 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import type * as Os from 'node:os' +import { join } from 'node:path' +import { + computeTrustKey, + computeTrustedHash, + readHookTrustEntries, + upsertHookTrustEntriesInContent, + type CodexTrustEntry +} from './config-toml-trust' + +const { getPathMock, homedirMock } = vi.hoisted(() => ({ + getPathMock: vi.fn<(name: string) => string>(), + homedirMock: vi.fn<() => string>() +})) + +vi.mock('electron', () => ({ + app: { + getPath: getPathMock + } +})) + +vi.mock('os', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + homedir: homedirMock + } +}) + +import { CodexHookService } from './hook-service' + +let tmpHome: string +let userDataDir: string +let previousUserDataPath: string | undefined + +beforeEach(() => { + tmpHome = mkdtempSync(join(tmpdir(), 'orca-codex-home-')) + userDataDir = mkdtempSync(join(tmpdir(), 'orca-codex-user-data-')) + previousUserDataPath = process.env.ORCA_USER_DATA_PATH + process.env.ORCA_USER_DATA_PATH = userDataDir + homedirMock.mockReturnValue(tmpHome) + getPathMock.mockImplementation((name: string) => { + if (name === 'userData') { + return userDataDir + } + throw new Error(`unexpected app.getPath(${name})`) + }) +}) + +afterEach(() => { + rmSync(tmpHome, { recursive: true, force: true }) + rmSync(userDataDir, { recursive: true, force: true }) + if (previousUserDataPath === undefined) { + delete process.env.ORCA_USER_DATA_PATH + } else { + process.env.ORCA_USER_DATA_PATH = previousUserDataPath + } + vi.clearAllMocks() +}) + +const USER_HOOK_COMMAND = 'echo my-personal-hook' + +function systemCodexDir(): string { + return join(tmpHome, '.codex') +} + +function runtimeHomeDir(): string { + return join(userDataDir, 'codex-runtime-home', 'home') +} + +function writeSystemUserHook(commands: string[] = [USER_HOOK_COMMAND]): void { + mkdirSync(systemCodexDir(), { recursive: true }) + writeFileSync( + join(systemCodexDir(), 'hooks.json'), + JSON.stringify({ + hooks: { + Stop: commands.map((command) => ({ hooks: [{ type: 'command', command }] })) + } + }) + ) +} + +// Simulates the Codex TUI persisting a /hooks approval: Codex writes a trust +// entry keyed to the file that declares the hook, using its own hash. The +// production hash algorithm is reproduced by computeTrustedHash. +function simulateCodexApproval(entry: CodexTrustEntry, options?: { hash?: string }): void { + const tomlPath = join(runtimeHomeDir(), 'config.toml') + const existing = existsSync(tomlPath) ? readFileSync(tomlPath, 'utf-8') : '' + const approvalEntry = options?.hash ? { ...entry, trustedHash: options.hash } : entry + writeFileSync(tomlPath, upsertHookTrustEntriesInContent(existing, [approvalEntry])) +} + +function runtimeUserStopEntry(): CodexTrustEntry { + // install() prepends the managed status hook on Stop, so the mirrored user + // hook lands at groupIndex 1. + return { + sourcePath: join(runtimeHomeDir(), 'hooks.json'), + eventLabel: 'stop', + groupIndex: 1, + handlerIndex: 0, + command: USER_HOOK_COMMAND + } +} + +function systemUserStopEntry(groupIndex = 0): CodexTrustEntry { + return { + sourcePath: join(systemCodexDir(), 'hooks.json'), + eventLabel: 'stop', + groupIndex, + handlerIndex: 0, + command: USER_HOOK_COMMAND + } +} + +function readSystemToml(): string { + const tomlPath = join(systemCodexDir(), 'config.toml') + return existsSync(tomlPath) ? readFileSync(tomlPath, 'utf-8') : '' +} + +describe('codex hook trust write-back promotion', () => { + it('keeps an in-Orca approval of a user hook across launches and promotes it to ~/.codex', () => { + writeSystemUserHook() + const service = new CodexHookService() + service.install() + + // The mirrored user hook has no system trust yet, so no runtime trust + // entry exists for it — Codex would show it as pending review. + const runtimeTomlPath = join(runtimeHomeDir(), 'config.toml') + const approvalKey = computeTrustKey(runtimeUserStopEntry()) + expect(readHookTrustEntries(runtimeTomlPath).get(approvalKey)).toBeUndefined() + + simulateCodexApproval(runtimeUserStopEntry()) + const approvedHash = computeTrustedHash(runtimeUserStopEntry()) + + service.install() + + // Approval survives the relaunch instead of being wiped as stale… + expect(readHookTrustEntries(runtimeTomlPath).get(approvalKey)?.trustedHash).toBe(approvedHash) + // …and is promoted into the user's real config keyed to their hooks.json. + const systemState = readHookTrustEntries(join(systemCodexDir(), 'config.toml')).get( + computeTrustKey(systemUserStopEntry()) + ) + expect(systemState?.trustedHash).toBe(approvedHash) + expect(systemState?.enabled).not.toBe(false) + + // Steady state: another launch with no external changes rewrites nothing. + const systemTomlAfterPromotion = readSystemToml() + const runtimeTomlAfterPromotion = readFileSync(runtimeTomlPath, 'utf-8') + service.install() + expect(readSystemToml()).toBe(systemTomlAfterPromotion) + expect(readFileSync(runtimeTomlPath, 'utf-8')).toBe(runtimeTomlAfterPromotion) + }) + + it('never promotes trust for the Orca-managed status hook into ~/.codex', () => { + writeSystemUserHook() + const service = new CodexHookService() + service.install() + + // Simulate Codex rewriting the managed Stop hook's trust entry (as an + // approval after hash drift would). + const runtimeHooksPath = join(runtimeHomeDir(), 'hooks.json') + const managedCommand = ( + JSON.parse(readFileSync(runtimeHooksPath, 'utf-8')) as { + hooks: { Stop: { hooks: { command: string }[] }[] } + } + ).hooks.Stop[0]!.hooks[0]!.command + simulateCodexApproval( + { + sourcePath: runtimeHooksPath, + eventLabel: 'stop', + groupIndex: 0, + handlerIndex: 0, + command: managedCommand + }, + { hash: 'sha256:codex-corrected-managed-hash' } + ) + + service.install() + + expect(readSystemToml()).not.toContain(managedCommand) + expect(readSystemToml()).not.toContain('codex-corrected-managed-hash') + }) + + it('does not resurrect trust the user revoked in ~/.codex/config.toml', () => { + writeSystemUserHook() + // Pre-trust the hook in the system config, as a terminal Codex session would. + const systemTomlPath = join(systemCodexDir(), 'config.toml') + writeFileSync(systemTomlPath, upsertHookTrustEntriesInContent('', [systemUserStopEntry()])) + + const service = new CodexHookService() + service.install() + + const runtimeTomlPath = join(runtimeHomeDir(), 'config.toml') + const approvalKey = computeTrustKey(runtimeUserStopEntry()) + expect(readHookTrustEntries(runtimeTomlPath).get(approvalKey)).toBeDefined() + + // User revokes in the system config; the runtime copy must not win. + writeFileSync(systemTomlPath, '') + service.install() + + expect(readHookTrustEntries(runtimeTomlPath).get(approvalKey)).toBeUndefined() + expect(readSystemToml()).not.toContain('[hooks.state.') + }) + + it('promotes an in-Orca disable of a mirrored user hook back to the system config', () => { + writeSystemUserHook() + const systemTomlPath = join(systemCodexDir(), 'config.toml') + writeFileSync(systemTomlPath, upsertHookTrustEntriesInContent('', [systemUserStopEntry()])) + + const service = new CodexHookService() + service.install() + + // User disables the hook via /hooks inside Orca-launched Codex. + const runtimeTomlPath = join(runtimeHomeDir(), 'config.toml') + const runtimeToml = readFileSync(runtimeTomlPath, 'utf-8') + const approvalKey = computeTrustKey(runtimeUserStopEntry()) + expect(readHookTrustEntries(runtimeTomlPath).get(approvalKey)?.enabled).not.toBe(false) + writeFileSync( + runtimeTomlPath, + upsertHookTrustEntriesInContent(runtimeToml, [{ ...runtimeUserStopEntry(), enabled: false }]) + ) + + service.install() + + const systemState = readHookTrustEntries(systemTomlPath).get( + computeTrustKey(systemUserStopEntry()) + ) + expect(systemState?.enabled).toBe(false) + // The mirrored runtime entry reflects the disable on the next launch too. + expect(readHookTrustEntries(runtimeTomlPath).get(approvalKey)?.enabled).toBe(false) + }) + + it('carries a Codex-written hash verbatim when it differs from the reproduced hash', () => { + // Simulates Codex changing its trust hash algorithm: the approval hash in + // the runtime config no longer matches computeTrustedHash's output. + writeSystemUserHook() + const service = new CodexHookService() + service.install() + + const driftedHash = 'sha256:codex-next-gen-hash-orca-cannot-reproduce' + simulateCodexApproval(runtimeUserStopEntry(), { hash: driftedHash }) + + service.install() + + const runtimeTomlPath = join(runtimeHomeDir(), 'config.toml') + const approvalKey = computeTrustKey(runtimeUserStopEntry()) + expect(readHookTrustEntries(runtimeTomlPath).get(approvalKey)?.trustedHash).toBe(driftedHash) + expect( + readHookTrustEntries(join(systemCodexDir(), 'config.toml')).get( + computeTrustKey(systemUserStopEntry()) + )?.trustedHash + ).toBe(driftedHash) + + // And the launch after that still keeps it. + service.install() + expect(readHookTrustEntries(runtimeTomlPath).get(approvalKey)?.trustedHash).toBe(driftedHash) + }) + + it('does not touch ~/.codex on the first launch after upgrading (no provenance yet)', () => { + // Simulates an existing install: runtime home fully materialized by a + // build without provenance snapshots, managed hooks only. + const service = new CodexHookService() + service.install() + rmSync(join(runtimeHomeDir(), '.orca-hook-trust-provenance.json'), { force: true }) + + service.install() + + expect(readSystemToml()).toBe('') + expect(existsSync(join(systemCodexDir(), 'config.toml'))).toBe(false) + }) + + it('re-promoting mirrored trust without provenance is a no-op on ~/.codex', () => { + // Existing install with a system-trusted user hook, upgraded to this + // build: the mirrored runtime entry has no provenance, so promotion must + // sit out this launch and leave the system config byte-identical. + writeSystemUserHook() + const systemTomlPath = join(systemCodexDir(), 'config.toml') + writeFileSync(systemTomlPath, upsertHookTrustEntriesInContent('', [systemUserStopEntry()])) + const service = new CodexHookService() + service.install() + rmSync(join(runtimeHomeDir(), '.orca-hook-trust-provenance.json'), { force: true }) + const systemTomlBefore = readSystemToml() + + service.install() + + expect(readSystemToml()).toBe(systemTomlBefore) + }) + + it('does not resurrect trust revoked in ~/.codex before the first provenance snapshot', () => { + // Old build mirrored a system-trusted hook into the runtime home; the + // user then revoked it in ~/.codex/config.toml and upgraded to this + // build. The stale runtime mirror must not be mistaken for an approval. + writeSystemUserHook() + const systemTomlPath = join(systemCodexDir(), 'config.toml') + writeFileSync(systemTomlPath, upsertHookTrustEntriesInContent('', [systemUserStopEntry()])) + const service = new CodexHookService() + service.install() + rmSync(join(runtimeHomeDir(), '.orca-hook-trust-provenance.json'), { force: true }) + writeFileSync(systemTomlPath, '') + + service.install() + + expect(readSystemToml()).not.toContain('[hooks.state.') + expect( + readHookTrustEntries(join(runtimeHomeDir(), 'config.toml')).get( + computeTrustKey(runtimeUserStopEntry()) + ) + ).toBeUndefined() + }) + + it('does not flip a hook the user disabled in ~/.codex back to enabled after upgrading', () => { + // Old build mirrored the hook enabled=true; the user then set + // enabled = false in ~/.codex/config.toml and upgraded to this build. + writeSystemUserHook() + const systemTomlPath = join(systemCodexDir(), 'config.toml') + writeFileSync(systemTomlPath, upsertHookTrustEntriesInContent('', [systemUserStopEntry()])) + const service = new CodexHookService() + service.install() + rmSync(join(runtimeHomeDir(), '.orca-hook-trust-provenance.json'), { force: true }) + writeFileSync( + systemTomlPath, + upsertHookTrustEntriesInContent('', [{ ...systemUserStopEntry(), enabled: false }]) + ) + + service.install() + + expect( + readHookTrustEntries(systemTomlPath).get(computeTrustKey(systemUserStopEntry()))?.enabled + ).toBe(false) + expect( + readHookTrustEntries(join(runtimeHomeDir(), 'config.toml')).get( + computeTrustKey(runtimeUserStopEntry()) + )?.enabled + ).toBe(false) + }) + + it('promotes one approval to every identical system hook collapsed by deduping', () => { + writeSystemUserHook([USER_HOOK_COMMAND, USER_HOOK_COMMAND]) + const service = new CodexHookService() + service.install() + + simulateCodexApproval(runtimeUserStopEntry()) + service.install() + + const systemTrust = readHookTrustEntries(join(systemCodexDir(), 'config.toml')) + const approvedHash = computeTrustedHash(runtimeUserStopEntry()) + expect(systemTrust.get(computeTrustKey(systemUserStopEntry(0)))?.trustedHash).toBe(approvedHash) + expect(systemTrust.get(computeTrustKey(systemUserStopEntry(1)))?.trustedHash).toBe(approvedHash) + }) + + it('skips promotion when the approved hook no longer exists in ~/.codex/hooks.json', () => { + writeSystemUserHook() + const service = new CodexHookService() + service.install() + + simulateCodexApproval(runtimeUserStopEntry()) + // User deletes the hook from their system hooks.json before relaunching. + writeFileSync(join(systemCodexDir(), 'hooks.json'), JSON.stringify({ hooks: {} })) + + service.install() + + expect(readSystemToml()).not.toContain('[hooks.state.') + // The runtime copy of the deleted hook (and its approval) is cleaned up. + const runtimeTomlPath = join(runtimeHomeDir(), 'config.toml') + expect( + readHookTrustEntries(runtimeTomlPath).get(computeTrustKey(runtimeUserStopEntry())) + ).toBeUndefined() + }) + + it('promotes approvals recorded while status hooks are disabled (refresh path)', () => { + writeSystemUserHook() + const service = new CodexHookService() + service.refreshRuntimeUserHooks() + + // Without the managed status hook, the mirrored user hook sits at group 0. + const refreshedRuntimeEntry: CodexTrustEntry = { + ...runtimeUserStopEntry(), + groupIndex: 0 + } + simulateCodexApproval(refreshedRuntimeEntry) + const approvedHash = computeTrustedHash(refreshedRuntimeEntry) + + service.refreshRuntimeUserHooks() + + expect( + readHookTrustEntries(join(systemCodexDir(), 'config.toml')).get( + computeTrustKey(systemUserStopEntry()) + )?.trustedHash + ).toBe(approvedHash) + expect( + readHookTrustEntries(join(runtimeHomeDir(), 'config.toml')).get( + computeTrustKey(refreshedRuntimeEntry) + )?.trustedHash + ).toBe(approvedHash) + }) +}) diff --git a/src/main/codex/hook-trust-promotion.ts b/src/main/codex/hook-trust-promotion.ts new file mode 100644 index 000000000000..36a570a662fe --- /dev/null +++ b/src/main/codex/hook-trust-promotion.ts @@ -0,0 +1,257 @@ +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { + createManagedCommandMatcher, + readHooksJson, + type HookDefinition +} from '../agent-hooks/installer-utils' +import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from './codex-home-paths' +import { + getCodexCanonicalTrustPath, + normalizeHookTrustKeyForLookup, + parseTrustKey, + readHookTrustEntries, + upsertHookTrustEntries, + type CodexTrustEntry +} from './config-toml-trust' +import { + CODEX_EVENT_NAME_BY_LABEL, + createCodexHookTrustEntry, + getCodexHookTrustSignature, + getCodexManagedScriptFileName +} from './codex-hook-identity' + +// Why: ~/.codex/config.toml is the single source of truth for user-hook +// trust, but the Codex TUI can only write approvals into the runtime +// CODEX_HOME it was launched with. Without promoting those approvals back, +// removeStaleRuntimeHookTrustEntries deletes them on the next launch and the +// user re-approves the same hooks forever. + +type HookTrustProvenanceEntry = { + trustedHash?: string + enabled?: boolean +} + +type HookTrustProvenanceFile = { + version: 1 + entries: Record +} + +function getProvenancePath(runtimeHomePath: string): string { + return join(runtimeHomePath, '.orca-hook-trust-provenance.json') +} + +function readHookTrustProvenance( + runtimeHomePath: string +): Map | null { + const provenancePath = getProvenancePath(runtimeHomePath) + if (!existsSync(provenancePath)) { + return null + } + try { + const parsed: unknown = JSON.parse(readFileSync(provenancePath, 'utf-8')) + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return null + } + const entries = (parsed as HookTrustProvenanceFile).entries + if (!entries || typeof entries !== 'object' || Array.isArray(entries)) { + return null + } + const result = new Map() + for (const [key, value] of Object.entries(entries)) { + if (value && typeof value === 'object' && !Array.isArray(value)) { + result.set(key, { + ...(typeof value.trustedHash === 'string' ? { trustedHash: value.trustedHash } : {}), + ...(typeof value.enabled === 'boolean' ? { enabled: value.enabled } : {}) + }) + } + } + return result + } catch { + return null + } +} + +/** + * Records the runtime config.toml trust state Orca leaves behind after an + * install/refresh, so the next launch can tell "entry Orca wrote" apart from + * "entry Codex wrote after a user approval". Call after all trust writes. + */ +export function snapshotCodexRuntimeHookTrustProvenance(): void { + try { + const runtimeHomePath = getOrcaManagedCodexHomePath() + const runtimeHooksPath = join(runtimeHomePath, 'hooks.json') + const canonicalRuntimeHooksPath = getCodexCanonicalTrustPath(runtimeHooksPath) + const entries: Record = {} + for (const [key, state] of readHookTrustEntries(join(runtimeHomePath, 'config.toml'))) { + const parsed = parseTrustKey(key) + if (!parsed || getCodexCanonicalTrustPath(parsed.sourcePath) !== canonicalRuntimeHooksPath) { + continue + } + entries[normalizeHookTrustKeyForLookup(key)] = { + ...(state.trustedHash !== undefined ? { trustedHash: state.trustedHash } : {}), + ...(state.enabled !== undefined ? { enabled: state.enabled } : {}) + } + } + const file: HookTrustProvenanceFile = { version: 1, entries } + writeFileSync(getProvenancePath(runtimeHomePath), `${JSON.stringify(file, null, 2)}\n`, { + encoding: 'utf-8', + mode: 0o600 + }) + } catch (error) { + // Best effort — a missing snapshot only means the next launch re-promotes + // entries that already match the system config, which upsert no-ops. + console.warn('[codex-hook-promotion] failed to snapshot hook trust provenance', error) + } +} + +/** + * Promotes hook approvals the user made inside Orca-launched Codex (written + * by Codex into the runtime config.toml) into ~/.codex/config.toml, keyed to + * the user's own hooks.json. Runs before the config mirror so the promoted + * trust is mirrored back on the same launch. + */ +export function promoteCodexRuntimeHookApprovalsToSystem(): void { + try { + promoteCodexRuntimeHookApprovalsToSystemUnsafe() + } catch (error) { + // Why: promotion is best-effort launch prep; a malformed runtime file + // must not block hook install or the Codex launch itself. + console.warn('[codex-hook-promotion] failed to promote runtime hook approvals', error) + } +} + +function promoteCodexRuntimeHookApprovalsToSystemUnsafe(): void { + const runtimeHomePath = getOrcaManagedCodexHomePath() + const systemHomePath = getSystemCodexHomePath() + const runtimeHooksPath = join(runtimeHomePath, 'hooks.json') + const systemHooksPath = join(systemHomePath, 'hooks.json') + const canonicalRuntimeHooksPath = getCodexCanonicalTrustPath(runtimeHooksPath) + if (canonicalRuntimeHooksPath === getCodexCanonicalTrustPath(systemHooksPath)) { + return + } + const runtimeTomlPath = join(runtimeHomePath, 'config.toml') + if (!existsSync(runtimeTomlPath)) { + return + } + // Why: without a snapshot of what Orca last wrote (first launch after + // upgrading to a build with promotion, or a corrupted snapshot), a mirrored + // copy of since-revoked system trust is indistinguishable from a genuine + // in-Orca approval. Promoting would resurrect trust the user revoked in + // ~/.codex, so skip this launch — install() writes the first snapshot and + // promotion starts on the next one. + const provenance = readHookTrustProvenance(runtimeHomePath) + if (!provenance) { + return + } + const runtimeTrust = readHookTrustEntries(runtimeTomlPath) + if (runtimeTrust.size === 0) { + return + } + // Why: promotion inspects the hooks.json layout Codex actually approved + // against — the one still on disk from the previous launch — so it must run + // before install() rewrites the runtime hooks.json. + const runtimeConfig = readHooksJson(runtimeHooksPath) + const systemConfig = readHooksJson(systemHooksPath) + if (!runtimeConfig?.hooks || !systemConfig?.hooks) { + return + } + const isManagedCommand = createManagedCommandMatcher(getCodexManagedScriptFileName()) + + const promotions: CodexTrustEntry[] = [] + for (const [key, state] of runtimeTrust) { + if (!state.trustedHash) { + continue + } + const parsed = parseTrustKey(key) + if (!parsed || getCodexCanonicalTrustPath(parsed.sourcePath) !== canonicalRuntimeHooksPath) { + continue + } + const previous = provenance.get(normalizeHookTrustKeyForLookup(key)) + if ( + previous && + previous.trustedHash === state.trustedHash && + (previous.enabled ?? true) === (state.enabled ?? true) + ) { + // Orca wrote this entry and nothing touched it since — not an approval. + continue + } + const eventName = CODEX_EVENT_NAME_BY_LABEL[parsed.eventLabel] + const runtimeDefinitions = runtimeConfig.hooks[eventName] + const definition = Array.isArray(runtimeDefinitions) + ? runtimeDefinitions[parsed.groupIndex] + : undefined + const hook = Array.isArray(definition?.hooks) + ? definition.hooks[parsed.handlerIndex] + : undefined + // Why: never write trust for Orca's managed status hook into the user's + // real config — mutating ~/.codex for Orca's own hooks is exactly what the + // runtime CODEX_HOME isolation exists to prevent. + if (!definition || !hook?.command || isManagedCommand(hook.command)) { + continue + } + const runtimeEntry = createCodexHookTrustEntry( + runtimeHooksPath, + eventName, + parsed.groupIndex, + parsed.handlerIndex, + definition, + hook + ) + if (!runtimeEntry) { + continue + } + collectSystemPromotionTargets( + promotions, + systemHooksPath, + systemConfig.hooks, + eventName, + getCodexHookTrustSignature(runtimeEntry), + isManagedCommand, + state.trustedHash, + state.enabled ?? true + ) + } + if (promotions.length > 0) { + upsertHookTrustEntries(join(systemHomePath, 'config.toml'), promotions) + } +} + +// Why: the runtime layout differs from the system one (managed hook +// prepended, duplicates collapsed), so approvals map back by hook content — +// and one runtime hook can map to several identical system entries. +function collectSystemPromotionTargets( + promotions: CodexTrustEntry[], + systemHooksPath: string, + systemHooks: Record, + eventName: string, + signature: string, + isManagedCommand: (command: string | undefined) => boolean, + trustedHash: string, + enabled: boolean +): void { + const systemDefinitions = systemHooks[eventName] + if (!Array.isArray(systemDefinitions)) { + return + } + systemDefinitions.forEach((systemDefinition, groupIndex) => { + const hooks = Array.isArray(systemDefinition.hooks) ? systemDefinition.hooks : [] + hooks.forEach((systemHook, handlerIndex) => { + if (isManagedCommand(systemHook.command)) { + return + } + const systemEntry = createCodexHookTrustEntry( + systemHooksPath, + eventName, + groupIndex, + handlerIndex, + systemDefinition, + systemHook + ) + if (!systemEntry || getCodexHookTrustSignature(systemEntry) !== signature) { + return + } + promotions.push({ ...systemEntry, trustedHash, enabled }) + }) + }) +} diff --git a/src/main/daemon/daemon-background-transient-facts.test.ts b/src/main/daemon/daemon-background-transient-facts.test.ts new file mode 100644 index 000000000000..acfcdb959f4e --- /dev/null +++ b/src/main/daemon/daemon-background-transient-facts.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from 'vitest' +import { BackgroundTransientFactRelay } from './daemon-background-transient-facts' +import type { DaemonTransientFact } from './types' + +function createRelay() { + const emitted: { sessionId: string; fact: DaemonTransientFact }[] = [] + const relay = new BackgroundTransientFactRelay((sessionId, fact) => + emitted.push({ sessionId, fact }) + ) + return { relay, emitted } +} + +describe('BackgroundTransientFactRelay', () => { + it('emits a bell fact for a backgrounded session', () => { + const { relay, emitted } = createRelay() + relay.setSessionBackground('s1', true) + relay.onSessionData('s1', 'build output\x07more') + expect(emitted).toEqual([{ sessionId: 's1', fact: { kind: 'bell' } }]) + }) + + it('keeps OSC escape state across chunks — a title terminator BEL is not a bell', () => { + const { relay, emitted } = createRelay() + relay.setSessionBackground('s1', true) + relay.onSessionData('s1', '\x1b]0;my working title') + relay.onSessionData('s1', ' continued\x07') + expect(emitted).toEqual([]) + }) + + it('emits nothing for sessions that are not backgrounded', () => { + const { relay, emitted } = createRelay() + relay.onSessionData('s1', 'ding\x07') + expect(emitted).toEqual([]) + }) + + it('emits command-finished with the OSC 133;D exit code', () => { + const { relay, emitted } = createRelay() + relay.setSessionBackground('s1', true) + relay.onSessionData('s1', '\x1b]133;D;0\x07') + expect(emitted).toEqual([{ sessionId: 's1', fact: { kind: 'command-finished', exitCode: 0 } }]) + }) + + it('stops emitting after un-background and reports the toggle as a state change', () => { + const { relay, emitted } = createRelay() + expect(relay.setSessionBackground('s1', true)).toBe(true) + expect(relay.setSessionBackground('s1', true)).toBe(false) + expect(relay.setSessionBackground('s1', false)).toBe(true) + expect(relay.setSessionBackground('s1', false)).toBe(false) + relay.onSessionData('s1', 'ding\x07') + expect(emitted).toEqual([]) + }) + + it('drops the tracker on session exit', () => { + const { relay, emitted } = createRelay() + relay.setSessionBackground('s1', true) + relay.onSessionExit('s1') + expect(relay.isBackgrounded('s1')).toBe(false) + relay.onSessionData('s1', 'ding\x07') + expect(emitted).toEqual([]) + }) + + it('never arms the stale-working-title timer (titles are main-authoritative)', () => { + vi.useFakeTimers() + try { + const { relay, emitted } = createRelay() + relay.setSessionBackground('s1', true) + // A working-spinner title followed by title-less output would arm the + // 3s stale timer if titles were being tracked. + relay.onSessionData('s1', '\x1b]0;⠋ Claude\x07') + relay.onSessionData('s1', 'output without titles') + expect(vi.getTimerCount()).toBe(0) + expect(emitted).toEqual([]) + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/main/daemon/daemon-background-transient-facts.ts b/src/main/daemon/daemon-background-transient-facts.ts new file mode 100644 index 000000000000..3867ab0eddd7 --- /dev/null +++ b/src/main/daemon/daemon-background-transient-facts.ts @@ -0,0 +1,106 @@ +/** + * Daemon-side transient-fact scanning for backgrounded sessions. + * + * While a session is backgrounded (its pane hidden in the renderer), the + * daemon→main stream copy may be keep-tail thinned under backlog — but the + * notification-bearing facts inside those bytes must never be lost. This + * relay runs the SAME shared scanners main uses (terminal-side-effect + * authority doc: semantics must not drift) over every raw chunk BEFORE any + * drop decision, and emits compact transientFact stream events in byte order. + * Main suppresses its own copies of these four scanners between the + * sessionBackgroundMarker handoffs, so no fact double-fires or goes missing. + * + * Title/agent-status facts are deliberately NOT relayed: they converge from + * the delivered kept tail (stale-working-title timer, snapshot-restores-title + * -state) and main fuses them with synthetic spinner frames the daemon never + * sees. + */ +import { + createTerminalTitleTracker, + type TerminalTitleTracker +} from '../../shared/terminal-output-side-effects' +import type { DaemonTransientFact } from './types' + +// Kill switch for the whole background keep-tail mechanism (thinning + +// daemon-side fact authority): ORCA_DAEMON_BACKGROUND_STREAM_DROP=0. +export const BACKGROUND_STREAM_DROP_ENABLED = process.env.ORCA_DAEMON_BACKGROUND_STREAM_DROP !== '0' + +export class BackgroundTransientFactRelay { + private trackersBySessionId = new Map() + private emitFact: (sessionId: string, fact: DaemonTransientFact) => void + + constructor(emitFact: (sessionId: string, fact: DaemonTransientFact) => void) { + this.emitFact = emitFact + } + + isBackgrounded(sessionId: string): boolean { + return this.trackersBySessionId.has(sessionId) + } + + backgroundedSessionIdSuffixes(): string[] { + return Array.from(this.trackersBySessionId.keys(), (id) => id.slice(-10)) + } + + /** Returns false when this was a no-op (already in the requested state) so + * the caller can skip a duplicate handoff marker — resyncs after adoption + * re-send the whole background set. */ + setSessionBackground(sessionId: string, background: boolean): boolean { + if (background === this.isBackgrounded(sessionId)) { + return false + } + if (background) { + this.trackersBySessionId.set( + sessionId, + createTerminalTitleTracker({ + onBell: () => this.emitFact(sessionId, { kind: 'bell' }), + onCommandFinished: (exitCode) => + this.emitFact(sessionId, { kind: 'command-finished', exitCode }), + // Note: recreating the tracker on each background toggle resets the + // PR-link dedup memory, so a link re-printed across toggles can + // re-fire — consumers treat pr-link as a latest-association update. + onPrLink: (link) => this.emitFact(sessionId, { kind: 'pr-link', link }), + onMode2031Subscribe: () => this.emitFact(sessionId, { kind: '2031-subscribe' }) + }) + ) + } else { + this.disposeTracker(sessionId) + } + return true + } + + /** Prime a fresh tracker's cross-chunk carry with the emulator's dangling + * incomplete escape at handoff time, so a sequence split across the + * background toggle neither mints a phantom bell nor loses its fact. A + * partial tail contains no complete sequence, so this can never fire. */ + seedSessionScanState(sessionId: string, partialEscapeTailAnsi: string): void { + if (partialEscapeTailAnsi.length > 0) { + this.trackersBySessionId + .get(sessionId) + ?.handleChunk(partialEscapeTailAnsi, { titleScanData: '' }) + } + } + + /** Feed one raw chunk, in byte order, BEFORE it is enqueued for delivery — + * facts must be captured even when the chunk is later keep-tail dropped. */ + onSessionData(sessionId: string, data: string): void { + // titleScanData:'' skips title extraction (titles stay main-authoritative) + // and keeps the stale-working-title timer permanently unarmed — only the + // four transient scanners consume the chunk. + this.trackersBySessionId.get(sessionId)?.handleChunk(data, { titleScanData: '' }) + } + + onSessionExit(sessionId: string): void { + this.disposeTracker(sessionId) + } + + dispose(): void { + for (const sessionId of Array.from(this.trackersBySessionId.keys())) { + this.disposeTracker(sessionId) + } + } + + private disposeTracker(sessionId: string): void { + this.trackersBySessionId.get(sessionId)?.dispose() + this.trackersBySessionId.delete(sessionId) + } +} diff --git a/src/main/daemon/daemon-entry.test.ts b/src/main/daemon/daemon-entry.test.ts index f2ac7a7ade58..e24f1c8b3fe9 100644 --- a/src/main/daemon/daemon-entry.test.ts +++ b/src/main/daemon/daemon-entry.test.ts @@ -29,4 +29,29 @@ describe('daemon-entry parseArgs', () => { it('throws with no args', () => { expect(() => parseArgs([])).toThrow('Usage:') }) + + it('omits logFilePath when --log-file is absent (adopted old daemons)', () => { + const result = parseArgs(['--socket', '/tmp/t.sock', '--token', '/tmp/t.token']) + expect(result).not.toHaveProperty('logFilePath') + }) + + it('parses --log-file when present', () => { + const result = parseArgs([ + '--socket', + '/tmp/t.sock', + '--token', + '/tmp/t.token', + '--log-file', + '/tmp/daemon.log' + ]) + expect(result).toEqual({ + socketPath: '/tmp/t.sock', + tokenPath: '/tmp/t.token', + logFilePath: '/tmp/daemon.log' + }) + }) + + it('still requires --socket and --token when --log-file is given', () => { + expect(() => parseArgs(['--log-file', '/tmp/daemon.log'])).toThrow('Usage:') + }) }) diff --git a/src/main/daemon/daemon-entry.ts b/src/main/daemon/daemon-entry.ts index aeffb7aa2a57..34c040439508 100644 --- a/src/main/daemon/daemon-entry.ts +++ b/src/main/daemon/daemon-entry.ts @@ -10,10 +10,20 @@ import { startDaemon, type DaemonHandle } from './daemon-main' import { createPtySubprocess } from './pty-subprocess' import { warmWindowsConptyOnce } from './windows-conpty-warmup' import { warmPwshAvailabilityCache } from '../pwsh' +import { createDaemonFileLog, createNoopDaemonFileLog } from './daemon-file-log' +import { PROTOCOL_VERSION } from './types' -export function parseArgs(argv: string[]): { socketPath: string; tokenPath: string } { +export type ParsedDaemonArgs = { + socketPath: string + tokenPath: string + /** Optional — absent for adopted old daemons and tests, which log nothing. */ + logFilePath?: string +} + +export function parseArgs(argv: string[]): ParsedDaemonArgs { let socketPath = '' let tokenPath = '' + let logFilePath = '' for (let i = 0; i < argv.length; i++) { if (argv[i] === '--socket' && argv[i + 1]) { @@ -22,18 +32,31 @@ export function parseArgs(argv: string[]): { socketPath: string; tokenPath: stri } else if (argv[i] === '--token' && argv[i + 1]) { tokenPath = argv[i + 1] i++ + } else if (argv[i] === '--log-file' && argv[i + 1]) { + logFilePath = argv[i + 1] + i++ } } if (!socketPath || !tokenPath) { - throw new Error('Usage: daemon-entry --socket --token ') + throw new Error('Usage: daemon-entry --socket --token [--log-file ]') } - return { socketPath, tokenPath } + return logFilePath ? { socketPath, tokenPath, logFilePath } : { socketPath, tokenPath } } async function main(): Promise { - const { socketPath, tokenPath } = parseArgs(process.argv.slice(2)) + // Why: the parent captures daemon startup stderr then destroys its end of the + // pipe once the daemon is ready. A later write here (e.g. the uncaughtException + // console.error below) would then hit a broken pipe and emit 'error' on + // process.stderr — with no listener that becomes an unhandled error that kills + // an otherwise healthy detached daemon. Swallow it: stderr is diagnostic only. + process.stderr.on('error', () => {}) + + const { socketPath, tokenPath, logFilePath } = parseArgs(process.argv.slice(2)) + // Fail-open: a broken log path must never block daemon startup. + const daemonLog = logFilePath ? createDaemonFileLog(logFilePath) : createNoopDaemonFileLog() + daemonLog.log('startup', { protocolVersion: PROTOCOL_VERSION, socketPath }) void warmPwshAvailabilityCache() // Why: node-pty can throw a C++ Napi::Error that escapes all JS try/catch @@ -55,36 +78,64 @@ async function main(): Promise { msg.includes('EBADF') || msg.includes('ENXIO')) if (isNativeError) { + daemonLog.log('uncaught-exception-suppressed', { name: err?.name, message: msg }) console.error('[daemon] Native PTY exception (suppressed):', err) return } + daemonLog.log('uncaught-exception-fatal', { name: err?.name, message: msg }) console.error('[daemon] Uncaught exception (fatal):', err) throw err }) let daemon: DaemonHandle | null = null + let shuttingDown = false + // Bound the wait so a wedged native shutdown can't leave the daemon running + // forever on SIGTERM/SIGINT (it would then survive a real quit, not just updates). + const SHUTDOWN_TIMEOUT_MS = 5000 - const shutdown = async (): Promise => { - if (daemon) { - await daemon.shutdown() - daemon = null + const shutdown = async (reason: string): Promise => { + // SIGTERM and SIGINT can both fire; guard against a double daemon.shutdown(). + if (shuttingDown) { + return + } + shuttingDown = true + daemonLog.log('shutdown', { reason }) + try { + if (daemon) { + await Promise.race([ + daemon.shutdown(), + new Promise((_, reject) => + setTimeout(() => reject(new Error('shutdown timeout')), SHUTDOWN_TIMEOUT_MS) + ) + ]) + daemon = null + } + } catch (err) { + // Never let a rejected shutdown() escape as an unhandled rejection and skip exit. + daemonLog.log('shutdown-error', { message: (err as Error)?.message }) + } finally { + daemonLog.close() + process.exit(0) } - process.exit(0) } - process.on('SIGTERM', () => void shutdown()) - process.on('SIGINT', () => void shutdown()) + process.on('SIGTERM', () => void shutdown('SIGTERM')) + process.on('SIGINT', () => void shutdown('SIGINT')) daemon = await startDaemon({ socketPath, tokenPath, + log: daemonLog, spawnSubprocess: (opts) => createPtySubprocess(opts) }) // Signal readiness to parent via IPC (if available) if (process.send) { - process.send({ type: 'ready' }) + // Why: Windows has no cheap OS query for a child's start time, so the + // daemon self-reports it here for the pid file's pid-recycling guard. + process.send({ type: 'ready', startedAtMs: Date.now() - process.uptime() * 1000 }) } + daemonLog.log('ready') warmWindowsConptyOnce() } diff --git a/src/main/daemon/daemon-errors.ts b/src/main/daemon/daemon-errors.ts new file mode 100644 index 000000000000..8077add319af --- /dev/null +++ b/src/main/daemon/daemon-errors.ts @@ -0,0 +1,22 @@ +// Error classes shared across the daemon protocol boundary (client, server, +// host). Split from types.ts, which is capped for wire-shape declarations. +export class TerminalAttachCanceledError extends Error { + constructor(sessionId: string) { + super(`Attach canceled for session ${sessionId}`) + this.name = 'TerminalAttachCanceledError' + } +} + +export class DaemonProtocolError extends Error { + constructor(message: string) { + super(message) + this.name = 'DaemonProtocolError' + } +} + +export class SessionNotFoundError extends Error { + constructor(sessionId: string) { + super(`Session not found: ${sessionId}`) + this.name = 'SessionNotFoundError' + } +} diff --git a/src/main/daemon/daemon-file-log.test.ts b/src/main/daemon/daemon-file-log.test.ts new file mode 100644 index 000000000000..90677b9dab83 --- /dev/null +++ b/src/main/daemon/daemon-file-log.test.ts @@ -0,0 +1,100 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createDaemonFileLog, createNoopDaemonFileLog } from './daemon-file-log' + +let dir: string + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'daemon-file-log-')) +}) +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +function readLines(filePath: string): Record[] { + return readFileSync(filePath, 'utf8') + .split('\n') + .filter((l) => l.length > 0) + .map((l) => JSON.parse(l) as Record) +} + +describe('createDaemonFileLog', () => { + it('appends NDJSON lines with src/ts/pid/event and terse details', () => { + const filePath = join(dir, 'daemon.log') + const log = createDaemonFileLog(filePath) + log.log('startup', { protocolVersion: 18 }) + log.log('session-created', { sessionId: 'abc', pid: 42 }) + + const lines = readLines(filePath) + expect(lines).toHaveLength(2) + expect(lines[0]).toMatchObject({ src: 'daemon', event: 'startup', protocolVersion: 18 }) + expect(typeof lines[0].ts).toBe('string') + expect(lines[0].pid).toBe(process.pid) + expect(lines[1]).toMatchObject({ event: 'session-created', sessionId: 'abc', pid: 42 }) + }) + + it('rotates at the byte cap and keeps only the configured rotated files', () => { + const filePath = join(dir, 'daemon.log') + const log = createDaemonFileLog(filePath, { maxBytes: 150, maxRotatedFiles: 2 }) + for (let i = 0; i < 40; i++) { + log.log('tick', { i }) + } + + expect(existsSync(filePath)).toBe(true) + expect(existsSync(`${filePath}.1`)).toBe(true) + expect(existsSync(`${filePath}.2`)).toBe(true) + // Only 2 rotated files are retained — the oldest is dropped, not kept. + expect(existsSync(`${filePath}.3`)).toBe(false) + + // The active file holds the most recent line. + const active = readLines(filePath) + expect(active.at(-1)).toMatchObject({ event: 'tick', i: 39 }) + }) + + it('is fail-open when the log directory cannot be created', () => { + // Make the parent a file so mkdir of the logs subdir fails (ENOTDIR). + const blocker = join(dir, 'blocker') + writeFileSync(blocker, 'x') + const filePath = join(blocker, 'logs', 'daemon.log') + + const log = createDaemonFileLog(filePath) + expect(() => log.log('startup')).not.toThrow() + expect(() => log.close()).not.toThrow() + expect(existsSync(filePath)).toBe(false) + }) + + it('never throws from log() even for non-serializable details', () => { + const filePath = join(dir, 'daemon.log') + const log = createDaemonFileLog(filePath) + const circular: Record = {} + circular.self = circular + expect(() => log.log('weird', circular)).not.toThrow() + // The bad line is dropped; a later good line still lands. + log.log('ok') + const lines = readLines(filePath) + expect(lines.map((l) => l.event)).toEqual(['ok']) + }) + + it('close() writes a terminal marker and stops further writes', () => { + const filePath = join(dir, 'daemon.log') + const log = createDaemonFileLog(filePath) + log.log('startup') + log.close() + log.log('after-close') + + const events = readLines(filePath).map((l) => l.event) + expect(events).toEqual(['startup', 'daemon-log-closed']) + }) +}) + +describe('createNoopDaemonFileLog', () => { + it('accepts log/close calls without touching the filesystem', () => { + const log = createNoopDaemonFileLog() + expect(() => { + log.log('startup', { x: 1 }) + log.close() + }).not.toThrow() + }) +}) diff --git a/src/main/daemon/daemon-file-log.ts b/src/main/daemon/daemon-file-log.ts new file mode 100644 index 000000000000..01090aedf9e6 --- /dev/null +++ b/src/main/daemon/daemon-file-log.ts @@ -0,0 +1,137 @@ +// Append-only NDJSON logger for the detached daemon process. The daemon runs +// out-of-process with stdio 'ignore', so console output goes nowhere; this +// writes lifecycle events to a rotated file under the app's logs directory so +// they land in diagnostic bundles (windows-terminal-update-survival-plan.md +// §Phase 0). Never log terminal input/output content or tokens. +// +// Two hard constraints: +// 1. FAIL-OPEN. Any error (EACCES, ENOSPC, bad path) disables logging and is +// swallowed — logging must never throw into daemon lifecycle logic or +// affect startup/shutdown. +// 2. Best-effort durability. Each line is a single synchronous appendFileSync +// so a process death mid-write can lose at most the last (partial) line; +// NDJSON readers skip a truncated trailing line. + +import { appendFileSync, existsSync, mkdirSync, renameSync, statSync, unlinkSync } from 'node:fs' +import { dirname } from 'node:path' + +const DEFAULT_MAX_BYTES = 5 * 1024 * 1024 // 5 MB +const DEFAULT_MAX_ROTATED_FILES = 2 // daemon.log + daemon.log.1 + daemon.log.2 +const PRIVATE_FILE_MODE = 0o600 + +/** Total files in the rotated daemon-log family (active + rotated). The bundle + * collector passes this to `listRotatedFiles` so it reads every rotated file. */ +export const DAEMON_LOG_MAX_FILES = DEFAULT_MAX_ROTATED_FILES + 1 + +export type DaemonFileLog = { + /** Append one lifecycle event. Terse fields only — never user data. */ + log(event: string, details?: Record): void + /** Best-effort marker that no further writes are expected. */ + close(): void +} + +export type DaemonFileLogOptions = { + readonly maxBytes?: number + readonly maxRotatedFiles?: number +} + +/** No-op logger used when the daemon was launched without `--log-file` (adopted + * old daemons, tests). Keeps every call site unconditional. */ +export function createNoopDaemonFileLog(): DaemonFileLog { + return { + log() {}, + close() {} + } +} + +export function createDaemonFileLog( + filePath: string, + opts: DaemonFileLogOptions = {} +): DaemonFileLog { + const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES + const maxRotatedFiles = opts.maxRotatedFiles ?? DEFAULT_MAX_ROTATED_FILES + + let disabled = false + let currentBytes = 0 + + function disable(): void { + disabled = true + } + + try { + mkdirSync(dirname(filePath), { recursive: true }) + currentBytes = existsSync(filePath) ? statSync(filePath).size : 0 + } catch { + // Unwritable path — stay fail-open; the first log() no-ops via `disabled`. + disable() + } + + // Cascade rename base → .1 → .2, dropping the oldest, then reset the active + // file. Any failure disables logging rather than risking a partial-rotation + // loop that keeps throwing on every subsequent line. + function rotate(): void { + // With no rotated slots there is nothing to cascade; return without the + // `currentBytes = 0` reset below, which would otherwise falsely report the + // still-growing active file as empty and defeat the overflow check forever. + if (maxRotatedFiles < 1) { + return + } + try { + for (let i = maxRotatedFiles; i >= 1; i--) { + const src = i === 1 ? filePath : `${filePath}.${i - 1}` + const dst = `${filePath}.${i}` + if (!existsSync(src)) { + continue + } + if (existsSync(dst)) { + unlinkSync(dst) + } + renameSync(src, dst) + } + currentBytes = 0 + } catch { + disable() + } + } + + function log(event: string, details: Record = {}): void { + if (disabled) { + return + } + let line: string + try { + line = `${JSON.stringify({ + src: 'daemon', + ts: new Date().toISOString(), + pid: process.pid, + event, + ...details + })}\n` + } catch { + // Non-serializable detail (circular ref) — drop the line, never crash. + return + } + const lineBytes = Buffer.byteLength(line, 'utf8') + if (currentBytes > 0 && currentBytes + lineBytes > maxBytes) { + rotate() + if (disabled) { + return + } + } + try { + appendFileSync(filePath, line, { mode: PRIVATE_FILE_MODE }) + currentBytes += lineBytes + } catch { + disable() + } + } + + return { + log, + close(): void { + // Best-effort marker; append is synchronous so there is nothing to flush. + log('daemon-log-closed') + disabled = true + } + } +} diff --git a/src/main/daemon/daemon-foreground-confirmation-protocol.test.ts b/src/main/daemon/daemon-foreground-confirmation-protocol.test.ts new file mode 100644 index 000000000000..4fbb3047d6ab --- /dev/null +++ b/src/main/daemon/daemon-foreground-confirmation-protocol.test.ts @@ -0,0 +1,9 @@ +import { describe, expect, it } from 'vitest' +import { PREVIOUS_DAEMON_PROTOCOL_VERSIONS, PROTOCOL_VERSION } from './types' + +describe('foreground-confirmation daemon protocol', () => { + it('rejects daemons from before the fresh-confirmation RPC', () => { + expect(PROTOCOL_VERSION).toBeGreaterThan(19) + expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(19) + }) +}) diff --git a/src/main/daemon/daemon-foreground-process-protocol.ts b/src/main/daemon/daemon-foreground-process-protocol.ts new file mode 100644 index 000000000000..01b050c58d32 --- /dev/null +++ b/src/main/daemon/daemon-foreground-process-protocol.ts @@ -0,0 +1,11 @@ +export type GetForegroundProcessRequest = { + id: string + type: 'getForegroundProcess' + payload: { + sessionId: string + } +} + +export type ConfirmForegroundProcessRequest = Omit & { + type: 'confirmForegroundProcess' +} diff --git a/src/main/daemon/daemon-health.test.ts b/src/main/daemon/daemon-health.test.ts index 94d0564d09b7..defbc8fd09a3 100644 --- a/src/main/daemon/daemon-health.test.ts +++ b/src/main/daemon/daemon-health.test.ts @@ -13,7 +13,9 @@ import { parseLinuxBootTimeSeconds, parseLinuxProcStartTicks, parseDaemonPidFile, - startTimeMatches + parseWindowsProcessIdentityJson, + startTimeMatches, + startTimesWithinTolerance } from './daemon-health' import type { SubprocessHandle } from './session' @@ -125,6 +127,26 @@ describe('daemon health', () => { await expect(healthCheckDaemon(socketPath, tokenPath)).resolves.toBe(false) }) + it('classifies a hello-rejected daemon as rejected, not unreachable', async () => { + // Why: 'rejected' means the daemon answered and refused adoption — the + // launcher may replace it. 'unreachable' also covers a wedged-but-live + // daemon, which must never be replaced while its pipe accepts connections. + const server = new DaemonServer({ + socketPath, + tokenPath, + spawnSubprocess: () => createMockSubprocess() + }) + await server.start() + + try { + writeFileSync(tokenPath, 'not-the-daemon-token', { mode: 0o600 }) + await expect(checkDaemonHealth(socketPath, tokenPath)).resolves.toBe('rejected') + await expect(healthCheckDaemon(socketPath, tokenPath)).resolves.toBe(false) + } finally { + await server.shutdown() + } + }) + it('does not unlink a live socket when the pid file does not match this daemon', async () => { if (process.platform === 'win32') { return @@ -286,6 +308,42 @@ describe('startTimeMatches', () => { }) }) +describe('parseWindowsProcessIdentityJson', () => { + it('parses command line and start time from the CIM query output', () => { + expect( + parseWindowsProcessIdentityJson( + '{"cmd":"Orca.exe daemon-entry.js","start":1700000000000}\r\n' + ) + ).toEqual({ commandLine: 'Orca.exe daemon-entry.js', startedAtMs: 1_700_000_000_000 }) + }) + + it('returns a null start time when CreationDate was unavailable', () => { + expect( + parseWindowsProcessIdentityJson('{"cmd":"Orca.exe daemon-entry.js","start":null}') + ).toEqual({ commandLine: 'Orca.exe daemon-entry.js', startedAtMs: null }) + }) + + it('returns null for a missing process or inaccessible command line', () => { + expect(parseWindowsProcessIdentityJson('')).toBeNull() + expect(parseWindowsProcessIdentityJson(' \r\n')).toBeNull() + expect(parseWindowsProcessIdentityJson('{"cmd":null,"start":123}')).toBeNull() + expect(parseWindowsProcessIdentityJson('not-json')).toBeNull() + }) +}) + +describe('startTimesWithinTolerance', () => { + it('fails open when either side is null', () => { + expect(startTimesWithinTolerance(null, 1_700_000_000_000, 1_500)).toBe(true) + expect(startTimesWithinTolerance(1_700_000_000_000, null, 1_500)).toBe(true) + expect(startTimesWithinTolerance(null, null, 1_500)).toBe(true) + }) + + it('matches within tolerance and rejects outside it', () => { + expect(startTimesWithinTolerance(1_700_000_001_000, 1_700_000_000_000, 1_500)).toBe(true) + expect(startTimesWithinTolerance(1_700_000_005_000, 1_700_000_000_000, 1_500)).toBe(false) + }) +}) + describe('killStaleDaemon pid identity guards', () => { let dir: string let socketPath: string diff --git a/src/main/daemon/daemon-health.ts b/src/main/daemon/daemon-health.ts index 96d4a885dea8..50e7226f73c1 100644 --- a/src/main/daemon/daemon-health.ts +++ b/src/main/daemon/daemon-health.ts @@ -24,8 +24,17 @@ const RESOLVER_HEALTH_CHECK_TIMEOUT_MS = 3_000 const KILL_WAIT_MS = 3_000 const KILL_POLL_MS = 100 const START_TIME_TOLERANCE_MS = 1_500 - -export type DaemonHealth = 'healthy' | 'unreachable' | 'pty-spawn-unhealthy' +// Why: on Windows the pid file's startedAtMs is the daemon's self-reported +// Node start time, while verification reads the OS process creation time — +// the gap between them is the exe bootstrap, which AV/disk pressure can +// stretch to seconds. Pid recycling differs by minutes-to-days, so a wide +// tolerance keeps the guard effective without false mismatches. +const WIN32_START_TIME_TOLERANCE_MS = 10_000 + +// 'rejected' means the daemon answered and refused the handshake (bad token, +// foreign protocol) — it can never be adopted, unlike 'unreachable', which +// also covers a live-but-wedged daemon that simply missed the RPC budget. +export type DaemonHealth = 'healthy' | 'unreachable' | 'rejected' | 'pty-spawn-unhealthy' type ParsedDaemonPid = { pid: number @@ -134,13 +143,13 @@ export function checkDaemonHealth(socketPath: string, tokenPath: string): Promis try { message = JSON.parse(line) as Record } catch { - settle('unreachable') + settle('rejected') return } if (message.type === 'hello') { if (!(message as HelloResponse).ok) { - settle('unreachable') + settle('rejected') return } // Why: a protocol-live daemon with a stale cwd or node-pty helper @@ -371,6 +380,10 @@ export function getProcessStartedAtMs(pid: number): number | null { } if (process.platform === 'win32') { + // Why: the only OS source is a CIM query costing a powershell spawn — + // too slow for this sync path. Windows pid files instead carry the + // daemon's self-reported start time from its ready message, and + // isDaemonProcess verifies it against CIM CreationDate asynchronously. return null } @@ -387,27 +400,61 @@ export function getProcessStartedAtMs(pid: number): number | null { } export function startTimeMatches(pid: number, expectedStartedAtMs: number | null): boolean { - if (expectedStartedAtMs === null) { - return true - } + return startTimesWithinTolerance( + getProcessStartedAtMs(pid), + expectedStartedAtMs, + START_TIME_TOLERANCE_MS + ) +} - const actualStartedAtMs = getProcessStartedAtMs(pid) - if (actualStartedAtMs === null) { +// Why: fail open on null — a pid file or OS query without a start time must +// not veto an otherwise-matching daemon (adoption safety beats recycle safety). +export function startTimesWithinTolerance( + actualStartedAtMs: number | null, + expectedStartedAtMs: number | null, + toleranceMs: number +): boolean { + if (expectedStartedAtMs === null || actualStartedAtMs === null) { return true } - - return Math.abs(actualStartedAtMs - expectedStartedAtMs) <= START_TIME_TOLERANCE_MS + return Math.abs(actualStartedAtMs - expectedStartedAtMs) <= toleranceMs } const execFileAsync = promisify(execFile) +export type WindowsProcessIdentity = { + commandLine: string + startedAtMs: number | null +} + +export function parseWindowsProcessIdentityJson(stdout: string): WindowsProcessIdentity | null { + const trimmed = stdout.trim() + if (!trimmed) { + return null + } + try { + const parsed = JSON.parse(trimmed) as { cmd?: unknown; start?: unknown } + if (typeof parsed.cmd !== 'string' || !parsed.cmd) { + return null + } + return { + commandLine: parsed.cmd, + startedAtMs: + typeof parsed.start === 'number' && Number.isFinite(parsed.start) ? parsed.start : null + } + } catch { + return null + } +} + // Why: the only reliable command-line source on Windows is a CIM query, which // costs a full powershell.exe spawn (300-800ms cold, worse under Defender). // Async because the sync version measurably froze the Electron main thread at // startup for the whole spawn (benchmark: ~0.5s warm, 3s timeout cap cold). -// Timed under ORCA_STARTUP_DIAGNOSTICS so the cold-start benchmark can -// attribute startup cost to these checks. -async function queryWindowsProcessCommandLine(pid: number): Promise { +// CreationDate rides along in the same spawn so start-time verification adds +// zero extra process launches. Timed under ORCA_STARTUP_DIAGNOSTICS so the +// cold-start benchmark can attribute startup cost to these checks. +async function queryWindowsProcessIdentity(pid: number): Promise { const startedAt = performance.now() try { const { stdout } = await execFileAsync( @@ -416,14 +463,17 @@ async function queryWindowsProcessCommandLine(pid: number): Promise { if (process.platform === 'win32') { - return queryWindowsProcessCommandLine(pid) + return (await queryWindowsProcessIdentity(pid))?.commandLine ?? null } try { diff --git a/src/main/daemon/daemon-host-relocation.test.ts b/src/main/daemon/daemon-host-relocation.test.ts new file mode 100644 index 000000000000..1d3ab98db906 --- /dev/null +++ b/src/main/daemon/daemon-host-relocation.test.ts @@ -0,0 +1,270 @@ +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync +} from 'node:fs' +import os from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +// Mutable Electron app stub, hoisted so the vi.mock factory closes over it. +const { electronApp } = vi.hoisted(() => ({ + electronApp: { + isPackaged: true, + userDataPath: '', + version: '9.9.9', + getPath: (): string => electronApp.userDataPath, + getVersion: (): string => electronApp.version + } +})) + +vi.mock('electron', () => ({ app: electronApp })) + +import { + buildDaemonHostManifest, + collectPinnedDaemonVersions, + getRelocatedDaemonHost, + materializeRelocatedDaemonHost, + pruneOldDaemonHosts +} from './daemon-host-relocation' + +let tempDir: string +let installDir: string +let userDataDir: string +let localAppDataDir: string +const originalPlatform = process.platform +const originalExecPath = process.execPath +const originalResourcesPath = process.resourcesPath +const originalLocalAppData = process.env.LOCALAPPDATA + +function setProcessProp(key: string, value: unknown): void { + Object.defineProperty(process, key, { value, configurable: true, writable: true }) +} + +// Build a win-unpacked fixture: exe + blobs + DLLs at root, daemon bundle and +// node-pty under resources, mirroring the packaged layout the copy expects. +function buildInstallFixture(root: string): void { + mkdirSync(root, { recursive: true }) + writeFileSync(join(root, 'Orca.exe'), 'exe-bytes') + for (const name of ['icudtl.dat', 'snapshot_blob.bin', 'v8_context_snapshot.bin']) { + writeFileSync(join(root, name), name) + } + writeFileSync(join(root, 'ffmpeg.dll'), 'dll') + writeFileSync(join(root, 'libEGL.dll'), 'dll') + const mainDir = join(root, 'resources', 'app.asar.unpacked', 'out', 'main') + mkdirSync(join(mainDir, 'chunks'), { recursive: true }) + writeFileSync(join(mainDir, 'daemon-entry.js'), 'entry') + writeFileSync(join(mainDir, 'chunks', 'a.js'), 'chunk') + writeFileSync(join(root, 'resources', 'app.asar.unpacked', 'out', 'package.json'), '{}') + const nativeDir = join(root, 'resources', 'node_modules', 'node-pty', 'build', 'Release') + mkdirSync(nativeDir, { recursive: true }) + writeFileSync(join(nativeDir, 'conpty.node'), 'native') + writeFileSync(join(nativeDir, 'conpty.pdb'), 'debug-symbols') + mkdirSync(join(nativeDir, 'conpty'), { recursive: true }) + writeFileSync(join(nativeDir, 'conpty', 'conpty.dll'), 'conpty-dll') + // Both win32 prebuilds exist in the packaged tree (build-time prune keeps the + // `win32-` prefix); the copy filter keeps the host arch's and drops the other. + const prebuildsRoot = join(root, 'resources', 'node_modules', 'node-pty', 'prebuilds') + for (const arch of ['win32-x64', 'win32-arm64']) { + mkdirSync(join(prebuildsRoot, arch), { recursive: true }) + writeFileSync(join(prebuildsRoot, arch, 'pty.node'), `${arch}-prebuild`) + } +} + +// The win32 prebuild dir the running host arch loads vs. the one that is pruned. +const HOST_PREBUILD = `win32-${process.arch}` +const OTHER_PREBUILD = HOST_PREBUILD === 'win32-arm64' ? 'win32-x64' : 'win32-arm64' + +beforeEach(() => { + tempDir = mkdtempSync(join(os.tmpdir(), 'daemon-host-relocation-')) + installDir = join(tempDir, 'app') + userDataDir = join(tempDir, 'userData') + mkdirSync(userDataDir, { recursive: true }) + localAppDataDir = join(tempDir, 'localAppData') + mkdirSync(localAppDataDir, { recursive: true }) + process.env.LOCALAPPDATA = localAppDataDir + buildInstallFixture(installDir) + electronApp.isPackaged = true + electronApp.userDataPath = userDataDir + electronApp.version = '9.9.9' + setProcessProp('platform', 'win32') + setProcessProp('execPath', join(installDir, 'Orca.exe')) + setProcessProp('resourcesPath', join(installDir, 'resources')) +}) + +afterEach(() => { + setProcessProp('platform', originalPlatform) + setProcessProp('execPath', originalExecPath) + setProcessProp('resourcesPath', originalResourcesPath) + if (originalLocalAppData === undefined) { + delete process.env.LOCALAPPDATA + } else { + process.env.LOCALAPPDATA = originalLocalAppData + } + try { + rmSync(tempDir, { recursive: true, force: true }) + } catch { + // Best-effort + } +}) + +describe('buildDaemonHostManifest', () => { + it('mirrors the win-unpacked layout: exe + data blobs + resources tree, no GPU DLLs', () => { + const appDir = 'C:\\app' + const ops = buildDaemonHostManifest({ + appDir, + execPath: 'C:\\app\\Orca.exe', + resourcesPath: 'C:\\app\\resources', + entrySourcePath: 'C:\\app\\resources\\app.asar.unpacked\\out\\main\\daemon-entry.js', + entryRelPath: 'resources/app.asar.unpacked/out/main/daemon-entry.js' + }) + const byDest = new Map(ops.map((op) => [op.destRel, op])) + // The host exe is renamed to a distinct image name (NOT the source basename) + // so the NSIS updater's name-based `taskkill /IM Orca.exe` can't kill it. + expect(byDest.get('orca-terminal-daemon.exe')?.kind).toBe('file') + expect(byDest.has('Orca.exe')).toBe(false) + const exeOp = ops.find((op) => op.sourcePath === 'C:\\app\\Orca.exe') + expect(exeOp?.destRel).not.toBe('Orca.exe') + // V8/ICU data blobs are read by the Electron bootstrap and kept. + expect(byDest.has('icudtl.dat')).toBe(true) + // GPU/graphics DLLs are never loaded by the windowless host, so not copied. + expect(byDest.has('ffmpeg.dll')).toBe(false) + expect(byDest.has('libEGL.dll')).toBe(false) + // Daemon bundle + node-pty mirrored at their real resources-relative paths. + expect(byDest.get('resources/app.asar.unpacked/out/main/daemon-entry.js')?.kind).toBe('file') + expect(byDest.get('resources/app.asar.unpacked/out/main/chunks')?.kind).toBe('dir') + // node-pty is copied with a filter dropping .pdb + non-host-arch prebuilds. + const nodePtyOp = byDest.get('resources/node_modules/node-pty') + expect(nodePtyOp?.kind).toBe('dir') + expect(nodePtyOp?.filter?.('node-pty/build/Release/conpty.node')).toBe(true) + expect(nodePtyOp?.filter?.('node-pty/build/Release/conpty.pdb')).toBe(false) + expect(nodePtyOp?.filter?.(`node-pty/prebuilds/${HOST_PREBUILD}/pty.node`)).toBe(true) + expect(nodePtyOp?.filter?.(`node-pty/prebuilds/${OTHER_PREBUILD}/pty.node`)).toBe(false) + }) +}) + +describe('materializeRelocatedDaemonHost', () => { + it('copies the tree, writes the marker, and returns mirrored fork paths', () => { + const result = materializeRelocatedDaemonHost() + expect(result).not.toBeNull() + const dest = join(localAppDataDir, 'Orca', 'daemon-host', '9.9.9') + expect(result?.execPath).toBe(join(dest, 'orca-terminal-daemon.exe')) + expect(result?.entryPath).toBe( + join(dest, 'resources', 'app.asar.unpacked', 'out', 'main', 'daemon-entry.js') + ) + expect(existsSync(result!.execPath)).toBe(true) + expect(existsSync(result!.entryPath)).toBe(true) + // node-pty native + conpty runtime copied at the require-resolvable path. + expect( + existsSync( + join(dest, 'resources', 'node_modules', 'node-pty', 'build', 'Release', 'conpty.node') + ) + ).toBe(true) + expect( + existsSync(join(dest, 'resources', 'app.asar.unpacked', 'out', 'main', 'chunks', 'a.js')) + ).toBe(true) + // Trim: GPU DLLs, .pdb debug symbols, and non-host-arch prebuilds excluded; + // the host arch's prebuild is retained so node-pty resolves its native addon. + expect(existsSync(join(dest, 'ffmpeg.dll'))).toBe(false) + expect(existsSync(join(dest, 'libEGL.dll'))).toBe(false) + expect( + existsSync( + join(dest, 'resources', 'node_modules', 'node-pty', 'build', 'Release', 'conpty.pdb') + ) + ).toBe(false) + const prebuildsDest = join(dest, 'resources', 'node_modules', 'node-pty', 'prebuilds') + expect(existsSync(join(prebuildsDest, HOST_PREBUILD, 'pty.node'))).toBe(true) + expect(existsSync(join(prebuildsDest, OTHER_PREBUILD, 'pty.node'))).toBe(false) + // Marker records the version + entry rel path, written into the published dir. + const marker = JSON.parse(readFileSync(join(dest, '.materialized.json'), 'utf8')) + expect(marker.version).toBe('9.9.9') + expect(marker.entryRelPath).toBe('resources/app.asar.unpacked/out/main/daemon-entry.js') + }) + + it('is idempotent: a valid marker short-circuits without recopying', () => { + materializeRelocatedDaemonHost() + const dest = join(localAppDataDir, 'Orca', 'daemon-host', '9.9.9') + // A recopy would rm the dest; a sentinel inside it must survive the 2nd call. + const sentinel = join(dest, 'sentinel.txt') + writeFileSync(sentinel, 'keep') + const result = materializeRelocatedDaemonHost() + expect(result?.execPath).toBe(join(dest, 'orca-terminal-daemon.exe')) + expect(existsSync(sentinel)).toBe(true) + }) + + it('fails open on a missing required input, leaving no dest or staging dir', () => { + rmSync(join(installDir, 'resources', 'node_modules', 'node-pty'), { + recursive: true, + force: true + }) + const result = materializeRelocatedDaemonHost() + expect(result).toBeNull() + const hostRoot = join(localAppDataDir, 'Orca', 'daemon-host') + // Neither the published dest nor any leftover staging dir remains. + const remaining = existsSync(hostRoot) ? readdirSync(hostRoot) : [] + expect(remaining).toEqual([]) + }) + + it('returns null off win32', () => { + setProcessProp('platform', 'darwin') + expect(materializeRelocatedDaemonHost()).toBeNull() + expect(existsSync(join(localAppDataDir, 'Orca', 'daemon-host'))).toBe(false) + }) +}) + +describe('getRelocatedDaemonHost', () => { + it('returns null when the marker version does not match the current version', () => { + const dest = join(localAppDataDir, 'Orca', 'daemon-host', '9.9.9') + mkdirSync(dirname(join(dest, 'x')), { recursive: true }) + writeFileSync(join(dest, 'Orca.exe'), 'exe') + mkdirSync(join(dest, 'resources', 'app.asar.unpacked', 'out', 'main'), { recursive: true }) + writeFileSync( + join(dest, 'resources', 'app.asar.unpacked', 'out', 'main', 'daemon-entry.js'), + 'e' + ) + writeFileSync( + join(dest, '.materialized.json'), + JSON.stringify({ + version: '8.8.8', + completedAt: '', + entryRelPath: 'resources/app.asar.unpacked/out/main/daemon-entry.js' + }) + ) + expect(getRelocatedDaemonHost()).toBeNull() + }) +}) + +describe('pruneOldDaemonHosts', () => { + it('removes unpinned non-current version dirs, keeping current and pinned', () => { + const root = join(localAppDataDir, 'Orca', 'daemon-host') + for (const v of ['9.9.9', '1.0.0', '2.0.0']) { + mkdirSync(join(root, v), { recursive: true }) + } + pruneOldDaemonHosts(new Set(['2.0.0'])) + expect(existsSync(join(root, '9.9.9'))).toBe(true) + expect(existsSync(join(root, '2.0.0'))).toBe(true) + expect(existsSync(join(root, '1.0.0'))).toBe(false) + }) +}) + +describe('collectPinnedDaemonVersions', () => { + it('pins the app version of a live daemon pid file and skips dead ones', () => { + const runtimeDir = join(userDataDir, 'daemon') + mkdirSync(runtimeDir, { recursive: true }) + writeFileSync( + join(runtimeDir, 'daemon-v4.pid'), + JSON.stringify({ pid: process.pid, startedAtMs: null, appVersion: '7.0.0' }) + ) + writeFileSync( + join(runtimeDir, 'daemon-v3.pid'), + JSON.stringify({ pid: 2147483646, startedAtMs: null, appVersion: '6.0.0' }) + ) + const pinned = collectPinnedDaemonVersions(runtimeDir) + expect(pinned.has('7.0.0')).toBe(true) + expect(pinned.has('6.0.0')).toBe(false) + }) +}) diff --git a/src/main/daemon/daemon-host-relocation.ts b/src/main/daemon/daemon-host-relocation.ts new file mode 100644 index 000000000000..ac674fdd290a --- /dev/null +++ b/src/main/daemon/daemon-host-relocation.ts @@ -0,0 +1,398 @@ +import { randomBytes } from 'node:crypto' +import { + cpSync, + existsSync, + mkdirSync, + readFileSync, + readdirSync, + renameSync, + rmSync, + writeFileSync +} from 'node:fs' +import { dirname, join, win32 as winPath } from 'node:path' +import { app } from 'electron' +import { parseDaemonPidFile, startTimeMatches } from './daemon-health' + +/** + * Relocates the terminal daemon's process image out of the app install + * directory into userData so it survives Windows auto-updates. + * + * Why: the daemon is forked as plain Node via ELECTRON_RUN_AS_NODE, so its + * image is the install-dir Orca.exe and its loaded modules (node-pty native, + * ConPTY runtime) map from the install dir. On update, electron-builder's NSIS + * installer deletes the old install and force-closes every process whose image + * lives under it — killing the daemon and every live terminal it owns. Copying + * the daemon's whole file closure to a version-keyed userData dir and forking + * from that copy takes its image + loaded modules out of the installer's reach. + * + * The copy keeps the ELECTRON binary run as node (not stock node.exe): a copy + * of Orca.exe (renamed to a distinct image name) is byte-identical, so + * run-as-node behavior — no console flashing, asar-correct — matches the in-dir + * fork exactly. The win-unpacked layout is mirrored verbatim so + * require('node-pty') and node-pty's native loader resolve the relocated tree + * identically to the packaged app. + * + * Fail-open everywhere: any failure returns null and the caller forks the + * install-dir host — the pre-relocation behavior, byte-identical off win32. + */ + +export type RelocatedDaemonHost = { + /** The relocated host exe to fork the daemon from (run as node). */ + execPath: string + /** The copied daemon-entry.js, mirrored under the relocated resources tree. */ + entryPath: string +} + +const HOST_SUBDIR = 'daemon-host' +const MARKER_NAME = '.materialized.json' + +// The relocated host is machine-specific runtime (~260MB). It must live under +// LOCAL appData, not the roaming userData dir, so a roaming profile or OneDrive +// Known-Folder-Move never syncs it (slow login/logout, sync bloat). This folder +// name is shared verbatim with the NSIS uninstall cleanup +// (config/nsis/daemon-host-uninstall.nsh), which removes +// %LOCALAPPDATA%\\daemon-host — keep the two in sync. +const LOCAL_HOST_ROOT_NAME = 'Orca' + +// The relocated host exe is a copy of Orca.exe renamed to a distinct image +// name. The NSIS updater's name-based kill (`taskkill /IM Orca.exe`) matches by +// image name, so a distinct name spares the daemon from that branch, while the +// userData path (outside $INSTDIR) spares it from the path-based branch. +const DAEMON_HOST_EXE_NAME = 'orca-terminal-daemon.exe' + +// V8 snapshots + ICU data the Electron bootstrap reads even under +// ELECTRON_RUN_AS_NODE; siblings of Orca.exe in win-unpacked. +const RUNTIME_DATA_FILES = ['icudtl.dat', 'snapshot_blob.bin', 'v8_context_snapshot.bin'] + +type CopyOp = { + sourcePath: string + /** Destination path relative to the host root, posix-separated. */ + destRel: string + kind: 'file' | 'dir' + /** When true, a missing source is skipped rather than failing the copy. */ + optional?: boolean + /** Per-source-path predicate for dir copies: return false to skip a path. */ + filter?: (sourcePath: string) => boolean +} + +type DaemonHostSources = { + appDir: string + execPath: string + resourcesPath: string + entrySourcePath: string + entryRelPath: string +} + +type MaterializeMarker = { + version: string + completedAt: string + entryRelPath: string +} + +// Uses win32 path semantics so Windows layout paths (drive letters, `\`) +// decompose correctly regardless of host OS — needed for cross-platform unit +// tests; production runs this on win32 only. +function toPosixRelative(fromDir: string, absPath: string): string { + return winPath.relative(fromDir, absPath).split(winPath.sep).join('/') +} + +function destPath(root: string, destRel: string): string { + return join(root, ...destRel.split('/')) +} + +// Mirror getDaemonEntryPath()'s resolution order (unpacked root first, then +// out/main) so the copied entry is the exact file the in-dir fork would run. +function resolveEntrySourcePath(resourcesPath: string): string { + const unpackedRoot = join(resourcesPath, 'app.asar.unpacked') + const direct = join(unpackedRoot, 'daemon-entry.js') + if (existsSync(direct)) { + return direct + } + return join(unpackedRoot, 'out', 'main', 'daemon-entry.js') +} + +// Discover the relocation inputs from the live packaged process, or null when +// relocation does not apply (non-win32, dev, or missing resourcesPath). +function collectDaemonHostSources(): DaemonHostSources | null { + if (process.platform !== 'win32' || !app.isPackaged) { + return null + } + const resourcesPath = process.resourcesPath + if (typeof resourcesPath !== 'string' || resourcesPath.length === 0) { + return null + } + const execPath = process.execPath + const appDir = winPath.dirname(execPath) + const entrySourcePath = resolveEntrySourcePath(resourcesPath) + return { + appDir, + execPath, + resourcesPath, + entrySourcePath, + entryRelPath: toPosixRelative(appDir, entrySourcePath) + } +} + +// node-pty ships debug symbols (.pdb) and a win32 prebuild dir per CPU arch; the +// run-as-node daemon loads neither the symbols nor any non-host-arch prebuild +// (verified against the live daemon's loaded module list), so they are filtered +// out of the copy — the bulk of node-pty's on-disk size. Keyed on the host arch +// rather than dropping arm64 outright so a future Windows-arm64 build keeps the +// `win32-arm64` prebuild it actually needs and prunes `win32-x64` instead. +const HOST_WIN_PREBUILD_DIR = `win32-${process.arch}`.toLowerCase() +function isRuntimeNodePtyPath(sourcePath: string): boolean { + const p = sourcePath.toLowerCase() + if (p.endsWith('.pdb')) { + return false + } + // Keep only the host arch's win32 prebuild; drop any other win32- dir. + const prebuild = p.match(/prebuilds[\\/](win32-[^\\/]+)/) + return !prebuild || prebuild[1] === HOST_WIN_PREBUILD_DIR +} + +/** + * The ordered copy plan. Every destRel mirrors the source's win-unpacked + * relative path so require() and node-pty's native loader resolve the mirror + * identically to the packaged app. Pure over its inputs so tests can assert the + * layout without a real build. + */ +export function buildDaemonHostManifest(sources: DaemonHostSources): CopyOp[] { + const { appDir, execPath, resourcesPath, entrySourcePath, entryRelPath } = sources + const ops: CopyOp[] = [] + + // Electron host binary + V8/ICU data blobs at the dest root. The exe is + // renamed to a distinct image name so the NSIS updater's name-based + // `taskkill /IM Orca.exe` can't match it; the blobs beside it are read by the + // Electron bootstrap by fixed name. Top-level DLLs are deliberately NOT copied + // — they are all GPU/graphics/media (swiftshader, vulkan, d3d, dxcompiler, + // ffmpeg) that a windowless run-as-node host never loads (verified empirically + // against the live daemon's module list), so copying them only wastes ~48MB. + ops.push({ sourcePath: execPath, destRel: DAEMON_HOST_EXE_NAME, kind: 'file' }) + for (const name of RUNTIME_DATA_FILES) { + ops.push({ sourcePath: join(appDir, name), destRel: name, kind: 'file', optional: true }) + } + + // Daemon bundle: entry + its sibling chunks/ + the unpacked out/package.json + // (CJS/ESM loader resolution), mirrored verbatim. + ops.push({ sourcePath: entrySourcePath, destRel: entryRelPath, kind: 'file' }) + const chunksDir = join(winPath.dirname(entrySourcePath), 'chunks') + ops.push({ + sourcePath: chunksDir, + destRel: toPosixRelative(appDir, chunksDir), + kind: 'dir', + optional: true + }) + const pkgJson = join(resourcesPath, 'app.asar.unpacked', 'out', 'package.json') + ops.push({ + sourcePath: pkgJson, + destRel: toPosixRelative(appDir, pkgJson), + kind: 'file', + optional: true + }) + + // node-pty package tree (native conpty.node + conpty/ runtime dir). It is a + // sibling of app.asar.unpacked; require('node-pty') resolves it by walking up + // from the mirrored daemon-entry dir to resources/node_modules. Filtered to + // drop .pdb debug symbols and other-arch prebuilds the host never loads. + const nodePtyDir = join(resourcesPath, 'node_modules', 'node-pty') + ops.push({ + sourcePath: nodePtyDir, + destRel: toPosixRelative(appDir, nodePtyDir), + kind: 'dir', + filter: isRuntimeNodePtyPath + }) + + return ops +} + +function executeManifest(ops: CopyOp[], stagingRoot: string): void { + for (const op of ops) { + if (!existsSync(op.sourcePath)) { + if (op.optional) { + continue + } + throw new Error(`daemon-host relocation: missing required input ${op.sourcePath}`) + } + const dest = destPath(stagingRoot, op.destRel) + mkdirSync(dirname(dest), { recursive: true }) + const { filter } = op + // Dereference symlinks so the copy holds no link back into the install dir. + cpSync(op.sourcePath, dest, { + recursive: op.kind === 'dir', + dereference: true, + force: true, + ...(filter ? { filter: (src: string) => filter(src) } : {}) + }) + } +} + +function readMarker(dir: string): MaterializeMarker | null { + try { + const parsed = JSON.parse( + readFileSync(join(dir, MARKER_NAME), 'utf8') + ) as Partial + if (typeof parsed.version === 'string' && typeof parsed.entryRelPath === 'string') { + return { + version: parsed.version, + completedAt: typeof parsed.completedAt === 'string' ? parsed.completedAt : '', + entryRelPath: parsed.entryRelPath + } + } + } catch { + // Missing/corrupt marker — treat as not materialized. + } + return null +} + +function hostRootDir(): string { + // Prefer LOCAL appData (see LOCAL_HOST_ROOT_NAME). Fall back to userData only + // if LOCALAPPDATA is somehow unset — a no-op off win32, where relocation never + // runs anyway; on win32 packaged the env var is always present. + const localAppData = process.env.LOCALAPPDATA + const base = + typeof localAppData === 'string' && localAppData.length > 0 + ? join(localAppData, LOCAL_HOST_ROOT_NAME) + : app.getPath('userData') + return join(base, HOST_SUBDIR) +} + +/** + * Cheap idempotency check: the relocated host for the current version, or null. + * Valid only when the marker matches this version AND the exe + entry exist, so + * a partial or stale copy never reports ready. + */ +export function getRelocatedDaemonHost(): RelocatedDaemonHost | null { + const sources = collectDaemonHostSources() + if (!sources) { + return null + } + const version = app.getVersion() + const dest = join(hostRootDir(), version) + const marker = readMarker(dest) + if (!marker || marker.version !== version) { + return null + } + const execPath = join(dest, DAEMON_HOST_EXE_NAME) + const entryPath = destPath(dest, marker.entryRelPath) + if (!existsSync(execPath) || !existsSync(entryPath)) { + return null + } + return { execPath, entryPath } +} + +/** + * Ensure the current version's daemon host is materialized under + * userData/daemon-host/, returning its fork paths or null (fail-open). + * Idempotent: a valid marker for this version short-circuits without recopying. + * The copy stages into a temp sibling and is published by atomic rename, so a + * crash mid-copy never leaves a half-populated dest. + */ +export function materializeRelocatedDaemonHost(): RelocatedDaemonHost | null { + const existing = getRelocatedDaemonHost() + if (existing) { + return existing + } + const sources = collectDaemonHostSources() + if (!sources) { + return null + } + const version = app.getVersion() + const root = hostRootDir() + const dest = join(root, version) + const staging = join(root, `${version}.staging-${randomBytes(6).toString('hex')}`) + try { + mkdirSync(root, { recursive: true }) + rmSync(staging, { recursive: true, force: true }) + executeManifest(buildDaemonHostManifest(sources), staging) + // Marker written LAST: an interrupted copy leaves a marker-less staging dir + // that the next launch discards, never a dest the cheap check trusts. + const marker: MaterializeMarker = { + version, + completedAt: new Date().toISOString(), + entryRelPath: sources.entryRelPath + } + writeFileSync(join(staging, MARKER_NAME), JSON.stringify(marker)) + // Replace any stale/partial dest, then publish the staging dir atomically. + rmSync(dest, { recursive: true, force: true }) + renameSync(staging, dest) + } catch { + try { + rmSync(staging, { recursive: true, force: true }) + } catch { + // Best-effort staging cleanup. + } + return null + } + return getRelocatedDaemonHost() +} + +function isDaemonPidAlive(pid: number, startedAtMs: number | null): boolean { + try { + process.kill(pid, 0) + } catch { + return false + } + return startTimeMatches(pid, startedAtMs) +} + +/** + * App versions still pinned by a live daemon, read from the daemon-v.pid + * files under `runtimeDir`. A surviving daemon runs from its version's host dir, + * so its dir must never be reclaimed while the process is alive. On win32 the + * start-time check cannot verify, so a matching pid pins conservatively. + */ +export function collectPinnedDaemonVersions(runtimeDir: string): Set { + const pinned = new Set() + let entries + try { + entries = readdirSync(runtimeDir, { withFileTypes: true }) + } catch { + return pinned + } + for (const entry of entries) { + if (!entry.isFile() || !/^daemon-v\d+\.pid$/.test(entry.name)) { + continue + } + let parsed + try { + parsed = parseDaemonPidFile(readFileSync(join(runtimeDir, entry.name), 'utf8')) + } catch { + continue + } + // appVersion null => a pre-relocation daemon forked from the install dir, + // which pins no host dir here. + if (parsed && parsed.appVersion !== null && isDaemonPidAlive(parsed.pid, parsed.startedAtMs)) { + pinned.add(parsed.appVersion) + } + } + return pinned +} + +/** + * Reclaim daemon-host/ dirs whose ver is neither the current version nor + * pinned by a live daemon. Best-effort — never throws; a still-locked or + * concurrently-staging dir is simply retried on a future launch. + */ +export function pruneOldDaemonHosts(pinnedVersions: ReadonlySet): void { + if (process.platform !== 'win32' || !app.isPackaged) { + return + } + const version = app.getVersion() + const root = hostRootDir() + let entries + try { + entries = readdirSync(root, { withFileTypes: true }) + } catch { + return + } + for (const entry of entries) { + if (!entry.isDirectory() || entry.name === version || pinnedVersions.has(entry.name)) { + continue + } + try { + rmSync(join(root, entry.name), { recursive: true, force: true }) + } catch { + // Still locked or already gone — retry on a future launch. + } + } +} diff --git a/src/main/daemon/daemon-init.test.ts b/src/main/daemon/daemon-init.test.ts index b6028a7a81ce..06344c0759f5 100644 --- a/src/main/daemon/daemon-init.test.ts +++ b/src/main/daemon/daemon-init.test.ts @@ -25,6 +25,8 @@ const { isPackagedMock, probeSocketExistsMock, writeFileSyncMock, + readFileSyncMock, + unlinkSyncMock, netConnectMock, forkMock, checkDaemonHealthMock, @@ -34,6 +36,7 @@ const { isDaemonStaleForCurrentBundleMock, killStaleDaemonMock, getProcessStartedAtMsMock, + parseDaemonPidFileMock, daemonClientMock, spawnerInstances, ensureRunningOverrides, @@ -51,6 +54,13 @@ const { const probeSocketExistsMock = vi.fn((_path?: string) => false) const writeFileSyncMock = vi.fn() + // Why: readFileSync throws by default so legacyDaemonProcessMayBeAlive's + // catch treats every legacy pid file as unreadable — matching the pre-fix + // cleanup behavior every existing test was written against. + const readFileSyncMock = vi.fn((): string => { + throw new Error('ENOENT') + }) + const unlinkSyncMock = vi.fn() const forkMock = vi.fn() const netConnectMock = vi.fn(() => { // Why: the real probeSocket() in daemon-init connects to the socket and @@ -83,7 +93,10 @@ const { const getDaemonLaunchIdentityMock = vi.fn(() => 'match') const isDaemonStaleForCurrentBundleMock = vi.fn(() => false) const killStaleDaemonMock = vi.fn(async () => true) - const getProcessStartedAtMsMock = vi.fn(() => 1_000_000) + const getProcessStartedAtMsMock = vi.fn((): number | null => 1_000_000) + const parseDaemonPidFileMock = vi.fn( + (): { pid: number; startedAtMs: number | null } | null => null + ) const daemonClientMock = vi.fn().mockImplementation(function MockDaemonClient() { return { @@ -145,6 +158,8 @@ const { isPackagedMock, probeSocketExistsMock, writeFileSyncMock, + readFileSyncMock, + unlinkSyncMock, netConnectMock, forkMock, checkDaemonHealthMock, @@ -154,6 +169,7 @@ const { isDaemonStaleForCurrentBundleMock, killStaleDaemonMock, getProcessStartedAtMsMock, + parseDaemonPidFileMock, daemonClientMock, spawnerInstances, ensureRunningOverrides, @@ -214,7 +230,8 @@ vi.mock('electron', () => ({ vi.mock('fs', () => ({ mkdirSync: vi.fn(), existsSync: (p: string) => probeSocketExistsMock(p) || p.includes('.pid'), - unlinkSync: vi.fn(), + unlinkSync: unlinkSyncMock, + readFileSync: readFileSyncMock, writeFileSync: writeFileSyncMock })) @@ -229,7 +246,8 @@ vi.mock('./daemon-health', () => ({ healthCheckDaemon: healthCheckDaemonMock, isDaemonStaleForCurrentBundle: isDaemonStaleForCurrentBundleMock, killStaleDaemon: killStaleDaemonMock, - getProcessStartedAtMs: getProcessStartedAtMsMock + getProcessStartedAtMs: getProcessStartedAtMsMock, + parseDaemonPidFile: parseDaemonPidFileMock })) vi.mock('./client', () => ({ DaemonClient: daemonClientMock })) @@ -358,6 +376,15 @@ async function importFresh() { daemonClientMock.mockClear() probeSocketExistsMock.mockClear() writeFileSyncMock.mockClear() + readFileSyncMock.mockReset() + readFileSyncMock.mockImplementation(() => { + throw new Error('ENOENT') + }) + unlinkSyncMock.mockClear() + parseDaemonPidFileMock.mockReset() + parseDaemonPidFileMock.mockReturnValue(null) + getProcessStartedAtMsMock.mockReset() + getProcessStartedAtMsMock.mockReturnValue(1_000_000) // Why: importing daemon-init *after* resetModules means the module-level // `spawner`/`adapter`/`restartInFlight` start fresh for every test, which is // the only way to reliably exercise the "first-time init" path and the @@ -996,7 +1023,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - ['--socket', '/fake/socket', '--token', '/fake/token'], + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ cwd: '/fake/userData', detached: true }) ) }) @@ -1122,7 +1156,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - ['--socket', '/fake/socket', '--token', '/fake/token'], + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ cwd: '/fake/userData', detached: true }) ) }) @@ -1239,7 +1280,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - ['--socket', '/fake/socket', '--token', '/fake/token'], + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ detached: true }) ) }) @@ -1344,6 +1392,123 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(child.unref).not.toHaveBeenCalled() }) + it('captures daemon startup stderr into the failure error', async () => { + const mod = await importFresh() + checkDaemonHealthMock.mockResolvedValue('unreachable') + await mod.initDaemonPtyProvider() + + const launcher = spawnerInstances[0].launcher as ( + socketPath: string, + tokenPath: string + ) => Promise<{ shutdown(): Promise }> + const handlers: Record void)[]> = { + message: [], + error: [], + exit: [] + } + const stderrDataCbs: ((chunk: Buffer) => void)[] = [] + const stderrDestroy = vi.fn() + const stderr = { + on(event: string, cb: (chunk: Buffer) => void) { + if (event === 'data') { + stderrDataCbs.push(cb) + } + return this + }, + off(event: string, cb: (chunk: Buffer) => void) { + if (event === 'data') { + const idx = stderrDataCbs.indexOf(cb) + if (idx !== -1) { + stderrDataCbs.splice(idx, 1) + } + } + return this + }, + destroy: stderrDestroy + } + const child = { + pid: 4321, + stderr, + on(event: string, cb: (arg?: unknown) => void) { + handlers[event]?.push(cb) + if (event === 'exit') { + // Why: deliver the stderr tail before the exit so the failure path + // sees the captured crash reason, mirroring a module-load crash. + queueMicrotask(() => { + for (const dataCb of stderrDataCbs.slice()) { + dataCb(Buffer.from("Error: Cannot find module 'electron'\n")) + } + cb(1) + }) + } + return this + }, + off: vi.fn((event: string, cb: (arg?: unknown) => void) => { + handlers[event] = handlers[event]?.filter((handler) => handler !== cb) ?? [] + return child + }), + disconnect: vi.fn(), + unref: vi.fn() + } + forkMock.mockReturnValueOnce(child) + + const error = await launcher('/fake/socket', '/fake/token').catch((err: Error) => err) + + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toMatch(/Cannot find module 'electron'/) + expect((error as Error).message).toMatch(/Daemon stderr \(tail\)/) + // Why: the piped stderr must be released so the detached daemon does not + // keep the parent event loop alive after the failure. + expect(stderrDestroy).toHaveBeenCalled() + }) + + it('destroys the daemon stderr pipe once the daemon signals ready', async () => { + const mod = await importFresh() + checkDaemonHealthMock.mockResolvedValue('unreachable') + await mod.initDaemonPtyProvider() + + const launcher = spawnerInstances[0].launcher as ( + socketPath: string, + tokenPath: string + ) => Promise<{ shutdown(): Promise }> + const handlers: Record void)[]> = { + message: [], + error: [], + exit: [] + } + const stderrOff = vi.fn() + const stderrDestroy = vi.fn() + const stderr = { + on() { + return this + }, + off: stderrOff, + destroy: stderrDestroy + } + const child = { + pid: 12345, + stderr, + on(event: string, cb: (arg?: unknown) => void) { + handlers[event]?.push(cb) + if (event === 'message') { + queueMicrotask(() => cb({ type: 'ready' })) + } + return this + }, + off: vi.fn(() => child), + disconnect: vi.fn(), + unref: vi.fn() + } + forkMock.mockReturnValueOnce(child) + + await launcher('/fake/socket', '/fake/token') + + expect(stderrOff).toHaveBeenCalledWith('data', expect.any(Function)) + expect(stderrDestroy).toHaveBeenCalledOnce() + expect(child.disconnect).toHaveBeenCalledOnce() + expect(child.unref).toHaveBeenCalledOnce() + }) + it('preserves a health-check-failing daemon when it owns live sessions', async () => { const mod = await importFresh() await mod.initDaemonPtyProvider() @@ -1413,7 +1578,7 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(forkMock).not.toHaveBeenCalled() }) - it('replaces a health-check-failing daemon when live sessions cannot be verified', async () => { + it('replaces a health-check-failing daemon when live sessions cannot be verified and the pipe is dead', async () => { const mod = await importFresh() await mod.initDaemonPtyProvider() @@ -1457,6 +1622,203 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(forkMock).toHaveBeenCalled() }) + it('adopts an unresponsive daemon whose pipe still accepts connections (update-relaunch wedge)', async () => { + // Why: the Windows update-relaunch regression — post-install disk/AV load + // wedges the daemon past the 3s health budget AND the 5s hello budget of + // the session-list re-verification, while its sessions are still alive. + // The old fail-closed path killed the daemon here. A pipe that accepts a + // raw connection proves the daemon is alive, so the launcher must adopt. + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + daemonClientMock.mockImplementationOnce(function MockDaemonClient() { + return { + ensureConnected: vi.fn(async () => { + throw new Error('Hello response timed out') + }), + request: vi.fn(), + disconnect: vi.fn() + } + }) + + const launcher = spawnerInstances[0].launcher as ( + socketPath: string, + tokenPath: string + ) => Promise<{ shutdown(): Promise }> + checkDaemonHealthMock.mockResolvedValueOnce('unreachable') + // The raw pipe probe succeeds even though every RPC timed out. + probeSocketExistsMock.mockReturnValue(true) + netConnectMock.mockImplementationOnce(() => { + const handlers: Record void)[]> = { connect: [], error: [] } + return { + on(event: string, cb: () => void) { + handlers[event]?.push(cb) + if (event === 'connect') { + queueMicrotask(() => cb()) + } + return this + }, + removeListener(event: string, cb: () => void) { + handlers[event] = handlers[event]?.filter((handler) => handler !== cb) ?? [] + return this + }, + destroy() {} + } + }) + + await launcher('/fake/socket', '/fake/token') + + expect(killStaleDaemonMock).not.toHaveBeenCalled() + expect(forkMock).not.toHaveBeenCalled() + }) + + it('replaces a hello-rejected daemon even though its pipe accepts connections', async () => { + // Why: 'rejected' means the daemon answered and refused the handshake — + // it can never be adopted, so keeping it alive would strand the app with + // no terminals forever. Replacement stays the only recovery. + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + daemonClientMock.mockImplementationOnce(function MockDaemonClient() { + return { + ensureConnected: vi.fn(async () => { + throw new Error('Hello rejected') + }), + request: vi.fn(), + disconnect: vi.fn() + } + }) + + const launcher = spawnerInstances[0].launcher as ( + socketPath: string, + tokenPath: string + ) => Promise<{ shutdown(): Promise }> + checkDaemonHealthMock.mockResolvedValueOnce('rejected') + probeSocketExistsMock.mockReturnValue(true) + forkMock.mockImplementationOnce(() => ({ + pid: 12345, + on(event: string, cb: (arg?: unknown) => void) { + if (event === 'message') { + queueMicrotask(() => cb({ type: 'ready' })) + } + return this + }, + off() { + return this + }, + disconnect: vi.fn(), + unref: vi.fn() + })) + + await launcher('/fake/socket', '/fake/token') + + expect(killStaleDaemonMock).toHaveBeenCalledWith( + FAKE_RUNTIME_DIR, + '/fake/socket', + '/fake/token' + ) + expect(forkMock).toHaveBeenCalled() + }) + + it('adopts a healthy daemon whose pid-file identity cannot be verified (null startedAtMs metadata)', async () => { + // Why: the regression contract — a pid file with startedAtMs null (all + // pre-fix Windows pid files) resolves launch identity to 'unknown'. With + // a live daemon answering on the pipe, that must ADOPT, never replace. + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + const launcher = spawnerInstances[0].launcher as ( + socketPath: string, + tokenPath: string + ) => Promise<{ shutdown(): Promise }> + getDaemonLaunchIdentityMock.mockReturnValueOnce('unknown') + isPackagedMock.mockReturnValue(true) + + await launcher('/fake/socket', '/fake/token') + + expect(killStaleDaemonMock).not.toHaveBeenCalled() + expect(forkMock).not.toHaveBeenCalled() + }) + + it('writes the daemon self-reported start time to the pid file when the OS query returns null', async () => { + // Why: getProcessStartedAtMs has no cheap Windows implementation, so the + // pid file's pid-recycling guard depends on the ready-message fallback. + const mod = await importFresh() + await mod.initDaemonPtyProvider() + + const launcher = spawnerInstances[0].launcher as ( + socketPath: string, + tokenPath: string + ) => Promise<{ shutdown(): Promise }> + checkDaemonHealthMock.mockResolvedValueOnce('unreachable') + getProcessStartedAtMsMock.mockReturnValue(null) + forkMock.mockImplementationOnce(() => ({ + pid: 12345, + on(event: string, cb: (arg?: unknown) => void) { + if (event === 'message') { + queueMicrotask(() => cb({ type: 'ready', startedAtMs: 1_700_000_123_456 })) + } + return this + }, + off() { + return this + }, + disconnect: vi.fn(), + unref: vi.fn() + })) + + await launcher('/fake/socket', '/fake/token') + + expect(writeFileSyncMock).toHaveBeenCalledWith( + `/fake/daemon/daemon-v${PROTOCOL_VERSION}.pid`, + JSON.stringify({ + pid: 12345, + startedAtMs: 1_700_000_123_456, + entryPath: FAKE_DAEMON_ENTRY_PATH, + appVersion: '1.2.3' + }), + { mode: 0o600 } + ) + }) + + it('keeps legacy daemon pid/token files when the probe fails but the pid-file process is alive', async () => { + // Why: deleting a live-but-wedged legacy daemon's token file makes its + // sessions permanently unadoptable — no future launch could authenticate. + const mod = await importFresh() + readFileSyncMock.mockReturnValue('{"pid":123}') + // process.pid is guaranteed alive, so the liveness probe succeeds. + parseDaemonPidFileMock.mockReturnValue({ pid: process.pid, startedAtMs: null }) + + await mod.initDaemonPtyProvider() + + const legacyUnlinks = unlinkSyncMock.mock.calls.filter( + ([p]) => typeof p === 'string' && (p.includes('.token') || p.includes('.pid')) + ) + expect(legacyUnlinks).toEqual([]) + }) + + it('cleans up legacy daemon pid/token files when the probe fails and the process is gone', async () => { + const mod = await importFresh() + readFileSyncMock.mockReturnValue('{"pid":123}') + // Why: spy on process.kill so the liveness probe deterministically reports + // "no such process" without depending on an unallocated real pid. + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => { + throw new Error('ESRCH') + }) + parseDaemonPidFileMock.mockReturnValue({ pid: 999_999, startedAtMs: null }) + + try { + await mod.initDaemonPtyProvider() + } finally { + killSpy.mockRestore() + } + + const tokenUnlinks = unlinkSyncMock.mock.calls.filter( + ([p]) => typeof p === 'string' && p.includes('.token') + ) + expect(tokenUnlinks.length).toBeGreaterThan(0) + }) + it('replaces a health-check-failing daemon when no live sessions would be lost', async () => { const mod = await importFresh() await mod.initDaemonPtyProvider() @@ -1499,7 +1861,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - ['--socket', '/fake/socket', '--token', '/fake/token'], + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ detached: true }) ) }) @@ -1584,7 +1953,14 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) expect(forkMock).toHaveBeenCalledWith( FAKE_DAEMON_ENTRY_PATH, - ['--socket', '/fake/socket', '--token', '/fake/token'], + expect.arrayContaining([ + '--socket', + '/fake/socket', + '--token', + '/fake/token', + '--log-file', + join(FAKE_USER_DATA_PATH, 'logs', 'daemon.log') + ]), expect.objectContaining({ detached: true }) ) }) diff --git a/src/main/daemon/daemon-init.ts b/src/main/daemon/daemon-init.ts index 3ba351c3576e..ad0227bae862 100644 --- a/src/main/daemon/daemon-init.ts +++ b/src/main/daemon/daemon-init.ts @@ -8,7 +8,7 @@ module-level spawner/adapter singletons must stay co-located so a future change cannot leave them drifting out of sync. */ import { join } from 'node:path' import { app } from 'electron' -import { mkdirSync, existsSync, unlinkSync, writeFileSync } from 'node:fs' +import { mkdirSync, existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs' import { fork } from 'node:child_process' import { connect } from 'node:net' import { @@ -34,8 +34,14 @@ import { getProcessStartedAtMs, checkDaemonHealth, isDaemonStaleForCurrentBundle, - killStaleDaemon + killStaleDaemon, + parseDaemonPidFile } from './daemon-health' +import { + collectPinnedDaemonVersions, + materializeRelocatedDaemonHost, + pruneOldDaemonHosts +} from './daemon-host-relocation' import { DegradedDaemonPtyProvider } from './degraded-daemon-pty-provider' import { getLocalPtyProvider, @@ -44,6 +50,7 @@ import { rebindLocalProviderListeners } from '../ipc/pty' import { isStartupDiagnosticsEnabled, logStartupDiagnostic } from '../startup/startup-diagnostics' +import { getDaemonLogFilePath } from '../observability/logs-directory' import { confirmSeededClaudeLivePtys, hasSeededUnconfirmedClaudePtys @@ -93,6 +100,18 @@ function getDaemonEntryPath(): string { return join(basePath, 'out', 'main', 'daemon-entry.js') } +// Why: the detached daemon writes lifecycle events to a rotated file so field +// failures are diagnosable from a bundle. Honor the same hard privacy switch +// the local trace sink honors (ORCA_DIAGNOSTICS_DISABLED); absence of the arg +// is fully supported, so gating it off is safe and adoption-neutral. +function daemonLogArgs(): string[] { + const disabled = (process.env.ORCA_DIAGNOSTICS_DISABLED ?? '').trim().toLowerCase() + if (disabled === '1' || disabled === 'true') { + return [] + } + return ['--log-file', getDaemonLogFilePath()] +} + // Why: before spawning a new daemon, check if an existing one is alive by // attempting a TCP connection to the socket. If it connects, the daemon // survived from a previous app session — reuse it instead of spawning. @@ -237,9 +256,7 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { // Why: a busy machine (e.g. right after an update) can time out the // health check while the daemon is alive and owning terminals. Killing // it would destroy every live session, so re-verify with a session list - // first. Only a verified non-empty list preserves: a daemon that cannot - // even list sessions cannot serve terminals, and replacing it is the - // only recovery. + // first. const liveSessionCount = await getAliveDaemonSessionCount(socketPath, tokenPath) if (liveSessionCount !== null && liveSessionCount > 0) { if (health === 'pty-spawn-unhealthy') { @@ -257,6 +274,20 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { ) return createPreservedDaemonHandle(runtimeDir) } + // Why: on a Windows update relaunch the daemon can be wedged past every + // RPC budget (final checkpoint flush + installer/AV disk pressure), so + // both the health check AND the session list time out while sessions + // are still alive — failing closed here is what killed those sessions. + // A pipe that still accepts connections proves a live daemon: adopt it + // and let the adapter reconnect once the daemon drains. 'rejected' + // means the daemon answered and refused the handshake — it can never be + // adopted, so replacement stays the only recovery. + if (liveSessionCount === null && health !== 'rejected' && (await probeSocket(socketPath))) { + console.warn( + '[daemon] Preserving unresponsive daemon because its socket still accepts connections' + ) + return createPreservedDaemonHandle(runtimeDir) + } } // Why: a raw socket can outlive a broken or wedged daemon. Kill by PID @@ -264,27 +295,70 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { await killStaleDaemon(runtimeDir, socketPath, tokenPath) const userDataPath = app.getPath('userData') - const child = fork(entryPath, ['--socket', socketPath, '--token', tokenPath], { - // Why: detached daemons can outlive dev worktrees. Starting from - // userData keeps process.cwd() valid after a repo/worktree is deleted. - cwd: userDataPath, - // Why: detached + unref lets the daemon outlive the Electron process. - // stdio 'ignore' prevents the child from holding the parent's stdout - // open, which would prevent Electron from exiting cleanly. - detached: true, - stdio: ['ignore', 'ignore', 'ignore', 'ipc'], - // Why: ELECTRON_RUN_AS_NODE makes the forked process run as a plain - // Node.js process instead of an Electron renderer/main process. Without - // it, Electron's GPU/display initialization can interfere with native - // module operations like node-pty's posix_spawn of the spawn-helper. - env: { - ...process.env, - ELECTRON_RUN_AS_NODE: '1', - // Why: the detached daemon is plain Node and cannot call Electron's - // app.getPath(), but shell-ready rcfiles must live outside swept tmp. - ORCA_USER_DATA_PATH: userDataPath + // Why: on win32 packaged, fork from a copy of the Electron runtime staged + // in userData so the daemon's image + loaded modules escape the install dir + // the NSIS updater deletes and force-closes. Staged here (not at app start) + // so the one-time copy stays off the first-paint path and is skipped on + // launches that adopt a live daemon. Fail-open: null → in-dir host, below. + const relocatedHost = materializeRelocatedDaemonHost() + // Fork the relocated entry when available; otherwise the install-dir entry. + const forkEntryPath = relocatedHost ? relocatedHost.entryPath : entryPath + const child = fork( + forkEntryPath, + ['--socket', socketPath, '--token', tokenPath, ...daemonLogArgs()], + { + // Why: detached daemons can outlive dev worktrees. Starting from + // userData keeps process.cwd() valid after a repo/worktree is deleted. + cwd: userDataPath, + // Why: detached + unref lets the daemon outlive the Electron process. + // stdout stays 'ignore' so the child never holds the parent's stdout + // open (which would block Electron exit); stderr is 'pipe' so a + // module-load crash during startup is captured instead of discarded + // (v1.4.129-rc.1 shipped a daemon that only logged "exited with code 1" + // because stderr was thrown away). The pipe is destroyed on readiness. + detached: true, + stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + // Why: run the relocated Orca.exe copy instead of the install-dir one. + // It is byte-identical, so run-as-node behavior is unchanged; only the + // image path moves out of the updater's kill zone. + ...(relocatedHost ? { execPath: relocatedHost.execPath } : {}), + // Why: ELECTRON_RUN_AS_NODE makes the forked process run as a plain + // Node.js process instead of an Electron renderer/main process. Without + // it, Electron's GPU/display initialization can interfere with native + // module operations like node-pty's posix_spawn of the spawn-helper. + env: { + ...process.env, + ELECTRON_RUN_AS_NODE: '1', + // Why: the detached daemon is plain Node and cannot call Electron's + // app.getPath(), but shell-ready rcfiles must live outside swept tmp. + ORCA_USER_DATA_PATH: userDataPath + } } - }) + ) + + // Why: keep only the startup-window stderr tail so a crash cause is + // visible without unbounded memory if the daemon spews before dying. + const STARTUP_STDERR_MAX_BYTES = 8192 + let startupStderr = '' + let collectingStderr = true + const onStartupStderr = (chunk: Buffer): void => { + if (!collectingStderr) { + return + } + startupStderr += chunk.toString('utf8') + if (startupStderr.length > STARTUP_STDERR_MAX_BYTES) { + startupStderr = startupStderr.slice(-STARTUP_STDERR_MAX_BYTES) + } + } + child.stderr?.on('data', onStartupStderr) + // Why: once the daemon is up (or has failed) the parent must not keep a + // live handle on the detached daemon's stderr — a piped stream would ref + // the parent event loop and prevent Electron from exiting cleanly. + const releaseStderr = (): void => { + collectingStderr = false + child.stderr?.off('data', onStartupStderr) + child.stderr?.destroy() + } // Wait for the daemon to signal readiness via IPC await new Promise((resolve, reject) => { @@ -304,6 +378,14 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { } settled = true cleanupStartupListeners() + // Why: stderr was previously discarded, so a startup crash surfaced only + // as "exited with code 1". Attach the captured tail to the thrown error + // (which the fallback path reports) and log it so the real cause shows. + const stderrTail = startupStderr.trim() + if (stderrTail) { + console.warn(`[daemon] startup failed; captured stderr tail:\n${stderrTail}`) + } + releaseStderr() if (child.pid) { try { process.kill(child.pid, 'SIGTERM') @@ -311,7 +393,9 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { // Already dead } } - reject(error) + reject( + stderrTail ? new Error(`${error.message}\nDaemon stderr (tail):\n${stderrTail}`) : error + ) } function onReadyMessage(msg: unknown): void { if (msg && typeof msg === 'object' && (msg as { type?: string }).type === 'ready') { @@ -327,19 +411,29 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { // killStaleDaemon() can verify the pid still belongs to the daemon // we forked before SIGTERMing it. Prevents pid-recycling hazard // where the OS hands the daemon's old pid to an unrelated process. + // Why the ready-message fallback: Windows has no cheap OS query + // for start time, so the daemon self-reports it — without this the + // recycling guard was permanently inert on win32. + const selfReported = (msg as { startedAtMs?: unknown }).startedAtMs writeFileSync( getDaemonPidPath(runtimeDir), serializeDaemonPidFile({ pid: child.pid, - startedAtMs: getProcessStartedAtMs(child.pid), + startedAtMs: + getProcessStartedAtMs(child.pid) ?? + (typeof selfReported === 'number' && Number.isFinite(selfReported) + ? selfReported + : null), entryPath, appVersion: app.getVersion() }), { mode: 0o600 } ) } - // Why: disconnect IPC channel and unref so Electron can exit - // without waiting for the daemon. The daemon keeps running. + // Why: disconnect IPC channel, release the stderr pipe, and unref so + // Electron can exit without waiting for the daemon. The daemon keeps + // running detached. + releaseStderr() child.disconnect() child.unref() resolve() @@ -398,6 +492,10 @@ export async function initDaemonPtyProvider(signal?: AbortSignal): Promise // throws, a stale spawner would prevent shutdownDaemon() from cleaning up // correctly on retry. const info = await newSpawner.ensureRunning() + // Reclaim superseded daemon-host copies on EVERY launch, not just on a fresh + // spawn: surviving daemons make spawns rare, so a spawn-only sweep would let + // old-version copies accumulate. Current + live-daemon-pinned versions stay. + pruneOldDaemonHosts(collectPinnedDaemonVersions(runtimeDir)) const launchMode = newSpawner.getHandle()?.mode logDaemonMilestone('daemon-current-ready') if (signal?.aborted) { @@ -744,6 +842,21 @@ export async function cleanupDaemonForProtocol( return { cleaned: didRequestShutdown || didKillStaleDaemon, killedCount } } +function legacyDaemonProcessMayBeAlive(runtimeDir: string, protocolVersion: number): boolean { + try { + const parsed = parseDaemonPidFile( + readFileSync(getDaemonPidPath(runtimeDir, protocolVersion), 'utf8') + ) + if (!parsed) { + return false + } + process.kill(parsed.pid, 0) + return true + } catch { + return false + } +} + async function createLegacyDaemonAdapters(runtimeDir: string): Promise { const adapters: DaemonPtyAdapter[] = [] for (const protocolVersion of PREVIOUS_DAEMON_PROTOCOL_VERSIONS) { @@ -753,23 +866,27 @@ async function createLegacyDaemonAdapters(runtimeDir: string): Promise void>> + resume: ReturnType void>> _simulateData: (data: string) => void _simulateExit: (code: number) => void } { @@ -42,11 +46,16 @@ function createMockSubprocess(): SubprocessHandle & { getForegroundProcess: vi.fn(() => null), write: vi.fn(), resize: vi.fn(), + pause: vi.fn<() => void>(), + resume: vi.fn<() => void>(), kill: vi.fn(() => setTimeout(() => onExitCb?.(0), 5)), forceKill: vi.fn(), signal: vi.fn(), onData(cb) { onDataCb = cb + if (dataOnSubscribe) { + cb(dataOnSubscribe) + } }, onExit(cb) { onExitCb = cb @@ -86,8 +95,10 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { env?: Record command?: string } | null + let subprocessDataOnSubscribe: string | undefined beforeEach(async () => { + subprocessDataOnSubscribe = undefined dir = createTestDir() socketPath = getDaemonSocketPath(dir) tokenPath = join(dir, 'test.token') @@ -97,7 +108,7 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { tokenPath, spawnSubprocess: (opts) => { lastSpawnOpts = opts - lastSubprocess = createMockSubprocess() + lastSubprocess = createMockSubprocess(subprocessDataOnSubscribe) return lastSubprocess } }) @@ -179,6 +190,135 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { }) }) + describe('producer flow control', () => { + it('routes pausePty/resumePty notifications to the daemon session subprocess', async () => { + const { id } = await adapter.spawn({ cols: 80, rows: 24 }) + + adapter.pauseProducer(id) + await waitFor(() => lastSubprocess.pause.mock.calls.length > 0) + + adapter.resumeProducer(id) + await waitFor(() => lastSubprocess.resume.mock.calls.length > 0) + }) + + it('sends pause/resume as fire-and-forget notifications on the current protocol', async () => { + const { id } = await adapter.spawn({ cols: 80, rows: 24 }) + const notifySpy = vi.spyOn(DaemonClient.prototype, 'notify') + try { + adapter.pauseProducer(id) + adapter.resumeProducer(id) + expect(notifySpy).toHaveBeenCalledWith('pausePty', { sessionId: id }) + expect(notifySpy).toHaveBeenCalledWith('resumePty', { sessionId: id }) + } finally { + notifySpy.mockRestore() + } + }) + + it('never sends pause/resume notifications on a legacy protocol version', () => { + const notifySpy = vi.spyOn(DaemonClient.prototype, 'notify') + const legacy = new DaemonPtyAdapter({ socketPath, tokenPath, protocolVersion: 18 }) + try { + legacy.pauseProducer('legacy-session') + legacy.resumeProducer('legacy-session') + expect(notifySpy).not.toHaveBeenCalled() + } finally { + legacy.dispose() + notifySpy.mockRestore() + } + }) + + it('owes paused sessions a resumePty on the next connect after a socket drop', async () => { + const { id } = await adapter.spawn({ cols: 80, rows: 24 }) + adapter.pauseProducer(id) + await waitFor(() => lastSubprocess.pause.mock.calls.length > 0) + + // Drop the daemon out from under the adapter: the in-flight pause has no + // matching resume anymore. + await server.shutdown() + await waitFor(() => !(adapter as unknown as { client: DaemonClient }).client.isConnected()) + + server = new DaemonServer({ + socketPath, + tokenPath, + spawnSubprocess: (opts) => { + lastSpawnOpts = opts + lastSubprocess = createMockSubprocess() + return lastSubprocess + } + }) + await server.start() + + const notifySpy = vi.spyOn(DaemonClient.prototype, 'notify') + try { + // Any reconnecting operation must flush the owed resume first. + await adapter.listProcesses() + expect(notifySpy).toHaveBeenCalledWith('resumePty', { sessionId: id }) + } finally { + notifySpy.mockRestore() + } + }) + }) + + describe('background stream thinning compatibility', () => { + it('reports background state on the authoritative-snapshot protocol', () => { + const notifySpy = vi.spyOn(DaemonClient.prototype, 'notify') + try { + adapter.setPtyBackgrounded('current-session', true) + expect(notifySpy).toHaveBeenCalledWith('setSessionBackground', { + sessionId: 'current-session', + background: true + }) + } finally { + notifySpy.mockRestore() + } + }) + + it('keeps preserved v19 sessions unthinned because their snapshots have no sequence', () => { + const notifySpy = vi.spyOn(DaemonClient.prototype, 'notify') + const legacy = new DaemonPtyAdapter({ socketPath, tokenPath, protocolVersion: 19 }) + try { + legacy.setPtyBackgrounded('legacy-session', true) + expect(notifySpy).toHaveBeenCalledWith('setSessionBackground', { + sessionId: 'legacy-session', + background: false + }) + } finally { + legacy.dispose() + notifySpy.mockRestore() + } + }) + + it('clears a preserved v19 background hint before attaching its stream', async () => { + const ensureConnectedSpy = vi + .spyOn(DaemonClient.prototype, 'ensureConnected') + .mockResolvedValue() + const requestSpy = vi.spyOn(DaemonClient.prototype, 'request').mockResolvedValue({ + isNew: true, + pid: null, + shellState: 'unsupported', + snapshot: null + } as never) + const notifySpy = vi.spyOn(DaemonClient.prototype, 'notify') + const legacy = new DaemonPtyAdapter({ socketPath, tokenPath, protocolVersion: 19 }) + try { + await legacy.spawn({ sessionId: 'legacy-session', cols: 80, rows: 24 }) + + expect(notifySpy).toHaveBeenCalledWith('setSessionBackground', { + sessionId: 'legacy-session', + background: false + }) + expect(notifySpy.mock.invocationCallOrder[0]).toBeLessThan( + requestSpy.mock.invocationCallOrder[0] + ) + } finally { + legacy.dispose() + notifySpy.mockRestore() + requestSpy.mockRestore() + ensureConnectedSpy.mockRestore() + } + }) + }) + describe('getAppliedSize', () => { it('reports the spawn dims before any resize', async () => { const { id } = await adapter.spawn({ cols: 80, rows: 24 }) @@ -219,6 +359,23 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { }) }) + describe('getBufferSnapshot', () => { + it('returns the daemon model with its absolute stream sequence', async () => { + const { id } = await adapter.spawn({ cols: 80, rows: 24 }) + lastSubprocess._simulateData('complete hidden output\r\n') + + const snapshot = await adapter.getBufferSnapshot(id, { scrollbackRows: 123 }) + + expect(snapshot).toMatchObject({ + data: expect.stringContaining('complete hidden output'), + cols: 80, + rows: 24, + seq: 'complete hidden output\r\n'.length, + source: 'headless' + }) + }) + }) + describe('shutdown', () => { it('kills the session', async () => { const { id } = await adapter.spawn({ cols: 80, rows: 24 }) @@ -332,9 +489,10 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { describe('spawn with sessionId (reattach)', () => { it('returns full snapshot and isReattach when reattaching', async () => { const sessionId = 'reattach-test-session' - const first = await adapter.spawn({ cols: 80, rows: 24, sessionId }) + const first = await adapter.spawn({ cols: 80, rows: 24, sessionId, launchAgent: 'droid' }) expect(first.id).toBe(sessionId) expect(first.isReattach).toBeUndefined() + expect(first.launchAgent).toBe('droid') // Write data so the headless emulator captures it lastSubprocess._simulateData('hello from shell\r\n') @@ -344,6 +502,7 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { const second = await adapter.spawn({ cols: 80, rows: 24, sessionId }) expect(second.id).toBe(sessionId) expect(second.isReattach).toBe(true) + expect(second.launchAgent).toBe('droid') expect(second.snapshot).toBeDefined() expect(second.snapshot).toContain('hello from shell') }) @@ -878,6 +1037,105 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { } }) + it('checkpoints before keep-history shutdown so sleep can cold restore latest output', async () => { + const adapterClass = DaemonPtyAdapter as unknown as { CHECKPOINT_INTERVAL_MS: number } + const previousInterval = adapterClass.CHECKPOINT_INTERVAL_MS + adapterClass.CHECKPOINT_INTERVAL_MS = 10_000 + + try { + historyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir }) + const { id } = await historyAdapter.spawn({ + cols: 80, + rows: 24, + cwd: '/home/user', + sessionId: 'sleep-checkpoint' + }) + const checkpointSpy = vi.spyOn(historyAdapter.getHistoryManager()!, 'checkpoint') + + lastSubprocess._simulateData('latest before sleep\r\n') + await historyAdapter.shutdown(id, { immediate: true, keepHistory: true }) + + expect(checkpointSpy).toHaveBeenCalledWith( + id, + expect.objectContaining({ snapshotAnsi: expect.stringContaining('latest before sleep') }) + ) + expect(existsSync(join(historyDir, getHistorySessionDirName(id)))).toBe(true) + + const restored = await historyAdapter.spawn({ + cols: 80, + rows: 24, + cwd: '/home/user', + sessionId: id + }) + expect(restored.coldRestore?.scrollback).toContain('latest before sleep') + historyAdapter.ackColdRestore(id) + + const remountAfterAck = await historyAdapter.spawn({ + cols: 80, + rows: 24, + cwd: '/home/user', + sessionId: id + }) + expect(remountAfterAck.coldRestore).toBeUndefined() + } finally { + adapterClass.CHECKPOINT_INTERVAL_MS = previousInterval + } + }) + + it('cold restores the second sleep/wake cycle with post-wake output', async () => { + const adapterClass = DaemonPtyAdapter as unknown as { CHECKPOINT_INTERVAL_MS: number } + const previousInterval = adapterClass.CHECKPOINT_INTERVAL_MS + adapterClass.CHECKPOINT_INTERVAL_MS = 10_000 + + try { + historyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir }) + const { id } = await historyAdapter.spawn({ + cols: 80, + rows: 24, + cwd: '/home/user', + sessionId: 'sleep-wake-cycles' + }) + + lastSubprocess._simulateData('first cycle content\r\n') + await historyAdapter.shutdown(id, { immediate: true, keepHistory: true }) + const metaPath = join(historyDir, getHistorySessionDirName(id), 'meta.json') + const checkpointPath = join(historyDir, getHistorySessionDirName(id), 'checkpoint.json') + // Why: keep-history sleep stays unclean so cold restore remains eligible; + // the final checkpoint is the deterministic handoff signal. + expect(JSON.parse(readFileSync(metaPath, 'utf-8')).endedAt).toBeNull() + expect(JSON.parse(readFileSync(checkpointPath, 'utf-8')).snapshotAnsi).toContain( + 'first cycle content' + ) + + const firstWake = await historyAdapter.spawn({ + cols: 80, + rows: 24, + cwd: '/home/user', + sessionId: id + }) + expect(firstWake.coldRestore?.scrollback).toContain('first cycle content') + historyAdapter.ackColdRestore(id) + expect(historyAdapter.hasPty(id)).toBe(true) + + lastSubprocess._simulateData('second cycle content\r\n') + await historyAdapter.shutdown(id, { immediate: true, keepHistory: true }) + expect(JSON.parse(readFileSync(metaPath, 'utf-8')).endedAt).toBeNull() + expect(JSON.parse(readFileSync(checkpointPath, 'utf-8')).snapshotAnsi).toContain( + 'second cycle content' + ) + + const secondWake = await historyAdapter.spawn({ + cols: 80, + rows: 24, + cwd: '/home/user', + sessionId: id + }) + expect(secondWake.coldRestore?.scrollback).toContain('second cycle content') + } finally { + adapterClass.CHECKPOINT_INTERVAL_MS = previousInterval + } + }) + it('writes meta.json with endedAt on exit', async () => { historyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir }) @@ -938,7 +1196,7 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { expect(existsSync(join(historyDir, getHistorySessionDirName(id)))).toBe(true) }) - it('persists final take records that are not represented in the snapshot', async () => { + itOnPosix('persists final take records that are not represented in the snapshot', async () => { historyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir }) const { id } = await historyAdapter.spawn({ @@ -1335,9 +1593,9 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { expect(result.coldRestore).toBeDefined() expect(result.coldRestore!.scrollback).toContain('raced output') - // Documented race delta: the fresh shell spawns with the renderer's - // requested params, not the recovered ones. - expect(lastSpawnOpts).toMatchObject({ sessionId, cols: 80, rows: 24 }) + // The unseeded race winner is replaced before exposure, so the retained + // shell uses the recovered dimensions as well as the recovered history. + expect(lastSpawnOpts).toMatchObject({ sessionId, cols: 100, rows: 30 }) // The recovery data must survive — openSession would have deleted it. expect(existsSync(join(sessionDir, 'scrollback.bin'))).toBe(true) const internals = historyAdapter as unknown as { @@ -1520,6 +1778,87 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { expect(meta.rows).toBe(24) }) + it('keeps recovered scrollback when the fresh daemon session re-anchors history', async () => { + const sessionId = 'cold-restore-reanchor' + const sessionDir = join(historyDir, getHistorySessionDirName(sessionId)) + mkdirSync(sessionDir, { recursive: true }) + writeFileSync( + join(sessionDir, 'meta.json'), + JSON.stringify({ + cwd: '/tmp', + cols: 80, + rows: 24, + startedAt: '2026-07-10T08:00:00Z', + endedAt: null, + exitCode: null + }) + ) + writeFileSync(join(sessionDir, 'scrollback.bin'), 'recovered marker\r\n') + subprocessDataOnSubscribe = 'fresh shell output\r\n' + historyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir }) + const result = await historyAdapter.spawn({ cols: 80, rows: 24, sessionId }) + expect(result.coldRestore?.scrollback).toContain('recovered marker') + + const internals = historyAdapter as unknown as { + checkpointSessions(sessionIds: Iterable): Promise> + } + await internals.checkpointSessions([sessionId]) + const checkpointPath = join(sessionDir, 'checkpoint.json') + const checkpoint = JSON.parse(readFileSync(checkpointPath, 'utf8')) + + expect(checkpoint.snapshotAnsi).toContain('recovered marker') + expect(checkpoint.snapshotAnsi).toContain('fresh shell output') + expect(checkpoint.snapshotAnsi.indexOf('recovered marker')).toBeLessThan( + checkpoint.snapshotAnsi.indexOf('fresh shell output') + ) + }) + + it('keeps recovery persistence suspended across an adapter restart after seed failure', async () => { + const sessionId = 'cold-restore-seed-failure' + const sessionDir = join(historyDir, getHistorySessionDirName(sessionId)) + mkdirSync(sessionDir, { recursive: true }) + writeFileSync( + join(sessionDir, 'meta.json'), + JSON.stringify({ + cwd: '/tmp', + cols: 80, + rows: 24, + startedAt: '2026-07-10T08:00:00Z', + endedAt: null, + exitCode: null + }) + ) + writeFileSync(join(sessionDir, 'scrollback.bin'), 'recovered marker\r\n') + + const first = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir }) + const originalWriteSync = HeadlessEmulator.prototype.writeSync + const writeSyncSpy = vi + .spyOn(HeadlessEmulator.prototype, 'writeSync') + .mockImplementation(function (this: HeadlessEmulator, data) { + return data.includes('recovered marker') ? false : originalWriteSync.call(this, data) + }) + try { + await first.spawn({ cols: 80, rows: 24, sessionId }) + lastSubprocess._simulateData('fresh-only output\r\n') + await first.disconnectOnly() + + historyAdapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir }) + const result = await historyAdapter.spawn({ cols: 80, rows: 24, sessionId }) + expect(result.coldRestore?.scrollback).toContain('recovered marker') + const internals = historyAdapter as unknown as { + checkpointSessions(sessionIds: Iterable): Promise> + } + await internals.checkpointSessions([sessionId]) + + expect(existsSync(join(sessionDir, 'checkpoint.json'))).toBe(false) + expect(readFileSync(join(sessionDir, 'scrollback.bin'), 'utf8')).toContain( + 'recovered marker' + ) + } finally { + writeSyncSpy.mockRestore() + } + }) + it('does not cold-restore for clean shutdown (endedAt set)', async () => { const sessionId = 'clean-exit' const sessionDir = join(historyDir, getHistorySessionDirName(sessionId)) diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index 56a775a8c992..e0d5ec598ca5 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -21,6 +21,8 @@ import { } from './types' import type { IPtyProvider, + PtyBackgroundStreamEvent, + PtyProviderBufferSnapshot, PtyProcessInfo, PtySpawnOptions, PtySpawnResult @@ -36,6 +38,14 @@ type ColdRestorePayload = { oscLinks?: TerminalOscLinkRange[] } +function getRecoveredHistorySeed(restoreInfo: ColdRestoreInfo): string | null { + // Why: alt-screen snapshots represent the TUI buffer; prefer its normal + // scrollback so a dead TUI is not revived as the fresh shell's active screen. + return restoreInfo.modes.alternateScreen + ? restoreInfo.scrollbackAnsi || restoreInfo.snapshotAnsi || null + : restoreInfo.rehydrateSequences + restoreInfo.snapshotAnsi +} + export type DaemonPtyAdapterOptions = { socketPath: string tokenPath: string @@ -71,8 +81,13 @@ export class DaemonPtyAdapter implements IPtyProvider { // lock, each would fork its own daemon process. This promise coalesces // concurrent respawns so only the first caller forks; the rest await it. private respawnPromise: Promise | null = null - private dataListeners: ((payload: { id: string; data: string }) => void)[] = [] + private dataListeners: ((payload: { + id: string + data: string + sequenceChars?: number + }) => void)[] = [] private exitListeners: ((payload: { id: string; code: number }) => void)[] = [] + private backgroundStreamListeners: ((payload: PtyBackgroundStreamEvent) => void)[] = [] private removeEventListener: (() => void) | null = null private initialCwds = new Map() // Why: React re-renders and StrictMode double-mounts can call createOrAttach @@ -85,6 +100,7 @@ export class DaemonPtyAdapter implements IPtyProvider { // mount → ??? The sticky cache returns the same cold restore data on the // second mount until the renderer explicitly acknowledges it. private coldRestoreCache = new Map() + private sleepRestoreSessionIds = new Set() private activeSessionIds = new Set() private dirtySessionVersions = new Map() // Why: a cold-restored session is a fresh shell whose on-disk checkpoint and @@ -101,6 +117,19 @@ export class DaemonPtyAdapter implements IPtyProvider { // Why: incremental checkpoints require the takePendingOutput RPC (v13+). // Against older daemons the tick falls back to full-snapshot checkpoints. private supportsIncrementalCheckpoints: boolean + // Why: producer pause/resume notifications require v19+; legacy daemons + // must never see them, so gating makes them silent no-ops there. + private supportsProducerFlowControl: boolean + private supportsAuthoritativeBufferSnapshots: boolean + private pausedProducerSessionIds = new Set() + // Why tracked here: the daemon's background set (keep-tail stream thinning + // + transient-fact scan authority) dies with the daemon process/socket; + // re-sync it on a fresh connection so hidden panes stay thinned. + private backgroundedSessionIds = new Set() + // Why: a daemon that survives a socket drop can still hold a pause whose + // resume died with the connection. Owe those sessions a resume on the next + // connect; the daemon's 5s failsafe covers the window in between. + private producerResumesOwedOnReconnect = new Set() private static CHECKPOINT_INTERVAL_MS = 5_000 // Why: a streaming session (build logs, `yes`) re-triggers a full multi-MB // snapshot checkpoint on every 5s tick via pending-buffer overflow or the @@ -125,6 +154,14 @@ export class DaemonPtyAdapter implements IPtyProvider { this.respawnFn = opts.respawn ?? null this.supportsCheckpoints = this.protocolVersion >= 4 this.supportsIncrementalCheckpoints = this.protocolVersion >= 13 + this.supportsProducerFlowControl = this.protocolVersion >= 19 + this.supportsAuthoritativeBufferSnapshots = this.protocolVersion >= 20 + this.client.onDisconnected(() => { + for (const id of this.pausedProducerSessionIds) { + this.producerResumesOwedOnReconnect.add(id) + } + this.pausedProducerSessionIds.clear() + }) } getHistoryManager(): HistoryManager | null { @@ -147,6 +184,12 @@ export class DaemonPtyAdapter implements IPtyProvider { } await this.ensureConnected() + // Why before createOrAttach: a preserved v19 daemon may remember this + // session as backgrounded. Ordered control delivery clears it before any + // newly attached stream bytes can be thinned without a recoverable seq. + if (!this.supportsAuthoritativeBufferSnapshots) { + this.setPtyBackgrounded(sessionId, false) + } // Why: detect crash-recovery history before spawning a replacement PTY so // the revived shell inherits the recovered cwd and dimensions instead of @@ -166,9 +209,9 @@ export class DaemonPtyAdapter implements IPtyProvider { restoreInfo = this.historyReader.detectColdRestore(sessionId) } } - const effectiveCwd = restoreInfo?.cwd ?? opts.cwd - const effectiveCols = restoreInfo?.cols ?? opts.cols - const effectiveRows = restoreInfo?.rows ?? opts.rows + let effectiveCwd = restoreInfo?.cwd ?? opts.cwd + let effectiveCols = restoreInfo?.cols ?? opts.cols + let effectiveRows = restoreInfo?.rows ?? opts.rows const shellReadySupported = opts.command ? supportsPtyStartupBarrier(opts.env ?? {}) : false const isCodexStartupCommand = @@ -184,26 +227,34 @@ export class DaemonPtyAdapter implements IPtyProvider { ? CODEX_SHELL_READY_TIMEOUT_MS : undefined - const result = await this.client.request('createOrAttach', { - sessionId, - cols: effectiveCols, - rows: effectiveRows, - cwd: effectiveCwd, - env: opts.env, - envToDelete: opts.envToDelete, - command: opts.command, - startupCommandDelivery: opts.startupCommandDelivery, - // Why: without this, the daemon always spawns cmd.exe (COMSPEC) or - // PowerShell as a fallback — regardless of which shell the renderer - // asked for in the "+" menu or persisted as the default. Forwarding - // the override makes the daemon path behave the same as the in-process - // LocalPtyProvider. - shellOverride: opts.shellOverride, - terminalWindowsWslDistro: opts.terminalWindowsWslDistro, - terminalWindowsPowerShellImplementation: opts.terminalWindowsPowerShellImplementation, - shellReadySupported, - ...(shellReadyTimeoutMs !== undefined ? { shellReadyTimeoutMs } : {}) - }) + const createOrAttach = (historySeed: string | null) => + this.client.request('createOrAttach', { + sessionId, + cols: effectiveCols, + rows: effectiveRows, + cwd: effectiveCwd, + env: opts.env, + envToDelete: opts.envToDelete, + command: opts.command, + startupCommandDelivery: opts.startupCommandDelivery, + launchAgent: opts.launchAgent, + // Why: without this, the daemon always spawns cmd.exe (COMSPEC) or + // PowerShell as a fallback — regardless of which shell the renderer + // asked for in the "+" menu or persisted as the default. Forwarding + // the override makes the daemon path behave the same as the in-process + // LocalPtyProvider. + shellOverride: opts.shellOverride, + terminalWindowsWslDistro: opts.terminalWindowsWslDistro, + terminalWindowsPowerShellImplementation: opts.terminalWindowsPowerShellImplementation, + shellReadySupported, + ...(shellReadyTimeoutMs !== undefined ? { shellReadyTimeoutMs } : {}), + ...(historySeed ? { historySeed } : {}) + }) + + let scrollback = restoreInfo ? getRecoveredHistorySeed(restoreInfo) : null + let result = await createOrAttach(scrollback) + const launchIdentity = (): { launchAgent?: NonNullable } => + result.launchAgent ? { launchAgent: result.launchAgent } : {} if (effectiveCwd) { this.initialCwds.set(sessionId, effectiveCwd) @@ -212,16 +263,25 @@ export class DaemonPtyAdapter implements IPtyProvider { // Why: the daemon RPC returns the shell pid of the backing subprocess. // Surfacing it through PtySpawnResult lets ipc/pty register with the // memory collector without a provider-specific accessor. - const pid = typeof result.pid === 'number' && result.pid > 0 ? result.pid : null + let pid = typeof result.pid === 'number' && result.pid > 0 ? result.pid : null // Why: check sticky cache first — StrictMode double-mounts call spawn // twice. The second call finds an existing daemon session (isNew=false) // but should still return the cached cold restore data. const cachedRestore = this.coldRestoreCache.get(sessionId) if (cachedRestore) { + // Why: wake after sleep also lands here, and the slept session's active + // tracking and history writer were dropped when sleep killed the PTY. + // Without re-registering both, checkpoints stop after wake and the + // second sleep/wake cycle restores a blank terminal. + this.activeSessionIds.add(sessionId) + if (this.historyManager) { + this.historyManager.reopenSession(sessionId) + } return { id: sessionId, pid, + ...launchIdentity(), coldRestore: cachedRestore, ...(!result.isNew ? { isReattach: true } : {}) } @@ -238,6 +298,21 @@ export class DaemonPtyAdapter implements IPtyProvider { if (result.isNew && restoreSkippedForLiveSession) { restoreInfo = this.historyReader?.detectColdRestore(sessionId, { ignoreCleanEnd: true }) ?? null + scrollback = restoreInfo ? getRecoveredHistorySeed(restoreInfo) : null + if (restoreInfo && scrollback) { + // Why: the aliveness probe raced with session death, so the first + // create lacked recovery bytes. Replace it before exposing the PTY. + await this.client.request('kill', { sessionId, immediate: true }) + effectiveCwd = restoreInfo.cwd + effectiveCols = restoreInfo.cols + effectiveRows = restoreInfo.rows + result = await createOrAttach(scrollback) + pid = typeof result.pid === 'number' && result.pid > 0 ? result.pid : null + this.initialCwds.set(sessionId, effectiveCwd) + } + } else if (!result.isNew && result.historySeeded === false) { + restoreInfo = this.historyReader?.detectColdRestore(sessionId) ?? null + scrollback = restoreInfo ? getRecoveredHistorySeed(restoreInfo) : null } const wasAlreadyManaged = this.activeSessionIds.has(sessionId) @@ -246,35 +321,37 @@ export class DaemonPtyAdapter implements IPtyProvider { // Cold restore: daemon created a new session but disk history shows // an unclean shutdown → return saved scrollback so the renderer can // display the previous terminal content. - if (result.isNew && restoreInfo) { - // Why prefer scrollbackAnsi for alt-screen: snapshotAnsi is the alt buffer - // (vim/less/htop); normal sessions use the full snapshot + rehydrate. - // Why the snapshotAnsi fallback: a hibernated TUI agent (empty scrollback) - // would otherwise get `|| null` → blank pane on wake. snapshotAnsi *alone* - // (no rehydrateSequences — they start with \x1b[?1049h, which the - // renderer's POST_REPLAY_MODE_RESET does NOT undo) lands the last frame as - // normal scrollback. An empty snapshot still yields null → no-op. - const isAltScreen = restoreInfo.modes.alternateScreen - const scrollback = isAltScreen - ? restoreInfo.scrollbackAnsi || restoreInfo.snapshotAnsi || null - : restoreInfo.rehydrateSequences + restoreInfo.snapshotAnsi + if (restoreInfo && (result.isNew || result.historySeeded === false)) { + const coldRestore = this.buildColdRestorePayload(restoreInfo) + const canReanchorHistory = !scrollback || result.historySeeded === true // Why: use registerWriter (not openSession) to avoid deleting the // existing checkpoint.json. If the revived daemon crashes again before // the next 5s tick, the checkpoint is the only recovery data available. if (this.historyManager) { - this.historyManager.registerWriter(sessionId) - this.sessionsNeedingFullCheckpoint.add(sessionId) - // Why: the revived generation has no valid checkpoint of its own; a - // cooldown inherited from the pre-crash generation (daemon respawn - // within one adapter) must not defer this re-anchor. - this.lastFullCheckpointAt.delete(sessionId) + if (canReanchorHistory) { + this.historyManager.registerWriter(sessionId) + this.sessionsNeedingFullCheckpoint.add(sessionId) + // Why: the revived generation has no valid checkpoint of its own; a + // cooldown inherited from the pre-crash generation (daemon respawn + // within one adapter) must not defer this re-anchor. + this.lastFullCheckpointAt.delete(sessionId) + } else { + // Preserve the old recovery files when the new daemon cannot include + // them; a fresh-only checkpoint would make the data loss permanent. + this.historyManager.suspendSession(sessionId) + } } - if (scrollback) { - const coldRestore = { scrollback, cwd: restoreInfo.cwd, oscLinks: restoreInfo.oscLinks } + if (coldRestore) { this.coldRestoreCache.set(sessionId, coldRestore) - return { id: sessionId, pid, coldRestore } + return { + id: sessionId, + pid, + ...launchIdentity(), + coldRestore, + ...(!result.isNew ? { isReattach: true } : {}) + } } - return { id: sessionId, pid } + return { id: sessionId, pid, ...launchIdentity() } } if (this.historyManager && result.isNew) { @@ -285,6 +362,10 @@ export class DaemonPtyAdapter implements IPtyProvider { rows: effectiveRows }) .catch((err) => console.warn('[history] openSession failed:', sessionId, err)) + } else if (this.historyManager && result.historySeeded === false) { + // Why: the daemon keeps this failure bit with the live session, so a new + // adapter cannot promote its fresh-only snapshot after an app restart. + this.historyManager.suspendSession(sessionId) } else if (this.historyManager) { // Why: on warm reattach after app relaunch, the HistoryManager is a // fresh instance with no writers. registerWriter adds the writer @@ -304,24 +385,50 @@ export class DaemonPtyAdapter implements IPtyProvider { const isReattach = !result.isNew if (!isReattach || !result.snapshot) { - return { id: sessionId, pid, ...(isReattach ? { isReattach: true } : {}) } + return { + id: sessionId, + pid, + ...launchIdentity(), + ...(isReattach ? { isReattach: true } : {}) + } } const isAltScreen = result.snapshot.modes.alternateScreen - const snapshotPayload = result.snapshot.rehydrateSequences + result.snapshot.snapshotAnsi + const snapshotPayload = + result.snapshot.scrollbackAnsi + + result.snapshot.rehydrateSequences + + result.snapshot.snapshotAnsi + // Why kitty flags ride beside the payload, not inside it: the snapshot + // string reaches renderer xterms too, where POST_REPLAY_REATTACH_RESET's + // deliberate kitty reset must win. Only the runtime emulator re-seed + // consumes the flags (terminal-query-authority.md §kitty). + const kittyKeyboardFlags = result.snapshot.modes.kittyKeyboardFlags return { id: sessionId, pid, + ...launchIdentity(), snapshot: snapshotPayload, snapshotCols: result.snapshot.cols, snapshotRows: result.snapshot.rows, + ...(typeof kittyKeyboardFlags === 'number' && kittyKeyboardFlags > 0 + ? { snapshotKittyKeyboardFlags: kittyKeyboardFlags } + : {}), isReattach: true, - isAlternateScreen: isAltScreen + isAlternateScreen: isAltScreen, + // Why: carry the mid-escape tail so the renderer can write it after the + // reattach reset — without it the local daemon reattach path renders a + // split escape's continuation literally, unlike the remote path (#7329). + ...(result.snapshot.pendingEscapeTailAnsi + ? { pendingEscapeTailAnsi: result.snapshot.pendingEscapeTailAnsi } + : {}) } } async attach(id: string): Promise { await this.ensureConnected() + if (!this.supportsAuthoritativeBufferSnapshots) { + this.setPtyBackgrounded(id, false) + } await this.client.request('createOrAttach', { sessionId: id, @@ -344,16 +451,62 @@ export class DaemonPtyAdapter implements IPtyProvider { this.client.notify('resize', { sessionId: id, cols, rows }) } + pauseProducer(id: string): void { + if (!this.supportsProducerFlowControl) { + return + } + this.pausedProducerSessionIds.add(id) + this.client.notify('pausePty', { sessionId: id }) + } + + resumeProducer(id: string): void { + this.producerResumesOwedOnReconnect.delete(id) + if (!this.supportsProducerFlowControl) { + return + } + this.pausedProducerSessionIds.delete(id) + this.client.notify('resumePty', { sessionId: id }) + } + + // Why fire-and-forget (like pausePty): a delivery hint for the daemon's + // keep-tail stream thinning. + setPtyBackgrounded(id: string, background: boolean): void { + if (!this.supportsProducerFlowControl) { + return + } + // Why: preserved v19 daemons can thin but cannot return the absolute + // snapshot sequence needed to recover a gap. Clear their stale hint too. + const safeBackground = this.supportsAuthoritativeBufferSnapshots && background + if (safeBackground) { + this.backgroundedSessionIds.add(id) + } else { + this.backgroundedSessionIds.delete(id) + } + this.client.notify('setSessionBackground', { sessionId: id, background: safeBackground }) + } + async shutdown(id: string, opts: { immediate?: boolean; keepHistory?: boolean }): Promise { - // Why: sleep/exact-stop must preserve restorable terminal history, - // so force a final checkpoint before killing the daemon session. + // Why: sleep/exact-stop kills the live PTY before the periodic checkpoint may run. + // Force a final snapshot so wake can restore the pane users left. if (opts.keepHistory) { + if (this.checkpointInFlight) { + await this.checkpointInFlight + } await this.checkpointSessions([id], { final: true, teardown: true }) + const restoreInfo = this.historyReader?.detectColdRestore(id) ?? null + const coldRestore = restoreInfo ? this.buildColdRestorePayload(restoreInfo) : null + if (coldRestore) { + this.coldRestoreCache.set(id, coldRestore) + this.sleepRestoreSessionIds.add(id) + } } await this.client.request('kill', { sessionId: id, immediate: opts.immediate ?? false }) this.activeSessionIds.delete(id) this.dirtySessionVersions.delete(id) - this.coldRestoreCache.delete(id) + if (!opts.keepHistory) { + this.coldRestoreCache.delete(id) + this.sleepRestoreSessionIds.delete(id) + } // Why: the !keepHistory close path doesn't take a final checkpoint, so a // session stranded in sessionsNeedingFullCheckpoint would never be cleared. // (Under keepHistory the final checkpoint above already cleared the flag, so @@ -389,12 +542,30 @@ export class DaemonPtyAdapter implements IPtyProvider { ackColdRestore(sessionId: string): void { this.coldRestoreCache.delete(sessionId) + this.sleepRestoreSessionIds.delete(sessionId) } clearTombstone(sessionId: string): void { this.killedSessionTombstones.delete(sessionId) } + private buildColdRestorePayload(restoreInfo: ColdRestoreInfo): ColdRestorePayload | null { + // Why prefer scrollbackAnsi for alt-screen: snapshotAnsi is the alt buffer + // (vim/less/htop); normal sessions use the full snapshot + rehydrate. + // Why the snapshotAnsi fallback: a hibernated TUI agent (empty scrollback) + // would otherwise get `|| null` → blank pane on wake. snapshotAnsi *alone* + // (no rehydrateSequences — they start with \x1b[?1049h, which the + // renderer's POST_REPLAY_MODE_RESET does NOT undo) lands the last frame as + // normal scrollback. An empty snapshot still yields null → no-op. + const scrollback = restoreInfo.modes.alternateScreen + ? restoreInfo.scrollbackAnsi || restoreInfo.snapshotAnsi || null + : restoreInfo.rehydrateSequences + restoreInfo.snapshotAnsi + if (!scrollback) { + return null + } + return { scrollback, cwd: restoreInfo.cwd, oscLinks: restoreInfo.oscLinks } + } + async sendSignal(id: string, signal: string): Promise { await this.client.request('signal', { sessionId: id, signal }) } @@ -432,6 +603,44 @@ export class DaemonPtyAdapter implements IPtyProvider { } } + async getBufferSnapshot( + id: string, + opts: { scrollbackRows?: number } = {} + ): Promise { + if (!this.supportsAuthoritativeBufferSnapshots) { + return null + } + try { + const result = await this.client.request('getSnapshot', { + sessionId: id, + ...(typeof opts.scrollbackRows === 'number' ? { scrollbackRows: opts.scrollbackRows } : {}) + }) + const snapshot = result.snapshot + // Why: older v19 daemons have no absolute output sequence. Their snapshot + // cannot safely reconcile stream bytes still queued on the other socket. + if (!snapshot || typeof snapshot.outputSequence !== 'number') { + return null + } + return { + data: snapshot.rehydrateSequences + snapshot.snapshotAnsi, + scrollbackAnsi: snapshot.scrollbackAnsi, + cols: snapshot.cols, + rows: snapshot.rows, + cwd: snapshot.cwd, + lastTitle: snapshot.lastTitle, + seq: snapshot.outputSequence, + source: 'headless', + oscLinks: snapshot.oscLinks, + alternateScreen: snapshot.modes.alternateScreen, + ...(snapshot.pendingEscapeTailAnsi + ? { pendingEscapeTailAnsi: snapshot.pendingEscapeTailAnsi } + : {}) + } + } catch { + return null + } + } + async clearBuffer(id: string): Promise { await this.client.request('clearScrollback', { sessionId: id }) this.markSessionDirty(id) @@ -460,6 +669,18 @@ export class DaemonPtyAdapter implements IPtyProvider { } } + async confirmForegroundProcess(id: string): Promise { + try { + const result = await this.client.request<{ foregroundProcess: string | null }>( + 'confirmForegroundProcess', + { sessionId: id } + ) + return result.foregroundProcess + } catch { + return null + } + } + async serialize(ids: string[]): Promise { const sessions: Record = {} for (const id of ids) { @@ -562,6 +783,8 @@ export class DaemonPtyAdapter implements IPtyProvider { this.dirtySessionVersions.clear() this.lastFullCheckpointAt.clear() this.sessionsNeedingFullCheckpoint.clear() + this.pausedProducerSessionIds.clear() + this.producerResumesOwedOnReconnect.clear() this.stopCheckpointTimer() for (const id of ids) { this.coldRestoreCache.delete(id) @@ -594,7 +817,9 @@ export class DaemonPtyAdapter implements IPtyProvider { return shells.filter((s) => existsSync(s)).map((s) => ({ name: basename(s), path: s })) } - onData(callback: (payload: { id: string; data: string }) => void): () => void { + onData( + callback: (payload: { id: string; data: string; sequenceChars?: number }) => void + ): () => void { this.dataListeners.push(callback) return () => { const idx = this.dataListeners.indexOf(callback) @@ -604,6 +829,16 @@ export class DaemonPtyAdapter implements IPtyProvider { } } + onBackgroundStreamEvent(callback: (payload: PtyBackgroundStreamEvent) => void): () => void { + this.backgroundStreamListeners.push(callback) + return () => { + const idx = this.backgroundStreamListeners.indexOf(callback) + if (idx !== -1) { + this.backgroundStreamListeners.splice(idx, 1) + } + } + } + onReplay(_callback: (payload: { id: string; data: string }) => void): () => void { return () => {} } @@ -623,6 +858,8 @@ export class DaemonPtyAdapter implements IPtyProvider { this.dirtySessionVersions.clear() this.lastFullCheckpointAt.clear() this.coldRestoreCache.clear() + this.pausedProducerSessionIds.clear() + this.producerResumesOwedOnReconnect.clear() this.removeEventListener?.() this.removeEventListener = null // Why: final checkpoints are written daemon-side in TerminalHost.dispose() @@ -659,6 +896,13 @@ export class DaemonPtyAdapter implements IPtyProvider { this.dirtySessionVersions.clear() this.lastFullCheckpointAt.clear() this.coldRestoreCache.clear() + // Why: the detached daemon keeps these PTYs alive for warm reattach; a + // pause left behind would block their shells for a failsafe window. + for (const id of this.pausedProducerSessionIds) { + this.client.notify('resumePty', { sessionId: id }) + } + this.pausedProducerSessionIds.clear() + this.producerResumesOwedOnReconnect.clear() this.removeEventListener?.() this.removeEventListener = null this.client.disconnect() @@ -666,8 +910,36 @@ export class DaemonPtyAdapter implements IPtyProvider { private async ensureConnected(): Promise { await this.client.ensureConnected() + // Why sampled before setupEventRouting: routing is (re)installed exactly + // once per connection, so "no listener yet" identifies a fresh connect — + // the only time the daemon-side backgrounded set needs a resync (it is + // process state that died with the previous daemon/socket). + const isFreshConnection = this.removeEventListener === null this.setupEventRouting() this.scheduleCheckpointTimer() + this.flushOwedProducerResumes() + if (isFreshConnection) { + this.resyncBackgroundedSessions() + } + } + + private resyncBackgroundedSessions(): void { + for (const id of this.backgroundedSessionIds) { + // Harmless no-op for sessions the daemon doesn't know (yet). + this.client.notify('setSessionBackground', { sessionId: id, background: true }) + } + } + + private flushOwedProducerResumes(): void { + if (this.producerResumesOwedOnReconnect.size === 0) { + return + } + for (const id of this.producerResumesOwedOnReconnect) { + // Why: resuming a session the fresh daemon doesn't know is a harmless + // no-op; leaving a survivor paused would waste 5s of failsafe latency. + this.client.notify('resumePty', { sessionId: id }) + } + this.producerResumesOwedOnReconnect.clear() } private stopCheckpointTimer(): void { @@ -981,6 +1253,13 @@ export class DaemonPtyAdapter implements IPtyProvider { } } + private emitBackgroundStreamEvent(payload: PtyBackgroundStreamEvent): void { + // oxlint-disable-next-line unicorn/no-useless-spread -- copy-safe: listeners may unsubscribe during iteration + for (const listener of [...this.backgroundStreamListeners]) { + listener(payload) + } + } + private async doRespawn(message = '[daemon] Daemon died — respawning'): Promise { console.warn(message) this.removeEventListener?.() @@ -1004,12 +1283,50 @@ export class DaemonPtyAdapter implements IPtyProvider { this.markSessionDirty(event.sessionId) // oxlint-disable-next-line unicorn/no-useless-spread -- copy-safe: listeners may unsubscribe during iteration for (const listener of [...this.dataListeners]) { - listener({ id: event.sessionId, data: event.payload.data }) + listener({ + id: event.sessionId, + data: event.payload.data, + ...(event.payload.sequenceChars === undefined + ? {} + : { sequenceChars: event.payload.sequenceChars }) + }) } + } else if (event.event === 'sessionBackgroundMarker') { + this.emitBackgroundStreamEvent({ + id: event.sessionId, + kind: 'backgroundMarker', + background: event.payload.background, + ...(event.payload.scanSeedAnsi !== undefined + ? { scanSeedAnsi: event.payload.scanSeedAnsi } + : {}) + }) + } else if (event.event === 'dataGap') { + this.emitBackgroundStreamEvent({ + id: event.sessionId, + kind: 'dataGap', + droppedChars: event.payload.droppedChars, + ...(event.payload.sequenceChars === undefined + ? {} + : { sequenceChars: event.payload.sequenceChars }) + }) + } else if (event.event === 'transientFact') { + this.emitBackgroundStreamEvent({ + id: event.sessionId, + kind: 'transientFact', + fact: event.payload + }) } else if (event.event === 'exit') { this.activeSessionIds.delete(event.sessionId) this.dirtySessionVersions.delete(event.sessionId) - this.coldRestoreCache.delete(event.sessionId) + // Why: an exited session must not be owed a resume on reconnect — a + // reused sessionId would receive a stray resumePty. Same for the + // background set: a reused id must start un-thinned. + this.pausedProducerSessionIds.delete(event.sessionId) + this.producerResumesOwedOnReconnect.delete(event.sessionId) + this.backgroundedSessionIds.delete(event.sessionId) + if (!this.sleepRestoreSessionIds.has(event.sessionId)) { + this.coldRestoreCache.delete(event.sessionId) + } // Why: an exited session can never be checkpointed again, so its pending // full-checkpoint flag is dead state. Without this, a cold-restored // session that exits before its first checkpoint leaks a permanent entry. diff --git a/src/main/daemon/daemon-pty-router.test.ts b/src/main/daemon/daemon-pty-router.test.ts index 47d44aa807c3..eb8acb86488f 100644 --- a/src/main/daemon/daemon-pty-router.test.ts +++ b/src/main/daemon/daemon-pty-router.test.ts @@ -1,10 +1,11 @@ import { describe, expect, it, vi } from 'vitest' import { DaemonPtyRouter } from './daemon-pty-router' import type { DaemonPtyAdapter } from './daemon-pty-adapter' -import type { PtySpawnOptions, PtySpawnResult } from '../providers/types' +import type { PtyBackgroundStreamEvent, PtySpawnOptions, PtySpawnResult } from '../providers/types' type AdapterMock = DaemonPtyAdapter & { - emitData: (id: string, data: string) => void + emitData: (id: string, data: string, sequenceChars?: number) => void + emitBackground: (event: PtyBackgroundStreamEvent) => void emitExit: (id: string, code: number) => void } @@ -24,7 +25,9 @@ function createAdapter( reconcileResult?: { alive: string[]; killed: string[] } ): AdapterMock { const writes: { id: string; data: string }[] = [] - const dataListeners: ((payload: { id: string; data: string }) => void)[] = [] + const dataListeners: ((payload: { id: string; data: string; sequenceChars?: number }) => void)[] = + [] + const backgroundListeners: ((payload: PtyBackgroundStreamEvent) => void)[] = [] const exitListeners: ((payload: { id: string; code: number }) => void)[] = [] return { spawn: vi.fn(async (opts: PtySpawnOptions): Promise => { @@ -44,6 +47,8 @@ function createAdapter( writes.push({ id, data }) }), resize: vi.fn(), + setPtyBackgrounded: vi.fn(), + getBufferSnapshot: vi.fn(async () => null), shutdown: vi.fn(async (id: string) => { const idx = sessions.indexOf(id) if (idx !== -1) { @@ -58,16 +63,28 @@ function createAdapter( acknowledgeDataEvent: vi.fn(), hasChildProcesses: vi.fn(async () => false), getForegroundProcess: vi.fn(async () => null), + confirmForegroundProcess: vi.fn(async () => `${label}-confirmed`), serialize: vi.fn(async () => '{}'), revive: vi.fn(async () => {}), getDefaultShell: vi.fn(async () => '/bin/zsh'), getProfiles: vi.fn(async () => []), - onData: vi.fn((callback: (payload: { id: string; data: string }) => void) => { - dataListeners.push(callback) + onData: vi.fn( + (callback: (payload: { id: string; data: string; sequenceChars?: number }) => void) => { + dataListeners.push(callback) + return () => { + const idx = dataListeners.indexOf(callback) + if (idx !== -1) { + dataListeners.splice(idx, 1) + } + } + } + ), + onBackgroundStreamEvent: vi.fn((callback: (payload: PtyBackgroundStreamEvent) => void) => { + backgroundListeners.push(callback) return () => { - const idx = dataListeners.indexOf(callback) + const idx = backgroundListeners.indexOf(callback) if (idx !== -1) { - dataListeners.splice(idx, 1) + backgroundListeners.splice(idx, 1) } } }), @@ -85,9 +102,14 @@ function createAdapter( reconcileOnStartup: vi.fn(async () => reconcileResult ?? { alive: sessions, killed: [] }), dispose: vi.fn(), disconnectOnly: vi.fn(async () => {}), - emitData: (id: string, data: string) => { + emitData: (id: string, data: string, sequenceChars?: number) => { for (const listener of dataListeners) { - listener({ id, data }) + listener({ id, data, ...(sequenceChars === undefined ? {} : { sequenceChars }) }) + } + }, + emitBackground: (event: PtyBackgroundStreamEvent) => { + for (const listener of backgroundListeners) { + listener(event) } }, emitExit: (id: string, code: number) => { @@ -100,6 +122,22 @@ function createAdapter( } describe('DaemonPtyRouter', () => { + it('routes fresh foreground confirmation to the session-owning daemon', async () => { + const current = createAdapter('current', ['current-session']) + const legacy = createAdapter('legacy', ['legacy-session']) + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + await router.discoverLegacySessions() + + await expect(router.confirmForegroundProcess('legacy-session')).resolves.toBe( + 'legacy-confirmed' + ) + await expect(router.confirmForegroundProcess('current-session')).resolves.toBe( + 'current-confirmed' + ) + expect(legacy.confirmForegroundProcess).toHaveBeenCalledWith('legacy-session') + expect(current.confirmForegroundProcess).toHaveBeenCalledWith('current-session') + }) + it('routes existing legacy sessions to their old daemon and new sessions to current daemon', async () => { const current = createAdapter('current') const legacy = createAdapter('legacy', ['legacy-session']) @@ -118,6 +156,62 @@ describe('DaemonPtyRouter', () => { expect(current.write).toHaveBeenCalledWith(fresh.id, 'new\n') }) + it('routes background hints and authoritative snapshots to the session owner', async () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy', ['legacy-session']) + const snapshot = { + data: 'legacy frame', + cols: 80, + rows: 24, + seq: 42, + source: 'headless' as const + } + vi.mocked(legacy.getBufferSnapshot).mockResolvedValue(snapshot) + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + await router.discoverLegacySessions() + + router.setPtyBackgrounded('legacy-session', true) + await expect( + router.getBufferSnapshot('legacy-session', { scrollbackRows: 50_000 }) + ).resolves.toEqual(snapshot) + + expect(legacy.setPtyBackgrounded).toHaveBeenCalledWith('legacy-session', true) + expect(current.setPtyBackgrounded).not.toHaveBeenCalled() + expect(legacy.getBufferSnapshot).toHaveBeenCalledWith('legacy-session', { + scrollbackRows: 50_000 + }) + }) + + it('forwards gap events and explicit sequence accounting from every adapter', () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy') + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + const dataSpy = vi.fn() + const backgroundSpy = vi.fn() + router.onData(dataSpy) + router.onBackgroundStreamEvent(backgroundSpy) + + current.emitData('current-session', '\x1b[6n', 0) + legacy.emitBackground({ + id: 'legacy-session', + kind: 'dataGap', + droppedChars: 512, + sequenceChars: 508 + }) + + expect(dataSpy).toHaveBeenCalledWith({ + id: 'current-session', + data: '\x1b[6n', + sequenceChars: 0 + }) + expect(backgroundSpy).toHaveBeenCalledWith({ + id: 'legacy-session', + kind: 'dataGap', + droppedChars: 512, + sequenceChars: 508 + }) + }) + it('drops a legacy mapping after the routed session exits', async () => { const current = createAdapter('current') const legacy = createAdapter('legacy', ['legacy-session']) diff --git a/src/main/daemon/daemon-pty-router.ts b/src/main/daemon/daemon-pty-router.ts index 1f80f770cd9a..18bf0f926b59 100644 --- a/src/main/daemon/daemon-pty-router.ts +++ b/src/main/daemon/daemon-pty-router.ts @@ -1,6 +1,8 @@ import type { DaemonPtyAdapter } from './daemon-pty-adapter' import type { IPtyProvider, + PtyBackgroundStreamEvent, + PtyProviderBufferSnapshot, PtyProcessInfo, PtySpawnOptions, PtySpawnResult @@ -11,7 +13,11 @@ export class DaemonPtyRouter implements IPtyProvider { private legacy: DaemonPtyAdapter[] private sessionAdapters = new Map() private unsubscribers: (() => void)[] = [] - private dataListeners: ((payload: { id: string; data: string }) => void)[] = [] + private dataListeners: ((payload: { + id: string + data: string + sequenceChars?: number + }) => void)[] = [] private exitListeners: ((payload: { id: string; code: number }) => void)[] = [] constructor(opts: { current: DaemonPtyAdapter; legacy: DaemonPtyAdapter[] }) { @@ -76,6 +82,18 @@ export class DaemonPtyRouter implements IPtyProvider { this.adapterFor(id).resize(id, cols, rows) } + pauseProducer(id: string): void { + this.adapterFor(id).pauseProducer(id) + } + + resumeProducer(id: string): void { + this.adapterFor(id).resumeProducer(id) + } + + setPtyBackgrounded(id: string, background: boolean): void { + this.adapterFor(id).setPtyBackgrounded(id, background) + } + async shutdown(id: string, opts: { immediate?: boolean; keepHistory?: boolean }): Promise { await this.adapterFor(id).shutdown(id, opts) // Why: sleep passes keepHistory=true and re-spawns against the same @@ -105,6 +123,13 @@ export class DaemonPtyRouter implements IPtyProvider { return (await this.adapterFor(id).getAppliedSize?.(id)) ?? null } + async getBufferSnapshot( + id: string, + opts?: { scrollbackRows?: number } + ): Promise { + return await this.adapterFor(id).getBufferSnapshot(id, opts) + } + async clearBuffer(id: string): Promise { await this.adapterFor(id).clearBuffer(id) } @@ -121,6 +146,10 @@ export class DaemonPtyRouter implements IPtyProvider { return this.adapterFor(id).getForegroundProcess(id) } + async confirmForegroundProcess(id: string): Promise { + return this.adapterFor(id).confirmForegroundProcess(id) + } + async serialize(ids: string[]): Promise { return this.current.serialize(ids) } @@ -144,7 +173,9 @@ export class DaemonPtyRouter implements IPtyProvider { return this.current.getProfiles() } - onData(callback: (payload: { id: string; data: string }) => void): () => void { + onData( + callback: (payload: { id: string; data: string; sequenceChars?: number }) => void + ): () => void { this.dataListeners.push(callback) return () => { const idx = this.dataListeners.indexOf(callback) @@ -154,6 +185,17 @@ export class DaemonPtyRouter implements IPtyProvider { } } + onBackgroundStreamEvent(callback: (payload: PtyBackgroundStreamEvent) => void): () => void { + const unsubscribes = this.allAdapters().map((adapter) => + adapter.onBackgroundStreamEvent(callback) + ) + return () => { + for (const unsubscribe of unsubscribes) { + unsubscribe() + } + } + } + onReplay(_callback: (payload: { id: string; data: string }) => void): () => void { return () => {} } diff --git a/src/main/daemon/daemon-server.test.ts b/src/main/daemon/daemon-server.test.ts index ae017e0ef028..3760ee89de29 100644 --- a/src/main/daemon/daemon-server.test.ts +++ b/src/main/daemon/daemon-server.test.ts @@ -10,6 +10,8 @@ import { PROTOCOL_VERSION, type DaemonRequest } from './types' import type { SubprocessHandle } from './session' import { getDaemonSocketPath } from './daemon-spawner' +const confirmForegroundProcessMock = vi.fn(async () => 'droid') + function createTestDir(): string { return mkdtempSync(join(tmpdir(), 'daemon-server-test-')) } @@ -23,6 +25,7 @@ function createMockSubprocess(): SubprocessHandle & { return { pid: 55555, getForegroundProcess: vi.fn(() => null), + confirmForegroundProcess: confirmForegroundProcessMock, write: vi.fn(), resize: vi.fn(), kill: vi.fn(() => setTimeout(() => onExitCb?.(0), 5)), @@ -65,6 +68,7 @@ describe('DaemonServer', () => { let client: DaemonClient beforeEach(() => { + confirmForegroundProcessMock.mockClear() dir = createTestDir() socketPath = getDaemonSocketPath(dir) tokenPath = join(dir, 'test.token') @@ -174,6 +178,34 @@ describe('DaemonServer', () => { }) }) + it('persists only an allowlisted launch identity across reattach', async () => { + await startServer() + const c = await connectClient() + + const first = await c.request('createOrAttach', { + sessionId: 'agent-session', + cols: 80, + rows: 24, + launchAgent: 'droid' + }) + expect(first).toMatchObject({ isNew: true, launchAgent: 'droid' }) + + const second = await c.request('createOrAttach', { + sessionId: 'agent-session', + cols: 80, + rows: 24 + }) + expect(second).toMatchObject({ isNew: false, launchAgent: 'droid' }) + + const unknown = await c.request('createOrAttach', { + sessionId: 'unknown-agent-session', + cols: 80, + rows: 24, + launchAgent: 'not-an-agent' + } as never) + expect(unknown).not.toHaveProperty('launchAgent') + }) + it('handles listSessions', async () => { await startServer() const c = await connectClient() @@ -279,6 +311,19 @@ describe('DaemonServer', () => { expect(result.cwd === null || typeof result.cwd === 'string').toBe(true) }) + it('awaits fresh foreground confirmation', async () => { + await startServer() + const c = await connectClient() + await c.request('createOrAttach', { sessionId: 'test-session', cols: 80, rows: 24 }) + + await expect( + c.request<{ foregroundProcess: string | null }>('confirmForegroundProcess', { + sessionId: 'test-session' + }) + ).resolves.toEqual({ foregroundProcess: 'droid' }) + expect(confirmForegroundProcessMock).toHaveBeenCalledTimes(1) + }) + it('returns error for unknown session operations', async () => { await startServer() const c = await connectClient() @@ -408,6 +453,72 @@ describe('DaemonServer', () => { vi.useRealTimers() } }) + + it('keeps exit behind final output held by the shallow socket gate', async () => { + vi.useFakeTimers() + try { + let subprocess: ReturnType + server = new DaemonServer({ + socketPath, + tokenPath, + spawnSubprocess: () => { + subprocess = createMockSubprocess() + return subprocess + } + }) + const daemon = server as unknown as DaemonServerPrivate + const refillCallbacks: (() => void)[] = [] + const controlSocket = { destroy: vi.fn() } as unknown as Socket + const streamSocket = { + destroyed: false, + destroy: vi.fn(), + writableLength: 128 * 1024, + write: vi.fn((_line: string, callback?: () => void) => { + if (callback) { + refillCallbacks.push(callback) + } + return true + }) + } as unknown as Socket & { + write: ReturnType + writableLength: number + } + + daemon.clients.set('client-1', { + clientId: 'client-1', + controlSocket, + streamSocket + }) + await daemon.routeRequest('client-1', { + id: 'req-1', + type: 'createOrAttach', + payload: { sessionId: 'test-session', cols: 80, rows: 24 } + }) + + const finalOutput = 'final-output'.repeat(1024) + subprocess!._simulateData(finalOutput) + subprocess!._simulateExit(42) + + // Only the refill sentinel may enter the already-deep socket; exit + // remains queued behind the final data for this session. + expect(refillCallbacks).toHaveLength(1) + const beforeRefill = streamSocket.write.mock.calls.map(([line]) => JSON.parse(String(line))) + expect(beforeRefill).toHaveLength(1) + expect(beforeRefill[0]).toMatchObject({ event: 'data', payload: { data: '' } }) + + streamSocket.writableLength = 0 + refillCallbacks[0]() + const delivered = streamSocket.write.mock.calls + .map( + ([line]) => JSON.parse(String(line)) as { event: string; payload: { data?: string } } + ) + .filter((message) => message.payload.data !== '') + expect(delivered.map((message) => message.event)).toEqual(['data', 'exit']) + expect(delivered[0]?.payload.data).toBe(finalOutput) + } finally { + vi.useRealTimers() + } + }) }) describe('authentication', () => { diff --git a/src/main/daemon/daemon-server.ts b/src/main/daemon/daemon-server.ts index 3dc1c648f0b9..fe87022e5c51 100644 --- a/src/main/daemon/daemon-server.ts +++ b/src/main/daemon/daemon-server.ts @@ -9,9 +9,20 @@ import { StringDecoder } from 'node:string_decoder' import { encodeNdjson, createNdjsonParser } from './ndjson' import { TerminalHost } from './terminal-host' import { DaemonStreamDataBatcher } from './daemon-stream-data-batcher' +import { + BackgroundTransientFactRelay, + BACKGROUND_STREAM_DROP_ENABLED +} from './daemon-background-transient-facts' +import { extractHiddenStartupRendererQueryData } from '../../shared/terminal-reply-query-extraction' +import { + recordDaemonStreamBacklogEvent, + startDaemonStreamBacklogProbe +} from './daemon-stream-backlog-probe' import { readCurrentProcessMacSystemResolverHealth } from '../network/macos-system-resolver-health' import type { SubprocessHandle } from './session' import { checkPtySpawnHealth } from './pty-subprocess' +import { createNoopDaemonFileLog, type DaemonFileLog } from './daemon-file-log' +import { isTuiAgent } from '../../shared/tui-agent-config' import { PROTOCOL_VERSION, NOTIFY_PREFIX, @@ -24,6 +35,7 @@ export type DaemonServerOptions = { socketPath: string tokenPath: string ptySpawnHealthCheck?: () => Promise + log?: DaemonFileLog spawnSubprocess: (opts: { sessionId: string cols: number @@ -48,10 +60,43 @@ export class DaemonServer { private socketPath: string private tokenPath: string private ptySpawnHealthCheck: () => Promise + private log: DaemonFileLog private clients = new Map() - private streamDataBatcher = new DaemonStreamDataBatcher((clientId) => this.clients.get(clientId)) + private streamDataBatcher = new DaemonStreamDataBatcher( + (clientId) => this.clients.get(clientId), + { + isSessionDroppable: (sessionId) => + BACKGROUND_STREAM_DROP_ENABLED && this.transientFactRelay.isBackgrounded(sessionId), + salvageDroppedData: (dropped) => { + if (!dropped.includes('\x1b')) { + return '' + } + const extracted = extractHiddenStartupRendererQueryData(dropped, '') + return ( + extracted.statelessQueryData + extracted.statefulQueryData + extracted.oscColorQueryData + ) + } + } + ) + // Fact scan authority for backgrounded sessions — facts ride the stream + // queue as control entries so they hold byte order with the data around + // them (a fact jumping the queue could arrive after the reveal snapshot + // that already reflects it). + private transientFactRelay = new BackgroundTransientFactRelay((sessionId, fact) => { + const clientId = this.streamClientIdBySessionId.get(sessionId) + if (clientId) { + this.streamDataBatcher.enqueueControlEvent(clientId, sessionId, { + type: 'event', + event: 'transientFact', + sessionId, + payload: fact + }) + } + }) + private streamClientIdBySessionId = new Map() private lastInputAtBySessionId = new Map() + private stopStreamBacklogProbe: () => void = () => {} // Why: main-process PTY IPC has the same recent-input bypass, but daemon // output reaches main only after this stream layer. Keeping the window here @@ -66,6 +111,15 @@ export class DaemonServer { this.token = randomUUID() this.host = new TerminalHost({ spawnSubprocess: opts.spawnSubprocess }) this.ptySpawnHealthCheck = opts.ptySpawnHealthCheck ?? checkPtySpawnHealth + this.stopStreamBacklogProbe = startDaemonStreamBacklogProbe(() => ({ + clients: Array.from(this.clients.values(), (client) => ({ + clientId: client.clientId, + socketBufferedBytes: client.streamSocket?.writableLength ?? 0, + batcherQueuedChars: this.streamDataBatcher.queuedCharsForClient(client.clientId) + })), + backgroundedSessionIdSuffixes: this.transientFactRelay.backgroundedSessionIdSuffixes() + })) + this.log = opts.log ?? createNoopDaemonFileLog() } async start(): Promise { @@ -93,6 +147,8 @@ export class DaemonServer { } async shutdown(): Promise { + this.stopStreamBacklogProbe() + this.transientFactRelay.dispose() this.host.dispose() this.streamDataBatcher.clear() @@ -139,23 +195,30 @@ export class DaemonServer { ): void { const hello = msg as HelloMessage if (hello.type !== 'hello') { + this.log.log('client-hello-rejected', { reason: 'expected-hello' }) socket.write(encodeNdjson({ type: 'hello', ok: false, error: 'Expected hello' })) socket.destroy() return } if (hello.version !== PROTOCOL_VERSION) { + this.log.log('client-hello-rejected', { + reason: 'protocol-mismatch', + clientVersion: hello.version + }) socket.write(encodeNdjson({ type: 'hello', ok: false, error: 'Protocol version mismatch' })) socket.destroy() return } if (hello.token !== this.token) { + this.log.log('client-hello-rejected', { reason: 'invalid-token', role: hello.role }) socket.write(encodeNdjson({ type: 'hello', ok: false, error: 'Invalid token' })) socket.destroy() return } + this.log.log('client-hello-accepted', { role: hello.role, clientId: hello.clientId }) socket.write(encodeNdjson({ type: 'hello', ok: true })) if (hello.role === 'control') { @@ -214,6 +277,10 @@ export class DaemonServer { const previous = client.streamSocket socket.removeAllListeners('data') client.streamSocket = socket + // Why: 'drain' is the wake-up for the batcher's shallow-gate held bulk. + socket.on('drain', () => { + this.streamDataBatcher.flush(client.clientId) + }) const cleanup = (): void => { socket.removeListener('close', cleanup) @@ -275,15 +342,22 @@ export class DaemonServer { envToDelete: p.envToDelete, command: p.command, startupCommandDelivery: p.startupCommandDelivery, + // Why: daemon RPC payloads are untrusted JSON. Persist only the + // allowlisted enum used for byte routing, never arbitrary identity. + ...(isTuiAgent(p.launchAgent) ? { launchAgent: p.launchAgent } : {}), shellOverride: p.shellOverride, terminalWindowsWslDistro: p.terminalWindowsWslDistro, terminalWindowsPowerShellImplementation: p.terminalWindowsPowerShellImplementation, shellReadySupported: p.shellReadySupported, + historySeed: p.historySeed, ...(p.shellReadyTimeoutMs !== undefined ? { shellReadyTimeoutMs: p.shellReadyTimeoutMs } : {}), streamClient: { onData: (data) => { + // Scan BEFORE enqueue: the batcher may keep-tail drop this + // chunk, but its facts must be captured regardless. + this.transientFactRelay.onSessionData(p.sessionId, data) const lastInputAt = this.lastInputAtBySessionId.get(p.sessionId) const isInteractiveOutput = data.length <= DaemonServer.INTERACTIVE_OUTPUT_MAX_CHARS && @@ -295,28 +369,49 @@ export class DaemonServer { }) }, onExit: (code) => { - // Why: exit tears down renderer handlers; flush final output first - // so the last few milliseconds of PTY data are not stranded. + // Why: exit tears down renderer handlers, so it must ride the + // ordered queue behind final output even when the shallow socket + // gate holds that output for a later drain pass. + this.log.log('session-exited', { sessionId: p.sessionId, code }) + this.streamDataBatcher.enqueueControlEvent(clientId, p.sessionId, { + type: 'event', + event: 'exit', + sessionId: p.sessionId, + payload: { code } + }) this.streamDataBatcher.flush(clientId) + recordDaemonStreamBacklogEvent('sessionExit', { + sessionIdSuffix: p.sessionId.slice(-10) + }) + this.transientFactRelay.onSessionExit(p.sessionId) + this.streamClientIdBySessionId.delete(p.sessionId) this.lastInputAtBySessionId.delete(p.sessionId) - if (client?.streamSocket) { - client.streamSocket.write( - encodeNdjson({ - type: 'event', - event: 'exit', - sessionId: p.sessionId, - payload: { code } - }) - ) - } } } }) + this.streamClientIdBySessionId.set(p.sessionId, clientId) + // Why an attach-time marker: the adapter resyncs the background set on + // a fresh connection, which can precede this attach — main's scan + // suppression must still start at the head of the new stream. + if (this.transientFactRelay.isBackgrounded(p.sessionId)) { + this.streamDataBatcher.enqueueControlEvent(clientId, p.sessionId, { + type: 'event', + event: 'sessionBackgroundMarker', + sessionId: p.sessionId, + payload: { background: true } + }) + } + this.log.log(result.isNew ? 'session-created' : 'session-attached', { + sessionId: p.sessionId, + pid: result.pid + }) return { isNew: result.isNew, snapshot: result.snapshot, pid: result.pid, - shellState: result.shellState + shellState: result.shellState, + ...(result.launchAgent ? { launchAgent: result.launchAgent } : {}), + ...(result.historySeeded !== undefined ? { historySeeded: result.historySeeded } : {}) } } @@ -347,8 +442,62 @@ export class DaemonServer { } return {} + case 'pausePty': + this.host.pauseProducer(request.payload.sessionId) + return {} + + case 'resumePty': + this.host.resumeProducer(request.payload.sessionId) + return {} + + case 'setSessionBackground': { + const sessionId = request.payload.sessionId + const background = request.payload.background === true + recordDaemonStreamBacklogEvent('setSessionBackground', { + sessionIdSuffix: sessionId.slice(-10), + background + }) + if (!this.transientFactRelay.setSessionBackground(sessionId, background)) { + return {} + } + if (background) { + // Prime the fresh relay tracker with the emulator's dangling + // incomplete escape so a sequence split across the handoff parses + // exactly as if the relay had seen the whole stream. + this.transientFactRelay.seedSessionScanState( + sessionId, + this.host.getPartialEscapeTailAnsi(sessionId) + ) + } + const streamClientId = this.streamClientIdBySessionId.get(sessionId) + if (!streamClientId) { + // Not attached yet — the attach-time marker covers the handoff. + return {} + } + // Reveal deliberately does NOT discard or force-flush the queued + // tail: main's model (hidden-output recovery buffer, tail previews) + // needs those bytes — a finished program's last output lives there — + // and the normal flush/drain loop delivers them within milliseconds + // (bounded ≤ the keep-tail drop cap), in order, ahead of the marker. + const scanSeedAnsi = background ? '' : this.host.getPartialEscapeTailAnsi(sessionId) + this.streamDataBatcher.enqueueControlEvent(streamClientId, sessionId, { + type: 'event', + event: 'sessionBackgroundMarker', + sessionId, + payload: { + background, + ...(scanSeedAnsi.length > 0 ? { scanSeedAnsi } : {}) + } + }) + return {} + } + case 'kill': this.lastInputAtBySessionId.delete(request.payload.sessionId) + this.log.log('session-killed', { + sessionId: request.payload.sessionId, + immediate: request.payload.immediate === true + }) this.host.kill(request.payload.sessionId, { immediate: request.payload.immediate }) return {} @@ -359,6 +508,7 @@ export class DaemonServer { case 'detach': // Note: detach token handling is simplified here — full implementation // would track tokens per client + this.log.log('session-detached', { sessionId: request.payload.sessionId }) return {} case 'getCwd': @@ -367,6 +517,11 @@ export class DaemonServer { case 'getForegroundProcess': return { foregroundProcess: this.host.getForegroundProcess(request.payload.sessionId) } + case 'confirmForegroundProcess': + return { + foregroundProcess: await this.host.confirmForegroundProcess(request.payload.sessionId) + } + case 'clearScrollback': this.host.clearScrollback(request.payload.sessionId) return {} @@ -374,8 +529,26 @@ export class DaemonServer { case 'listSessions': return { sessions: this.host.listSessions() } - case 'getSnapshot': - return { snapshot: this.host.getSnapshot(request.payload.sessionId) } + case 'getSnapshot': { + const snapshotStart = performance.now() + const requestedScrollbackRows = request.payload.scrollbackRows + const scrollbackRows = + typeof requestedScrollbackRows === 'number' && Number.isFinite(requestedScrollbackRows) + ? Math.max(0, Math.min(50_000, Math.floor(requestedScrollbackRows))) + : undefined + const snapshot = this.host.getSnapshot(request.payload.sessionId, { scrollbackRows }) + const snapshotMs = performance.now() - snapshotStart + if (snapshotMs >= 25) { + // Serialize stalls block the daemon's single thread — every pty's + // echo included. Surfaced here so multi-second typing stalls can be + // attributed to checkpoint storms (issue #5096 family) in the field. + recordDaemonStreamBacklogEvent('slowGetSnapshot', { + sessionIdSuffix: request.payload.sessionId.slice(-10), + snapshotMs: Math.round(snapshotMs) + }) + } + return { snapshot } + } case 'getSize': return { size: this.host.getAppliedSize(request.payload.sessionId) } @@ -402,6 +575,10 @@ export class DaemonServer { return { healthy: true } case 'shutdown': + this.log.log('shutdown', { + reason: 'rpc', + killSessions: request.payload.killSessions === true + }) if (request.payload.killSessions) { this.host.dispose() } @@ -422,13 +599,12 @@ export class DaemonServer { // Why: write/resize are notification-heavy and intentionally do not wait // for replies. If their target session is gone, this synthetic exit is the // only signal the renderer gets to clear stale terminal pane bindings. - client.streamSocket.write( - encodeNdjson({ - type: 'event', - event: 'exit', - sessionId, - payload: { code } - }) - ) + this.streamDataBatcher.enqueueControlEvent(client.clientId, sessionId, { + type: 'event', + event: 'exit', + sessionId, + payload: { code } + }) + this.streamDataBatcher.flush(client.clientId) } } diff --git a/src/main/daemon/daemon-stream-backlog-probe.ts b/src/main/daemon/daemon-stream-backlog-probe.ts new file mode 100644 index 000000000000..444d1deb2509 --- /dev/null +++ b/src/main/daemon/daemon-stream-backlog-probe.ts @@ -0,0 +1,55 @@ +/** + * Env-gated diagnostics for the daemon→main stream backlog: samples the + * batcher queue and each stream socket's user-space write buffer so + * multi-second echo lag can be attributed to the hop that actually holds the + * bytes. Enable by setting ORCA_DAEMON_STREAM_BACKLOG_FILE to a writable + * path; zero cost otherwise. The timer only observes and appends JSONL — it + * never mutates delivery state. + */ +import { appendFileSync } from 'node:fs' + +export type StreamBacklogClientSample = { + clientId: string + socketBufferedBytes: number + batcherQueuedChars: number +} + +export type StreamBacklogSample = { + clients: StreamBacklogClientSample[] + backgroundedSessionIdSuffixes?: string[] +} + +const SAMPLE_INTERVAL_MS = 250 + +/** Event-level entries interleaved with the periodic samples — used to + * attribute WHO mutated pacing state, not just when counts changed. */ +export function recordDaemonStreamBacklogEvent( + event: string, + detail: Record +): void { + const filePath = process.env.ORCA_DAEMON_STREAM_BACKLOG_FILE + if (!filePath) { + return + } + try { + appendFileSync(filePath, `${JSON.stringify({ atMs: Date.now(), event, ...detail })}\n`) + } catch { + // Diagnostics must never break the daemon. + } +} + +export function startDaemonStreamBacklogProbe(sample: () => StreamBacklogSample): () => void { + const filePath = process.env.ORCA_DAEMON_STREAM_BACKLOG_FILE + if (!filePath) { + return () => {} + } + const timer = setInterval(() => { + try { + appendFileSync(filePath, `${JSON.stringify({ atMs: Date.now(), ...sample() })}\n`) + } catch { + // Diagnostics must never break the daemon. + } + }, SAMPLE_INTERVAL_MS) + timer.unref?.() + return () => clearInterval(timer) +} diff --git a/src/main/daemon/daemon-stream-data-batcher.test.ts b/src/main/daemon/daemon-stream-data-batcher.test.ts index 8777434e1d91..32d85ff87b0b 100644 --- a/src/main/daemon/daemon-stream-data-batcher.test.ts +++ b/src/main/daemon/daemon-stream-data-batcher.test.ts @@ -6,12 +6,37 @@ import { createNdjsonParser } from './ndjson' function createBatcher(options?: ConstructorParameters[1]) { const streamSocket = { destroyed: false, + writableLength: 0, write: vi.fn() - } as unknown as Socket & { write: ReturnType } + } as unknown as Socket & { write: ReturnType; writableLength: number } const batcher = new DaemonStreamDataBatcher(() => ({ streamSocket }), options) return { batcher, streamSocket } } +function writtenData(streamSocket: { write: ReturnType }): string { + return streamSocket.write.mock.calls + .map(([line]) => { + const parsed = JSON.parse(String(line)) as { payload?: { data?: string } } + return parsed.payload?.data ?? '' + }) + .join('') +} + +type ParsedWrite = { + event: string + sessionId?: string + payload?: { data?: string } +} + +// A held pass arms a zero-payload data event whose kernel-flush callback +// refills the queue; it carries no content, so assertions about delivered +// output must ignore it. +function nonSentinelWrites(streamSocket: { write: ReturnType }): ParsedWrite[] { + return streamSocket.write.mock.calls + .map(([line]) => JSON.parse(String(line)) as ParsedWrite) + .filter((message) => !(message.event === 'data' && (message.payload?.data ?? '') === '')) +} + describe('DaemonStreamDataBatcher', () => { it('coalesces background output before writing daemon stream events', () => { vi.useFakeTimers() @@ -22,7 +47,7 @@ describe('DaemonStreamDataBatcher', () => { batcher.enqueue('client-1', 'session-1', 'b') expect(streamSocket.write).not.toHaveBeenCalled() - vi.advanceTimersByTime(7) + vi.advanceTimersByTime(1) expect(streamSocket.write).not.toHaveBeenCalled() vi.advanceTimersByTime(1) @@ -45,7 +70,7 @@ describe('DaemonStreamDataBatcher', () => { expect(streamSocket.write).toHaveBeenCalledTimes(1) expect(String(streamSocket.write.mock.calls[0]?.[0])).toContain('\\u001b[20;2Hredraw') - vi.advanceTimersByTime(8) + vi.advanceTimersByTime(2) expect(streamSocket.write).toHaveBeenCalledTimes(1) } finally { vi.useRealTimers() @@ -65,7 +90,7 @@ describe('DaemonStreamDataBatcher', () => { }) expect(streamSocket.write).not.toHaveBeenCalled() - vi.advanceTimersByTime(8) + vi.advanceTimersByTime(2) expect(streamSocket.write).toHaveBeenCalledTimes(1) expect(String(streamSocket.write.mock.calls[0]?.[0])).toContain(`${pending}redraw`) } finally { @@ -91,7 +116,7 @@ describe('DaemonStreamDataBatcher', () => { ) expect(String(streamSocket.write.mock.calls[0]?.[0])).toContain('"data":"echo"') - vi.advanceTimersByTime(8) + vi.advanceTimersByTime(2) expect(streamSocket.write).toHaveBeenCalledTimes(2) expect(String(streamSocket.write.mock.calls[1]?.[0])).toContain( '"sessionId":"session-background"' @@ -102,6 +127,447 @@ describe('DaemonStreamDataBatcher', () => { } }) + it('holds bulk output while the socket buffer is deep and resumes on the next flush', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + const bulk = 'x'.repeat(64 * 1024) + + streamSocket.writableLength = 128 * 1024 + batcher.enqueue('client-1', 'session-bulk', bulk) + vi.advanceTimersByTime(2) + expect(nonSentinelWrites(streamSocket)).toHaveLength(0) + expect(batcher.queuedCharsForClient('client-1')).toBe(bulk.length) + + // Socket drained (server routes 'drain' to flush): held bulk writes. + streamSocket.writableLength = 0 + batcher.flush('client-1') + expect(writtenData(streamSocket)).toBe(bulk) + expect(batcher.queuedCharsForClient('client-1')).toBe(0) + } finally { + vi.useRealTimers() + } + }) + + it('lets interactive echo jump bulk held behind a deep socket', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + + streamSocket.writableLength = 128 * 1024 + batcher.enqueue('client-1', 'session-bulk', 'x'.repeat(64 * 1024)) + vi.advanceTimersByTime(2) + expect(nonSentinelWrites(streamSocket)).toHaveLength(0) + + batcher.enqueue('client-1', 'session-typing', 'echo', { + flushImmediately: true, + flushMaxChars: 1024 + }) + const written = nonSentinelWrites(streamSocket) + expect(written).toHaveLength(1) + expect(written[0]?.sessionId).toBe('session-typing') + // The bulk stays held — order across sessions has no contract, and the + // deep socket is exactly what the echo must not queue behind. + expect(batcher.queuedCharsForClient('client-1')).toBe(64 * 1024) + } finally { + vi.useRealTimers() + } + }) + + it('lets a small session write through the gate while a flooding session holds (per-session fairness)', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + + streamSocket.writableLength = 128 * 1024 + batcher.enqueue('client-1', 'session-flood', 'x'.repeat(256 * 1024)) + // Non-interactive small output (echo that missed the 100ms fast-path). + batcher.enqueue('client-1', 'session-typing', 'echo-line') + vi.advanceTimersByTime(2) + + // The flood holds; the tiny session's bytes must NOT wait behind it. + const written = nonSentinelWrites(streamSocket) + expect(written.some((m) => m.sessionId === 'session-typing')).toBe(true) + expect(writtenData(streamSocket)).toContain('echo-line') + expect(written.some((m) => m.sessionId === 'session-flood')).toBe(false) + expect(batcher.queuedCharsForClient('client-1')).toBe(256 * 1024) + } finally { + vi.useRealTimers() + } + }) + + it('never reorders bytes within a session around the small-session bypass', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + + streamSocket.writableLength = 128 * 1024 + // Same session: big entry then (non-adjacent) small entry. + batcher.enqueue('client-1', 'session-a', 'x'.repeat(256 * 1024)) + batcher.enqueue('client-1', 'session-b', 'other') + batcher.enqueue('client-1', 'session-a', 'tail') + vi.advanceTimersByTime(2) + const written = streamSocket.write.mock.calls.map(([line]) => String(line)).join('') + // session-a held its first entry, so its tail must be held too. + expect(written).not.toContain('tail') + + streamSocket.writableLength = 0 + batcher.flush('client-1') + expect(writtenData(streamSocket)).toContain('x'.repeat(64)) + // Full reassembly, in order, once drained. + const aPayload = streamSocket.write.mock.calls + .map( + ([line]) => + JSON.parse(String(line)) as { sessionId?: string; payload?: { data?: string } } + ) + .filter((m) => m.sessionId === 'session-a') + .map((m) => m.payload?.data ?? '') + .join('') + expect(aPayload).toBe(`${'x'.repeat(256 * 1024)}tail`) + } finally { + vi.useRealTimers() + } + }) + + it('slices oversized held entries so one write cannot re-deepen the socket unboundedly', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + const bulk = 'y'.repeat(64 * 1024 + 5) + + batcher.enqueue('client-1', 'session-bulk', bulk) + vi.advanceTimersByTime(2) + // Two slices: 64K then the 5-char remainder; payload reassembles intact. + expect(streamSocket.write).toHaveBeenCalledTimes(2) + expect(writtenData(streamSocket)).toBe(bulk) + } finally { + vi.useRealTimers() + } + }) + + it('stops mid-queue when a written slice is followed by a still-deep socket', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + const first = 'a'.repeat(70 * 1024) + + batcher.enqueue('client-1', 'session-bulk', first) + // First slice write fills the socket past the gate; the remainder holds. + streamSocket.write.mockImplementation(() => { + streamSocket.writableLength = 200 * 1024 + return false + }) + vi.advanceTimersByTime(2) + expect(nonSentinelWrites(streamSocket)).toHaveLength(1) + expect(batcher.queuedCharsForClient('client-1')).toBe(first.length - 64 * 1024) + + streamSocket.writableLength = 0 + streamSocket.write.mockImplementation(() => true) + batcher.flush('client-1') + expect(writtenData(streamSocket)).toBe(first) + } finally { + vi.useRealTimers() + } + }) + + it('writes through the gate once held bulk exceeds the memory safety valve', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + const huge = 'z'.repeat(32 * 1024 * 1024 + 1) + + streamSocket.writableLength = 128 * 1024 + batcher.enqueue('client-1', 'session-bulk', huge) + vi.advanceTimersByTime(2) + // Deep socket, but holding would exceed the valve: old write-through + // behavior wins over bounded echo latency. + expect(writtenData(streamSocket).length).toBeGreaterThan(0) + } finally { + vi.useRealTimers() + } + }) + + it('does not split surrogate pairs at the bulk slice boundary', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + // Position an astral char to straddle the 64K slice boundary. + const bulk = `${'a'.repeat(64 * 1024 - 1)}😀${'b'.repeat(10)}` + + batcher.enqueue('client-1', 'session-bulk', bulk) + vi.advanceTimersByTime(2) + expect(writtenData(streamSocket)).toBe(bulk) + for (const [line] of streamSocket.write.mock.calls) { + expect(String(line)).not.toContain('�') + } + } finally { + vi.useRealTimers() + } + }) + + it('keep-tail drops a droppable session over the cap and delivers a gap before the kept tail', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher({ + isSessionDroppable: (sessionId) => sessionId === 'session-bg' + }) + // Two enqueues that together cross the 1MB cap. + batcher.enqueue('client-1', 'session-bg', 'a'.repeat(900 * 1024)) + batcher.enqueue('client-1', 'session-bg', 'b'.repeat(300 * 1024)) + expect(batcher.queuedCharsForClient('client-1')).toBe(512 * 1024) + vi.advanceTimersByTime(2) + + const messages = streamSocket.write.mock.calls.map( + ([line]) => + JSON.parse(String(line)) as { + event: string + payload: { data?: string; droppedChars?: number } + } + ) + expect(messages[0]?.event).toBe('dataGap') + expect(messages[0]?.payload.droppedChars).toBe((900 + 300 - 512) * 1024) + const delivered = messages + .filter((m) => m.event === 'data') + .map((m) => m.payload.data ?? '') + .join('') + expect(delivered.length).toBe(512 * 1024) + // Keep-TAIL: the newest bytes survive. + expect(delivered.endsWith('b'.repeat(300 * 1024))).toBe(true) + } finally { + vi.useRealTimers() + } + }) + + it('accounts every dropped char across repeated drops (gap sums + delivered = enqueued)', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher({ isSessionDroppable: () => true }) + // Deep socket: data holds; a gap entry (~100B) may still write through — + // it always precedes the kept tail, so a second drop mints a second gap. + streamSocket.writableLength = 128 * 1024 + batcher.enqueue('client-1', 'session-bg', 'a'.repeat(1024 * 1024 + 1)) + batcher.enqueue('client-1', 'session-bg', 'b'.repeat(600 * 1024)) + batcher.enqueue('client-1', 'session-bg', 'c'.repeat(600 * 1024)) + vi.advanceTimersByTime(2) + + streamSocket.writableLength = 0 + batcher.flush('client-1') + const messages = streamSocket.write.mock.calls.map( + ([line]) => + JSON.parse(String(line)) as { + event: string + payload: { data?: string; droppedChars?: number } + } + ) + const gapChars = messages + .filter((m) => m.event === 'dataGap') + .reduce((sum, m) => sum + (m.payload.droppedChars ?? 0), 0) + const dataMessages = messages.filter((m) => m.event === 'data') + const deliveredChars = dataMessages.reduce((sum, m) => sum + (m.payload.data?.length ?? 0), 0) + expect(deliveredChars).toBeLessThanOrEqual(1024 * 1024) + expect(gapChars + deliveredChars).toBe(1024 * 1024 + 1 + 1200 * 1024) + // The newest bytes always survive. + expect(dataMessages.at(-1)?.payload.data?.endsWith('c')).toBe(true) + } finally { + vi.useRealTimers() + } + }) + + it('salvages reply-eliciting query bytes out of dropped data', () => { + vi.useFakeTimers() + try { + const dsr = '\x1b[6n' + const { batcher, streamSocket } = createBatcher({ + isSessionDroppable: () => true, + salvageDroppedData: (dropped) => (dropped.includes(dsr) ? dsr : '') + }) + // The DSR probe sits in the oldest (dropped) region. + batcher.enqueue('client-1', 'session-bg', `flood${dsr}${'x'.repeat(900 * 1024)}`) + batcher.enqueue('client-1', 'session-bg', 'y'.repeat(300 * 1024)) + vi.advanceTimersByTime(2) + + const messages = streamSocket.write.mock.calls.map( + ([line]) => + JSON.parse(String(line)) as { + event: string + payload: { data?: string; droppedChars?: number; sequenceChars?: number } + } + ) + expect(messages[0]?.event).toBe('dataGap') + // The salvaged query rides right after the gap, before the kept tail. + expect(messages[1]?.event).toBe('data') + expect(messages[1]?.payload.data).toBe(dsr) + expect(messages[1]?.payload.sequenceChars).toBe(0) + const originalSequenceChars = messages.reduce( + (sum, message) => + sum + + (message.event === 'dataGap' + ? (message.payload.sequenceChars ?? 0) + : (message.payload.sequenceChars ?? message.payload.data?.length ?? 0)), + 0 + ) + expect(originalSequenceChars).toBe(`flood${dsr}${'x'.repeat(900 * 1024)}`.length + 300 * 1024) + } finally { + vi.useRealTimers() + } + }) + + it('shrinks keep-tails as more backgrounded sessions queue (global aggregate budget)', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher({ isSessionDroppable: () => true }) + streamSocket.writableLength = 128 * 1024 // deep socket: queues accumulate + // 17 backgrounded sessions × 768KB — each below the single-session cap, + // but a reveal would have to drain the ~13MB aggregate (measured 2.5s + // hidden-restore). The global budget thins each to ~2MB/17 ≈ 120KB. + for (let s = 0; s < 17; s++) { + batcher.enqueue('client-1', `session-${s}`, '#'.repeat(768 * 1024)) + } + const totalQueued = batcher.queuedCharsForClient('client-1') + expect(totalQueued).toBeLessThan(3 * 1024 * 1024) + // Every session still keeps at least a full screen of newest tail. + streamSocket.writableLength = 0 + batcher.flush('client-1') + const perSession = new Map() + for (const m of nonSentinelWrites(streamSocket)) { + if (m.event === 'data' && m.sessionId) { + perSession.set( + m.sessionId, + (perSession.get(m.sessionId) ?? 0) + (m.payload?.data?.length ?? 0) + ) + } + } + for (let s = 0; s < 17; s++) { + expect(perSession.get(`session-${s}`) ?? 0).toBeGreaterThanOrEqual(64 * 1024) + } + } finally { + vi.useRealTimers() + } + }) + + it('never drops sessions that are not droppable', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher({ isSessionDroppable: () => false }) + const bulk = 'v'.repeat(2 * 1024 * 1024) + batcher.enqueue('client-1', 'session-visible', bulk) + vi.advanceTimersByTime(2) + expect(writtenData(streamSocket)).toBe(bulk) + } finally { + vi.useRealTimers() + } + }) + + it('delivers control events in byte order with the session data around them', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + batcher.enqueue('client-1', 'session-1', 'before') + batcher.enqueueControlEvent('client-1', 'session-1', { + type: 'event', + event: 'transientFact', + sessionId: 'session-1', + payload: { kind: 'bell' } + }) + batcher.enqueue('client-1', 'session-1', 'after') + vi.advanceTimersByTime(2) + + const messages = streamSocket.write.mock.calls.map( + ([line]) => JSON.parse(String(line)) as { event: string; payload: { data?: string } } + ) + expect(messages.map((m) => m.event)).toEqual(['data', 'transientFact', 'data']) + expect(messages[0]?.payload.data).toBe('before') + expect(messages[2]?.payload.data).toBe('after') + } finally { + vi.useRealTimers() + } + }) + + it("holds a control event behind its session's held bulk (order latch)", () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + streamSocket.writableLength = 128 * 1024 + batcher.enqueue('client-1', 'session-bulk', 'x'.repeat(64 * 1024)) + batcher.enqueueControlEvent('client-1', 'session-bulk', { + type: 'event', + event: 'sessionBackgroundMarker', + sessionId: 'session-bulk', + payload: { background: true } + }) + vi.advanceTimersByTime(2) + expect(nonSentinelWrites(streamSocket)).toHaveLength(0) + + streamSocket.writableLength = 0 + batcher.flush('client-1') + expect(nonSentinelWrites(streamSocket).map((m) => m.event)).toEqual([ + 'data', + 'sessionBackgroundMarker' + ]) + } finally { + vi.useRealTimers() + } + }) + + it('delivers a held queued tail (data + facts, in order) once the socket drains', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + streamSocket.writableLength = 128 * 1024 + batcher.enqueue('client-1', 'session-bg', 'x'.repeat(64 * 1024)) + batcher.enqueueControlEvent('client-1', 'session-bg', { + type: 'event', + event: 'transientFact', + sessionId: 'session-bg', + payload: { kind: 'bell' } + }) + batcher.enqueue('client-1', 'session-bg', 'DONE') + vi.advanceTimersByTime(2) + + // Reveal never discards: a finished program's last output must reach + // main's model (restore reads it). The normal drain loop delivers it. + streamSocket.writableLength = 0 + batcher.flush('client-1') + expect(batcher.queuedCharsForClient('client-1')).toBe(0) + const messages = nonSentinelWrites(streamSocket) + expect(messages.map((m) => m.event)).toEqual(['data', 'transientFact', 'data']) + expect(messages.at(-1)?.payload?.data).toBe('DONE') + } finally { + vi.useRealTimers() + } + }) + + it('arms one kernel-flush refill sentinel per held pass and resumes without waiting for drain', () => { + vi.useFakeTimers() + try { + const { batcher, streamSocket } = createBatcher() + const flushCallbacks: (() => void)[] = [] + streamSocket.write.mockImplementation((_line: string, cb?: () => void) => { + if (cb) { + flushCallbacks.push(cb) + } + return true + }) + + streamSocket.writableLength = 128 * 1024 + batcher.enqueue('client-1', 'session-bulk', 'x'.repeat(64 * 1024)) + vi.advanceTimersByTime(2) + // Held pass → exactly one sentinel armed; further held passes don't stack. + expect(flushCallbacks).toHaveLength(1) + batcher.flush('client-1') + expect(flushCallbacks).toHaveLength(1) + + // Kernel flushed the in-flight bytes (socket now shallow): the sentinel + // callback resumes the held bulk with no 'drain' event involved. + streamSocket.writableLength = 0 + flushCallbacks[0]() + expect(writtenData(streamSocket)).toBe('x'.repeat(64 * 1024)) + expect(batcher.queuedCharsForClient('client-1')).toBe(0) + } finally { + vi.useRealTimers() + } + }) + it('writes large stream data as parser-sized NDJSON events', () => { vi.useFakeTimers() try { @@ -113,7 +579,7 @@ describe('DaemonStreamDataBatcher', () => { const parser = createNdjsonParser(onMessage, onError, { maxLineBytes }) batcher.enqueue('client-1', 'session-1', data) - vi.advanceTimersByTime(8) + vi.advanceTimersByTime(2) for (const [line] of streamSocket.write.mock.calls) { parser.feed(String(line)) } diff --git a/src/main/daemon/daemon-stream-data-batcher.ts b/src/main/daemon/daemon-stream-data-batcher.ts index 3374222f17f5..84f7465b913b 100644 --- a/src/main/daemon/daemon-stream-data-batcher.ts +++ b/src/main/daemon/daemon-stream-data-batcher.ts @@ -1,19 +1,63 @@ import type { Socket } from 'node:net' import { encodeNdjson, NDJSON_MAX_LINE_BYTES } from './ndjson' +import { recordDaemonStreamBacklogEvent } from './daemon-stream-backlog-probe' +import { + clampToSafeSplitIndex, + encodeStreamDataEvent, + writeStreamDataEvents +} from './daemon-stream-data-split' +import { + backgroundSessionDropCapChars, + backgroundSessionKeepTailChars, + dropOldestQueuedForSession, + type PendingStreamDataBatch +} from './daemon-stream-keep-tail-drop' +import type { DaemonEvent } from './types' type StreamDataClient = { streamSocket: Socket | null } -type PendingStreamDataBatch = { - timer: ReturnType | null - queue: { sessionId: string; data: string }[] - queuedChars: number -} - -// Why: match main-process PTY IPC batching to avoid adding latency while -// removing daemon socket writes and JSON framing during bursty output. -const STREAM_DATA_BATCH_INTERVAL_MS = 8 +// Why 2ms: under continuous agent output every chunk waits an expected +// half-window here AND again in main's PTY batch — at 8ms each that was +// ~8ms of the measured ~19ms DSR-under-load latency. 2ms keeps burst +// coalescing (~500 socket writes/s worst case, ~100B framing overhead per +// write against MB/s payloads) while cutting the fixed latency tax 4x. +const STREAM_DATA_BATCH_INTERVAL_MS = 2 + +// Why a shallow socket: the stream socket is one FIFO for every session, and +// bytes already written can never be overtaken — a deep user-space buffer +// buries a visible pane's keystroke echo behind bulk output for other panes +// (measured 192MB / 6+s under 12 flooding hidden agents). Bulk writes stop at +// this depth and the remainder is HELD here, where the interactive +// flushSession path can still jump it; socket 'drain' refills. Echo latency +// is then bounded by the shallow depth, not by how much bulk is in flight. +// 128KB must stay above the socket's ~16KB highWaterMark so a held state +// implies a false write() and therefore a guaranteed 'drain' wake-up. +// Kill switch: ORCA_DAEMON_SHALLOW_SOCKET_GATE=0 restores pre-gate unbounded +// socket writes for field debugging and true fix-off A/B benches. +const SHALLOW_SOCKET_WRITE_GATE_BYTES = + process.env.ORCA_DAEMON_SHALLOW_SOCKET_GATE === '0' ? Number.POSITIVE_INFINITY : 128 * 1024 +// Why sliced writes: enqueue coalesces per-session entries, so a held entry +// can grow to megabytes; writing it whole would re-deepen the socket past the +// gate in one call. +const BULK_WRITE_SLICE_CHARS = 64 * 1024 +// Safety valve: if held bulk ever exceeds this, write through to the socket +// (exactly the pre-gate behavior) — bounded daemon memory beats bounded echo +// latency in the extreme. Must sit FAR above the pacer's pause watermark plus +// its overshoot (observed ~5MB with 17 paused sessions' in-flight pty reads): +// an engaged valve deepens the socket and buries interactive echo behind the +// whole backlog (measured as bimodal ~2.4s key medians when this was 8MB). +const HELD_WRITE_THROUGH_TOTAL_CHARS = 32 * 1024 * 1024 +// Why a small-session bypass: the hold is there to stop FLOODS from burying +// everyone else; a session with only a few KB queued (keystroke echo, prompt +// redraws, query replies) is never the flood and must not wait FIFO behind +// other sessions' megabytes. The daemon's 100ms interactive fast-path is a +// heuristic that misses under event-loop load (measured: echo classified +// non-interactive rode the held queue for ~2.4s); this bypass is the +// deterministic backstop. Worst socket over-deepening per flush is +// sessions × this ≈ tens of KB. +const SMALL_SESSION_HOLD_BYPASS_CHARS = 4 * 1024 type EnqueueOptions = { flushImmediately?: boolean @@ -22,90 +66,25 @@ type EnqueueOptions = { type DaemonStreamDataBatcherOptions = { maxLineBytes?: number -} - -function encodeStreamDataEvent(sessionId: string, data: string): string { - return encodeNdjson({ - type: 'event', - event: 'data', - sessionId, - payload: { data } - }) -} - -function streamDataEventLineBytes(sessionId: string, data: string): number { - return Buffer.byteLength(encodeStreamDataEvent(sessionId, data), 'utf8') -} - -function isHighSurrogate(value: number): boolean { - return value >= 0xd800 && value <= 0xdbff -} - -function isLowSurrogate(value: number): boolean { - return value >= 0xdc00 && value <= 0xdfff -} - -function clampToSafeSplitIndex(value: string, start: number, end: number): number { - if (end <= start || end >= value.length) { - return end - } - const prev = value.charCodeAt(end - 1) - const next = value.charCodeAt(end) - return isHighSurrogate(prev) && isLowSurrogate(next) ? end - 1 : end -} - -function nextSafeSplitIndex(value: string, start: number): number { - const next = Math.min(value.length, start + 1) - if ( - next < value.length && - isHighSurrogate(value.charCodeAt(start)) && - isLowSurrogate(value.charCodeAt(next)) - ) { - return next + 1 - } - return next -} - -function splitStreamDataForNdjson(sessionId: string, data: string, maxLineBytes: number): string[] { - if (streamDataEventLineBytes(sessionId, data) <= maxLineBytes) { - return [data] - } - - const chunks: string[] = [] - let start = 0 - while (start < data.length) { - let low = start + 1 - let high = data.length - let best = start - - while (low <= high) { - const rawMid = Math.floor((low + high) / 2) - const mid = clampToSafeSplitIndex(data, start, rawMid) - if (mid <= start) { - low = rawMid + 1 - continue - } - - if (streamDataEventLineBytes(sessionId, data.slice(start, mid)) <= maxLineBytes) { - best = mid - low = rawMid + 1 - } else { - high = rawMid - 1 - } - } - - const end = best > start ? best : nextSafeSplitIndex(data, start) - chunks.push(data.slice(start, end)) - start = end - } - - return chunks + /** Fires after each stream-socket write — the only place backlog grows, so + * the backlog pacer checks its watermark here. */ + onAfterSocketWrite?: () => void + /** True for sessions whose queued output may be keep-tail dropped + * (main-marked background sessions). */ + isSessionDroppable?: (sessionId: string) => boolean + /** Carve reply-eliciting query bytes (DSR/DA/DECRQM/OSC color probes) out + * of dropped data — the hidden program blocks on the reply, so those few + * bytes must still be delivered even when their flood is not. */ + salvageDroppedData?: (dropped: string) => string } export class DaemonStreamDataBatcher { private pendingByClient = new Map() private getClient: (clientId: string) => StreamDataClient | undefined private maxLineBytes: number + private onAfterSocketWrite: (() => void) | undefined + private isSessionDroppable: (sessionId: string) => boolean + private salvageDroppedData: (dropped: string) => string constructor( getClient: (clientId: string) => StreamDataClient | undefined, @@ -113,6 +92,9 @@ export class DaemonStreamDataBatcher { ) { this.getClient = getClient this.maxLineBytes = Math.max(1, options.maxLineBytes ?? NDJSON_MAX_LINE_BYTES) + this.onAfterSocketWrite = options.onAfterSocketWrite + this.isSessionDroppable = options.isSessionDroppable ?? (() => false) + this.salvageDroppedData = options.salvageDroppedData ?? (() => '') } enqueue(clientId: string, sessionId: string, data: string, options: EnqueueOptions = {}): void { @@ -121,19 +103,45 @@ export class DaemonStreamDataBatcher { return } - let batch = this.pendingByClient.get(clientId) - if (!batch) { - batch = { timer: null, queue: [], queuedChars: 0 } - this.pendingByClient.set(clientId, batch) - } - + const batch = this.getOrCreateBatch(clientId) const last = batch.queue.at(-1) - if (last?.sessionId === sessionId) { + // Never coalesce across a control entry — it marks a position in the + // session's byte order. + if (last?.sessionId === sessionId && !last.control) { last.data += data } else { batch.queue.push({ sessionId, data }) } batch.queuedChars += data.length + batch.queuedCharsBySession.set( + sessionId, + (batch.queuedCharsBySession.get(sessionId) ?? 0) + data.length + ) + + if (this.isSessionDroppable(sessionId)) { + // Keep-tail scales down as more backgrounded sessions queue, bounding + // the AGGREGATE a reveal must drain (see daemon-stream-keep-tail-drop). + const droppableQueued = this.countDroppableSessionsWithQueuedData(batch) + const dropCap = backgroundSessionDropCapChars(droppableQueued) + const keepTail = backgroundSessionKeepTailChars(droppableQueued) + if ((batch.queuedCharsBySession.get(sessionId) ?? 0) > dropCap) { + dropOldestQueuedForSession(batch, sessionId, keepTail, this.salvageDroppedData) + } + if (droppableQueued > (batch.lastDroppableSessionCount ?? 0)) { + // The shared budget tightened: re-trim sessions that already finished + // producing — they never re-enter this path on their own. + for (const [queuedSessionId, queued] of Array.from(batch.queuedCharsBySession)) { + if ( + queued > dropCap && + queuedSessionId !== sessionId && + this.isSessionDroppable(queuedSessionId) + ) { + dropOldestQueuedForSession(batch, queuedSessionId, keepTail, this.salvageDroppedData) + } + } + } + batch.lastDroppableSessionCount = droppableQueued + } if ( options.flushImmediately === true && @@ -148,6 +156,43 @@ export class DaemonStreamDataBatcher { } } + /** Append a pre-shaped stream event at the current position in the + * session's byte order (scan handoff markers, gaps, transient facts). */ + enqueueControlEvent(clientId: string, sessionId: string, control: DaemonEvent): void { + const client = this.getClient(clientId) + if (!client?.streamSocket || client.streamSocket.destroyed) { + return + } + const batch = this.getOrCreateBatch(clientId) + batch.queue.push({ sessionId, data: '', control }) + if (!batch.timer) { + batch.timer = setTimeout(() => this.flush(clientId), STREAM_DATA_BATCH_INTERVAL_MS) + } + } + + private countDroppableSessionsWithQueuedData(batch: PendingStreamDataBatch): number { + let count = 0 + for (const [sessionId, queued] of batch.queuedCharsBySession) { + if (queued > 0 && this.isSessionDroppable(sessionId)) { + count++ + } + } + return count + } + + private getOrCreateBatch(clientId: string): PendingStreamDataBatch { + let batch = this.pendingByClient.get(clientId) + if (!batch) { + batch = { timer: null, queue: [], queuedChars: 0, queuedCharsBySession: new Map() } + this.pendingByClient.set(clientId, batch) + } + return batch + } + + queuedCharsForClient(clientId: string): number { + return this.pendingByClient.get(clientId)?.queuedChars ?? 0 + } + flush(clientId: string): void { const batch = this.pendingByClient.get(clientId) if (!batch) { @@ -158,16 +203,113 @@ export class DaemonStreamDataBatcher { clearTimeout(batch.timer) batch.timer = null } - this.pendingByClient.delete(clientId) const client = this.getClient(clientId) if (!client?.streamSocket || client.streamSocket.destroyed) { + // Same as pre-gate behavior: a vanished stream socket drops the batch — + // the model owns the bytes and reconnect restores from a snapshot. + this.pendingByClient.delete(clientId) return } - for (const entry of batch.queue) { - this.writeStreamDataEvent(client.streamSocket, entry.sessionId, entry.data) + const socket = client.streamSocket + // Sessions that held an entry must hold ALL their later entries in this + // pass — writing around a held entry would reorder that session's bytes. + const heldSessions = new Set() + const retained: PendingStreamDataBatch['queue'] = [] + while (batch.queue.length > 0) { + const entry = batch.queue[0] + if (entry.control) { + // Control entries only respect the held-session order latch — they + // are ~100B, so writing them onto a deep socket is as harmless as the + // small-session bypass. + if (heldSessions.has(entry.sessionId)) { + retained.push(entry) + batch.queue.shift() + continue + } + batch.queue.shift() + socket.write(encodeNdjson(entry.control)) + this.onAfterSocketWrite?.() + continue + } + const socketDeep = (socket.writableLength ?? 0) >= SHALLOW_SOCKET_WRITE_GATE_BYTES + if (socketDeep && batch.queuedChars <= HELD_WRITE_THROUGH_TOTAL_CHARS) { + const sessionHeld = batch.queuedCharsBySession.get(entry.sessionId) ?? 0 + if (heldSessions.has(entry.sessionId) || sessionHeld > SMALL_SESSION_HOLD_BYPASS_CHARS) { + // Hold this flooding session's entry; small talkers keep flowing. + // The socket's 'drain' (routed back to flush by the server) + // resumes held bulk. No timer: a deep socket implies a prior + // false write(), so 'drain' is guaranteed. + heldSessions.add(entry.sessionId) + retained.push(entry) + batch.queue.shift() + continue + } + } else if (socketDeep) { + // Valve engaged: held bulk exceeded the memory cap and is being + // written through onto a deep socket — echo protection is off until + // it drains. Rare enough to be worth a diagnostics event every time. + recordDaemonStreamBacklogEvent('heldWriteThrough', { + heldChars: batch.queuedChars, + socketBufferedBytes: socket.writableLength ?? 0 + }) + } + const end = + entry.data.length <= BULK_WRITE_SLICE_CHARS + ? entry.data.length + : clampToSafeSplitIndex(entry.data, 0, BULK_WRITE_SLICE_CHARS) + const slice = entry.data.slice(0, end) + const entrySequenceChars = entry.sequenceChars ?? entry.data.length + const sliceSequenceChars = entrySequenceChars === 0 ? 0 : slice.length + if (end >= entry.data.length) { + batch.queue.shift() + } else { + entry.data = entry.data.slice(end) + const remainingSequenceChars = entrySequenceChars - sliceSequenceChars + entry.sequenceChars = + remainingSequenceChars === entry.data.length ? undefined : remainingSequenceChars + } + batch.queuedChars -= slice.length + const sessionHeldAfter = + (batch.queuedCharsBySession.get(entry.sessionId) ?? slice.length) - slice.length + if (sessionHeldAfter <= 0) { + batch.queuedCharsBySession.delete(entry.sessionId) + } else { + batch.queuedCharsBySession.set(entry.sessionId, sessionHeldAfter) + } + writeStreamDataEvents(socket, entry.sessionId, slice, this.maxLineBytes, sliceSequenceChars) + this.onAfterSocketWrite?.() + } + if (retained.length > 0) { + batch.queue = retained + // Held entries must not wait for the socket's 'drain' alone: drain only + // fires when the user-space buffer fully EMPTIES, so bulk would advance + // one gate-depth per daemon event-loop turn — seconds of dead time for + // a multi-MB hidden backlog on a busy daemon (measured: hidden-restore + // 2.5s vs the 1.5s budget). Arm ONE ~90B empty data event whose + // kernel-flush callback re-flushes while bytes are still in flight, so + // main never starves. (An empty socket write's callback fires + // immediately — verified — so the sentinel must be a real protocol + // no-op line.) Event-driven, no timers; the per-client latch stops + // sentinel stacking; 'drain' remains the backstop. + this.armHeldQueueRefill(socket, clientId, retained[0].sessionId) + return + } + this.pendingByClient.delete(clientId) + } + + private refillArmedClients = new Set() + + private armHeldQueueRefill(socket: Socket, clientId: string, sessionId: string): void { + if (this.refillArmedClients.has(clientId) || socket.destroyed) { + return } + this.refillArmedClients.add(clientId) + socket.write(encodeStreamDataEvent(sessionId, ''), () => { + this.refillArmedClients.delete(clientId) + this.flush(clientId) + }) } private queuedCharsForSession(batch: PendingStreamDataBatch, sessionId: string): number { @@ -203,6 +345,7 @@ export class DaemonStreamDataBatcher { batch.queue = retained batch.queuedChars -= flushedChars + batch.queuedCharsBySession.delete(sessionId) if (batch.queue.length === 0) { if (batch.timer) { clearTimeout(batch.timer) @@ -217,7 +360,19 @@ export class DaemonStreamDataBatcher { } for (const entry of flushed) { - this.writeStreamDataEvent(client.streamSocket, entry.sessionId, entry.data) + if (entry.control) { + client.streamSocket.write(encodeNdjson(entry.control)) + this.onAfterSocketWrite?.() + } else { + writeStreamDataEvents( + client.streamSocket, + entry.sessionId, + entry.data, + this.maxLineBytes, + entry.sequenceChars ?? entry.data.length + ) + this.onAfterSocketWrite?.() + } } } @@ -234,13 +389,4 @@ export class DaemonStreamDataBatcher { this.pendingByClient.delete(id) } } - - private writeStreamDataEvent(streamSocket: Socket, sessionId: string, data: string): void { - // Why: createNdjsonParser rejects oversized lines. Terminal output can - // burst faster than the batch interval, so writer-side chunking prevents - // the daemon from dropping its own stream events at the receiver. - for (const chunk of splitStreamDataForNdjson(sessionId, data, this.maxLineBytes)) { - streamSocket.write(encodeStreamDataEvent(sessionId, chunk)) - } - } } diff --git a/src/main/daemon/daemon-stream-data-split.ts b/src/main/daemon/daemon-stream-data-split.ts new file mode 100644 index 000000000000..0e15cf495237 --- /dev/null +++ b/src/main/daemon/daemon-stream-data-split.ts @@ -0,0 +1,114 @@ +/** + * Surrogate-safe splitting for daemon stream data events: NDJSON line-size + * chunking (the receiver's parser rejects oversized lines) and the safe-index + * clamp shared by the batcher's bulk write slicing and keep-tail dropping. + */ +import { encodeNdjson } from './ndjson' +import type { Socket } from 'node:net' + +export function encodeStreamDataEvent( + sessionId: string, + data: string, + sequenceChars?: number +): string { + return encodeNdjson({ + type: 'event', + event: 'data', + sessionId, + payload: { data, ...(sequenceChars === undefined ? {} : { sequenceChars }) } + }) +} + +function streamDataEventLineBytes(sessionId: string, data: string, sequenceChars?: number): number { + return Buffer.byteLength(encodeStreamDataEvent(sessionId, data, sequenceChars), 'utf8') +} + +function isHighSurrogate(value: number): boolean { + return value >= 0xd800 && value <= 0xdbff +} + +function isLowSurrogate(value: number): boolean { + return value >= 0xdc00 && value <= 0xdfff +} + +export function clampToSafeSplitIndex(value: string, start: number, end: number): number { + if (end <= start || end >= value.length) { + return end + } + const prev = value.charCodeAt(end - 1) + const next = value.charCodeAt(end) + return isHighSurrogate(prev) && isLowSurrogate(next) ? end - 1 : end +} + +function nextSafeSplitIndex(value: string, start: number): number { + const next = Math.min(value.length, start + 1) + if ( + next < value.length && + isHighSurrogate(value.charCodeAt(start)) && + isLowSurrogate(value.charCodeAt(next)) + ) { + return next + 1 + } + return next +} + +export function splitStreamDataForNdjson( + sessionId: string, + data: string, + maxLineBytes: number, + sequenceChars?: number +): string[] { + if (streamDataEventLineBytes(sessionId, data, sequenceChars) <= maxLineBytes) { + return [data] + } + + const chunks: string[] = [] + let start = 0 + while (start < data.length) { + let low = start + 1 + let high = data.length + let best = start + + while (low <= high) { + const rawMid = Math.floor((low + high) / 2) + const mid = clampToSafeSplitIndex(data, start, rawMid) + if (mid <= start) { + low = rawMid + 1 + continue + } + + if ( + streamDataEventLineBytes(sessionId, data.slice(start, mid), sequenceChars) <= maxLineBytes + ) { + best = mid + low = rawMid + 1 + } else { + high = rawMid - 1 + } + } + + const end = best > start ? best : nextSafeSplitIndex(data, start) + chunks.push(data.slice(start, end)) + start = end + } + + return chunks +} + +export function writeStreamDataEvents( + streamSocket: Pick, + sessionId: string, + data: string, + maxLineBytes: number, + sequenceChars = data.length +): void { + const explicitSequenceChars = sequenceChars === data.length ? undefined : sequenceChars + for (const chunk of splitStreamDataForNdjson( + sessionId, + data, + maxLineBytes, + explicitSequenceChars + )) { + streamSocket.write(encodeStreamDataEvent(sessionId, chunk, explicitSequenceChars)) + } +} diff --git a/src/main/daemon/daemon-stream-events.ts b/src/main/daemon/daemon-stream-events.ts new file mode 100644 index 000000000000..1644642bd097 --- /dev/null +++ b/src/main/daemon/daemon-stream-events.ts @@ -0,0 +1,78 @@ +// ─── Events (Daemon → Client, on stream socket) ──────────────────── +import type { TerminalGitHubPRLink } from '../../shared/terminal-github-pr-link-detector' + +export type DataEvent = { + type: 'event' + event: 'data' + sessionId: string + payload: { data: string; sequenceChars?: number } +} + +export type ExitEvent = { + type: 'event' + event: 'exit' + sessionId: string + payload: { code: number } +} + +export type TerminalErrorEvent = { + type: 'event' + event: 'terminalError' + sessionId: string + payload: { message: string } +} + +// Why these ride the stream socket (not control): each marks a POSITION in a +// session's byte stream — scan-authority handoffs and dropped ranges are only +// meaningful relative to the data events around them. Old mains ignore +// unknown stream events, and only new mains send setSessionBackground. The +// v20 bump is for sequence-safe recovery snapshots, not these tolerated events. + +/** Scan-authority handoff marker: bytes before this event were (not) scanned + * by the daemon's transient-fact relay; main flips its own scanners at + * exactly this position so no fact double-fires or goes missing. + * scanSeedAnsi (un-background only) carries the emulator's dangling + * incomplete escape so main can prime its fresh scanner carry — a sequence + * split across the handoff must not mint a phantom bell or lose its fact. */ +export type SessionBackgroundMarkerEvent = { + type: 'event' + event: 'sessionBackgroundMarker' + sessionId: string + payload: { background: boolean; scanSeedAnsi?: string } +} + +/** A backgrounded session's oldest undelivered output was dropped at the + * daemon (keep-tail thinning). The daemon emulator ingested every byte — + * only this monitoring stream is thinned. */ +export type DataGapEvent = { + type: 'event' + event: 'dataGap' + sessionId: string + payload: { droppedChars: number; sequenceChars?: number } +} + +/** Notification-bearing fact detected by the daemon while it holds scan + * authority for a backgrounded session. Title/agent-status facts stay + * main-side: they converge from the kept tail (stale-working-title timer, + * snapshot-restores-title-state) and fuse with main-fabricated synthetic + * frames the daemon never sees. */ +export type DaemonTransientFact = + | { kind: 'bell' } + | { kind: 'command-finished'; exitCode: number | null } + | { kind: 'pr-link'; link: TerminalGitHubPRLink } + | { kind: '2031-subscribe' } + +export type TransientFactEvent = { + type: 'event' + event: 'transientFact' + sessionId: string + payload: DaemonTransientFact +} + +export type DaemonEvent = + | DataEvent + | ExitEvent + | TerminalErrorEvent + | SessionBackgroundMarkerEvent + | DataGapEvent + | TransientFactEvent diff --git a/src/main/daemon/daemon-stream-keep-tail-drop.ts b/src/main/daemon/daemon-stream-keep-tail-drop.ts new file mode 100644 index 000000000000..0dc57e535225 --- /dev/null +++ b/src/main/daemon/daemon-stream-keep-tail-drop.ts @@ -0,0 +1,182 @@ +/** + * Keep-tail thinning for backgrounded sessions' queued stream data. Hidden + * panes' stream copy is a monitoring feed (tail previews, agent status) — the + * daemon emulator holds the complete model and reveal restores from its + * snapshot. Once a backgrounded session's undelivered output exceeds the cap, + * its OLDEST bytes are dropped down to the keep-tail and a dataGap event + * takes their place, so the feed stays tail-fresh, daemon memory stays + * bounded, and the producer is never paused (no reveal catch-up). + */ +import { clampToSafeSplitIndex } from './daemon-stream-data-split' +import { recordDaemonStreamBacklogEvent } from './daemon-stream-backlog-probe' +import type { DaemonEvent, DataGapEvent } from './types' + +// A control entry carries a whole pre-shaped stream event (background marker, +// data gap, transient fact) that must ride at its exact position in the +// session's byte order; its data is always '' so it never counts against the +// gate or drop caps, and drops never remove it. +export type StreamQueueEntry = { + sessionId: string + data: string + /** Original PTY characters represented by data. Salvaged query copies are + * delivered bytes but represent zero new positions in the source stream. */ + sequenceChars?: number + control?: DaemonEvent +} + +export type PendingStreamDataBatch = { + timer: ReturnType | null + queue: StreamQueueEntry[] + queuedChars: number + // Per-session held totals so the flush hold can spare small talkers + // (echo/replies) from waiting behind other sessions' floods. + queuedCharsBySession: Map + // Last droppable-sessions-with-queued-data count seen by the keep-tail + // logic: when it GROWS the shared budget tightens, and sessions that + // finished producing must be re-trimmed (they will never re-enqueue). + lastDroppableSessionCount?: number +} + +// The keep-tail must comfortably cover a full TUI repaint (~cols×rows×SGR ≈ +// 100KB) so the delivered tail always re-renders a coherent screen. +// Hysteresis (cap = 2× keep) bounds drop churn. +// Kill switch: ORCA_DAEMON_BACKGROUND_STREAM_DROP=0 disables thinning. +const BACKGROUND_SESSION_KEEP_TAIL_CHARS = 512 * 1024 +const BACKGROUND_SESSION_MIN_KEEP_TAIL_CHARS = 64 * 1024 +// Why a GLOBAL budget too: the per-session cap bounds each flood, but N +// backgrounded sessions can still queue N×cap in aggregate — and a reveal +// (worktree switch) then waits behind the whole aggregate at the gated drain +// rate (~8MB/s event-loop-turn-bound; measured 9MB queued → 2.5s hidden +// restore vs the 1.5s budget). Shrinking each session's keep-tail as more +// backgrounded sessions queue keeps the total ~2MB, so any reveal drains in +// ~250ms while every pane still keeps at least a full screen of tail. +const BACKGROUND_GLOBAL_KEEP_BUDGET_CHARS = 2 * 1024 * 1024 + +export function backgroundSessionKeepTailChars(droppableSessionsWithQueuedData: number): number { + return Math.min( + BACKGROUND_SESSION_KEEP_TAIL_CHARS, + Math.max( + BACKGROUND_SESSION_MIN_KEEP_TAIL_CHARS, + Math.floor(BACKGROUND_GLOBAL_KEEP_BUDGET_CHARS / Math.max(1, droppableSessionsWithQueuedData)) + ) + ) +} + +export function backgroundSessionDropCapChars(droppableSessionsWithQueuedData: number): number { + return backgroundSessionKeepTailChars(droppableSessionsWithQueuedData) * 2 +} +// Mirrors main's DROPPED_QUERY_SALVAGE_MAX_CHARS: salvage past this means a +// pathological query stream; keep the O(1) memory guarantee. A prior drop's +// salvage entry is itself the oldest data and re-salvages through the next +// drop, so query order is preserved across repeated drops. +const DROPPED_QUERY_SALVAGE_MAX_CHARS = 4096 + +/** Trim the session's OLDEST queued data down to the keep-tail and leave (or + * grow) a dataGap control entry where the dropped bytes were. Control + * entries are never dropped. Boundary note: the kept tail can start + * mid-escape-sequence — deliberate; the receiver treats a gap as a + * tail-preview reset and transient-fact scanning is daemon-authoritative + * for droppable sessions, so nothing downstream parses across the cut. */ +export function dropOldestQueuedForSession( + batch: PendingStreamDataBatch, + sessionId: string, + keepTailChars: number, + salvageDroppedData: (dropped: string) => string +): void { + let toDrop = (batch.queuedCharsBySession.get(sessionId) ?? 0) - keepTailChars + if (toDrop <= 0) { + return + } + const totalDropped = toDrop + let droppedSequenceChars = 0 + let salvaged = '' + const salvageIntoCap = (dropped: string): void => { + if (salvaged.length >= DROPPED_QUERY_SALVAGE_MAX_CHARS) { + return + } + salvaged = (salvaged + salvageDroppedData(dropped)).slice(0, DROPPED_QUERY_SALVAGE_MAX_CHARS) + } + let existingGap: DataGapEvent | null = null + let insertGapAt = -1 + for (let i = 0; i < batch.queue.length && toDrop > 0; i++) { + const entry = batch.queue[i] + if (entry.sessionId !== sessionId) { + continue + } + if (entry.control) { + if (entry.control.event === 'dataGap') { + existingGap = entry.control + } + continue + } + if (entry.data.length <= toDrop) { + toDrop -= entry.data.length + droppedSequenceChars += entry.sequenceChars ?? entry.data.length + salvageIntoCap(entry.data) + if (insertGapAt === -1) { + insertGapAt = i + } + batch.queue.splice(i, 1) + i-- + } else { + const cut = clampToSafeSplitIndex(entry.data, 0, toDrop) + if (cut > 0) { + const entrySequenceChars = entry.sequenceChars ?? entry.data.length + const cutSequenceChars = entrySequenceChars === 0 ? 0 : cut + droppedSequenceChars += cutSequenceChars + salvageIntoCap(entry.data.slice(0, cut)) + entry.data = entry.data.slice(cut) + const remainingSequenceChars = entrySequenceChars - cutSequenceChars + entry.sequenceChars = + remainingSequenceChars === entry.data.length ? undefined : remainingSequenceChars + if (insertGapAt === -1) { + insertGapAt = i + } + } + toDrop = 0 + } + } + const dropped = totalDropped - toDrop + if (dropped <= 0) { + return + } + batch.queuedChars -= dropped + batch.queuedCharsBySession.set( + sessionId, + Math.max(0, (batch.queuedCharsBySession.get(sessionId) ?? 0) - dropped) + ) + if (existingGap) { + const priorSequenceChars = existingGap.payload.sequenceChars ?? existingGap.payload.droppedChars + existingGap.payload.droppedChars += dropped + existingGap.payload.sequenceChars = priorSequenceChars + droppedSequenceChars + } else { + recordDaemonStreamBacklogEvent('backgroundKeepTailDrop', { + sessionIdSuffix: sessionId.slice(-10), + droppedChars: dropped + }) + batch.queue.splice(Math.max(0, insertGapAt), 0, { + sessionId, + data: '', + control: { + type: 'event', + event: 'dataGap', + sessionId, + payload: { droppedChars: dropped, sequenceChars: droppedSequenceChars } + } + }) + insertGapAt = Math.max(0, insertGapAt) + 1 + } + if (salvaged.length > 0) { + // Salvaged query bytes ride as a tiny data entry at the gap position — + // the writing program is blocked on their replies. + const at = existingGap + ? batch.queue.findIndex((e) => e.control === existingGap) + 1 + : insertGapAt + batch.queue.splice(at, 0, { sessionId, data: salvaged, sequenceChars: 0 }) + batch.queuedChars += salvaged.length + batch.queuedCharsBySession.set( + sessionId, + (batch.queuedCharsBySession.get(sessionId) ?? 0) + salvaged.length + ) + } +} diff --git a/src/main/daemon/degraded-daemon-fallback-shutdown.ts b/src/main/daemon/degraded-daemon-fallback-shutdown.ts new file mode 100644 index 000000000000..0d4932d6c20a --- /dev/null +++ b/src/main/daemon/degraded-daemon-fallback-shutdown.ts @@ -0,0 +1,25 @@ +import type { IPtyProvider } from '../providers/types' + +export async function shutdownDegradedFallbackSessions( + sessionProviders: Map, + fallback: T +): Promise { + const ids = [...sessionProviders] + .filter(([, provider]) => provider === fallback) + .map(([id]) => id) + const results = await Promise.allSettled( + ids.map(async (id) => { + await fallback.shutdown(id, { immediate: true }) + sessionProviders.delete(id) + }) + ) + // Why: fallback cleanup must not abort the user's daemon-restart recovery path. + const failed = results.filter((result) => result.status === 'rejected') + if (failed.length > 0) { + console.warn( + `[daemon] ${failed.length} local fallback PTY session(s) failed to shut down during daemon restart; continuing restart`, + ...failed.map((result) => (result as PromiseRejectedResult).reason) + ) + } + return results.length - failed.length +} diff --git a/src/main/daemon/degraded-daemon-pty-provider.test.ts b/src/main/daemon/degraded-daemon-pty-provider.test.ts index 7bd656fc6fbb..188173816db0 100644 --- a/src/main/daemon/degraded-daemon-pty-provider.test.ts +++ b/src/main/daemon/degraded-daemon-pty-provider.test.ts @@ -4,13 +4,14 @@ import type { DaemonPtyAdapter } from './daemon-pty-adapter' import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from '../providers/types' type ProviderMock = IPtyProvider & { - emitData: (id: string, data: string) => void + emitData: (id: string, data: string, sequenceChars?: number) => void emitReplay: (id: string, data: string) => void emitExit: (id: string, code: number) => void } function createProvider(label: string, sessions: string[] = []): ProviderMock { - const dataListeners: ((payload: { id: string; data: string }) => void)[] = [] + const dataListeners: ((payload: { id: string; data: string; sequenceChars?: number }) => void)[] = + [] const replayListeners: ((payload: { id: string; data: string }) => void)[] = [] const exitListeners: ((payload: { id: string; code: number }) => void)[] = [] return { @@ -36,20 +37,23 @@ function createProvider(label: string, sessions: string[] = []): ProviderMock { acknowledgeDataEvent: vi.fn(), hasChildProcesses: vi.fn(async () => false), getForegroundProcess: vi.fn(async () => null), + confirmForegroundProcess: vi.fn(async () => `${label}-confirmed`), serialize: vi.fn(async () => '{}'), revive: vi.fn(async () => {}), listProcesses: vi.fn(async () => sessions.map((id) => ({ id, cwd: '', title: label }))), getDefaultShell: vi.fn(async () => '/bin/zsh'), getProfiles: vi.fn(async () => []), - onData: vi.fn((callback: (payload: { id: string; data: string }) => void) => { - dataListeners.push(callback) - return () => { - const idx = dataListeners.indexOf(callback) - if (idx !== -1) { - dataListeners.splice(idx, 1) + onData: vi.fn( + (callback: (payload: { id: string; data: string; sequenceChars?: number }) => void) => { + dataListeners.push(callback) + return () => { + const idx = dataListeners.indexOf(callback) + if (idx !== -1) { + dataListeners.splice(idx, 1) + } } } - }), + ), onReplay: vi.fn((callback: (payload: { id: string; data: string }) => void) => { replayListeners.push(callback) return () => { @@ -68,9 +72,9 @@ function createProvider(label: string, sessions: string[] = []): ProviderMock { } } }), - emitData: (id: string, data: string) => { + emitData: (id: string, data: string, sequenceChars?: number) => { for (const listener of dataListeners) { - listener({ id, data }) + listener({ id, data, ...(sequenceChars === undefined ? {} : { sequenceChars }) }) } }, emitReplay: (id: string, data: string) => { @@ -105,6 +109,19 @@ function createDaemonAdapter( } describe('DegradedDaemonPtyProvider', () => { + it('routes fresh foreground confirmation to the session owner', async () => { + const current = createDaemonAdapter('daemon', ['daemon-session']) + const fallback = createProvider('fallback') + const provider = new DegradedDaemonPtyProvider({ current, legacy: [], fallback }) + await provider.discoverDaemonSessions() + const fresh = await provider.spawn({ cols: 80, rows: 24 }) + + await expect(provider.confirmForegroundProcess('daemon-session')).resolves.toBe( + 'daemon-confirmed' + ) + await expect(provider.confirmForegroundProcess(fresh.id)).resolves.toBe('fallback-confirmed') + }) + it('routes discovered daemon sessions to the daemon and fresh PTYs to the fallback', async () => { const current = createDaemonAdapter('daemon', ['daemon-session']) const fallback = createProvider('fallback') @@ -151,6 +168,30 @@ describe('DegradedDaemonPtyProvider', () => { expect(fallback.write).not.toHaveBeenCalled() }) + it('routes authoritative recovery snapshots to the owning daemon', async () => { + const current = createDaemonAdapter('daemon', ['daemon-session']) + const fallback = createProvider('fallback') + const snapshot = { + data: 'alt frame', + scrollbackAnsi: 'normal history', + cols: 80, + rows: 24, + seq: 42, + source: 'headless' as const + } + current.getBufferSnapshot = vi.fn(async () => snapshot) + const provider = new DegradedDaemonPtyProvider({ current, legacy: [], fallback }) + + await provider.discoverDaemonSessions() + + await expect( + provider.getBufferSnapshot('daemon-session', { scrollbackRows: 50_000 }) + ).resolves.toEqual(snapshot) + expect(current.getBufferSnapshot).toHaveBeenCalledWith('daemon-session', { + scrollbackRows: 50_000 + }) + }) + it('forwards replay output from fallback and daemon providers', () => { const current = createDaemonAdapter('daemon') const fallback = createProvider('fallback') @@ -174,6 +215,22 @@ describe('DegradedDaemonPtyProvider', () => { }) }) + it('preserves explicit sequence accounting on daemon data events', () => { + const current = createDaemonAdapter('daemon') + const fallback = createProvider('fallback') + const provider = new DegradedDaemonPtyProvider({ current, legacy: [], fallback }) + const dataSpy = vi.fn() + provider.onData(dataSpy) + + current.emitData('daemon-session', '\x1b[6n', 0) + + expect(dataSpy).toHaveBeenCalledWith({ + id: 'daemon-session', + data: '\x1b[6n', + sequenceChars: 0 + }) + }) + it('detaches provider subscriptions without disposing the underlying providers', () => { const current = createDaemonAdapter('daemon') const fallback = createProvider('fallback') diff --git a/src/main/daemon/degraded-daemon-pty-provider.ts b/src/main/daemon/degraded-daemon-pty-provider.ts index a7b8c68fa194..572cb0aca37f 100644 --- a/src/main/daemon/degraded-daemon-pty-provider.ts +++ b/src/main/daemon/degraded-daemon-pty-provider.ts @@ -1,6 +1,9 @@ import type { DaemonPtyAdapter } from './daemon-pty-adapter' +import { shutdownDegradedFallbackSessions } from './degraded-daemon-fallback-shutdown' import type { IPtyProvider, + PtyBackgroundStreamEvent, + PtyProviderBufferSnapshot, PtyProcessInfo, PtySpawnOptions, PtySpawnResult @@ -23,7 +26,11 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { private fallback: ManagedPtyProvider private sessionProviders = new Map() private unsubscribers: (() => void)[] = [] - private dataListeners: ((payload: { id: string; data: string }) => void)[] = [] + private dataListeners: ((payload: { + id: string + data: string + sequenceChars?: number + }) => void)[] = [] private exitListeners: ((payload: { id: string; code: number }) => void)[] = [] constructor(opts: { @@ -93,6 +100,18 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { this.providerFor(id).resize(id, cols, rows) } + pauseProducer(id: string): void { + this.providerFor(id).pauseProducer?.(id) + } + + resumeProducer(id: string): void { + this.providerFor(id).resumeProducer?.(id) + } + + setPtyBackgrounded(id: string, background: boolean): void { + this.providerFor(id).setPtyBackgrounded?.(id, background) + } + async shutdown(id: string, opts: { immediate?: boolean; keepHistory?: boolean }): Promise { await this.providerFor(id).shutdown(id, opts) if (!opts.keepHistory) { @@ -116,6 +135,15 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { return (await this.providerFor(id).getAppliedSize?.(id)) ?? null } + async getBufferSnapshot( + id: string, + opts?: { scrollbackRows?: number } + ): Promise { + // Why: a preserved legacy daemon can still thin its monitoring stream; + // recovery must reach the adapter that owns that session's full model. + return (await this.providerFor(id).getBufferSnapshot?.(id, opts)) ?? null + } + async clearBuffer(id: string): Promise { await this.providerFor(id).clearBuffer(id) } @@ -132,6 +160,10 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { return this.providerFor(id).getForegroundProcess(id) } + async confirmForegroundProcess(id: string): Promise { + return this.providerFor(id).confirmForegroundProcess?.(id) ?? null + } + async serialize(ids: string[]): Promise { return this.fallback.serialize(ids) } @@ -155,7 +187,9 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { return this.fallback.getProfiles() } - onData(callback: (payload: { id: string; data: string }) => void): () => void { + onData( + callback: (payload: { id: string; data: string; sequenceChars?: number }) => void + ): () => void { this.dataListeners.push(callback) return () => { const idx = this.dataListeners.indexOf(callback) @@ -165,6 +199,17 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { } } + onBackgroundStreamEvent(callback: (payload: PtyBackgroundStreamEvent) => void): () => void { + const unsubscribes = this.allProviders().flatMap( + (provider) => provider.onBackgroundStreamEvent?.(callback) ?? [] + ) + return () => { + for (const unsubscribe of unsubscribes) { + unsubscribe() + } + } + } + onReplay(callback: (payload: { id: string; data: string }) => void): () => void { const unsubscribes = this.allProviders().map((provider) => provider.onReplay(callback)) let active = true @@ -237,28 +282,7 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { } async shutdownFallbackSessions(): Promise { - const ids = [...this.sessionProviders] - .filter(([, provider]) => provider === this.fallback) - .map(([id]) => id) - const results = await Promise.allSettled( - ids.map(async (id) => { - await this.fallback.shutdown(id, { immediate: true }) - this.sessionProviders.delete(id) - }) - ) - // Why: this runs first in the daemon-restart sequence. A throw here would - // abort the whole restart and leave "Restart daemon" — the user's recovery - // path for a wedged terminal — unusable, recreating the original lockup. So - // it is best-effort: log failures, keep restarting, and only count the - // sessions that actually shut down. - const failed = results.filter((result) => result.status === 'rejected') - if (failed.length > 0) { - console.warn( - `[daemon] ${failed.length} local fallback PTY session(s) failed to shut down during daemon restart; continuing restart`, - ...failed.map((result) => (result as PromiseRejectedResult).reason) - ) - } - return results.length - failed.length + return shutdownDegradedFallbackSessions(this.sessionProviders, this.fallback) } getCurrentDaemonSessionIds(): string[] { diff --git a/src/main/daemon/headless-emulator-fidelity.fuzz.test.ts b/src/main/daemon/headless-emulator-fidelity.fuzz.test.ts new file mode 100644 index 000000000000..8ce1191722de --- /dev/null +++ b/src/main/daemon/headless-emulator-fidelity.fuzz.test.ts @@ -0,0 +1,430 @@ +import { describe, expect, it } from 'vitest' +import { HeadlessEmulator } from './headless-emulator' +import { + buildAgentTuiStreamOps, + mulberry32, + splitIntoRandomChunks, + type AgentTuiStreamDims +} from '../../shared/agent-tui-ansi-fuzz-stream' +import { + POST_REPLAY_LIVE_SNAPSHOT_RESET_PARITY, + SNAPSHOT_REPLAY_PREAMBLE_ALT, + SNAPSHOT_REPLAY_PREAMBLE_NORMAL, + bufferHasSerializeHostileWrappedRow, + createRendererParityTerminal, + cursorPosition, + normalBufferRowsTrimmed, + visibleRowStyles, + visibleRows, + writeChunksToTerminal +} from '../../shared/terminal-restore-parity-fixture' + +// Differential garble gate for the hidden-terminal model/view contract +// (docs/reference/terminal-model-view-contract.md): with the hidden-delivery +// gate on, a hidden pane receives NOTHING — main's HeadlessEmulator is the +// source of truth and reveal repaints the renderer xterm from +// preamble + rehydrateSequences + snapshotAnsi (applyMainBufferSnapshot). +// This fuzz feeds seeded agent-TUI byte streams to the production emulator +// and to an always-visible renderer-parity terminal, then asserts the +// serialize→replay round trip reproduces the exact screen the renderer would +// have shown. Any diff = a garble bug on reveal. +// +// Runtime knobs: +// FUZZ_ITERATIONS=5000 deep/nightly mode (default 300, <60s combined with +// the reveal-reconciliation suite) +// FUZZ_SEED=1234 re-run exactly one seed (repro from a failure log) + +const DEFAULT_ITERATIONS = 300 +const FIXED_SEED = readPositiveIntEnv('FUZZ_SEED') +const ITERATIONS = + FIXED_SEED !== null ? 1 : (readPositiveIntEnv('FUZZ_ITERATIONS') ?? DEFAULT_ITERATIONS) +// Matches HIDDEN_OUTPUT_RESTORE_SCROLLBACK_ROWS in pty-connection.ts — the +// scrollback budget the reveal restore actually requests from main. +const HIDDEN_OUTPUT_RESTORE_SCROLLBACK_ROWS = 5000 + +function readPositiveIntEnv(name: string): number | null { + const raw = Number(process.env[name]) + return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : null +} + +const DIMS: readonly AgentTuiStreamDims[] = [ + { cols: 80, rows: 24 }, + { cols: 100, rows: 30 }, + { cols: 120, rows: 40 } +] + +type FidelityCase = { + seed: number + dims: AgentTuiStreamDims + ops: string[] + chunked: boolean +} + +type FidelityDiff = { + stage: string + expected: unknown + actual: unknown + /** True when the always-visible buffer matches the known upstream + * @xterm/addon-serialize blank-leading-wrapped-row bug predicate — see + * bufferHasSerializeHostileWrappedRow and the skipped repro test below. */ + knownSerializeWrapBug?: boolean +} + +function buildCase(seed: number): FidelityCase { + const rng = mulberry32(seed) + const dims = DIMS[Math.floor(rng() * DIMS.length)]! + const opCount = 12 + Math.floor(rng() * 28) + const ops = buildAgentTuiStreamOps(rng, dims, { + includeMouseModes: true, + includeOscHyperlinks: false, + opCount + }) + return { seed, dims, ops, chunked: true } +} + +function firstDiff(stage: string, expected: unknown, actual: unknown): FidelityDiff | null { + return JSON.stringify(expected) === JSON.stringify(actual) ? null : { stage, expected, actual } +} + +async function runFidelityCase(testCase: FidelityCase): Promise { + const stream = testCase.ops.join('') + const chunks = testCase.chunked + ? splitIntoRandomChunks(mulberry32(testCase.seed ^ 0x9e3779b9), stream, { + minLen: 3, + maxLen: 120 + }) + : [stream] + const emulator = new HeadlessEmulator({ cols: testCase.dims.cols, rows: testCase.dims.rows }) + const control = createRendererParityTerminal(testCase.dims) + const restored = createRendererParityTerminal(testCase.dims) + try { + for (const chunk of chunks) { + await emulator.write(chunk) + } + await writeChunksToTerminal(control.terminal, chunks) + + // Stage 1 — model fidelity: the emulator's screen must already match the + // renderer twin before any serialization enters the picture. + const modelDiff = firstDiff( + 'model-visible (HeadlessEmulator vs renderer twin)', + visibleRows(control.terminal), + emulator.getVisibleLines() + ) + if (modelDiff) { + return modelDiff + } + + // Stage 2 — reveal round trip: serialize exactly like + // serializeHiddenOutputRecoveryBuffer, replay exactly like + // applyMainBufferSnapshot, then compare against the always-visible twin. + const alt = emulator.isAlternateScreen + const snapshot = emulator.getSnapshot({ + scrollbackRows: alt ? 0 : HIDDEN_OUTPUT_RESTORE_SCROLLBACK_ROWS + }) + await writeChunksToTerminal(restored.terminal, [ + alt ? SNAPSHOT_REPLAY_PREAMBLE_ALT : SNAPSHOT_REPLAY_PREAMBLE_NORMAL, + snapshot.rehydrateSequences + snapshot.snapshotAnsi, + POST_REPLAY_LIVE_SNAPSHOT_RESET_PARITY + ]) + + const diffs = [ + firstDiff( + 'restore-visible-text', + visibleRows(control.terminal), + visibleRows(restored.terminal) + ), + firstDiff( + 'restore-visible-styles', + visibleRowStyles(control.terminal), + visibleRowStyles(restored.terminal) + ), + firstDiff( + 'restore-cursor', + cursorPosition(control.terminal), + cursorPosition(restored.terminal) + ), + firstDiff( + 'restore-mode-bracketed-paste', + control.terminal.modes.bracketedPasteMode, + restored.terminal.modes.bracketedPasteMode + ), + // Why alt is excluded from the two comparisons below: + // - scrollback: serializeHeadlessTerminalBuffer (orca-runtime.ts) + // deliberately forces scrollbackRows=0 while an alt-screen TUI is + // active, so normal-buffer history is not part of the alt contract. + // - application cursor: HeadlessEmulator.getModes reports + // applicationCursor false on the alternate buffer, so rehydrate omits + // ?1h there by design. + alt + ? null + : firstDiff( + 'restore-scrollback-text', + normalBufferRowsTrimmed(control.terminal), + normalBufferRowsTrimmed(restored.terminal) + ), + alt + ? null + : firstDiff( + 'restore-mode-application-cursor', + control.terminal.modes.applicationCursorKeysMode, + restored.terminal.modes.applicationCursorKeysMode + ) + ] + const diff = diffs.find((candidate) => candidate !== null) ?? null + if (!diff) { + return null + } + if (bufferHasSerializeHostileWrappedRow(control.terminal)) { + return { ...diff, knownSerializeWrapBug: true } + } + return diff + } finally { + emulator.dispose() + control.terminal.dispose() + restored.terminal.dispose() + } +} + +/** Greedy op-drop minimizer: re-runs the full differential pipeline on + * smaller op lists so a failure report carries the smallest byte stream that + * still diverges (plus its seed for exact replay via FUZZ_SEED). */ +async function minimizeFailure(testCase: FidelityCase): Promise { + let current = { ...testCase, chunked: false } + if ((await runFidelityCase(current)) === null) { + current = { ...testCase, chunked: true } + } + let budget = 400 + let shrunk = true + while (shrunk && budget > 0) { + shrunk = false + for (let i = current.ops.length - 1; i >= 0 && budget > 0; i--) { + const candidate = { ...current, ops: current.ops.toSpliced(i, 1) } + budget -= 1 + if ((await runFidelityCase(candidate)) !== null) { + current = candidate + shrunk = true + } + } + } + return current +} + +function formatFailure(minimized: FidelityCase, diff: FidelityDiff | null): string { + return [ + `HeadlessEmulator fidelity divergence — stage: ${diff?.stage ?? 'unknown'}`, + `seed: ${minimized.seed} (re-run: FUZZ_SEED=${minimized.seed} pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/headless-emulator-fidelity.fuzz.test.ts)`, + `dims: ${minimized.dims.cols}x${minimized.dims.rows} chunked: ${minimized.chunked}`, + `minimized ops (${minimized.ops.length}): ${JSON.stringify(minimized.ops)}`, + `expected (always-visible renderer twin): ${JSON.stringify(diff?.expected)}`, + `actual (snapshot restore replay): ${JSON.stringify(diff?.actual)}` + ].join('\n') +} + +describe('headless emulator snapshot fidelity fuzz', () => { + // Known-legitimate divergence, pinned so it cannot silently regress into a + // real one: xterm marks OSC 8 hyperlink cells underlined, SerializeAddon + // never re-emits OSC 8, and production compensates by shipping the ranges + // out-of-band in snapshot.oscLinks (collectHeadlessOscLinkRanges) for the + // renderer link provider to re-register. Byte-replay therefore keeps the + // TEXT but not the link underline — the metadata must carry the range. + it('drops OSC 8 underline from byte replay but preserves the range in snapshot metadata', async () => { + const emulator = new HeadlessEmulator({ cols: 60, rows: 10 }) + const restored = createRendererParityTerminal({ cols: 60, rows: 10 }) + try { + await emulator.write('\x1b]8;;https://example.com/pr/7\x07review link\x1b]8;;\x07 tail') + const snapshot = emulator.getSnapshot({ scrollbackRows: 5000 }) + await writeChunksToTerminal(restored.terminal, [ + SNAPSHOT_REPLAY_PREAMBLE_NORMAL, + snapshot.rehydrateSequences + snapshot.snapshotAnsi, + POST_REPLAY_LIVE_SNAPSHOT_RESET_PARITY + ]) + expect(visibleRows(restored.terminal)[0]).toBe('review link tail') + expect(snapshot.oscLinks).toContainEqual({ + row: 0, + startCol: 0, + endCol: 11, + uri: 'https://example.com/pr/7' + }) + } finally { + emulator.dispose() + restored.terminal.dispose() + } + }) + + it(`matches an always-visible renderer twin across ${ITERATIONS} seeded agent-TUI streams`, async () => { + // The known-and-pinned serialize wrap bug (A) is tolerated + counted so + // deep mode (FUZZ_ITERATIONS) surfaces only GENUINELY NEW divergences. + // Bugs B (bold-reset, fixed by the addon patch) and C (margin cursor, + // fixed by the absolute-cursor epilogue) are no longer tolerated — a + // regression fails the corpus loudly and the unskipped repros below. + let knownSerializeWrapBugHits = 0 + for (let i = 0; i < ITERATIONS; i++) { + const seed = FIXED_SEED ?? 1 + i + const testCase = buildCase(seed) + const diff = await runFidelityCase(testCase) + if (diff?.knownSerializeWrapBug) { + knownSerializeWrapBugHits += 1 + continue + } + if (diff) { + const minimized = await minimizeFailure(testCase) + const minimizedDiff = await runFidelityCase(minimized) + expect.fail(formatFailure(minimized, minimizedDiff ?? diff)) + } + } + // Guard the tolerance from swallowing the suite: the predicate tripping + // on most seeds means the gate has gone degenerate. + expect(knownSerializeWrapBugHits).toBeLessThan(Math.max(3, ITERATIONS * 0.5)) + }, 600_000) + + // ── HEADLINE FINDING (do not delete while unfixed upstream) ────────────── + // @xterm/addon-serialize 0.15.0-beta.287 does not round-trip null cells + // that touch a soft-wrap boundary. Two variants, both found by this fuzz + // and minimized below. Every Orca snapshot consumer is affected: hidden + // reveal, parked-tab reveal, sleep/wake restore, and mobile subscribe + // replay paint lost/shifted characters or stray '-' fillers whenever a TUI + // erased inside a soft-wrapped line (shell line editing, status lines wider + // than the pane, Claude Code in-place prompt redraws). + // + // V1 — cell loss (found by seed 31, minimized to 2 ops): + // Root cause: the wrap-validity ternary in SerializeAddon.ts (~L214) + // nextRowFirstChar.getChars() && isNextRowFirstCharDoubleWidth + // ? this._nullCellCount <= 1 : this._nullCellCount <= 0 + // binds as `(chars && doubleWidth) ? ...`, so a null-leading wrapped row + // passes as a "natural" wrap. The serializer then emits the previous row as + // full-width text (leaving xterm in wrap-pending) and skips the null cell + // with CUF (`ESC[1C`) — but CUF clamps at the right margin instead of + // crossing the wrap boundary, so the next character overwrites the previous + // row's last cell and the whole tail shifts left by one. + // cols=20: write 'ABCDEFGHIJKLMNOPQRSTUVWXYZ12\r\n' then '\x1b[1A\x1b[1K' + // live rows: ['ABCDEFGHIJKLMNOPQRST', ' VWXYZ12'] + // serialize(): 'ABCDEFGHIJKLMNOPQRST\x1b[1CVWXYZ12\x1b[8D' + // replayed rows: ['ABCDEFGHIJKLMNOPQRSV', 'WXYZ12'] ← 'T' eaten, tail shifted + // + // V2 — stray filler '-' (found by seed 157, minimized below): when the + // SOURCE row of a wrapped pair is entirely null (a TUI erased the whole + // first half of a wrapped line), the addon's forced-wrap "magic" writes + // nullCellCount+1 dashes and then cleans up with + // ESC[A ESC[(length-nullCellCount)C ESC[(nullCellCount)X ... + // With length === nullCellCount that cursor-forward becomes `ESC[0C`, and + // CSI param 0 means 1, so the ECH erase lands one cell right and the first + // '-' stays visible on the restored row. + // Unskip once the upstream fix (or a local serialize post-processor) lands. + it.skip('round-trips a wrapped line whose continuation row starts with an erased cell', async () => { + const emulator = new HeadlessEmulator({ cols: 20, rows: 6 }) + const control = createRendererParityTerminal({ cols: 20, rows: 6 }) + const restored = createRendererParityTerminal({ cols: 20, rows: 6 }) + try { + const bytes = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ12\r\n', '\x1b[1A\x1b[1K'] + for (const chunk of bytes) { + await emulator.write(chunk) + } + await writeChunksToTerminal(control.terminal, bytes) + const snapshot = emulator.getSnapshot({ scrollbackRows: 5000 }) + await writeChunksToTerminal(restored.terminal, [ + SNAPSHOT_REPLAY_PREAMBLE_NORMAL, + snapshot.rehydrateSequences + snapshot.snapshotAnsi, + POST_REPLAY_LIVE_SNAPSHOT_RESET_PARITY + ]) + expect(visibleRows(restored.terminal)).toEqual(visibleRows(control.terminal)) + } finally { + emulator.dispose() + control.terminal.dispose() + restored.terminal.dispose() + } + }) + + // V2 repro of the headline finding above (stray '-' filler on a fully + // erased wrapped source row). Unskip alongside the V1 repro. + it.skip('round-trips a wrapped line whose source row was fully erased', async () => { + const emulator = new HeadlessEmulator({ cols: 20, rows: 6 }) + const control = createRendererParityTerminal({ cols: 20, rows: 6 }) + const restored = createRendererParityTerminal({ cols: 20, rows: 6 }) + try { + // Wrap a 28-char line, then erase the entire first (source) row of the + // wrapped pair: cursor up twice onto it, EL 2. + const bytes = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ12\r\n', '\x1b[2A\x1b[2K'] + for (const chunk of bytes) { + await emulator.write(chunk) + } + await writeChunksToTerminal(control.terminal, bytes) + const snapshot = emulator.getSnapshot({ scrollbackRows: 5000 }) + await writeChunksToTerminal(restored.terminal, [ + SNAPSHOT_REPLAY_PREAMBLE_NORMAL, + snapshot.rehydrateSequences + snapshot.snapshotAnsi, + POST_REPLAY_LIVE_SNAPSHOT_RESET_PARITY + ]) + // Fails today: restored row 0 shows '-' where the live row is blank. + expect(visibleRows(restored.terminal)).toEqual(visibleRows(control.terminal)) + } finally { + emulator.dispose() + control.terminal.dispose() + restored.terminal.dispose() + } + }) + + // ── Bug B regression guard: SGR bold on a dim→bold-only cell transition ── + // Upstream @xterm/addon-serialize emitted `\x1b[1;22m` for this transition; + // SGR 22 (normalIntensity) clears BOTH bold and dim, so the restored cell + // lost its bold. FIXED by the intensity-group reorder in + // config/patches/@xterm__addon-serialize@0.15.0-beta.287.patch (22 before + // 1/2). Found by fuzz seeds 435, 770, 1321; mechanism in + // notes/garble-fuzz-divergences.md (Bug B). + it('preserves bold when serializing a dim cell followed by a bold-only cell', async () => { + const emulator = new HeadlessEmulator({ cols: 20, rows: 4 }) + const control = createRendererParityTerminal({ cols: 20, rows: 4 }) + const restored = createRendererParityTerminal({ cols: 20, rows: 4 }) + try { + // 'A' dim, 'B' bold-only. Live: A=dim, B=bold. The patched serializer + // emits 22;1 for the B transition (clear before re-set). + const bytes = ['\x1b[2mA\x1b[22m\x1b[1mB\x1b[0m'] + for (const chunk of bytes) { + await emulator.write(chunk) + } + await writeChunksToTerminal(control.terminal, bytes) + const snapshot = emulator.getSnapshot({ scrollbackRows: 5000 }) + await writeChunksToTerminal(restored.terminal, [ + SNAPSHOT_REPLAY_PREAMBLE_NORMAL, + snapshot.rehydrateSequences + snapshot.snapshotAnsi, + POST_REPLAY_LIVE_SNAPSHOT_RESET_PARITY + ]) + expect(visibleRowStyles(restored.terminal)).toEqual(visibleRowStyles(control.terminal)) + } finally { + emulator.dispose() + control.terminal.dispose() + restored.terminal.dispose() + } + }) + + // ── Bug C regression guard: cursor exact when the last row fills the margin ── + // Upstream @xterm/addon-serialize computes its relative cursor-restore from + // a wrap-pending position and lands one column short. FIXED Orca-side: the + // emulator snapshot appends an absolute CUP from the source's authoritative + // cursor (serializeWithAbsoluteCursor). Found by fuzz seeds 454, 1696; + // mechanism in notes/garble-fuzz-divergences.md (Bug C). + it('restores the cursor exactly when the last content row fills the right margin', async () => { + const emulator = new HeadlessEmulator({ cols: 10, rows: 4 }) + const control = createRendererParityTerminal({ cols: 10, rows: 4 }) + const restored = createRendererParityTerminal({ cols: 10, rows: 4 }) + try { + // Fill row 0 to exactly 10 cols (wrap-pending), then CUP the cursor to a + // known lower-row column. Live cursor is (x=4, y=2). + const bytes = ['0123456789\x1b[3;5H'] + for (const chunk of bytes) { + await emulator.write(chunk) + } + await writeChunksToTerminal(control.terminal, bytes) + const snapshot = emulator.getSnapshot({ scrollbackRows: 5000 }) + await writeChunksToTerminal(restored.terminal, [ + SNAPSHOT_REPLAY_PREAMBLE_NORMAL, + snapshot.rehydrateSequences + snapshot.snapshotAnsi, + POST_REPLAY_LIVE_SNAPSHOT_RESET_PARITY + ]) + expect(cursorPosition(restored.terminal)).toEqual(cursorPosition(control.terminal)) + } finally { + emulator.dispose() + control.terminal.dispose() + restored.terminal.dispose() + } + }) +}) diff --git a/src/main/daemon/headless-emulator.test.ts b/src/main/daemon/headless-emulator.test.ts index 1a7dd6c5abe6..b9630b8ff7e3 100644 --- a/src/main/daemon/headless-emulator.test.ts +++ b/src/main/daemon/headless-emulator.test.ts @@ -98,6 +98,74 @@ describe('HeadlessEmulator', () => { uri: 'https://example.com/issue/1234' }) }) + + it('serializes split synchronized rich TUI frames for model-backed replay', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 12 }) + const richFrame = [ + '\x1b[?2026h', + '\x1b[?1049h', + '\x1b[2J\x1b[H', + '\x1b[?25l', + '\x1b[2;36m╭────────────────────────────╮\x1b[0m\r\n', + '\x1b[2;36m│ Codex rich restore 🟢 ███░ │\x1b[0m\r\n', + '\x1b[2;36m│ status streaming │\x1b[0m\r\n', + '\x1b[2;36m╰────────────────────────────╯\x1b[0m', + '\x1b[6;4H\x1b[?25h', + '\x1b[?2026l' + ].join('') + + // Why: hidden rich TUI bytes may arrive split across DEC 2026 frame + // boundaries; model/view work needs the headless model to preserve the + // final visible state before renderer writes can be removed. + await emulator.write(richFrame.slice(0, 17)) + await emulator.write(richFrame.slice(17, 91)) + await emulator.write(richFrame.slice(91)) + + const snapshot = emulator.getSnapshot() + expect(snapshot.modes.alternateScreen).toBe(true) + expect(snapshot.snapshotAnsi).toContain('Codex rich restore') + expect(snapshot.snapshotAnsi).toContain('🟢') + expect(snapshot.snapshotAnsi).toContain('███░') + expect(snapshot.snapshotAnsi).toContain('╭') + expect(snapshot.snapshotAnsi).not.toContain('\x1b[?2026h') + + const replay = new HeadlessEmulator({ cols: snapshot.cols, rows: snapshot.rows }) + try { + await replay.write(snapshot.rehydrateSequences + snapshot.snapshotAnsi) + const replayed = replay.getSnapshot() + expect(replayed.modes.alternateScreen).toBe(true) + expect(replayed.snapshotAnsi).toContain('Codex rich restore') + expect(replayed.snapshotAnsi).toContain('🟢') + expect(replayed.snapshotAnsi).toContain('███░') + } finally { + replay.dispose() + } + }) + + it('preserves the normal buffer behind an alternate-screen snapshot', async () => { + emulator = new HeadlessEmulator({ cols: 40, rows: 6 }) + await emulator.write('shell history one\r\nshell history two') + await emulator.write('\x1b[?1049h\x1b[2J\x1b[HTUI frame') + + const snapshot = emulator.getSnapshot() + expect(snapshot.scrollbackAnsi).toContain('shell history one') + expect(snapshot.snapshotAnsi).toContain('TUI frame') + expect(snapshot.snapshotAnsi).not.toContain('shell history one') + + const replay = new HeadlessEmulator({ cols: snapshot.cols, rows: snapshot.rows }) + try { + await replay.write( + snapshot.scrollbackAnsi + snapshot.rehydrateSequences + snapshot.snapshotAnsi + ) + expect(replay.getVisibleLines().join('\n')).toContain('TUI frame') + + await replay.write('\x1b[?1049l') + expect(replay.getVisibleLines().join('\n')).toContain('shell history one') + expect(replay.getVisibleLines().join('\n')).toContain('shell history two') + } finally { + replay.dispose() + } + }) }) describe('OSC-7 CWD tracking', () => { @@ -305,6 +373,49 @@ describe('HeadlessEmulator', () => { expect(emulator.getSnapshot().modes.sgrMouseMode).toBe(false) }) + it('tracks kitty keyboard flags for emulator re-seed parity', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(0) + + await emulator.write('\x1b[=5;1u') + expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(5) + }) + + it('round-trips a pushed CSI > 1 u flag through the core-internals read path', async () => { + // Why: getKittyKeyboardFlags reads _core.coreService.kittyKeyboard.flags, + // a private xterm surface. If an xterm upgrade breaks that path this + // must fail loudly instead of the responder silently answering ?0u. + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + + await emulator.write('\x1b[>1u') + expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(1) + }) + + it('snapshots the active-buffer kitty flags (alt screen keeps its own set)', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + // Kitty flags are per screen buffer: entering the alt screen swaps to + // its own (empty) flag set, exactly what a CSI ? u reply would report. + await emulator.write('\x1b[=5;1u\x1b[?1049h') + expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(0) + + await emulator.write('\x1b[=3;1u') + expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(3) + + await emulator.write('\x1b[?1049l') + expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(5) + }) + + it('never pushes kitty flags into rehydrateSequences', async () => { + // Why: POST_REPLAY_REATTACH_RESET's deliberate kitty reset must stay + // authoritative for renderer replays (terminal-query-authority.md). + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + await emulator.write('\x1b[?1049h\x1b[=5;1u') + + const snapshot = emulator.getSnapshot() + expect(snapshot.modes.kittyKeyboardFlags).toBe(5) + expect(snapshot.rehydrateSequences).not.toContain('u') + }) + it('tracks split SGR mouse reporting sequences', async () => { emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) @@ -498,6 +609,48 @@ describe('HeadlessEmulator', () => { expect(snapshot.rehydrateSequences).toContain('\x1b[?1006h') expect(snapshot.rehydrateSequences).not.toContain('\x1b[?1002h') }) + + it('records kitty flags without pushing them into renderer rehydration', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + // OMP/pi negotiate progressive enhancement with a level-1 push. + await emulator.write('\x1b[>1u') + + const snapshot = emulator.getSnapshot() + expect(snapshot.modes.kittyKeyboardFlags).toBe(1) + // Why: renderer replay deliberately resets stale CSI-u state; the daemon + // warm-reattach path re-seeds the model from modes.kittyKeyboardFlags. + expect(snapshot.rehydrateSequences).not.toContain('\x1b[=1;1u') + }) + + it('omits kitty rehydration after the TUI pops its flags', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + await emulator.write('\x1b[>1u') + await emulator.write('\x1b[ { + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + await emulator.write('\x1b[?1049h\x1b[>1u') + + const snapshot = emulator.getSnapshot() + const altScreenIndex = snapshot.rehydrateSequences.indexOf('\x1b[?1049h') + const kittyIndex = snapshot.rehydrateSequences.indexOf('\x1b[=1;1u') + expect(altScreenIndex).toBeGreaterThanOrEqual(0) + expect(kittyIndex).toBe(-1) + }) + + it('drops kitty rehydration after a TUI soft reset (DECSTR)', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + await emulator.write('\x1b[>1u') + await emulator.write('\x1b[!p') + + const snapshot = emulator.getSnapshot() + expect(snapshot.modes.kittyKeyboardFlags).toBe(0) + }) }) describe('dispose', () => { diff --git a/src/main/daemon/headless-emulator.ts b/src/main/daemon/headless-emulator.ts index fb0a9c190d41..e7da2a4589e5 100644 --- a/src/main/daemon/headless-emulator.ts +++ b/src/main/daemon/headless-emulator.ts @@ -3,11 +3,21 @@ import { Terminal } from '@xterm/headless' import { SerializeAddon } from '@xterm/addon-serialize' import { Unicode11Addon } from '@xterm/addon-unicode11' import { activateOrcaTerminalUnicodeProvider } from '../../shared/terminal-unicode-provider' -import { extractLastOscTitle } from '../../shared/agent-detection' +import { + readSavedCursorRegister, + serializeWithAbsoluteCursor +} from '../../shared/terminal-serialize-absolute-cursor' +import { advancePartialEscapeTail } from '../../shared/terminal-partial-escape-tail' +import type { TerminalViewAttributes } from '../../shared/terminal-view-attributes' import { collectHeadlessOscLinkRanges } from './headless-osc-link-ranges' -import { extractOscScanTail, scanOsc7Uris } from './osc7-uri-extraction' -import { parseFileUriPath } from './osc7-file-uri' -import { TerminalPrivateModeTracker } from './terminal-private-mode-tracker' +import { buildRehydrateSequences } from './terminal-mode-rehydrate-sequences' +import { TerminalMouseModeMirror } from './terminal-mouse-mode-mirror' +import { TerminalOscCwdTitleScanner } from './terminal-osc-cwd-title-scanner' +import { splitTerminalSnapshotAnsi } from './terminal-snapshot-ansi-buffers' +import { + installTerminalViewAttributeResponder, + type TerminalViewAttributeResponder +} from './terminal-view-attribute-responder' import type { TerminalSnapshot, TerminalModes } from './types' import type { TerminalOscLinkRange } from '../../shared/terminal-osc-link-ranges' @@ -15,40 +25,87 @@ export type HeadlessEmulatorOptions = { cols: number rows: number scrollback?: number + /** Phase-5 model query responder sink (terminal-query-authority.md). + * When set, xterm-core auto-replies generated while parsing a write + * flagged `forwardQueryReplies` are forwarded here; all other emissions + * (seeds, hydration, snapshot replay, unsolicited core pushes) are + * discarded. The daemon Session must NEVER pass this — its emulator + * stays write-only forever (contract invariant: the daemon never + * answers). */ + onQueryReply?: (reply: string) => void pathFlavor?: 'posix' | 'win32' remotePosixFileUriAuthority?: boolean } +export type HeadlessEmulatorWriteOptions = { + /** Reply ownership captured at ingestion for this exact chunk. Default + * false is the main-side replay guard (twin of the renderer's + * replay-guard.ts): seed/hydration/snapshot writes never forward. */ + forwardQueryReplies?: boolean +} + type TerminalWithSynchronousWrite = Terminal & { _core?: { writeSync?: (data: string) => void + // Why: kitty keyboard flags are not on the public IModes; read the core + // service state the CSI =/>/< u handlers mutate. + coreService?: { + kittyKeyboard?: { flags?: number } + } } } const DEFAULT_SCROLLBACK = 5000 -const OSC_SCAN_TAIL_LIMIT = 4096 +// Keep in sync with the renderer twin in terminal-capability-replies.ts +// (main must not import renderer modules). +const CONPTY_DA1_RESPONSE = '\x1b[?61;4c' export class HeadlessEmulator { private terminal: Terminal private serializer: SerializeAddon - private cwd: string | null = null - private lastTitle: string | null = null - private oscScanTail = '' - private privateModes = new TerminalPrivateModeTracker() - private restoredOscLinks: TerminalOscLinkRange[] = [] - private disposed = false + // Why: our restructure owns cwd/title via TerminalOscCwdTitleScanner and the + // DECSET mouse modes via TerminalMouseModeMirror (functionally identical to + // main's inline cwd/lastTitle/oscScanTail + TerminalPrivateModeTracker, which + // only tracks the same mouse modes). restoredOscLinks/disposed/partialEscapeTail + // are declared below. + private oscText: TerminalOscCwdTitleScanner + private mouseModes = new TerminalMouseModeMirror() private readonly pathFlavor?: 'posix' | 'win32' private readonly remotePosixFileUriAuthority: boolean + private restoredOscLinks: TerminalOscLinkRange[] = [] + private disposed = false + private onQueryReply: ((reply: string) => void) | null + private conptyDa1OverrideInstalled = false + private viewAttributeResponder: TerminalViewAttributeResponder | null = null + // Why: replies must be scoped to the exact write that carried the query. + // The window opens around the parse of a forward-flagged chunk and closes + // with it, so seeds/snapshots and unsolicited core emissions (e.g. native + // 997 pushes from option mutations) can never leak to the PTY. + private queryReplyForwardingDepth = 0 + // Why: a chunk ending mid-escape leaves the sequence in xterm's parser, not + // the buffer, so serialize() drops it and the next chunk's continuation + // renders literal after a restore (Bug E, notes/garble-fuzz-divergences.md). + // Committed alongside mouseModes: only after xterm parsed the same bytes. + private partialEscapeTail = '' constructor(opts: HeadlessEmulatorOptions) { this.pathFlavor = opts.pathFlavor this.remotePosixFileUriAuthority = opts.remotePosixFileUriAuthority === true + this.oscText = new TerminalOscCwdTitleScanner({ + pathFlavor: this.pathFlavor, + remotePosixAuthority: this.remotePosixFileUriAuthority + }) this.terminal = new Terminal({ cols: opts.cols, rows: opts.rows, scrollback: opts.scrollback ?? DEFAULT_SCROLLBACK, allowProposedApi: true, - logLevel: 'off' + logLevel: 'off', + // Why: parity with the renderer's buildDefaultTerminalOptions — parse + // CSI =/>/< u pushes so CSI ? u answers with the flags the hidden app + // actually pushed. Write-only daemon use is unaffected: keyboard state + // never alters serialization (terminal-query-authority.md §kitty). + vtExtensions: { kittyKeyboard: true } }) this.serializer = new SerializeAddon() @@ -62,33 +119,137 @@ export class HeadlessEmulator { this.terminal.loadAddon(new Unicode11Addon()) activateOrcaTerminalUnicodeProvider(this.terminal) - // Why no onData wiring: this emulator exists purely for state tracking - // (snapshots, cwd, mode flags). It MUST NOT respond to terminal query - // sequences (DA1/DA2, DSR, OSC 10/11/12, DECRPM). The emulator parses - // data in-process synchronously before `handleSubprocessData` forwards - // it to the renderer over IPC, so any reply it emits would land on the - // shell's stdin ahead of the renderer's xterm reply and win the race. - // The renderer is the authoritative responder (it has the real theme, - // cursor position, and paste mode); a daemon-side reply would be a - // double-reply with wrong values. OSC 11 was the visible casualty: - // Claude Code's /theme auto always saw the emulator's default-black - // background regardless of Orca's configured terminal theme. + // Why onData is gated behind onQueryReply: by default this emulator is + // pure state tracking and MUST NOT respond to terminal query sequences + // (DA1/DA2, DSR, OSC 10/11/12, DECRPM). The daemon emulator parses data + // in-process synchronously before `handleSubprocessData` forwards it to + // the renderer over IPC, so any reply it emitted would land on the + // shell's stdin ahead of the renderer's xterm reply and win the race — + // a double-reply with default-xterm values (OSC 11 default-black was + // the visible casualty). Only main's runtime per-PTY emulators pass a + // sink, and even then replies flow only for chunks the hidden-delivery + // gate DROPPED, where the renderer never sees the bytes and main is the + // single answerer. See docs/reference/terminal-query-authority.md. + this.onQueryReply = opts.onQueryReply ?? null + if (this.onQueryReply) { + this.terminal.onData((reply) => this.emitQueryReply(reply)) + } + } + + /** Main-side twin of the renderer's terminal-capability-replies.ts: + * ConPTY 1.22+ blocks at spawn waiting for a DA1 reply, and the override + * variant (`CSI ?61;4c`) must win. Returning true consumes the query so + * xterm core's default `?1;2c` cannot double-reply (custom CSI handlers + * run before core's; false falls through). The reply still routes through + * the forwarding window, so replayed/seeded bytes never answer. */ + installConptyPrimaryDeviceAttributesOverride(): void { + // Why idempotent: the spawn mark can land after daemon stream data + // already created the emulator, so the override is installed both at + // creation and retrofitted at mark time — never stacked. + if (this.conptyDa1OverrideInstalled) { + return + } + this.conptyDa1OverrideInstalled = true + this.terminal.parser.registerCsiHandler({ final: 'c' }, (params) => { + const isPrimaryQuery = params.length === 0 || (params.length === 1 && params[0] === 0) + if (!isPrimaryQuery) { + return false + } + this.emitQueryReply(CONPTY_DA1_RESPONSE) + return true + }) + } + + /** Phase-5 slice-2 view-attribute bridge: the headless core has no theme + * service, so OSC 4/10/11/12 queries and DSR ?996n are answered from the + * renderer's pushed attributes via these parser handlers — never from + * emulator defaults. Runtime-only, like onQueryReply: the daemon Session + * must NEVER call this (its emulator stays write-only forever). */ + installViewAttributeResponder(getBaseAttributes: () => TerminalViewAttributes | null): void { + if (this.viewAttributeResponder) { + return + } + this.viewAttributeResponder = installTerminalViewAttributeResponder({ + parser: this.terminal.parser, + getBaseAttributes, + // emitQueryReply keeps replies inside the per-chunk forwarding window, + // so seeded/replayed view-attribute queries answer no one. + emitReply: (reply) => this.emitQueryReply(reply) + }) + } + + /** Applies a renderer view-attribute push: cursor options make xterm core + * answer DECRQSS DECSCUSR / DECRQM 12 renderer-true, and the per-PTY OSC + * color overrides are dropped because a theme apply overwrites mutated + * colors on visible panes too (ThemeService._setTheme parity). Option + * writes happen outside any forwarding window, so any core emission they + * trigger is discarded (main-side replay guard). */ + applyPushedViewAttributes(attributes: TerminalViewAttributes): void { + if (this.disposed) { + return + } + this.terminal.options.cursorStyle = attributes.cursorStyle + this.terminal.options.cursorBlink = attributes.cursorBlink + this.viewAttributeResponder?.clearColorOverrides() + } + + /** Re-seed parity for snapshot `modes.kittyKeyboardFlags` + * (terminal-query-authority.md §kitty): replays the persisted flags + * through the same `CSI = flags ; 1 u` parse a live push uses, so hidden + * `CSI ? u` reports them instead of `?0u`. Routed as an UNFLAGGED write — + * outside any forwarding window, it can never answer anything — and never + * into renderer rehydrateSequences (POST_REPLAY_REATTACH_RESET's kitty + * reset stays authoritative). */ + applyKittyKeyboardFlags(flags: number): Promise { + if (!Number.isInteger(flags) || flags <= 0) { + return Promise.resolve() + } + return this.write(`\x1b[=${flags};1u`) + } + + private emitQueryReply(reply: string): void { + if (this.queryReplyForwardingDepth > 0 && this.onQueryReply) { + this.onQueryReply(reply) + } + } + + /** Severs the reply sink at PTY teardown. Queued writeChain links may + * still parse after dispose is requested, and daemon respawns reuse + * session ids — a late reply must never reach a successor PTY. */ + disableQueryReplyForwarding(): void { + this.onQueryReply = null } - write(data: string): Promise { + write(data: string, opts: HeadlessEmulatorWriteOptions = {}): Promise { if (this.disposed) { return Promise.resolve() } - if (this.tryWriteSync(data)) { + const forwardQueryReplies = opts.forwardQueryReplies === true + if (this.tryWriteSync(data, { forwardQueryReplies })) { return Promise.resolve() } - this.scanInputForOscState(data) + this.oscText.scan(data) + // Why the sentinel: xterm parses queued writes asynchronously, so opening + // the window at enqueue time would leak it over earlier queued unflagged + // chunks (seed/hydration bytes parsing while depth > 0). Write callbacks + // fire in FIFO parse order, so a zero-byte write whose callback opens the + // window brackets the parse of exactly this chunk; the data callback + // closes it. + if (forwardQueryReplies) { + this.terminal.write('', () => { + this.queryReplyForwardingDepth += 1 + }) + } return new Promise((resolve) => { this.terminal.write(data, () => { + if (forwardQueryReplies) { + this.queryReplyForwardingDepth -= 1 + } // Why: snapshots combine serialized xterm state with mirrored mouse // modes. Commit the mirror only after xterm has parsed the same bytes. - this.privateModes.scan(data) + this.mouseModes.scan(data) + this.partialEscapeTail = advancePartialEscapeTail(this.partialEscapeTail, data) resolve() }) }) @@ -105,27 +266,28 @@ export class HeadlessEmulator { return this.tryWriteSync(data) } - private tryWriteSync(data: string): boolean { + private tryWriteSync(data: string, opts: HeadlessEmulatorWriteOptions = {}): boolean { const writeSync = (this.terminal as TerminalWithSynchronousWrite)._core?.writeSync if (typeof writeSync !== 'function') { return false } - this.scanInputForOscState(data) + this.oscText.scan(data) + const forwardQueryReplies = opts.forwardQueryReplies === true + if (forwardQueryReplies) { + this.queryReplyForwardingDepth += 1 + } // Why: hidden renderer restore snapshots are requested immediately after // PTY bursts; queued headless writes can snapshot half-cleared TUI rows. - writeSync.call((this.terminal as TerminalWithSynchronousWrite)._core, data) - this.privateModes.scan(data) - return true - } - - private scanInputForOscState(data: string): void { - const oscInput = this.oscScanTail + data - this.oscScanTail = this.extractOscScanTail(oscInput) - this.scanOsc7(oscInput) - const lastTitle = extractLastOscTitle(oscInput) - if (lastTitle !== null) { - this.lastTitle = lastTitle + try { + writeSync.call((this.terminal as TerminalWithSynchronousWrite)._core, data) + } finally { + if (forwardQueryReplies) { + this.queryReplyForwardingDepth -= 1 + } } + this.mouseModes.scan(data) + this.partialEscapeTail = advancePartialEscapeTail(this.partialEscapeTail, data) + return true } resize(cols: number, rows: number): void { @@ -146,32 +308,65 @@ export class HeadlessEmulator { getSnapshot(opts: { scrollbackRows?: number } = {}): TerminalSnapshot { const modes = this.getModes() - const snapshotAnsi = this.normalizeSnapshotAnsiForModes( - this.serializer.serialize({ scrollback: opts.scrollbackRows }), - modes + // Why serializeWithAbsoluteCursor: SerializeAddon's relative cursor + // restore lands one column short after a margin-filling final row leaves + // replay wrap-pending; the trailing CUP survives the alt-marker slice. + // The saved-cursor register rides along so a post-restore DECRC lands + // where the hidden TUI saved, not at home. + const serializedAnsi = serializeWithAbsoluteCursor( + this.serializer, + this.terminal, + { scrollback: opts.scrollbackRows }, + readSavedCursorRegister(this.terminal) ) - return { + const { snapshotAnsi, scrollbackAnsi } = splitTerminalSnapshotAnsi(serializedAnsi, modes) + const snapshot: TerminalSnapshot = { snapshotAnsi, - scrollbackAnsi: '', + scrollbackAnsi, oscLinks: collectHeadlessOscLinkRanges( this.terminal, opts.scrollbackRows, this.restoredOscLinks ), - rehydrateSequences: this.buildRehydrateSequences(modes), - cwd: this.cwd, + rehydrateSequences: buildRehydrateSequences(modes), + cwd: this.oscText.cwd, modes, cols: this.terminal.cols, rows: this.terminal.rows, scrollbackLines: this.terminal.buffer.normal.length - this.terminal.rows, - lastTitle: this.lastTitle ?? undefined + lastTitle: this.oscText.lastTitle ?? undefined, + // Why: written LAST by the restorer (after any reset) so the next live + // chunk completes this dangling sequence instead of rendering it literally + // (Bug E / #7329). Its bytes are already counted by the snapshot seq. + ...(this.partialEscapeTail.length > 0 + ? { pendingEscapeTailAnsi: this.partialEscapeTail } + : {}) + } + if (this.partialEscapeTail.length > 0) { + // Why a separate field, not part of snapshotAnsi: consumers write their + // own reset sequences after the snapshot body, and any ESC written after + // a dangling partial would abort it. The restorer must write this LAST, + // immediately before post-snapshot live chunks. Its bytes are already + // counted by the snapshot seq (they were ingested), so tail-slicing + // arithmetic is unchanged. + snapshot.pendingEscapeTailAnsi = this.partialEscapeTail } + return snapshot } get isAlternateScreen(): boolean { return this.terminal.buffer.active.type === 'alternate' } + /** The dangling incomplete escape at the current stream position (empty + * when none). Scan-authority handoffs seed the other side's fact scanners + * with it so a sequence split across the handoff neither mints a phantom + * bell (unseen OSC terminator) nor loses its fact. Contains no complete + * sequence by construction, so seeding can never double-fire. */ + get partialEscapeTailAnsi(): string { + return this.partialEscapeTail + } + /** Why: PSReadLine's Ctrl+L repaint is only safe at an empty prompt — with * pending input it re-renders at a cached buffer row that ConPTY's fixed * viewport doesn't track, painting the input well below the prompt. The @@ -199,15 +394,15 @@ export class HeadlessEmulator { } getCwd(): string | null { - return this.cwd + return this.oscText.cwd } setCwd(cwd: string | null): void { - this.cwd = cwd + this.oscText.cwd = cwd } setLastTitle(title: string): void { - this.lastTitle = title + this.oscText.lastTitle = title } setRestoredOscLinks(links: TerminalOscLinkRange[] | undefined): void { @@ -224,92 +419,25 @@ export class HeadlessEmulator { this.terminal.dispose() } - private scanOsc7(data: string): void { - scanOsc7Uris(data, (uri) => { - this.parseOsc7Uri(uri) - }) - } - - private extractOscScanTail(input: string): string { - return extractOscScanTail(input, OSC_SCAN_TAIL_LIMIT) - } - - private normalizeSnapshotAnsiForModes(snapshotAnsi: string, modes: TerminalModes): string { - if (!modes.alternateScreen) { - return snapshotAnsi - } - const alternateScreenMarker = '\x1b[?1049h' - const start = snapshotAnsi.lastIndexOf(alternateScreenMarker) - if (start === -1) { - return snapshotAnsi - } - // Why: rehydrateSequences already enters the alternate screen and restores - // mouse modes. Dropping SerializeAddon's duplicate ?1049h keeps mobile's - // "slice from last alt-screen marker" replay from discarding those modes. - return snapshotAnsi.slice(start + alternateScreenMarker.length) - } - - private parseOsc7Uri(uri: string): void { - const parsed = parseFileUriPath(uri, { - pathFlavor: this.pathFlavor, - remotePosixAuthority: this.remotePosixFileUriAuthority - }) - if (parsed) { - this.cwd = parsed - } - } - private getModes(): TerminalModes { const buffer = this.terminal.buffer.active - const mouseTrackingMode = this.privateModes.mouseTrackingMode + const mouseTrackingMode = this.mouseModes.mouseTrackingMode return { bracketedPaste: this.terminal.modes.bracketedPasteMode, mouseTracking: mouseTrackingMode !== 'none', mouseTrackingMode, - sgrMouseMode: this.privateModes.sgrMouseMode, - sgrMousePixelsMode: this.privateModes.sgrMousePixelsMode, + sgrMouseMode: this.mouseModes.sgrMouseMode, + sgrMousePixelsMode: this.mouseModes.sgrMousePixelsMode, applicationCursor: buffer.type === 'normal' ? this.terminal.modes.applicationCursorKeysMode : false, - alternateScreen: buffer.type === 'alternate' + alternateScreen: buffer.type === 'alternate', + kittyKeyboardFlags: this.getKittyKeyboardFlags() } } - private buildRehydrateSequences(modes: TerminalModes): string { - const seqs: string[] = [] - if (modes.alternateScreen) { - seqs.push('\x1b[?1049h') - } - if (modes.bracketedPaste) { - seqs.push('\x1b[?2004h') - } - if (modes.applicationCursor) { - seqs.push('\x1b[?1h') - } - // Why: mobile alt-screen scroll gestures need xterm's mouse mode restored - // from cold snapshots; OpenCode/OpenTUI enables scrollable panes this way. - switch (modes.mouseTracking ? (modes.mouseTrackingMode ?? 'vt200') : 'none') { - case 'x10': - seqs.push('\x1b[?9h') - break - case 'vt200': - seqs.push('\x1b[?1000h') - break - case 'drag': - seqs.push('\x1b[?1002h') - break - case 'any': - seqs.push('\x1b[?1003h') - break - case 'none': - break - } - // Why: xterm tracks the mouse protocol and SGR encoding as independent - // modes, so snapshots must preserve the encoding even when reporting is off. - if (modes.sgrMousePixelsMode) { - seqs.push('\x1b[?1016h') - } else if (modes.sgrMouseMode) { - seqs.push('\x1b[?1006h') - } - return seqs.join('') + private getKittyKeyboardFlags(): number { + const flags = (this.terminal as TerminalWithSynchronousWrite)._core?.coreService?.kittyKeyboard + ?.flags + return typeof flags === 'number' ? flags : 0 } } diff --git a/src/main/daemon/hibernation-cold-restore-repro.test.ts b/src/main/daemon/hibernation-cold-restore-repro.test.ts index d3b5f4ee0e2a..4d5281364d97 100644 --- a/src/main/daemon/hibernation-cold-restore-repro.test.ts +++ b/src/main/daemon/hibernation-cold-restore-repro.test.ts @@ -133,7 +133,7 @@ describe('agent hibernation cold-restore (alt-screen TUI)', () => { // src/renderer/src/components/terminal-pane/layout-serialization.ts (copied // as a literal because a main-process test must not import a renderer module). const POST_REPLAY_MODE_RESET = - '\x1b[0 q\x1b[<99u\x1b[=0u\x1b[?25h\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1004l\x1b[?1006l\x1b[?2004l' + '\x1b[0 q\x1b[<99u\x1b[=0u\x1b[?25h\x1b[?9l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1016l\x1b[?1004l\x1b[?2004l' const fresh = new HeadlessEmulator({ cols: 80, rows: 24 }) fresh.writeSync('\x1b[2J\x1b[3J\x1b[H') fresh.writeSync(adapterScrollback as string) diff --git a/src/main/daemon/history-manager.ts b/src/main/daemon/history-manager.ts index 0edcdb91ba25..47b96b145473 100644 --- a/src/main/daemon/history-manager.ts +++ b/src/main/daemon/history-manager.ts @@ -132,6 +132,31 @@ export class HistoryManager { }) } + // Why: wake after sleep re-spawns a session whose history was closed by the + // sleep-time kill. Re-register the writer without deleting checkpoint.json + // (still the only recovery data until the next tick) and clear endedAt so + // the next sleep can cold-restore this session again. + reopenSession(sessionId: string): void { + this.disabledSessions.delete(sessionId) + this.registerWriter(sessionId) + const writer = this.writers.get(sessionId) + if (!writer) { + return + } + try { + this.updateMeta(writer.dir, { endedAt: null, exitCode: null }) + } catch (err) { + this.handleWriteError(sessionId, err) + } + } + + suspendSession(sessionId: string): void { + // Why: if a fresh daemon cannot accept recovered scrollback, leaving its + // writer active would let the next checkpoint overwrite the only good copy. + this.writers.delete(sessionId) + this.disabledSessions.delete(sessionId) + } + /** Appends one take batch to the incremental log. Returns 'needs-checkpoint' * when the log is at capacity — the caller must take a full snapshot, which * subsumes the un-appended records (they were already applied to the live diff --git a/src/main/daemon/history-reader.ts b/src/main/daemon/history-reader.ts index f6661b500444..8d31e3c638dd 100644 --- a/src/main/daemon/history-reader.ts +++ b/src/main/daemon/history-reader.ts @@ -152,7 +152,13 @@ export class HistoryReader { }) try { if (checkpoint) { - if (!emulator.writeSync(checkpoint.rehydrateSequences + checkpoint.snapshotAnsi)) { + if ( + !emulator.writeSync( + (checkpoint.scrollbackAnsi ?? '') + + checkpoint.rehydrateSequences + + checkpoint.snapshotAnsi + ) + ) { return null } emulator.setRestoredOscLinks(checkpoint.oscLinks) @@ -198,12 +204,8 @@ export class HistoryReader { cwd: string | null, meta: SessionMeta ): ColdRestoreInfo { - // Why: HeadlessEmulator.getSnapshot() doesn't populate scrollbackAnsi - // (it's always ''). For non-alt-screen snapshots, snapshotAnsi IS the - // normal buffer content and is safe to use as scrollback. For alt-screen - // snapshots, snapshotAnsi is the serialized TUI buffer (not raw PTY - // stream); return empty instead — the adapter skips cold restore when - // scrollbackAnsi is falsy. + // Why: legacy normal snapshots stored their buffer only in snapshotAnsi; + // current alt snapshots carry their normal buffer in scrollbackAnsi. const scrollbackAnsi = snapshot.scrollbackAnsi || (snapshot.modes?.alternateScreen ? '' : snapshot.snapshotAnsi) return { diff --git a/src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts b/src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts new file mode 100644 index 000000000000..937dca27bc41 --- /dev/null +++ b/src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts @@ -0,0 +1,188 @@ +// Regression guard: bound the volume of whole-process-table scans the daemon +// schedules for persisted sessions. On Windows each agent-foreground refresh +// forks a powershell.exe/CIM whole-table scan (the daemon-side analogue of +// #6288), so an idle shell with no agent identity and no recent output must +// retry slowly no matter how often readers poll getForegroundProcess; PTY +// output re-arms the fast retry so agent starts still resolve promptly, and +// sessions with a cached agent identity keep the 1s refresh unrelaxed. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +const { spawnMock, isPwshAvailableMock, resolveAgentForegroundProcessMock } = vi.hoisted(() => ({ + spawnMock: vi.fn(), + isPwshAvailableMock: vi.fn(), + resolveAgentForegroundProcessMock: vi.fn() +})) + +vi.mock('node-pty', () => ({ + spawn: spawnMock +})) + +vi.mock('../pwsh', () => ({ + isPwshAvailable: isPwshAvailableMock +})) + +// Resolve PowerShell family names to deterministic absolute paths so these +// tests run on non-Windows CI (mirrors pty-subprocess.test.ts). +const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' +const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' +const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe' +vi.mock('../providers/windows-powershell-executable', () => ({ + resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') => + family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS, + resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') => + family === 'pwsh.exe' + ? [PWSH7_ABS, WINDOWS_POWERSHELL_ABS, CMD_ABS] + : [WINDOWS_POWERSHELL_ABS, CMD_ABS], + getWindowsCmdPath: () => CMD_ABS +})) + +vi.mock('../providers/agent-foreground-process', () => ({ + resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => ({ + available: true, + processName: await resolveAgentForegroundProcessMock(...args) + }) +})) + +import { createPtySubprocess } from './pty-subprocess' + +// Well past any hot window or retry throttle so t=0 reads behave as idle. +const BASE_TIME_MS = 1_000_000 + +function mockPtyProcess(processName: string, pid = 12345) { + const onDataListeners: ((data: string) => void)[] = [] + return { + pid, + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn(), + process: processName, + onData: vi.fn((cb: (data: string) => void) => { + onDataListeners.push(cb) + return { dispose: vi.fn() } + }), + onExit: vi.fn(() => ({ dispose: vi.fn() })), + _simulateData: (data: string) => onDataListeners.forEach((cb) => cb(data)) + } +} + +async function flushAsyncTicks(count = 6): Promise { + for (let i = 0; i < count; i++) { + await Promise.resolve() + } +} + +// One renderer/daemon reader poll: read the foreground and let the scheduled +// background refresh (if any) settle so its cache write lands before the next. +async function readForegroundAt( + handle: { getForegroundProcess: () => string | null }, + atMs: number +): Promise { + vi.setSystemTime(BASE_TIME_MS + atMs) + const foreground = handle.getForegroundProcess() + await flushAsyncTicks() + return foreground +} + +describe('daemon pty foreground scan cadence', () => { + let platform: PropertyDescriptor | undefined + let previousUserDataPath: string | undefined + let userDataPath: string + + beforeEach(() => { + spawnMock.mockReset() + isPwshAvailableMock.mockReset() + isPwshAvailableMock.mockReturnValue(false) + resolveAgentForegroundProcessMock.mockReset() + previousUserDataPath = process.env.ORCA_USER_DATA_PATH + userDataPath = mkdtempSync(join(tmpdir(), 'daemon-pty-scan-cadence-test-')) + process.env.ORCA_USER_DATA_PATH = userDataPath + platform = Object.getOwnPropertyDescriptor(process, 'platform') + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(BASE_TIME_MS) + }) + + afterEach(() => { + vi.useRealTimers() + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + if (previousUserDataPath === undefined) { + delete process.env.ORCA_USER_DATA_PATH + } else { + process.env.ORCA_USER_DATA_PATH = previousUserDataPath + } + rmSync(userDataPath, { recursive: true, force: true }) + }) + + function spawnShellSubprocess(shellProcessName: string, targetPlatform: 'win32' | 'darwin') { + Object.defineProperty(process, 'platform', { configurable: true, value: targetPlatform }) + const proc = mockPtyProcess(shellProcessName) + spawnMock.mockReturnValue(proc) + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + return { proc, handle } + } + + it('bounds scans for an idle Windows shell polled every 2s to the 15s retry tier', async () => { + resolveAgentForegroundProcessMock.mockResolvedValue('powershell.exe') + const { handle } = spawnShellSubprocess('powershell.exe', 'win32') + + for (let atMs = 0; atMs <= 60_000; atMs += 2_000) { + expect(await readForegroundAt(handle, atMs)).toBe('powershell.exe') + } + + // Scans at t=0s, 16s, 32s, 48s. Pre-fix (5s retry) the same 31 reads drove + // 11 whole-table scans; the 2s read cadence itself would drive 31. + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(4) + }) + + it('re-arms the fast retry when PTY output appears on an idle Windows shell', async () => { + resolveAgentForegroundProcessMock.mockResolvedValueOnce('powershell.exe') + const { proc, handle } = spawnShellSubprocess('powershell.exe', 'win32') + + await readForegroundAt(handle, 0) + await readForegroundAt(handle, 2_000) + await readForegroundAt(handle, 4_000) + await readForegroundAt(handle, 6_000) + // Idle: only the t=0 scan ran (6s is within the relaxed 15s retry). + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(1) + + // The user launches an agent; its startup output re-arms the 5s retry. + resolveAgentForegroundProcessMock.mockResolvedValue('claude') + vi.setSystemTime(BASE_TIME_MS + 6_500) + proc._simulateData('claude\r\n') + + await readForegroundAt(handle, 8_000) + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(2) + // The resolved identity is served from the cache on the next read. + expect(await readForegroundAt(handle, 8_500)).toBe('claude') + }) + + it('keeps the fast identity refresh for a Windows session with a cached agent', async () => { + resolveAgentForegroundProcessMock.mockResolvedValue('codex') + const { handle } = spawnShellSubprocess('powershell.exe', 'win32') + + await readForegroundAt(handle, 0) + expect(await readForegroundAt(handle, 1_000)).toBe('codex') + await readForegroundAt(handle, 3_000) + await readForegroundAt(handle, 5_000) + + // Every read past the 1s cache TTL refreshes (t=0s, 1s, 3s, 5s): agent-exit + // detection through the identity cache must not be relaxed by the idle tier. + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(4) + }) + + it('keeps the 5s retry for an idle POSIX shell with no output', async () => { + resolveAgentForegroundProcessMock.mockResolvedValue('zsh') + const { handle } = spawnShellSubprocess('zsh', 'darwin') + + for (let atMs = 0; atMs <= 30_000; atMs += 2_000) { + expect(await readForegroundAt(handle, atMs)).toBe('zsh') + } + + // Scans at t=0s, 6s, 12s, 18s, 24s, 30s — the cheap `ps` path is unchanged. + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(6) + }) +}) diff --git a/src/main/daemon/pty-subprocess.test.ts b/src/main/daemon/pty-subprocess.test.ts index ad8f14cb0688..908ef9a68b27 100644 --- a/src/main/daemon/pty-subprocess.test.ts +++ b/src/main/daemon/pty-subprocess.test.ts @@ -56,7 +56,12 @@ vi.mock('../providers/local-pty-utils', async (importOriginal) => { }) vi.mock('../providers/agent-foreground-process', () => ({ - resolveAgentForegroundProcess: resolveAgentForegroundProcessMock + resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => { + const value = await resolveAgentForegroundProcessMock(...args) + return value && typeof value === 'object' && 'available' in value + ? value + : { available: true, processName: value } + } })) import { createPtySubprocess, checkPtySpawnHealth } from './pty-subprocess' @@ -514,6 +519,111 @@ describe('createPtySubprocess', () => { } }) + it('preserves the ordinary fallback when Windows process enumeration is unavailable', async () => { + const proc = mockPtyProcess() + proc.process = 'powershell.exe' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + resolveAgentForegroundProcessMock.mockResolvedValue({ + available: false, + processName: 'powershell.exe' + }) + + try { + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + + expect(handle.getForegroundProcess()).toBe('powershell.exe') + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + expect(handle.getForegroundProcess()).toBe('powershell.exe') + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + + it('awaits a fresh delayed Windows scan instead of serving the shell fallback', async () => { + const proc = mockPtyProcess() + proc.process = 'powershell.exe' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + let resolveFresh!: (processName: string) => void + resolveAgentForegroundProcessMock.mockReturnValue( + new Promise((resolve) => { + resolveFresh = resolve + }) + ) + + try { + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + const confirmation = handle.confirmForegroundProcess!() + let settled = false + void confirmation.then(() => { + settled = true + }) + await Promise.resolve() + expect(settled).toBe(false) + + resolveFresh('droid') + await expect(confirmation).resolves.toBe('droid') + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledExactlyOnceWith( + proc.pid, + 'powershell.exe', + expect.objectContaining({ fresh: true, forceProcessScan: true }) + ) + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + + it('returns null when a fresh Windows confirmation scan is unavailable', async () => { + const proc = mockPtyProcess() + proc.process = 'powershell.exe' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + resolveAgentForegroundProcessMock.mockResolvedValue({ + available: false, + processName: 'powershell.exe' + }) + + try { + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + await expect(handle.confirmForegroundProcess!()).resolves.toBeNull() + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + + it('returns null when a recognized Windows fallback disappears during confirmation', async () => { + const proc = mockPtyProcess() + proc.process = 'droid' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + resolveAgentForegroundProcessMock.mockResolvedValue({ + available: true, + processName: null + }) + + try { + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + await expect(handle.confirmForegroundProcess!()).resolves.toBeNull() + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + it('serves Unix agent foreground when node-pty reports an agent child process', async () => { const proc = mockPtyProcess() proc.process = 'uv' @@ -2372,6 +2482,32 @@ describe('createPtySubprocess', () => { } }) + it('does not issue a second Windows ConPTY kill when force follows graceful kill', () => { + const proc = mockPtyProcess(123456) as ReturnType & { + destroy: ReturnType + } + proc.destroy = vi.fn(() => proc.kill()) + spawnMock.mockReturnValue(proc) + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => { + throw new Error('already gone') + }) + const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + try { + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + handle.kill() + handle.forceKill() + handle.dispose() + + expect(proc.kill).toHaveBeenCalledOnce() + expect(killSpy).not.toHaveBeenCalled() + expect(proc.destroy).not.toHaveBeenCalled() + } finally { + killSpy.mockRestore() + restorePlatform(origPlatform) + } + }) + it('dispose() on Windows skips destroy after forceKill falls back to node-pty kill()', () => { const proc = mockPtyProcess(123456) as ReturnType & { destroy: ReturnType diff --git a/src/main/daemon/pty-subprocess.ts b/src/main/daemon/pty-subprocess.ts index a4fdfce15ee1..5d36ebe9d693 100644 --- a/src/main/daemon/pty-subprocess.ts +++ b/src/main/daemon/pty-subprocess.ts @@ -41,7 +41,8 @@ import { } from '../pty/powerlevel10k-wizard-env' import { isWindowsGitBashShellPath, resolveWindowsGitBashShellPath } from '../git-bash' import { WINDOWS_GIT_BASH_SHELL } from '../../shared/windows-terminal-shell' -import { resolveAgentForegroundProcess } from '../providers/agent-foreground-process' +import { resolveAgentForegroundProcessWithAvailability } from '../providers/agent-foreground-process' +import { readWindowsConptyProcessIds } from '../providers/windows-conpty-process-membership' import { isAgentForegroundWrapperProcess, recognizeAgentProcess, @@ -64,6 +65,12 @@ const PANE_IDENTITY_ENV_KEYS = [ ] as const const FOREGROUND_AGENT_CACHE_TTL_MS = 1000 const SHELL_FOREGROUND_REFRESH_RETRY_MS = 5_000 +// Why: a Windows refresh forks a powershell.exe whole-process-table CIM scan +// (~10-40x heavier than POSIX `ps`). An idle shell with no agent identity and +// no recent output retries far slower; output re-arms the 5s retry so an agent +// start (which always prints) is still resolved promptly. +const WINDOWS_IDLE_SHELL_FOREGROUND_REFRESH_RETRY_MS = 15_000 +const SHELL_FOREGROUND_OUTPUT_HOT_WINDOW_MS = 10_000 const STARTUP_AGENT_FOREGROUND_BOOTSTRAP_MS = 5_000 const PTY_SPAWN_HEALTH_TIMEOUT_MS = 4_000 // Why: a busy machine right after an upgrade can make one short-lived shell @@ -840,7 +847,11 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl } } + let lastOutputAt = 0 proc.onData((data) => { + if (data.length > 0) { + lastOutputAt = Date.now() + } if (onDataCb) { onDataCb(data) } else { @@ -912,10 +923,16 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl return } const now = Date.now() - const retryMs = + const idleNoEvidenceShell = fallbackIsShell && !getActiveStartupAgentForeground(now) && !cachedAgentForeground - ? SHELL_FOREGROUND_REFRESH_RETRY_MS - : FOREGROUND_AGENT_CACHE_TTL_MS + // Why: on Windows each refresh is a whole-table CIM scan; only shells with + // no agent evidence and no recent output relax, so agent-identity refresh + // (cached identity → 1s TTL) and post-output starts keep the fast retry. + const retryMs = !idleNoEvidenceShell + ? FOREGROUND_AGENT_CACHE_TTL_MS + : process.platform === 'win32' && now - lastOutputAt > SHELL_FOREGROUND_OUTPUT_HOT_WINDOW_MS + ? WINDOWS_IDLE_SHELL_FOREGROUND_REFRESH_RETRY_MS + : SHELL_FOREGROUND_REFRESH_RETRY_MS if (foregroundRefreshInFlight || now - lastForegroundRefreshStartedAt < retryMs) { return } @@ -924,10 +941,10 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl // Why: daemon foreground reads are sync and run on the IPC hot path. // Refresh derived identities (shell/wrapper/helper -> codex/claude/etc.) // in the background and serve them from a short cache on later reads. - void resolveAgentForegroundProcess(proc.pid, fallbackProcess, { + void resolveAgentForegroundProcessWithAvailability(proc.pid, fallbackProcess, { contextPaths: agentForegroundContextPaths }) - .then((processName) => { + .then(({ processName }) => { if (dead) { return } @@ -1029,6 +1046,56 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl return null } }, + confirmForegroundProcess: async () => { + if (dead || !proc.pid) { + return null + } + try { + const fallbackProcess = getFallbackForegroundProcess() + if ( + !fallbackProcess || + (recognizeAgentProcess(fallbackProcess) && process.platform !== 'win32') || + (process.platform !== 'win32' && !shouldInspectFallbackForegroundProcess(fallbackProcess)) + ) { + return fallbackProcess + } + // Why: cached/in-flight scans may predate the OSC command boundary. + // Confirmation requires one shared process snapshot started afterward. + const resolution = await resolveAgentForegroundProcessWithAvailability( + proc.pid, + fallbackProcess, + { + contextPaths: agentForegroundContextPaths, + fresh: true, + ...(process.platform === 'win32' + ? { + forceProcessScan: true, + readWindowsConptyProcessIds: () => readWindowsConptyProcessIds(proc.pid) + } + : {}) + } + ) + if (dead || !resolution.available) { + return null + } + const recognized = recognizeAgentProcess(resolution.processName) + if (recognized) { + cachedAgentForeground = { + processName: recognized.processName, + refreshedAt: Date.now() + } + startupAgentForeground = null + return recognized.processName + } + // Why: a successful post-boundary scan that resolves no agent is the + // authority that retires stale cached/startup identity. + cachedAgentForeground = null + startupAgentForeground = null + return resolution.processName + } catch { + return null + } + }, write: (data) => { if (dead) { return @@ -1052,6 +1119,30 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl dead = true } }, + // Why pause/resume work on Windows too: node-pty's base Terminal + // implements both as socket pause/resume (lib/terminal.js), and + // WindowsTerminal wires _socket to the ConPTY conout pipe — pausing stops + // conout reads so ConPTY's bounded buffer backpressures the child. + pause: () => { + if (dead) { + return + } + try { + proc.pause() + } catch { + /* native handle already torn down — flow control is best-effort */ + } + }, + resume: () => { + if (dead) { + return + } + try { + proc.resume() + } catch { + /* native handle already torn down — flow control is best-effort */ + } + }, clear: () => { if (dead) { return @@ -1078,7 +1169,9 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl // has run, proc.pid refers to a recycled pid. Sending SIGKILL would // terminate an unrelated process. The fd release is handled by // dispose()/destroy(); forceKill is strictly for signalling a live child. - if (dead) { + // Why: Windows node-pty kill already closes ConPTY; retrying it through + // forceKill can double-close the native handle during workspace teardown. + if (dead || (process.platform === 'win32' && nodePtyKillIssued)) { return } try { diff --git a/src/main/daemon/reattach-snapshot.test.ts b/src/main/daemon/reattach-snapshot.test.ts index a8bdf2524429..aec624cbf01b 100644 --- a/src/main/daemon/reattach-snapshot.test.ts +++ b/src/main/daemon/reattach-snapshot.test.ts @@ -37,7 +37,7 @@ function createMockSubprocess(): SubprocessHandle & { // for a reattach. Alt-screen sessions include the full ANSI snapshot because function buildReattachPayload(snapshot: ReturnType) { const isAltScreen = snapshot.modes.alternateScreen - const fullPayload = snapshot.rehydrateSequences + snapshot.snapshotAnsi + const fullPayload = snapshot.scrollbackAnsi + snapshot.rehydrateSequences + snapshot.snapshotAnsi return { rehydrateSequences: snapshot.rehydrateSequences, snapshotAnsi: snapshot.snapshotAnsi, @@ -274,6 +274,24 @@ describe('reattach snapshot flow', () => { expect(payload.fullPayload).toContain('Codex TUI content') }) + it('returns to preserved shell history after the reattached TUI exits', async () => { + const emulator = new HeadlessEmulator({ cols: 80, rows: 10 }) + await emulator.write('shell output before Codex\r\n$ codex') + await emulator.write('\x1b[?1049h\x1b[2J\x1b[HCodex TUI content') + const payload = buildReattachPayload(emulator.getSnapshot()) + emulator.dispose() + + const replay = new HeadlessEmulator({ cols: 80, rows: 10 }) + try { + await replay.write(payload.fullPayload) + expect(replay.getVisibleLines().join('\n')).toContain('Codex TUI content') + await replay.write('\x1b[?1049l') + expect(replay.getVisibleLines().join('\n')).toContain('shell output before Codex') + } finally { + replay.dispose() + } + }) + it('SIGWINCH repaint after rehydrate produces clean single render', async () => { const h = createHost() await h.createOrAttach({ diff --git a/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts b/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts new file mode 100644 index 000000000000..8f8256519a4a --- /dev/null +++ b/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts @@ -0,0 +1,182 @@ +import { describe, expect, it } from 'vitest' +import { Terminal } from '@xterm/headless' +import { HeadlessEmulator } from './headless-emulator' + +// Repro for #7329: "remote server + terminal" — typing gets escape sequences +// injected/wrapped around it and follow-up commands are corrupted. +// +// The remote-server path serializes terminal state on the daemon via +// HeadlessEmulator.getSnapshot() (SerializeAddon + buildRehydrateSequences) and +// replays it into the renderer xterm, then applies POST_REPLAY_REATTACH_RESET. +// This test drives the REAL daemon serializer and a REAL renderer-side xterm to +// see what the user's terminal ends up looking like after a subscribe/reattach. + +const RESET_TERMINAL_CURSOR_STYLE = '\x1b[0 q' +const RESET_KITTY_KEYBOARD_PROTOCOL = '\x1b[<99u\x1b[=0u' +const RESET_MOUSE_REPORTING = '\x1b[?9l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1016l' +// Verbatim from layout-serialization.ts (the reattach path the remote onSnapshot uses). +const POST_REPLAY_REATTACH_RESET = `${RESET_TERMINAL_CURSOR_STYLE}${RESET_KITTY_KEYBOARD_PROTOCOL}\x1b[?25h${RESET_MOUSE_REPORTING}\x1b[?1004l` + +function writeXterm(term: Terminal, data: string): Promise { + return new Promise((resolve) => term.write(data, resolve)) +} + +async function emulatorWrite(emu: HeadlessEmulator, data: string): Promise { + await emu.write(data) +} + +/** Replay a daemon snapshot into a renderer xterm exactly like the remote + * onSnapshot → replayDataCallback path: clear, write rehydrate+snapshot, + * then the reattach mode reset. */ +async function replayRemoteSnapshot( + term: Terminal, + snapshot: { rehydrateSequences: string; snapshotAnsi: string; pendingEscapeTailAnsi?: string } +): Promise { + await writeXterm(term, '\x1b[2J\x1b[3J\x1b[H') + await writeXterm(term, snapshot.rehydrateSequences + snapshot.snapshotAnsi) + await writeXterm(term, POST_REPLAY_REATTACH_RESET) + // The fix: the restorer writes the pending mid-escape tail LAST, after the + // reset (mirrors drainReplayDataQueue in pty-connection.ts). + if (snapshot.pendingEscapeTailAnsi) { + await writeXterm(term, snapshot.pendingEscapeTailAnsi) + } +} + +function renderVisible(term: Terminal): string { + const buf = term.buffer.active + const lines: string[] = [] + for (let y = 0; y < term.rows; y += 1) { + lines.push(buf.getLine(buf.viewportY + y)?.translateToString(true) ?? '') + } + return lines.join('\n').replace(/\s+$/g, '') +} + +describe('#7329 remote-server snapshot corruption', () => { + it('disarms rehydrated mouse modes but keeps bracketed paste after a reattach snapshot', async () => { + const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + try { + // A live remote shell that armed bracketed paste (bash 4.4+/readline + // default) and vt200+SGR mouse (a TUI the user just exited uncleanly). + await emulatorWrite(emu, '\x1b[?2004h\x1b[?1000h\x1b[?1006h') + await emulatorWrite(emu, 'user@host:~$ ') + + const snapshot = emu.getSnapshot({ scrollbackRows: 0 }) + // The daemon snapshot re-arms the modes it observed. + expect(snapshot.rehydrateSequences).toContain('\x1b[?2004h') + expect(snapshot.modes.bracketedPaste).toBe(true) + expect(snapshot.modes.mouseTracking).toBe(true) + + await replayRemoteSnapshot(term, snapshot) + + // Bracketed paste survives — the live shell armed it and won't re-arm + // until the next prompt. Mouse reporting must NOT survive: with a plain + // shell in the foreground, xterm would emit `35;x;yM` motion reports the + // shell echoes as literal input on every pointer move. (Live agent panes + // preserve mouse via POST_REPLAY_LIVE_AGENT_REATTACH_RESET instead.) + expect(term.modes.bracketedPasteMode).toBe(true) + expect(term.modes.mouseTrackingMode).toBe('none') + } finally { + emu.dispose() + term.dispose() + } + }) + + it('disarms any-motion (?1003) and pixel-encoded (?1016) mouse modes left by a killed TUI', async () => { + const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + try { + // An agent TUI armed any-motion tracking, then was SIGKILLed — no + // disarm bytes ever reach the daemon, so its tracker keeps the mode. + await emulatorWrite(emu, '\x1b[?1003h\x1b[?1016h') + await emulatorWrite(emu, 'user@host:~$ ') + + const snapshot = emu.getSnapshot({ scrollbackRows: 0 }) + expect(snapshot.rehydrateSequences).toContain('\x1b[?1003h') + expect(snapshot.rehydrateSequences).toContain('\x1b[?1016h') + + await replayRemoteSnapshot(term, snapshot) + + expect(term.modes.mouseTrackingMode).toBe('none') + } finally { + emu.dispose() + term.dispose() + } + }) + + it('drops a mid-escape tail so continuation bytes render literally after reattach', async () => { + const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + try { + // A remote PTY read that ends mid-escape: the shell was about to paint a + // colored prompt but the read boundary split the SGR sequence. The next + // read carries the continuation. The daemon serializes BETWEEN the two + // reads (e.g. the client subscribes/reattaches right then). + await emulatorWrite(emu, 'first line\r\n') + await emulatorWrite(emu, '\x1b[3') // <-- partial SGR: "\x1b[38;5;...m" started + + const snapshot = emu.getSnapshot({ scrollbackRows: 0 }) + // The serializer still cannot put the dangling "\x1b[3" in the screen ANSI + // (it lives in the parser)... + expect(snapshot.snapshotAnsi).not.toContain('\x1b[3') + // ...but the emulator now ships it as a separate pending-escape tail. + expect(snapshot.pendingEscapeTailAnsi).toBe('\x1b[3') + + await replayRemoteSnapshot(term, snapshot) + + // The continuation of the split escape arrives as the next live chunk. + await writeXterm(term, '8;5;196mred$ yes\r\n') + + const visible = renderVisible(term) + // FIXED: the tail was replayed after the reset, so the continuation + // "8;5;196m" completes the SGR escape and is consumed — not rendered + // literally. The visible text is just the prompt + typed command. + expect(visible).not.toContain('8;5;196m') + expect(visible).toContain('red$ yes') + } finally { + emu.dispose() + term.dispose() + } + }) + + it('does not eat the continuation byte when the tail and continuation are contiguous', async () => { + // The safety property the fix relies on (mirrors the snapshot-seq accounting + // in orca-runtime/getOutputAfterSnapshotSeq): the snapshot seq counts the + // tail bytes, so the FIRST live chunk after the snapshot is the exact + // continuation and completes the dangling sequence with no eaten byte. + const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + try { + await emulatorWrite(emu, '\x1b[38;5;') // dangling: params so far + const snapshot = emu.getSnapshot({ scrollbackRows: 0 }) + expect(snapshot.pendingEscapeTailAnsi).toBe('\x1b[38;5;') + await replayRemoteSnapshot(term, snapshot) + // Continuation completes the SGR then prints a visible token. + await writeXterm(term, '82mHELLO') + const visible = renderVisible(term) + // No byte of "82m" leaks; the token renders whole (color applied). + expect(visible).toBe('HELLO') + } finally { + emu.dispose() + term.dispose() + } + }) + + it('documents the residual edge: an idle-death tail eats the next output byte', async () => { + // KNOWN, ACCEPTED trade-off: if a mid-escape read is the LAST thing the + // process emits (it dies/idles and never sends the continuation), the tail + // sits armed in the parser and the NEXT unrelated output loses its first + // byte. This is strictly narrower than the bug it fixes (which garbled every + // real split escape), and pre-fix such a stream simply dropped the partial. + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) + try { + await writeXterm(term, 'prompt$ ') + await writeXterm(term, '\x1b[3') // armed tail, no continuation ever comes + await writeXterm(term, 'yes\r\n') // unrelated later output + // The 'y' is absorbed as a CSI parameter of the dangling sequence. + expect(renderVisible(term)).toBe('prompt$ es') + } finally { + term.dispose() + } + }) +}) diff --git a/src/main/daemon/session-ingest-throughput.bench.test.ts b/src/main/daemon/session-ingest-throughput.bench.test.ts new file mode 100644 index 000000000000..e226ddf869d5 --- /dev/null +++ b/src/main/daemon/session-ingest-throughput.bench.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from 'vitest' +import { performance } from 'node:perf_hooks' +import { Session, type SubprocessHandle } from './session' + +// Benchmark harness for the terminal performance initiative: measures the +// daemon-side ingest rate (Session.handleSubprocessData -> HeadlessEmulator +// write + pending-output recording + client fanout) for the same workload +// shapes as tools/benchmarks/terminal-pipeline-bench.mjs. Bare headless +// xterm parses these at ~80-100 MB/s; the end-to-end Orca pipeline measured +// 2-15 MB/s (baseline-jul02) — this isolates the daemon layer's share. +// Run with: +// ORCA_TERMINAL_PERF_BENCH=1 pnpm vitest run \ +// src/main/daemon/session-ingest-throughput.bench.test.ts \ +// --config config/vitest.config.ts +const benchEnabled = process.env.ORCA_TERMINAL_PERF_BENCH === '1' + +const COLS = 114 +const ROWS = 85 +const TARGET_BYTES = 10 * 1024 * 1024 +const CHUNK = 64 * 1024 + +function asciiLog(targetBytes: number): string { + const parts: string[] = [] + let bytes = 0 + let line = 0 + while (bytes < targetBytes) { + line++ + const s = `\x1b[32m[build ${String(line).padStart(6, '0')}]\x1b[0m compile transform resolve bundle emit chunk module (${line % 5000}ms)\r\n` + parts.push(s) + bytes += s.length + } + return parts.join('') +} + +function agentTui(targetBytes: number): string { + const statusRows = 10 + const parts: string[] = [] + let bytes = 0 + let frame = 0 + let painted = false + const push = (s: string): void => { + parts.push(s) + bytes += Buffer.byteLength(s, 'utf8') + } + while (bytes < targetBytes) { + frame++ + push('\x1b[?2026h') + if (painted) { + push(`\x1b[${statusRows}A\x1b[0J`) + } + push(`\x1b[2m●\x1b[0m transcript line for frame ${frame} with some words\r\n`) + for (let r = 0; r < statusRows; r++) { + push( + `\x1b[38;5;${33 + (r % 6)}m⠼ task ${frame % 100}·${r}\x1b[0m ${'▇'.repeat((frame + r) % 40)}\r\n` + ) + } + painted = true + push('\x1b[?2026l') + } + return parts.join('') +} + +function makeSubprocess(): SubprocessHandle & { emit: (data: string) => void } { + let onData: ((data: string) => void) | null = null + return { + pid: 4242, + getForegroundProcess: () => 'bench', + write: () => {}, + resize: () => {}, + kill: () => {}, + forceKill: () => {}, + signal: () => {}, + onData: (cb) => { + onData = cb + }, + onExit: () => {}, + dispose: () => {}, + emit: (data: string) => onData?.(data) + } +} + +function ingest(fixture: string, drainPendingEveryChunks: number | null): number { + const subprocess = makeSubprocess() + const session = new Session({ + sessionId: 'bench', + cols: COLS, + rows: ROWS, + subprocess, + shellReadySupported: false + }) + session.attachClient({ onData: () => {}, onExit: () => {} }) + // Warmup primes JIT paths. + subprocess.emit(fixture.slice(0, 256 * 1024)) + session.takePendingOutput(false) + const start = performance.now() + let chunks = 0 + for (let i = 0; i < fixture.length; i += CHUNK) { + subprocess.emit(fixture.slice(i, i + CHUNK)) + chunks++ + // Why: without periodic takes the 2MB pending cap overflows and recording + // short-circuits, understating the real steady-state cost. The 5s adapter + // tick drains in production; drain per ~1.5MB approximates a hot session. + if (drainPendingEveryChunks && chunks % drainPendingEveryChunks === 0) { + session.takePendingOutput(false) + } + } + const ms = performance.now() - start + session.dispose() + return ms +} + +describe.skipIf(!benchEnabled)('daemon session ingest throughput', () => { + it('measures MB/s per workload shape', () => { + const rows: string[] = [] + for (const [name, fixture] of [ + ['ascii-log', asciiLog(TARGET_BYTES)], + ['agent-tui', agentTui(TARGET_BYTES)] + ] as const) { + const bytes = Buffer.byteLength(fixture, 'utf8') + const ms = ingest(fixture, 24) + const rate = bytes / 1024 / 1024 / (ms / 1000) + rows.push( + `${name}: ${rate.toFixed(1)} MB/s (${ms.toFixed(0)}ms for ${(bytes / 1024 / 1024).toFixed(1)}MB)` + ) + } + // eslint-disable-next-line no-console -- bench harness output + console.log(`\n[session-ingest] ${COLS}x${ROWS}\n ${rows.join('\n ')}`) + expect(rows.length).toBe(2) + }) +}) diff --git a/src/main/daemon/session.test.ts b/src/main/daemon/session.test.ts index 478b4ea99f0f..ade8b18fe155 100644 --- a/src/main/daemon/session.test.ts +++ b/src/main/daemon/session.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { Session } from './session' +import { PRODUCER_PAUSE_FAILSAFE_MS, Session } from './session' import type { SessionState, ShellReadyState } from './types' // Stub the subprocess — Session talks to it via an interface, not child_process directly. @@ -11,6 +11,8 @@ function createMockSubprocess() { let killed = false let clearCalls = 0 let pid = 12345 + let pauseCalls = 0 + let resumeCalls = 0 return { written, @@ -21,6 +23,12 @@ function createMockSubprocess() { get pid() { return pid }, + get pauseCalls() { + return pauseCalls + }, + get resumeCalls() { + return resumeCalls + }, foregroundProcess: null as string | null, getForegroundProcess(): string | null { return this.foregroundProcess @@ -29,6 +37,12 @@ function createMockSubprocess() { written.push(data) }, resize(_cols: number, _rows: number) {}, + pause() { + pauseCalls++ + }, + resume() { + resumeCalls++ + }, get clearCalls() { return clearCalls }, @@ -174,14 +188,22 @@ describe('Session', () => { describe('emulator does not reply to terminal queries', () => { // Why: daemon emulator parses in-process synchronously — before - // handleSubprocessData forwards bytes to the renderer over IPC — so any - // auto-reply it emits races ahead of the renderer's xterm and clobbers - // it with default-xterm values (no theme, stale cursor). The renderer is - // the authoritative responder; a daemon-side reply to any query is a bug. + // handleSubprocessData forwards bytes onward — so any auto-reply it + // emits races ahead of the live answerer and clobbers it with + // default-xterm values (no theme, stale cursor). Query authority is + // structural (terminal-query-authority.md): a delivered chunk is + // answered by the consuming view's xterm, a hidden-dropped chunk by + // MAIN's runtime model responder. The daemon emulator is neither — it + // stays write-only forever, and these pins are permanent. it.each([ + ['OSC 10 foreground-color', '\x1b]10;?\x07'], ['OSC 11 background-color', '\x1b]11;?\x07'], + ['OSC 12 cursor-color', '\x1b]12;?\x1b\\'], ['DA1 device-attributes', '\x1b[c'], - ['DSR cursor-position', '\x1b[6n'] + ['DA2 secondary device-attributes', '\x1b[>c'], + ['DSR terminal status', '\x1b[5n'], + ['DSR cursor-position', '\x1b[6n'], + ['DECRPM bracketed-paste mode', '\x1b[?2004$p'] ])('does not reply to %s query', async (_label, query) => { createSession({ shellReadySupported: false }) subprocess.simulateData(query) @@ -260,6 +282,15 @@ describe('Session', () => { expect(session.getSnapshot()?.snapshotAnsi).not.toContain('orca-shell-ready') }) + it('publishes an absolute output sequence with live snapshots', () => { + createSession() + subprocess.simulateData('first') + subprocess.simulateData('🟢second') + + expect(session.getSnapshot()?.outputSequence).toBe('first🟢second'.length) + expect(session.takePendingOutput(true)?.snapshot?.outputSequence).toBe('first🟢second'.length) + }) + it('releases held marker-prefix bytes before flushing queued input on timeout', () => { createSession({ shellReadySupported: true, shellReadyTimeoutMs: 100 }) const received: string[] = [] @@ -600,4 +631,103 @@ describe('Session', () => { expect(session.state).toBe('exited') }) }) + + describe('producer flow control', () => { + it('pauses the subprocess and auto-resumes via the lost-resume failsafe', () => { + createSession() + session.pauseProducer() + expect(subprocess.pauseCalls).toBe(1) + expect(subprocess.resumeCalls).toBe(0) + + vi.advanceTimersByTime(PRODUCER_PAUSE_FAILSAFE_MS - 1) + expect(subprocess.resumeCalls).toBe(0) + vi.advanceTimersByTime(1) + expect(subprocess.resumeCalls).toBe(1) + }) + + it('resumeProducer resumes once and cancels the failsafe timer', () => { + createSession() + session.pauseProducer() + session.resumeProducer() + expect(subprocess.resumeCalls).toBe(1) + + vi.advanceTimersByTime(PRODUCER_PAUSE_FAILSAFE_MS * 2) + expect(subprocess.resumeCalls).toBe(1) + }) + + it('resumeProducer without a matching pause is a no-op', () => { + createSession() + session.resumeProducer() + expect(subprocess.resumeCalls).toBe(0) + }) + + it('re-pausing re-arms the failsafe window', () => { + createSession() + session.pauseProducer() + vi.advanceTimersByTime(PRODUCER_PAUSE_FAILSAFE_MS - 1_000) + session.pauseProducer() + + vi.advanceTimersByTime(PRODUCER_PAUSE_FAILSAFE_MS - 1) + expect(subprocess.resumeCalls).toBe(0) + vi.advanceTimersByTime(1) + expect(subprocess.resumeCalls).toBe(1) + }) + + it('kill() resumes a paused producer before signalling the child', () => { + createSession() + session.pauseProducer() + session.kill() + expect(subprocess.resumeCalls).toBe(1) + expect(subprocess.killed).toBe(true) + }) + + it('dispose() resumes a paused producer and clears the failsafe', () => { + createSession() + session.pauseProducer() + session.dispose() + expect(subprocess.resumeCalls).toBe(1) + expect(vi.getTimerCount()).toBe(0) + }) + + it('subprocess exit clears the failsafe without resuming a reaped child', () => { + createSession() + session.pauseProducer() + subprocess.simulateExit(0) + vi.advanceTimersByTime(PRODUCER_PAUSE_FAILSAFE_MS * 2) + expect(subprocess.resumeCalls).toBe(0) + }) + + it('ignores pauseProducer on an exited session', () => { + createSession() + subprocess.simulateExit(0) + session.pauseProducer() + expect(subprocess.pauseCalls).toBe(0) + expect(vi.getTimerCount()).toBe(0) + }) + + it('detaching the last client resumes a paused producer', () => { + createSession() + const token = session.attachClient({ onData: () => {}, onExit: () => {} }) + session.pauseProducer() + session.detachClient(token) + expect(subprocess.resumeCalls).toBe(1) + }) + + it('keeps the pause while another client is still attached', () => { + createSession() + const token = session.attachClient({ onData: () => {}, onExit: () => {} }) + session.attachClient({ onData: () => {}, onExit: () => {} }) + session.pauseProducer() + session.detachClient(token) + expect(subprocess.resumeCalls).toBe(0) + }) + + it('detachAllClients resumes a paused producer', () => { + createSession() + session.attachClient({ onData: () => {}, onExit: () => {} }) + session.pauseProducer() + session.detachAllClients() + expect(subprocess.resumeCalls).toBe(1) + }) + }) }) diff --git a/src/main/daemon/session.ts b/src/main/daemon/session.ts index d156aeb48022..06404fd92462 100644 --- a/src/main/daemon/session.ts +++ b/src/main/daemon/session.ts @@ -9,6 +9,7 @@ import { type ShellReadyScanState } from '../shell-ready-marker-scanner' import { isPowerShellProcess } from '../../shared/shell-process-detection' +import type { TuiAgent } from '../../shared/types' import type { PendingOutputRecord, SessionState, @@ -31,17 +32,29 @@ const KILL_TIMEOUT_MS = 5_000 // Worst-case wire size for a full take is ~6x this (each control char // JSON-escapes to six bytes) and must stay under NDJSON_MAX_LINE_BYTES (16MB). const PENDING_OUTPUT_MAX_BYTES = 2 * 1024 * 1024 +// Why: producer pause is requested over a fire-and-forget notification, so the +// matching resume can be lost (main crash, dropped socket). A lost resume must +// never wedge a shell: auto-resume after this window; a still-flooded main +// re-asserts the pause on its next watermark check. +export const PRODUCER_PAUSE_FAILSAFE_MS = 5_000 export type SubprocessHandle = { pid: number /** Live foreground process name of the PTY (node-pty's `.process`), e.g. * 'claude' / 'codex' / 'zsh'. Null once the child has exited. */ getForegroundProcess(): string | null + /** Await process-table evidence captured after this confirmation request. */ + confirmForegroundProcess?(): Promise /** True when shell launch args already delivered the startup command, so the * terminal host must skip its stdin fallback write. */ startupCommandDeliveredInShellArgs?: boolean write(data: string): void resize(cols: number, rows: number): void + /** Stop reading the PTY fd (node-pty pause()) so the kernel/ConPTY buffer + * fills and a flooding child blocks on write. Optional: handles that + * cannot pause simply omit it and flow control degrades to a no-op. */ + pause?(): void + resume?(): void /** Resync the native PTY's own screen state after a frontend clear. * No-op except on Windows/ConPTY, where a stale ConPTY cursor row makes * the next prompt repaint land below a blank gap. */ @@ -62,9 +75,11 @@ export type SessionOptions = { cols: number rows: number terminalHandle?: string + launchAgent?: TuiAgent subprocess: SubprocessHandle shellReadySupported: boolean shellReadyTimeoutMs?: number + historySeed?: string scrollback?: number // Why: fired once the session reaches a terminal state (natural exit or // kill-timeout force-dispose) so the owner (TerminalHost) can reap it — @@ -83,6 +98,7 @@ type AttachedClient = { export class Session { readonly sessionId: string readonly terminalHandle: string | null + readonly launchAgent: TuiAgent | null private _state: SessionState = 'running' private _shellState: ShellReadyState private _exitCode: number | null = null @@ -101,10 +117,15 @@ export class Session { private pendingOutputBytes = 0 private pendingOutputOverflowed = false private pendingOutputSeq = 0 + private outputSequence = 0 + private producerPaused = false + private producerPauseFailsafeTimer: ReturnType | null = null + private readonly _historySeeded: boolean | undefined constructor(opts: SessionOptions) { this.sessionId = opts.sessionId this.terminalHandle = opts.terminalHandle ?? null + this.launchAgent = opts.launchAgent ?? null this.subprocess = opts.subprocess this.onSessionExit = opts.onExit const size = normalizePtySize(opts.cols, opts.rows) @@ -117,6 +138,10 @@ export class Session { // responder; any daemon reply races ahead via in-process parsing and // clobbers the renderer's answer. See the comment in HeadlessEmulator. }) + // Why: recovery must precede listener registration; shells can emit their + // prompt synchronously as soon as onData subscribes. + this._historySeeded = + opts.historySeed === undefined ? undefined : this.emulator.writeSync(opts.historySeed) if (opts.shellReadySupported) { this._shellState = 'pending' @@ -141,6 +166,10 @@ export class Session { return this._shellState } + get historySeeded(): boolean | undefined { + return this._historySeeded + } + get exitCode(): number | null { return this._exitCode } @@ -188,12 +217,52 @@ export class Session { this.subprocess.resize(cols, rows) } + /** Producer-side flow control: stop reading the PTY fd so the flooding + * child blocks on write (kernel backpressure). Arms the lost-resume + * failsafe; re-pausing re-arms it (main re-asserts during long floods). */ + pauseProducer(): void { + if (this._state === 'exited' || this._disposed) { + return + } + this.producerPaused = true + this.subprocess.pause?.() + if (this.producerPauseFailsafeTimer) { + clearTimeout(this.producerPauseFailsafeTimer) + } + this.producerPauseFailsafeTimer = setTimeout(() => { + this.producerPauseFailsafeTimer = null + this.producerPaused = false + this.subprocess.resume?.() + }, PRODUCER_PAUSE_FAILSAFE_MS) + } + + resumeProducer(): void { + this.releaseProducerPause({ resume: true }) + } + + private releaseProducerPause(opts: { resume: boolean }): void { + if (this.producerPauseFailsafeTimer) { + clearTimeout(this.producerPauseFailsafeTimer) + this.producerPauseFailsafeTimer = null + } + if (!this.producerPaused) { + return + } + this.producerPaused = false + if (opts.resume) { + this.subprocess.resume?.() + } + } + kill(): void { if (this._state === 'exited' || this._isTerminating) { return } this._isTerminating = true + // Why: a paused child can be blocked inside write(); resume before + // signalling so it can run signal handlers and actually exit. + this.releaseProducerPause({ resume: true }) this.subprocess.kill() this.killTimer = setTimeout(() => { @@ -221,17 +290,30 @@ export class Session { if (idx !== -1) { this.attachedClients.splice(idx, 1) } + // Why: with no attached client, nobody will ever send resumePty — a + // paused shell would sit wedged until the failsafe. Resume eagerly. + if (this.attachedClients.length === 0) { + this.releaseProducerPause({ resume: true }) + } } detachAllClients(): void { this.attachedClients.length = 0 + this.releaseProducerPause({ resume: true }) } - getSnapshot(): TerminalSnapshot | null { + getSnapshot(opts: { scrollbackRows?: number } = {}): TerminalSnapshot | null { if (this._disposed) { return null } - return this.emulator.getSnapshot() + return { ...this.emulator.getSnapshot(opts), outputSequence: this.outputSequence } + } + + getPartialEscapeTailAnsi(): string { + if (this._disposed) { + return '' + } + return this.emulator.partialEscapeTailAnsi } // Why: the size the PTY actually applied (emulator dims, which Session.resize @@ -272,7 +354,7 @@ export class Session { : records, seq: this.pendingOutputSeq, overflowed, - snapshot: includeSnapshot ? this.emulator.getSnapshot() : null + snapshot: includeSnapshot ? this.getSnapshot() : null } } @@ -284,6 +366,10 @@ export class Session { return this.subprocess.getForegroundProcess() } + async confirmForegroundProcess(): Promise { + return this.subprocess.confirmForegroundProcess?.() ?? this.subprocess.getForegroundProcess() + } + clearScrollback(): void { if (this._disposed) { return @@ -414,6 +500,9 @@ export class Session { return } this._disposed = true + // Why: never leave a paused fd behind on any teardown path — the handle's + // own dead-guard makes this a no-op when the child is already reaped. + this.releaseProducerPause({ resume: true }) if (this.killTimer) { clearTimeout(this.killTimer) this.killTimer = null @@ -480,6 +569,10 @@ export class Session { return } + // Why: daemon stream thinning can omit bytes before main sees them. The + // absolute count lets an authoritative snapshot cover those gaps while + // renderer reconciliation deduplicates any queued post-snapshot tail. + this.outputSequence += data.length // Feed data to headless emulator for state tracking this.emulator.write(data) this.recordPendingOutput({ kind: 'output', data }) @@ -497,6 +590,9 @@ export class Session { this._exitCode = code this._state = 'exited' + // Why resume:false — the child is reaped, so there is nothing to unblock; + // only the failsafe timer must not outlive the session. + this.releaseProducerPause({ resume: false }) this.releaseHeldShellReadyBytes() if (this.killTimer) { diff --git a/src/main/daemon/terminal-history-incremental-restore.test.ts b/src/main/daemon/terminal-history-incremental-restore.test.ts index 8cd9a42a307d..544ff2a4c752 100644 --- a/src/main/daemon/terminal-history-incremental-restore.test.ts +++ b/src/main/daemon/terminal-history-incremental-restore.test.ts @@ -183,7 +183,7 @@ describe('incremental terminal history restore', () => { expect(restore!.scrollbackAnsi).not.toContain('cleared away') }) - it('skips restorable content for sessions crashed inside the alt screen', async () => { + it('preserves normal history without treating active alt content as scrollback', async () => { await manager.appendIncrements(SESSION_ID, 1, [ { kind: 'output', data: 'normal output\r\n\x1b[?1049halt screen content' } ]) @@ -191,9 +191,8 @@ describe('incremental terminal history restore', () => { const restore = reader.detectColdRestore(SESSION_ID) expect(restore).not.toBeNull() expect(restore!.modes.alternateScreen).toBe(true) - // Why: the adapter skips cold restore when scrollbackAnsi is empty — alt - // buffer contents must not replay into a fresh shell. - expect(restore!.scrollbackAnsi).toBe('') + expect(restore!.scrollbackAnsi).toContain('normal output') + expect(restore!.scrollbackAnsi).not.toContain('alt screen content') }) it('resets the log on checkpoint so old records are not replayed twice', async () => { diff --git a/src/main/daemon/terminal-host-create-contract.ts b/src/main/daemon/terminal-host-create-contract.ts new file mode 100644 index 000000000000..a60570ac5fe8 --- /dev/null +++ b/src/main/daemon/terminal-host-create-contract.ts @@ -0,0 +1,33 @@ +import type { StartupCommandDelivery } from '../../shared/codex-startup-delivery' +import type { TuiAgent } from '../../shared/types' +import type { ShellReadyState, TerminalSnapshot } from './types' + +export type CreateOrAttachOptions = { + sessionId: string + cols: number + rows: number + cwd?: string + env?: Record + envToDelete?: string[] + command?: string + startupCommandDelivery?: StartupCommandDelivery + launchAgent?: TuiAgent + /** Explicit shell the renderer asked for, forwarded to the subprocess. */ + shellOverride?: string + terminalWindowsWslDistro?: string | null + terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe' + shellReadySupported?: boolean + shellReadyTimeoutMs?: number + historySeed?: string + streamClient: { onData: (data: string) => void; onExit: (code: number) => void } +} + +export type CreateOrAttachResult = { + isNew: boolean + snapshot: TerminalSnapshot | null + pid: number | null + shellState: ShellReadyState + historySeeded?: boolean + launchAgent?: TuiAgent + attachToken: symbol +} diff --git a/src/main/daemon/terminal-host.ts b/src/main/daemon/terminal-host.ts index 2a54ce2c19bc..203719d354e2 100644 --- a/src/main/daemon/terminal-host.ts +++ b/src/main/daemon/terminal-host.ts @@ -3,44 +3,13 @@ import { normalizePtySize } from './daemon-pty-size' import { resolveProcessCwd } from '../providers/process-cwd' import type { StartupCommandDelivery } from '../../shared/codex-startup-delivery' import { buildStartupCommandSubmission } from '../../shared/startup-command-submission' -import type { - SessionInfo, - TakePendingOutputResult, - TerminalSnapshot, - ShellReadyState -} from './types' +import type { SessionInfo, TakePendingOutputResult, TerminalSnapshot } from './types' import { SessionNotFoundError } from './types' +import type { CreateOrAttachOptions, CreateOrAttachResult } from './terminal-host-create-contract' -const DEFAULT_MAX_TOMBSTONES = 1000 - -export type CreateOrAttachOptions = { - sessionId: string - cols: number - rows: number - cwd?: string - env?: Record - envToDelete?: string[] - command?: string - startupCommandDelivery?: StartupCommandDelivery - /** Explicit shell the renderer asked for (e.g. 'wsl.exe' for "New WSL - * terminal" from the "+" menu). Forwarded to the subprocess spawner so the - * daemon path honors per-tab shell selection the same way LocalPtyProvider - * does. */ - shellOverride?: string - terminalWindowsWslDistro?: string | null - terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe' - shellReadySupported?: boolean - shellReadyTimeoutMs?: number - streamClient: { onData: (data: string) => void; onExit: (code: number) => void } -} +export type { CreateOrAttachOptions, CreateOrAttachResult } from './terminal-host-create-contract' -export type CreateOrAttachResult = { - isNew: boolean - snapshot: TerminalSnapshot | null - pid: number | null - shellState: ShellReadyState - attachToken: symbol -} +const DEFAULT_MAX_TOMBSTONES = 1000 export type TerminalHostOptions = { spawnSubprocess: (opts: { @@ -105,6 +74,8 @@ export class TerminalHost { snapshot, pid: existing.pid, shellState: existing.shellState, + ...(existing.launchAgent ? { launchAgent: existing.launchAgent } : {}), + ...(existing.historySeeded !== undefined ? { historySeeded: existing.historySeeded } : {}), attachToken: token } } @@ -138,8 +109,10 @@ export class TerminalHost { cols: size.cols, rows: size.rows, terminalHandle: opts.env?.ORCA_TERMINAL_HANDLE, + launchAgent: opts.launchAgent, subprocess, shellReadySupported: opts.shellReadySupported ?? false, + historySeed: opts.historySeed, // Why: reap the dead session (dispose emulator + drop from the map) the // moment its subprocess exits, instead of retaining it for the daemon's // lifetime. Nothing reads a dead session's emulator (getSnapshot/ @@ -180,6 +153,8 @@ export class TerminalHost { snapshot: null, pid: subprocess.pid, shellState: session.shellState, + ...(session.launchAgent ? { launchAgent: session.launchAgent } : {}), + ...(session.historySeeded !== undefined ? { historySeeded: session.historySeeded } : {}), attachToken: token } } @@ -192,6 +167,21 @@ export class TerminalHost { this.getAliveSession(sessionId).resize(cols, rows) } + // Why null-not-throw (unlike write/resize): pause/resume are best-effort + // flow-control hints; a session that exited while the notify was in flight + // must not surface an error or a synthetic exit. + pauseProducer(sessionId: string): void { + const session = this.sessions.get(sessionId) + if (!session || !session.isAlive) { + return + } + session.pauseProducer() + } + + resumeProducer(sessionId: string): void { + this.sessions.get(sessionId)?.resumeProducer() + } + kill(sessionId: string, opts: { immediate?: boolean } = {}): void { const session = this.getAliveSession(sessionId) this.recordTombstone(sessionId) @@ -254,6 +244,14 @@ export class TerminalHost { return session.getForegroundProcess() } + async confirmForegroundProcess(sessionId: string): Promise { + const session = this.sessions.get(sessionId) + if (!session || !session.isAlive) { + return null + } + return session.confirmForegroundProcess() + } + clearScrollback(sessionId: string): void { this.getAliveSession(sessionId).clearScrollback() } @@ -261,12 +259,22 @@ export class TerminalHost { // Why: unlike getAliveSession (which throws), this returns null for dead/missing // sessions. Checkpoint is best-effort — a session that exited between the timer // firing and the RPC arriving should not throw. - getSnapshot(sessionId: string): TerminalSnapshot | null { + getSnapshot(sessionId: string, opts: { scrollbackRows?: number } = {}): TerminalSnapshot | null { const session = this.sessions.get(sessionId) if (!session || !session.isAlive) { return null } - return session.getSnapshot() + return session.getSnapshot(opts) + } + + // Why: scan-authority handoff seed (null-not-throw like getSnapshot) — the + // emulator's dangling incomplete escape at the current stream position. + getPartialEscapeTailAnsi(sessionId: string): string { + const session = this.sessions.get(sessionId) + if (!session || !session.isAlive) { + return '' + } + return session.getPartialEscapeTailAnsi() } // Why: read-only readback of the size the PTY actually applied (null-not-throw diff --git a/src/main/daemon/terminal-mode-rehydrate-sequences.ts b/src/main/daemon/terminal-mode-rehydrate-sequences.ts new file mode 100644 index 000000000000..77e3603d4f5f --- /dev/null +++ b/src/main/daemon/terminal-mode-rehydrate-sequences.ts @@ -0,0 +1,47 @@ +import type { TerminalModes } from './types' + +// Why no kitty flags here: rehydrateSequences feeds renderer xterms, and +// POST_REPLAY_REATTACH_RESET's deliberate kitty reset (stale CSI-u Ctrl+C +// hazard) must stay authoritative. modes.kittyKeyboardFlags exists for +// emulator re-seed parity only; a re-seeded emulator answers ?0u and +// protocol-conformant programs re-push. +export function buildRehydrateSequences(modes: TerminalModes): string { + const seqs: string[] = [] + if (modes.alternateScreen) { + // Why: normal-buffer serialization can leave its pen active, while the + // separately serialized alt body assumes it starts from default SGR. + seqs.push('\x1b[0m\x1b[?1049h') + } + if (modes.bracketedPaste) { + seqs.push('\x1b[?2004h') + } + if (modes.applicationCursor) { + seqs.push('\x1b[?1h') + } + // Why: mobile alt-screen scroll gestures need xterm's mouse mode restored + // from cold snapshots; OpenCode/OpenTUI enables scrollable panes this way. + switch (modes.mouseTracking ? (modes.mouseTrackingMode ?? 'vt200') : 'none') { + case 'x10': + seqs.push('\x1b[?9h') + break + case 'vt200': + seqs.push('\x1b[?1000h') + break + case 'drag': + seqs.push('\x1b[?1002h') + break + case 'any': + seqs.push('\x1b[?1003h') + break + case 'none': + break + } + // Why: xterm tracks the mouse protocol and SGR encoding as independent + // modes, so snapshots must preserve the encoding even when reporting is off. + if (modes.sgrMousePixelsMode) { + seqs.push('\x1b[?1016h') + } else if (modes.sgrMouseMode) { + seqs.push('\x1b[?1006h') + } + return seqs.join('') +} diff --git a/src/main/daemon/terminal-mouse-mode-mirror.ts b/src/main/daemon/terminal-mouse-mode-mirror.ts new file mode 100644 index 000000000000..8f8b284f7f4b --- /dev/null +++ b/src/main/daemon/terminal-mouse-mode-mirror.ts @@ -0,0 +1,119 @@ +import type { TerminalModes } from './types' + +type MouseTrackingMode = NonNullable + +// Why: PTY/SSH chunks can split a long combined DECSET before the final h/l. +// Keep parser state far beyond normal mode lists while still bounding memory. +const PRIVATE_MODE_SCAN_TAIL_LIMIT = 4096 + +/** + * Mirrors DECSET mouse-protocol/encoding state from the raw byte stream. + * xterm's public modes API does not expose which mouse protocol is active, + * so snapshots track it independently of the headless terminal; callers + * must feed `scan()` the same bytes the terminal parsed, in order. + */ +export class TerminalMouseModeMirror { + private scanTail = '' + private trackingModeState: MouseTrackingMode = 'none' + private sgrMouseModeState = false + private sgrMousePixelsModeState = false + + get mouseTrackingMode(): MouseTrackingMode { + return this.trackingModeState + } + + get sgrMouseMode(): boolean { + return this.sgrMouseModeState + } + + get sgrMousePixelsMode(): boolean { + return this.sgrMousePixelsModeState + } + + scan(data: string): void { + // Why the pre-filter: this runs on the daemon's per-chunk hot path for + // every session; a flood chunk with no private-mode/reset introducer + // must not pay the regex pass (measured share of a 2.2x ingest + // regression — findings log 2026-07-03). Split sequences stay correct: + // an introducer split across chunks either left a non-empty scanTail + // (previous partial) or ends this chunk, which extractScanTail retains. + if ( + this.scanTail.length === 0 && + !data.includes('\x1b[?') && + !data.includes('\x1bc') && + !data.includes('\x9b') + ) { + this.scanTail = this.extractScanTail(data) + return + } + const input = this.scanTail.length === 0 ? data : this.scanTail + data + this.scanTail = this.extractScanTail(input) + // oxlint-disable-next-line no-control-regex -- terminal escape sequences require control chars + const privateModeRe = /\x1bc|\x1b\[\?([0-9;]+)([hl])|\x9b\?([0-9;]+)([hl])/g + let match: RegExpExecArray | null + while ((match = privateModeRe.exec(input)) !== null) { + if (match[0] === '\x1bc') { + this.trackingModeState = 'none' + this.sgrMouseModeState = false + this.sgrMousePixelsModeState = false + continue + } + const params = match[1] ?? match[3] + const enabled = (match[2] ?? match[4]) === 'h' + for (const rawParam of params.split(';')) { + if (rawParam === '') { + continue + } + const param = Number(rawParam) + if (!Number.isInteger(param)) { + continue + } + if (param === 9) { + this.trackingModeState = enabled ? 'x10' : 'none' + } + if (param === 1000) { + this.trackingModeState = enabled ? 'vt200' : 'none' + } + if (param === 1002) { + this.trackingModeState = enabled ? 'drag' : 'none' + } + if (param === 1003) { + this.trackingModeState = enabled ? 'any' : 'none' + } + if (param === 1006) { + this.sgrMouseModeState = enabled + this.sgrMousePixelsModeState = false + } + if (param === 1016) { + this.sgrMouseModeState = false + this.sgrMousePixelsModeState = enabled + } + } + } + } + + private extractScanTail(input: string): string { + const start = Math.max(input.lastIndexOf('\x1b'), input.lastIndexOf('\x9b')) + if (start === -1) { + return '' + } + const tail = input.slice(start) + if (tail.length > PRIVATE_MODE_SCAN_TAIL_LIMIT) { + return '' + } + if (tail === '\x1b' || tail === '\x1b[' || tail === '\x9b') { + return tail + } + if (tail.startsWith('\x1b[?')) { + return this.isIncompleteParams(tail.slice(3)) ? tail : '' + } + if (tail.startsWith('\x9b?')) { + return this.isIncompleteParams(tail.slice(2)) ? tail : '' + } + return '' + } + + private isIncompleteParams(params: string): boolean { + return /^[0-9;]*$/.test(params) + } +} diff --git a/src/main/daemon/terminal-osc-cwd-title-scanner.ts b/src/main/daemon/terminal-osc-cwd-title-scanner.ts new file mode 100644 index 000000000000..f3736d7c009d --- /dev/null +++ b/src/main/daemon/terminal-osc-cwd-title-scanner.ts @@ -0,0 +1,53 @@ +import { extractLastOscTitle } from '../../shared/agent-detection' +import { parseFileUriPath } from './osc7-file-uri' +import { extractOscScanTail, scanOsc7Uris } from './osc7-uri-extraction' + +const OSC_SCAN_TAIL_LIMIT = 4096 + +/** Mirror of the OSC sequences the emulator tracks outside xterm: OSC 7 cwd + * updates and OSC 0/2 titles. Keeps an unterminated-sequence tail so + * sequences split across PTY chunks still parse. Uses the bounded regex-free + * scanners so giant pasted chunks stay cheap. */ +export type TerminalOscCwdTitleScannerOptions = { + pathFlavor?: 'posix' | 'win32' + remotePosixAuthority?: boolean +} + +export class TerminalOscCwdTitleScanner { + private scanTail = '' + private readonly parseOptions: TerminalOscCwdTitleScannerOptions + cwd: string | null = null + lastTitle: string | null = null + + constructor(options: TerminalOscCwdTitleScannerOptions = {}) { + this.parseOptions = options + } + + scan(data: string): void { + // Why the pre-filter: this runs on the daemon's per-chunk hot path; flood + // chunks with no OSC introducer must not pay the title/URI walks + // (measured share of a 2.2x ingest regression — findings log 2026-07-03). + // Correctness across splits: an OSC intro spanning chunks either left a + // non-empty scanTail or this chunk ends with a bare ESC, which + // extractOscScanTail retains for the next call. + if (this.scanTail.length === 0 && !data.includes('\x1b]')) { + this.scanTail = data.endsWith('\x1b') ? extractOscScanTail(data, OSC_SCAN_TAIL_LIMIT) : '' + return + } + const input = this.scanTail.length === 0 ? data : this.scanTail + data + this.scanTail = extractOscScanTail(input, OSC_SCAN_TAIL_LIMIT) + scanOsc7Uris(input, (uri) => { + const parsed = parseFileUriPath(uri, { + pathFlavor: this.parseOptions.pathFlavor, + remotePosixAuthority: this.parseOptions.remotePosixAuthority + }) + if (parsed) { + this.cwd = parsed + } + }) + const lastTitle = extractLastOscTitle(input) + if (lastTitle !== null) { + this.lastTitle = lastTitle + } + } +} diff --git a/src/main/daemon/terminal-snapshot-ansi-buffers.ts b/src/main/daemon/terminal-snapshot-ansi-buffers.ts new file mode 100644 index 000000000000..e0b16d56d8f3 --- /dev/null +++ b/src/main/daemon/terminal-snapshot-ansi-buffers.ts @@ -0,0 +1,21 @@ +import type { TerminalModes } from './types' + +export function splitTerminalSnapshotAnsi( + snapshotAnsi: string, + modes: TerminalModes +): { snapshotAnsi: string; scrollbackAnsi: string } { + if (!modes.alternateScreen) { + return { snapshotAnsi, scrollbackAnsi: '' } + } + const alternateScreenMarker = '\x1b[?1049h' + const start = snapshotAnsi.lastIndexOf(alternateScreenMarker) + if (start === -1) { + return { snapshotAnsi, scrollbackAnsi: '' } + } + // Why: rehydrateSequences owns the alt-screen transition. Keeping the + // normal buffer separate lets an already-alt renderer rebuild it safely. + return { + scrollbackAnsi: snapshotAnsi.slice(0, start), + snapshotAnsi: snapshotAnsi.slice(start + alternateScreenMarker.length) + } +} diff --git a/src/main/daemon/terminal-snapshot-serialize-roundtrip.test.ts b/src/main/daemon/terminal-snapshot-serialize-roundtrip.test.ts new file mode 100644 index 000000000000..b54227652ddf --- /dev/null +++ b/src/main/daemon/terminal-snapshot-serialize-roundtrip.test.ts @@ -0,0 +1,254 @@ +// Round-trip guards for two @xterm/addon-serialize defects that garbled +// hidden-terminal snapshot restores (serialize a buffer, replay into a fresh +// identical terminal, compare): +// +// BUG B (fixed by config/patches/@xterm__addon-serialize@*.patch): the SGR +// attribute diff emitted bold/dim set params before the shared intensity +// reset 22, so "1;22" wiped a freshly set bold and a bare "22" dropped a +// still-set bold/dim. +// +// BUG C (hardened Orca-side via serializeWithAbsoluteCursor): a final content +// row filled exactly to the right margin leaves replay wrap-pending, and the +// addon's RELATIVE cursor restore then lands one column short. +import './xterm-env-polyfill' +import { describe, expect, it } from 'vitest' +import { Terminal } from '@xterm/headless' +import { SerializeAddon } from '@xterm/addon-serialize' +import { HeadlessEmulator } from './headless-emulator' +import { serializeWithAbsoluteCursor } from '../../shared/terminal-serialize-absolute-cursor' + +type TerminalHarness = { terminal: Terminal; addon: SerializeAddon } + +function createTerminal(cols = 10, rows = 5, scrollback = 100): TerminalHarness { + const terminal = new Terminal({ cols, rows, scrollback, allowProposedApi: true }) + const addon = new SerializeAddon() + terminal.loadAddon(addon) + return { terminal, addon } +} + +function write(terminal: Terminal, data: string): Promise { + return new Promise((resolve) => terminal.write(data, () => resolve())) +} + +async function replay(data: string, cols = 10, rows = 5, scrollback = 100): Promise { + const { terminal } = createTerminal(cols, rows, scrollback) + await write(terminal, data) + return terminal +} + +function cellAt( + terminal: Terminal, + viewportRow: number, + col: number +): NonNullable< + ReturnType>['getCell']> +> { + const buffer = terminal.buffer.active + const line = buffer.getLine(buffer.baseY + viewportRow) + if (!line) { + throw new Error(`no line at viewport row ${viewportRow}`) + } + const cell = line.getCell(col) + if (!cell) { + throw new Error(`no cell at ${viewportRow},${col}`) + } + return cell +} + +function visibleText(terminal: Terminal): string[] { + const buffer = terminal.buffer.active + const lines: string[] = [] + for (let row = 0; row < terminal.rows; row += 1) { + lines.push(buffer.getLine(buffer.baseY + row)?.translateToString(true) ?? '') + } + return lines +} + +async function roundTripStyles(source: string): Promise { + const { terminal, addon } = createTerminal() + await write(terminal, source) + return replay(addon.serialize()) +} + +describe('SGR intensity round-trip (BUG B, addon patch)', () => { + it('restores bold set immediately after dim is cleared (minimized repro)', async () => { + const restored = await roundTripStyles('\x1b[2mA\x1b[22m\x1b[1mB') + const b = cellAt(restored, 0, 1) + expect(b.getChars()).toBe('B') + expect(!!b.isBold()).toBe(true) + expect(!!b.isDim()).toBe(false) + }) + + it('keeps bold when dim is dropped from a bold+dim run', async () => { + const restored = await roundTripStyles('\x1b[1;2mA\x1b[22m\x1b[1mB') + const b = cellAt(restored, 0, 1) + expect(!!b.isBold()).toBe(true) + expect(!!b.isDim()).toBe(false) + }) + + it('keeps dim when bold is dropped from a bold+dim run', async () => { + const restored = await roundTripStyles('\x1b[1;2mA\x1b[22m\x1b[2mB') + const b = cellAt(restored, 0, 1) + expect(!!b.isDim()).toBe(true) + expect(!!b.isBold()).toBe(false) + }) + + it('non-regression: bold after normal text', async () => { + const restored = await roundTripStyles('A\x1b[1mB') + expect(!!cellAt(restored, 0, 0).isBold()).toBe(false) + expect(!!cellAt(restored, 0, 1).isBold()).toBe(true) + }) + + it('non-regression: dim after bold', async () => { + const restored = await roundTripStyles('\x1b[1mA\x1b[22m\x1b[2mB') + const a = cellAt(restored, 0, 0) + const b = cellAt(restored, 0, 1) + expect(!!a.isBold()).toBe(true) + expect(!!a.isDim()).toBe(false) + expect(!!b.isDim()).toBe(true) + expect(!!b.isBold()).toBe(false) + }) + + it('non-regression: bold+dim accumulation survives', async () => { + const restored = await roundTripStyles('\x1b[1mA\x1b[2mB') + const b = cellAt(restored, 0, 1) + expect(!!b.isBold()).toBe(true) + expect(!!b.isDim()).toBe(true) + }) + + it('non-regression: italic after underline is cleared (dedicated resets)', async () => { + const restored = await roundTripStyles('\x1b[4mA\x1b[24m\x1b[3mB') + const b = cellAt(restored, 0, 1) + expect(!!b.isItalic()).toBe(true) + expect(!!b.isUnderline()).toBe(false) + }) + + it('non-regression: underline after italic is cleared (dedicated resets)', async () => { + const restored = await roundTripStyles('\x1b[3mA\x1b[23m\x1b[4mB') + const b = cellAt(restored, 0, 1) + expect(!!b.isUnderline()).toBe(true) + expect(!!b.isItalic()).toBe(false) + }) + + it('non-regression: underline dropped alongside bold set', async () => { + const restored = await roundTripStyles('\x1b[4mA\x1b[24m\x1b[1;4mB\x1b[24mC') + const c = cellAt(restored, 0, 2) + expect(!!c.isBold()).toBe(true) + expect(!!c.isUnderline()).toBe(false) + }) +}) + +describe('cursor restore after wrap-pending replay (BUG C, absolute-cursor hardening)', () => { + const REPRO = '0123456789\x1b[3;5H' + + it('documents the upstream defect: plain serialize lands one column short', async () => { + // Why this pin: the Orca hardening exists only because of this relative- + // restore defect. If an addon bump makes this fail, the hardening can go. + const { terminal, addon } = createTerminal(10, 5) + await write(terminal, REPRO) + expect(terminal.buffer.active.cursorX).toBe(4) + const restored = await replay(addon.serialize()) + expect(restored.buffer.active.cursorX).toBe(3) + }) + + it('HeadlessEmulator snapshot restores the exact cursor (minimized repro)', async () => { + const emulator = new HeadlessEmulator({ cols: 10, rows: 5 }) + expect(emulator.writeSync(REPRO)).toBe(true) + const snapshot = emulator.getSnapshot() + const restored = await replay(snapshot.snapshotAnsi) + expect(restored.buffer.active.cursorX).toBe(4) + expect(restored.buffer.active.cursorY).toBe(2) + expect(visibleText(restored)[0]).toBe('0123456789') + emulator.dispose() + }) + + it('serializeWithAbsoluteCursor restores the exact cursor', async () => { + const { terminal, addon } = createTerminal(10, 5) + await write(terminal, REPRO) + const restored = await replay(serializeWithAbsoluteCursor(addon, terminal)) + expect(restored.buffer.active.cursorX).toBe(4) + expect(restored.buffer.active.cursorY).toBe(2) + }) + + it('never changes already-correct restores at various cursor positions', async () => { + const positions = ['\x1b[1;1H', '\x1b[2;4H', '\x1b[5;10H', '\x1b[4;1H'] + for (const cup of positions) { + const { terminal, addon } = createTerminal(10, 5) + await write(terminal, `hello\r\nworld${cup}`) + const plainRestore = await replay(addon.serialize()) + const hardenedRestore = await replay(serializeWithAbsoluteCursor(addon, terminal)) + expect(hardenedRestore.buffer.active.cursorX).toBe(terminal.buffer.active.cursorX) + expect(hardenedRestore.buffer.active.cursorY).toBe(terminal.buffer.active.cursorY) + expect(hardenedRestore.buffer.active.cursorX).toBe(plainRestore.buffer.active.cursorX) + expect(hardenedRestore.buffer.active.cursorY).toBe(plainRestore.buffer.active.cursorY) + expect(visibleText(hardenedRestore)).toEqual(visibleText(plainRestore)) + } + }) + + it('leaves a wrap-pending source untouched so replay stays wrap-pending', async () => { + const { terminal, addon } = createTerminal(10, 5) + await write(terminal, '0123456789') + // cursorX == cols marks pending wrap; a CUP would clamp and clear it. + expect(terminal.buffer.active.cursorX).toBe(10) + const plain = addon.serialize() + expect(serializeWithAbsoluteCursor(addon, terminal)).toBe(plain) + const restored = await replay(plain) + await write(restored, 'Z') + expect(visibleText(restored)[1]).toBe('Z') + }) + + it('handles a wrap-pending row that is NOT the final content row', async () => { + const { terminal, addon } = createTerminal(10, 5) + // Row 0 fills to the margin and wraps into row 1, then the cursor moves. + await write(terminal, '0123456789ABC\x1b[2;2H') + expect(terminal.buffer.active.cursorY).toBe(1) + expect(terminal.buffer.active.cursorX).toBe(1) + const plainRestore = await replay(addon.serialize()) + const hardenedRestore = await replay(serializeWithAbsoluteCursor(addon, terminal)) + expect(hardenedRestore.buffer.active.cursorX).toBe(1) + expect(hardenedRestore.buffer.active.cursorY).toBe(1) + expect(visibleText(hardenedRestore)).toEqual(visibleText(plainRestore)) + expect(hardenedRestore.buffer.active.cursorX).toBe(plainRestore.buffer.active.cursorX) + expect(hardenedRestore.buffer.active.cursorY).toBe(plainRestore.buffer.active.cursorY) + }) + + it('restores alt-screen snapshots without disturbing correct positioning', async () => { + const { terminal, addon } = createTerminal(10, 5) + await write(terminal, 'shell$\x1b[?1049h\x1b[2J\x1b[HTUI ROW\x1b[2;3H') + expect(terminal.buffer.active.type).toBe('alternate') + const restored = await replay(serializeWithAbsoluteCursor(addon, terminal)) + expect(restored.buffer.active.type).toBe('alternate') + expect(restored.buffer.active.cursorX).toBe(2) + expect(restored.buffer.active.cursorY).toBe(1) + expect(visibleText(restored)[0]).toBe('TUI ROW') + }) + + it('fixes the wrap-pending off-by-one inside the alt screen too', async () => { + const { terminal, addon } = createTerminal(10, 5) + await write(terminal, '\x1b[?1049h0123456789\x1b[3;5H') + const restored = await replay(serializeWithAbsoluteCursor(addon, terminal)) + expect(restored.buffer.active.type).toBe('alternate') + expect(restored.buffer.active.cursorX).toBe(4) + expect(restored.buffer.active.cursorY).toBe(2) + }) + + it('restores scrolled-back buffers with the cursor at its base-relative spot', async () => { + const { terminal, addon } = createTerminal(10, 3, 50) + for (let i = 0; i < 8; i += 1) { + await write(terminal, `line${i}\r\n`) + } + await write(terminal, '\x1b[2;3H') + const source = { x: terminal.buffer.active.cursorX, y: terminal.buffer.active.cursorY } + const restored = await replay(serializeWithAbsoluteCursor(addon, terminal), 10, 3, 50) + expect(restored.buffer.active.cursorX).toBe(source.x) + expect(restored.buffer.active.cursorY).toBe(source.y) + expect(visibleText(restored)).toEqual(visibleText(terminal)) + expect(restored.buffer.active.length).toBe(terminal.buffer.active.length) + }) + + it('keeps empty buffers serializing to an empty string', async () => { + const { terminal, addon } = createTerminal(10, 5) + expect(addon.serialize()).toBe('') + expect(serializeWithAbsoluteCursor(addon, terminal)).toBe('') + }) +}) diff --git a/src/main/daemon/terminal-view-attribute-responder.ts b/src/main/daemon/terminal-view-attribute-responder.ts new file mode 100644 index 000000000000..68ff83c349fb --- /dev/null +++ b/src/main/daemon/terminal-view-attribute-responder.ts @@ -0,0 +1,191 @@ +/** + * Phase 5 slice 2 (docs/reference/terminal-query-authority.md §View-attribute + * bridge): OSC 4/10/11/12 and DSR ?996n responder handlers for the runtime + * headless emulator. The headless xterm core has no theme service, so these + * handlers compute replies from the renderer's pushed attribute snapshot, + * with per-PTY OSC SET mutations layered on top — mirroring exactly what the + * renderer's ThemeService reports for a visible pane. Replies route through + * the caller's emit sink, which the slice-1 forwarding window already gates, + * so seeded/replayed bytes and delivered chunks never produce a reply. + */ +import type { Terminal } from '@xterm/headless' +import { + formatXColorRgbSpec, + parseXColorSpec, + TERMINAL_VIEW_ANSI_COLOR_COUNT, + type TerminalViewAttributes, + type TerminalViewRgb +} from '../../shared/terminal-view-attributes' + +type ViewAttributeParser = Pick + +export type TerminalViewAttributeResponderDeps = { + parser: ViewAttributeParser + /** Last renderer push, or null before the first push. Null means SILENCE + * for every view-attribute query — a fabricated default would resurrect + * the default-black OSC-11 bug (design invariant 3). */ + getBaseAttributes: () => TerminalViewAttributes | null + /** Must already be replay/forwarding-window gated by the caller. */ + emitReply: (reply: string) => void +} + +export type TerminalViewAttributeResponder = { + /** A changed renderer attribute push replaces the whole palette, exactly + * like xterm's ThemeService `_setTheme` overwrites OSC-SET-mutated colors + * on a visible pane's theme apply. Identical re-pushes (fresh renderer + * process) are filtered in main's store and never reach this. */ + clearColorOverrides: () => void +} + +type SpecialColorSlot = 'foreground' | 'background' | 'cursor' + +// OSC 10/11/12 stack extra params onto consecutive slots (xterm's +// _setOrReportSpecialColor): `OSC 10;?;?` reports foreground then background. +const SPECIAL_COLOR_SLOTS: SpecialColorSlot[] = ['foreground', 'background', 'cursor'] +const SPECIAL_COLOR_IDENTS: Record = { + foreground: '10', + background: '11', + cursor: '12' +} + +function isValidColorIndex(value: number): boolean { + return value >= 0 && value < TERMINAL_VIEW_ANSI_COLOR_COUNT +} + +// Mirror of xterm's rgb.relativeLuminance2 (common/Color.ts, WCAG formula) — +// the math CoreBrowserTerminal._reportColorScheme answers ?996n with. +function relativeLuminance([r, g, b]: TerminalViewRgb): number { + const linear = (channel: number): number => { + const c = channel / 255 + return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4) + } + return linear(r) * 0.2126 + linear(g) * 0.7152 + linear(b) * 0.0722 +} + +export function installTerminalViewAttributeResponder( + deps: TerminalViewAttributeResponderDeps +): TerminalViewAttributeResponder { + // Why per-instance maps: SET mutations are per PTY (one emulator per PTY); + // they die with the emulator at teardown, like every other model state. + // They deliberately survive a reveal→re-hide cycle even though the revealed + // xterm restores without palette mutations (SerializeAddon emits no OSC + // color SETs): the TUI never reset its SET, so holding it is + // protocol-correct — the visible-side loss is the pre-existing restore + // limitation, not this model's. + const ansiOverrides = new Map() + const specialOverrides = new Map() + + const reportColor = (ident: string, rgb: TerminalViewRgb): void => { + // Why ST (not BEL) and 16-bit channels: byte-for-byte parity with the + // renderer xterm's reply (CoreBrowserTerminal._handleColorEvent). + deps.emitReply(`\x1b]${ident};${formatXColorRgbSpec(rgb)}\x1b\\`) + } + + const handleSpecialColor = (data: string, offset: number): boolean => { + const slots = data.split(';') + for (let i = 0; i < slots.length; ++i, ++offset) { + if (offset >= SPECIAL_COLOR_SLOTS.length) { + break + } + const slot = SPECIAL_COLOR_SLOTS[offset] + if (slots[i] === '?') { + const base = deps.getBaseAttributes() + if (base) { + reportColor(SPECIAL_COLOR_IDENTS[slot], specialOverrides.get(slot) ?? base[slot]) + } + } else { + const rgb = parseXColorSpec(slots[i]) + if (rgb) { + specialOverrides.set(slot, rgb) + } + } + } + // True consumes the sequence; the headless core's own OSC 10/11/12 + // handler only fires an onColor event nothing consumes. + return true + } + + deps.parser.registerOscHandler(4, (data) => { + const slots = data.split(';') + while (slots.length > 1) { + const idx = slots.shift() as string + const spec = slots.shift() as string + if (!/^\d+$/.test(idx)) { + continue + } + const index = Number.parseInt(idx, 10) + if (!isValidColorIndex(index)) { + continue + } + if (spec === '?') { + const base = deps.getBaseAttributes() + if (base) { + reportColor(`4;${index}`, ansiOverrides.get(index) ?? base.ansi[index]) + } + } else { + const rgb = parseXColorSpec(spec) + if (rgb) { + ansiOverrides.set(index, rgb) + } + } + } + return true + }) + deps.parser.registerOscHandler(10, (data) => handleSpecialColor(data, 0)) + deps.parser.registerOscHandler(11, (data) => handleSpecialColor(data, 1)) + deps.parser.registerOscHandler(12, (data) => handleSpecialColor(data, 2)) + + // OSC 104/110/111/112 restore the themed color — dropping the override + // falls back to the pushed base, the model twin of ThemeService.restoreColor. + deps.parser.registerOscHandler(104, (data) => { + if (!data) { + ansiOverrides.clear() + return true + } + for (const slot of data.split(';')) { + if (/^\d+$/.test(slot)) { + ansiOverrides.delete(Number.parseInt(slot, 10)) + } + } + return true + }) + deps.parser.registerOscHandler(110, () => { + specialOverrides.delete('foreground') + return true + }) + deps.parser.registerOscHandler(111, () => { + specialOverrides.delete('background') + return true + }) + deps.parser.registerOscHandler(112, () => { + specialOverrides.delete('cursor') + return true + }) + + deps.parser.registerCsiHandler({ prefix: '?', final: 'n' }, (params) => { + if (params[0] !== 996) { + // Fall through to the core for every other private DSR (?6n CPR etc.). + return false + } + const base = deps.getBaseAttributes() + if (base) { + // Why luminance and not base.colorSchemeMode: a visible xterm answers + // ?996n from the relative luminance of the CURRENT (OSC-SET-mutated) + // background vs foreground (CoreBrowserTerminal._reportColorScheme), + // so a dark terminal theme in a light app mode still answers dark. + // colorSchemeMode is the app mode and feeds the 2031/997 path only. + const background = specialOverrides.get('background') ?? base.background + const foreground = specialOverrides.get('foreground') ?? base.foreground + const dark = relativeLuminance(background) < relativeLuminance(foreground) + deps.emitReply(`\x1b[?997;${dark ? 1 : 2}n`) + } + return true + }) + + return { + clearColorOverrides: () => { + ansiOverrides.clear() + specialOverrides.clear() + } + } +} diff --git a/src/main/daemon/types.ts b/src/main/daemon/types.ts index a38cc21a425d..550b211aa748 100644 --- a/src/main/daemon/types.ts +++ b/src/main/daemon/types.ts @@ -1,15 +1,24 @@ import type { TerminalOscLinkRange } from '../../shared/terminal-osc-link-ranges' +import type { + ConfirmForegroundProcessRequest, + GetForegroundProcessRequest +} from './daemon-foreground-process-protocol' + +export type { + ConfirmForegroundProcessRequest, + GetForegroundProcessRequest +} from './daemon-foreground-process-protocol' // ─── Protocol Version ──────────────────────────────────────────────── import type { StartupCommandDelivery } from '../../shared/codex-startup-delivery' - +import type { TuiAgent } from '../../shared/types' // Why: daemons can survive app updates. Bump for IPC wire-shape changes, or // when daemon-baked behavior cannot be delivered by on-disk wrapper refresh. // Why: bump when adding daemon wire behavior so same-version old daemons do // not silently accept the handshake and then reject new RPCs. -export const PROTOCOL_VERSION = 18 +export const PROTOCOL_VERSION = 21 export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [ - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ] as const // ─── Session State Machine ────────────────────────────────────────── @@ -20,8 +29,15 @@ export type ShellReadyState = 'pending' | 'ready' | 'timed_out' | 'unsupported' // ─── Terminal Snapshot ────────────────────────────────────────────── export type TerminalSnapshot = { snapshotAnsi: string - /** Scrollback portion only (rows above the visible viewport). Write this - * to preserve history without interfering with TUI repaints. */ + /** Trailing incomplete escape sequence the emulator ingested but xterm's + * parser is still holding (a PTY read ended mid-escape). Restorers must + * write this LAST — after their own post-replay resets, immediately before + * post-snapshot live chunks — so the continuation bytes complete it + * exactly as live (Bug E / #7329, notes/garble-fuzz-divergences.md). Its + * bytes are already counted by the snapshot seq. */ + pendingEscapeTailAnsi?: string + /** Normal buffer captured separately while snapshotAnsi holds an active + * alternate buffer. Empty for normal-screen snapshots. */ scrollbackAnsi: string oscLinks?: TerminalOscLinkRange[] rehydrateSequences: string @@ -31,6 +47,9 @@ export type TerminalSnapshot = { rows: number scrollbackLines: number lastTitle?: string + /** Absolute UTF-16 character count ingested by this live daemon session. + * Optional because persisted snapshots and older v19 daemons lack it. */ + outputSequence?: number } export type TerminalModes = { @@ -41,6 +60,15 @@ export type TerminalModes = { sgrMousePixelsMode?: boolean applicationCursor: boolean alternateScreen: boolean + /** Kitty keyboard protocol flags (CSI = u pushes) for emulator re-seed + * parity ONLY. Consumed by the daemon warm-reattach path: the spawn + * result threads them into seedHeadlessTerminal, which re-applies them to + * the fresh runtime emulator (HeadlessEmulator.applyKittyKeyboardFlags) + * so hidden `CSI ? u` answers the real flags instead of ?0u. + * rehydrateSequences must never push these into a renderer xterm — + * POST_REPLAY_REATTACH_RESET's deliberate kitty reset stays authoritative + * (terminal-query-authority.md §kitty). */ + kittyKeyboardFlags?: number } // The on-disk checkpoint.json shape lives in daemon-checkpoint-file.ts (it @@ -79,6 +107,7 @@ export type CreateOrAttachRequest = { envToDelete?: string[] command?: string startupCommandDelivery?: StartupCommandDelivery + launchAgent?: TuiAgent /** Explicit Windows shell override selected by the user (e.g. 'wsl.exe'). * The daemon forwards this to its subprocess spawner so each tab honors * the shell picked in the "+" menu or the persisted default-shell setting, @@ -94,6 +123,8 @@ export type CreateOrAttachRequest = { terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe' shellReadySupported?: boolean shellReadyTimeoutMs?: number + /** Recovered ANSI applied before the new subprocess can emit startup output. */ + historySeed?: string } } @@ -124,6 +155,38 @@ export type ResizeRequest = { } } +// ─── Producer flow control (v19+) ─────────────────────────────────── +// Why fire-and-forget notifications (like write/resize): pause/resume ride the +// hot data path and are best-effort — the daemon-side 5s failsafe, not an RPC +// reply, is what guarantees a paused shell can never stay wedged. +export type PausePtyRequest = { + id: string + type: 'pausePty' + payload: { + sessionId: string + } +} + +export type ResumePtyRequest = { + id: string + type: 'resumePty' + payload: { + sessionId: string + } +} + +// Why the notification stays backward-tolerated: unknown notify types are +// swallowed by old daemons. The adapter's v20 capability gate separately +// prevents v19 thinning without a sequence-safe recovery snapshot. +export type SetSessionBackgroundRequest = { + id: string + type: 'setSessionBackground' + payload: { + sessionId: string + background: boolean + } +} + export type KillRequest = { id: string type: 'kill' @@ -163,14 +226,6 @@ export type GetCwdRequest = { } } -export type GetForegroundProcessRequest = { - id: string - type: 'getForegroundProcess' - payload: { - sessionId: string - } -} - export type ClearScrollbackRequest = { id: string type: 'clearScrollback' @@ -207,6 +262,7 @@ export type GetSnapshotRequest = { type: 'getSnapshot' payload: { sessionId: string + scrollbackRows?: number } } @@ -267,12 +323,16 @@ export type DaemonRequest = | CancelCreateOrAttachRequest | WriteRequest | ResizeRequest + | PausePtyRequest + | ResumePtyRequest + | SetSessionBackgroundRequest | KillRequest | SignalRequest | ListSessionsRequest | DetachRequest | GetCwdRequest | GetForegroundProcessRequest + | ConfirmForegroundProcessRequest | ClearScrollbackRequest | ShutdownRequest | PingRequest @@ -303,8 +363,9 @@ export type CreateOrAttachResult = { snapshot: TerminalSnapshot | null pid: number | null shellState: ShellReadyState + historySeeded?: boolean + launchAgent?: TuiAgent } - export type GetSnapshotResult = { snapshot: TerminalSnapshot | null } @@ -340,30 +401,9 @@ export type DaemonSessionInfo = SessionInfo & { protocolVersion: number } -// ─── Events (Daemon → Client, on stream socket) ──────────────────── - -export type DataEvent = { - type: 'event' - event: 'data' - sessionId: string - payload: { data: string } -} - -export type ExitEvent = { - type: 'event' - event: 'exit' - sessionId: string - payload: { code: number } -} - -export type TerminalErrorEvent = { - type: 'event' - event: 'terminalError' - sessionId: string - payload: { message: string } -} - -export type DaemonEvent = DataEvent | ExitEvent | TerminalErrorEvent +// Stream-socket event shapes live in daemon-stream-events.ts; re-exported so +// existing importers keep one types entry point. +export * from './daemon-stream-events' // ─── Binary Frame Protocol (Daemon ↔ PTY Subprocess) ──────────────── // @@ -388,23 +428,10 @@ export const FRAME_MAX_PAYLOAD = 1024 * 1024 // 1MB export const NOTIFY_PREFIX = 'notify_' // ─── Error types ──────────────────────────────────────────────────── -export class TerminalAttachCanceledError extends Error { - constructor(sessionId: string) { - super(`Attach canceled for session ${sessionId}`) - this.name = 'TerminalAttachCanceledError' - } -} - -export class DaemonProtocolError extends Error { - constructor(message: string) { - super(message) - this.name = 'DaemonProtocolError' - } -} - -export class SessionNotFoundError extends Error { - constructor(sessionId: string) { - super(`Session not found: ${sessionId}`) - this.name = 'SessionNotFoundError' - } -} +// Re-exported so existing importers of `./types` keep working; the classes +// live in daemon-errors.ts (this file is capped for wire-shape declarations). +export { + TerminalAttachCanceledError, + DaemonProtocolError, + SessionNotFoundError +} from './daemon-errors' diff --git a/src/main/droid/hook-service.ts b/src/main/droid/hook-service.ts index 920e079989d2..946f5ac88097 100644 --- a/src/main/droid/hook-service.ts +++ b/src/main/droid/hook-service.ts @@ -1,5 +1,6 @@ import { homedir } from 'node:os' import { join } from 'node:path' +import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { buildManagedCommandHook, @@ -12,8 +13,14 @@ import { wrapWindowsHookCommand, writeHooksJson, writeManagedScript, - type HookDefinition + type HookDefinition, + type HooksConfig } from '../agent-hooks/installer-utils' +import { + readHooksJsonRemote, + writeHooksJsonRemote, + writeManagedScriptRemote +} from '../agent-hooks/installer-utils-remote' // Why: SessionStart is installed (not just listened for) so that resuming a // droid session via `droid --resume` resets the per-pane prompt/tool caches @@ -64,8 +71,8 @@ function getManagedCommand(scriptPath: string): string { : wrapPosixHookCommand(scriptPath) } -function getManagedScript(): string { - if (process.platform === 'win32') { +function getManagedScript(target: 'local' | 'posix' = 'local'): string { + if (target === 'local' && process.platform === 'win32') { return [ '@echo off', 'setlocal', @@ -111,6 +118,45 @@ function getManagedScript(): string { ].join('\n') } +// Why: local install() and installRemote() must produce byte-identical Factory +// settings.json hook trees; sharing this mutation is what keeps the SSH install +// from drifting off the local one (the exact class of bug that left Droid with +// no remote installer at all — issue #7253). +function buildInstalledDroidConfig( + config: HooksConfig, + command: string, + scriptFileName: string +): void { + const nextHooks = { ...config.hooks } + const isManagedCommand = createManagedCommandMatcher(scriptFileName) + const managedEvents = new Set(DROID_EVENTS.map((event) => event.eventName)) + + // Why: sweep managed entries out of events we no longer subscribe to. + for (const [eventName, definitions] of Object.entries(nextHooks)) { + if (managedEvents.has(eventName) || !Array.isArray(definitions)) { + continue + } + const cleaned = removeManagedCommands(definitions, isManagedCommand) + if (cleaned.length === 0) { + delete nextHooks[eventName] + } else { + nextHooks[eventName] = cleaned + } + } + + for (const event of DROID_EVENTS) { + const current = Array.isArray(nextHooks[event.eventName]) ? nextHooks[event.eventName] : [] + const cleaned = removeManagedCommands(current, isManagedCommand) + const definition: HookDefinition = { + ...event.definition, + hooks: [buildManagedCommandHook(command)] + } + nextHooks[event.eventName] = [...cleaned, definition] + } + + config.hooks = nextHooks +} + export class DroidHookService { getStatus(): AgentHookInstallStatus { const configPath = getConfigPath() @@ -189,41 +235,55 @@ export class DroidHookService { } } - const command = getManagedCommand(scriptPath) - const nextHooks = { ...config.hooks } - const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName()) - const managedEvents = new Set(DROID_EVENTS.map((event) => event.eventName)) + buildInstalledDroidConfig(config, getManagedCommand(scriptPath), getManagedScriptFileName()) + writeManagedScript(scriptPath, getManagedScript()) + writeHooksJson(configPath, config) + return this.getStatus() + } - // Why: sweep managed entries out of events we no longer subscribe to. - for (const [eventName, definitions] of Object.entries(nextHooks)) { - if (managedEvents.has(eventName)) { - continue + // Why: SSH remotes run the Droid CLI on the remote host, so its hook config + // and managed script must be written into the remote ~/.factory + ~/.orca via + // SFTP. Without this, Droid never fires the managed hook over SSH and its + // status row is absent from the task tree (issue #7253). Mirrors the local + // install() but always emits POSIX script/paths — even from a Windows host. + async installRemote(sftp: SFTPWrapper, remoteHome: string): Promise { + const home = remoteHome.replace(/\/$/, '') + const remoteConfigPath = `${home}/.factory/settings.json` + const remoteScriptPath = `${home}/.orca/agent-hooks/droid-hook.sh` + try { + const config = await readHooksJsonRemote(sftp, remoteConfigPath) + if (!config) { + return { + agent: 'droid', + state: 'error', + configPath: remoteConfigPath, + managedHooksPresent: false, + detail: 'Could not parse remote Factory settings.json' + } } - if (!Array.isArray(definitions)) { - continue - } - const cleaned = removeManagedCommands(definitions, isManagedCommand) - if (cleaned.length === 0) { - delete nextHooks[eventName] - } else { - nextHooks[eventName] = cleaned - } - } - for (const event of DROID_EVENTS) { - const current = Array.isArray(nextHooks[event.eventName]) ? nextHooks[event.eventName] : [] - const cleaned = removeManagedCommands(current, isManagedCommand) - const definition: HookDefinition = { - ...event.definition, - hooks: [buildManagedCommandHook(command)] + buildInstalledDroidConfig(config, wrapPosixHookCommand(remoteScriptPath), 'droid-hook.sh') + // Why: script first, config last — a partial config write must never + // point Droid at a script that isn't on disk yet. + await writeManagedScriptRemote(sftp, remoteScriptPath, getManagedScript('posix')) + await writeHooksJsonRemote(sftp, remoteConfigPath, config) + + return { + agent: 'droid', + state: 'installed', + configPath: remoteConfigPath, + managedHooksPresent: true, + detail: null + } + } catch (err) { + return { + agent: 'droid', + state: 'error', + configPath: remoteConfigPath, + managedHooksPresent: false, + detail: err instanceof Error ? err.message : String(err) } - nextHooks[event.eventName] = [...cleaned, definition] } - - config.hooks = nextHooks - writeManagedScript(scriptPath, getManagedScript()) - writeHooksJson(configPath, config) - return this.getStatus() } remove(): AgentHookInstallStatus { diff --git a/src/main/emulator/serve-sim-state-watcher.test.ts b/src/main/emulator/serve-sim-state-watcher.test.ts index 006531dff20d..bf9d7a61fa15 100644 --- a/src/main/emulator/serve-sim-state-watcher.test.ts +++ b/src/main/emulator/serve-sim-state-watcher.test.ts @@ -6,6 +6,17 @@ import { ServeSimStateWatcher, type ServeSimStateDetectedEvent } from './serve-s const TEST_UDID = '11111111-2222-3333-4444-555555555555' +let isolatedStateDirSeq = 0 +// Why: the default state dir is the real $TMPDIR/serve-sim — a leftover state +// file from an actual simulator session would leak extra events into tests +// that only exercise PTY ingestion. Point at a dir that never exists. +function createIsolatedWatcher(): ServeSimStateWatcher { + isolatedStateDirSeq += 1 + return new ServeSimStateWatcher({ + stateDir: join(tmpdir(), `orca-serve-sim-test-none-${process.pid}-${isolatedStateDirSeq}`) + }) +} + async function waitForEvent( events: ServeSimStateDetectedEvent[], predicate: (event: ServeSimStateDetectedEvent) => boolean @@ -68,7 +79,7 @@ describe('ServeSimStateWatcher', () => { }) it('suppresses Orca-managed sessions only while they are marked managed', async () => { - const watcher = new ServeSimStateWatcher() + const watcher = createIsolatedWatcher() const events: ServeSimStateDetectedEvent[] = [] const payload = JSON.stringify({ device: TEST_UDID, @@ -95,7 +106,7 @@ describe('ServeSimStateWatcher', () => { }) it('prunes worktree-scoped dedupe keys on forget so a re-bound worktree re-emits', () => { - const watcher = new ServeSimStateWatcher() + const watcher = createIsolatedWatcher() const events: ServeSimStateDetectedEvent[] = [] const payload = JSON.stringify({ device: TEST_UDID, @@ -122,7 +133,7 @@ describe('ServeSimStateWatcher', () => { }) it('dedupes one helper without hiding a later helper for the same simulator', () => { - const watcher = new ServeSimStateWatcher() + const watcher = createIsolatedWatcher() const events: ServeSimStateDetectedEvent[] = [] const firstPayload = JSON.stringify({ device: TEST_UDID, diff --git a/src/main/external-editor-launch.test.ts b/src/main/external-editor-launch.test.ts index 507e9b5700d0..8ced95ffd2f2 100644 --- a/src/main/external-editor-launch.test.ts +++ b/src/main/external-editor-launch.test.ts @@ -1,8 +1,22 @@ -import { describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { resolveCliCommandMock } = vi.hoisted(() => ({ + resolveCliCommandMock: vi.fn((command: string) => command) +})) + +vi.mock('./codex-cli/command', () => ({ + resolveCliCommand: resolveCliCommandMock +})) + import { getCmdExePath } from './win32-utils' import { resolveExternalEditorLaunchSpec } from './external-editor-launch' describe('resolveExternalEditorLaunchSpec', () => { + beforeEach(() => { + resolveCliCommandMock.mockReset() + resolveCliCommandMock.mockImplementation((command: string) => command) + }) + it('keeps simple CLI commands on the executable launch path', () => { const spec = resolveExternalEditorLaunchSpec('cursor', '/tmp/workspace', { platform: 'darwin' @@ -121,4 +135,123 @@ describe('resolveExternalEditorLaunchSpec', () => { spawnArgs: ['/d', '/s', '/c', 'nvim --clean C:\\workspaces\\orca'] }) }) + + it.each(['code', 'code-insiders'])( + 'opens modern WSL UNC workspaces with %s in the matching VS Code remote', + (editorCommand) => { + expect( + resolveExternalEditorLaunchSpec( + editorCommand, + '\\\\wsl.localhost\\Ubuntu\\home\\aliuq\\project', + { platform: 'win32' } + ).spawnArgs + ).toEqual(['--remote', 'wsl+Ubuntu', '/home/aliuq/project']) + } + ) + + it.each([ + [ + 'legacy WSL UNC workspace', + '\\\\wsl$\\Debian\\home\\ada\\project', + 'wsl+Debian', + '/home/ada/project' + ], + ['modern WSL distro root', '\\\\wsl.localhost\\Ubuntu', 'wsl+Ubuntu', '/'], + ['legacy WSL distro root', '\\\\wsl$\\Debian', 'wsl+Debian', '/'] + ])('opens a %s in the matching VS Code remote', (_label, pathValue, authority, linuxPath) => { + expect( + resolveExternalEditorLaunchSpec('code', pathValue, { platform: 'win32' }).spawnArgs + ).toEqual(['--remote', authority, linuxPath]) + }) + + it.each([ + 'C:\\Program Files\\Microsoft VS Code\\Code.exe', + 'C:\\Program Files\\Microsoft VS Code Insiders\\Code - Insiders.exe', + 'C:\\Tools\\CODE.CMD', + 'C:\\Tools\\code.bat', + 'C:\\Tools\\code-insiders.cmd' + ])('recognizes the direct Windows VS Code launcher %s', (editorCommand) => { + expect( + resolveExternalEditorLaunchSpec( + editorCommand, + '\\\\wsl.localhost\\Ubuntu\\home\\ada\\project', + { platform: 'win32' } + ).spawnArgs + ).toEqual(['--remote', 'wsl+Ubuntu', '/home/ada/project']) + }) + + it.each([ + ['code', 'C:\\Tools\\CODE.CMD'], + ['code', 'C:\\Tools\\code.bat'], + ['code-insiders', 'C:\\Tools\\code-insiders.cmd'] + ])('recognizes the resolved Windows VS Code launcher %s', (editorCommand, resolvedCommand) => { + resolveCliCommandMock.mockReturnValueOnce(resolvedCommand) + + expect( + resolveExternalEditorLaunchSpec( + editorCommand, + '\\\\wsl.localhost\\Ubuntu\\home\\ada\\project', + { platform: 'win32' } + ) + ).toEqual({ + kind: 'executable', + hideWindowsConsole: true, + spawnCmd: resolvedCommand, + spawnArgs: ['--remote', 'wsl+Ubuntu', '/home/ada/project'] + }) + }) + + it('preserves spaces in WSL distro and folder arguments', () => { + expect( + resolveExternalEditorLaunchSpec( + 'code', + '\\\\wsl.localhost\\Ubuntu Preview\\home\\Ada Lovelace\\project', + { platform: 'win32' } + ).spawnArgs + ).toEqual(['--remote', 'wsl+Ubuntu Preview', '/home/Ada Lovelace/project']) + }) + + it.each(['darwin', 'linux'] as const)('keeps WSL-looking paths local on %s', (platform) => { + const pathValue = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\project' + expect(resolveExternalEditorLaunchSpec('code', pathValue, { platform }).spawnArgs).toEqual([ + pathValue + ]) + }) + + it.each(['C:\\workspaces\\orca', '\\\\server\\share\\project'])( + 'keeps the non-WSL Windows path %s local', + (pathValue) => { + expect( + resolveExternalEditorLaunchSpec('code', pathValue, { platform: 'win32' }).spawnArgs + ).toEqual([pathValue]) + } + ) + + it('does not add VS Code remote arguments to other editors', () => { + const pathValue = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\project' + + expect( + resolveExternalEditorLaunchSpec('C:\\Tools\\cursor.exe', pathValue, { + platform: 'win32' + }).spawnArgs + ).toEqual(['--new-window', pathValue]) + expect( + resolveExternalEditorLaunchSpec('C:\\Tools\\codium.exe', pathValue, { + platform: 'win32' + }).spawnArgs + ).toEqual([pathValue]) + }) + + it('does not rewrite compound VS Code commands', () => { + const pathValue = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\project' + + expect( + resolveExternalEditorLaunchSpec('code --reuse-window', pathValue, { platform: 'win32' }) + ).toEqual({ + kind: 'shell', + hideWindowsConsole: true, + spawnCmd: getCmdExePath(), + spawnArgs: ['/d', '/s', '/c', `code --reuse-window ${pathValue}`] + }) + }) }) diff --git a/src/main/external-editor-launch.ts b/src/main/external-editor-launch.ts index 8e5c4a0b3973..b86ca3e896f1 100644 --- a/src/main/external-editor-launch.ts +++ b/src/main/external-editor-launch.ts @@ -1,10 +1,12 @@ import { existsSync } from 'node:fs' import { basename, posix, win32 } from 'node:path' +import { parseWslUncPath } from '../shared/wsl-paths' import { resolveCliCommand } from './codex-cli/command' import { getCmdExePath } from './win32-utils' export const EXTERNAL_EDITOR_CLI_COMMAND = 'code' const WINDOWS_CONSOLE_EDITORS = new Set(['nvim', 'vim']) +const VSCODE_REMOTE_EDITORS = new Set(['code', 'code-insiders', 'code - insiders']) export type ExternalEditorLaunchSpec = | { @@ -106,12 +108,24 @@ function shouldShowWindowsConsole( return platform === 'win32' && WINDOWS_CONSOLE_EDITORS.has(getLauncherBaseName(command, options)) } -function buildExecutableArgs(editorCommand: string, pathValue: string): string[] { - if (getLauncherBaseName(editorCommand) === 'cursor') { +function buildExecutableArgs( + editorCommand: string, + pathValue: string, + platform: NodeJS.Platform +): string[] { + const launcherBaseName = getLauncherBaseName(editorCommand) + if (launcherBaseName === 'cursor') { // Why: Cursor can route bare folder launches through the last active // workbench. A new window keeps "Open in Cursor" scoped to this worktree. return ['--new-window', pathValue] } + if (platform === 'win32' && VSCODE_REMOTE_EDITORS.has(launcherBaseName)) { + const wslPath = parseWslUncPath(pathValue) + if (wslPath) { + // Why: VS Code otherwise treats a WSL UNC path as a local Windows folder. + return ['--remote', `wsl+${wslPath.distro}`, wslPath.linuxPath] + } + } return [pathValue] } @@ -156,7 +170,7 @@ export function resolveExternalEditorLaunchSpec( kind: 'executable', hideWindowsConsole: !shouldShowWindowsConsole(editorCommand, platform), spawnCmd: editorCommand, - spawnArgs: buildExecutableArgs(editorCommand, pathValue) + spawnArgs: buildExecutableArgs(editorCommand, pathValue, platform) } } @@ -169,6 +183,6 @@ export function resolveExternalEditorLaunchSpec( kind: 'executable', hideWindowsConsole: !shouldShowWindowsConsole(editorCommand, platform), spawnCmd: editorCommand, - spawnArgs: buildExecutableArgs(editorCommand, pathValue) + spawnArgs: buildExecutableArgs(editorCommand, pathValue, platform) } } diff --git a/src/main/git/branch-rename.test.ts b/src/main/git/branch-rename.test.ts index 9b0917f7c9b6..023bb542011c 100644 --- a/src/main/git/branch-rename.test.ts +++ b/src/main/git/branch-rename.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { - branchHasUpstream, + probeBranchUpstream, renameCurrentBranch, resolveUniqueBranchName, type GitExec @@ -12,8 +12,8 @@ const noUpstreamError = new Error( ' git push --set-upstream origin feature' ) -describe('branchHasUpstream', () => { - it('is true when @{u} resolves to a tracking ref', async () => { +describe('probeBranchUpstream', () => { + it('reports has-upstream when @{u} resolves to a tracking ref', async () => { const exec: GitExec = vi.fn(async (args: string[]) => { if (args[0] === 'symbolic-ref') { return { stdout: 'feature\n', stderr: '' } @@ -23,10 +23,10 @@ describe('branchHasUpstream', () => { } throw new Error(`unexpected git args: ${args.join(' ')}`) }) - expect(await branchHasUpstream(exec)).toBe(true) + expect(await probeBranchUpstream(exec)).toEqual({ outcome: 'has-upstream' }) }) - it('is false when there is no upstream', async () => { + it('reports no-upstream when there is no upstream', async () => { const exec: GitExec = vi.fn(async (args: string[]) => { if (args[0] === 'symbolic-ref') { return { stdout: 'feature\n', stderr: '' } @@ -39,10 +39,10 @@ describe('branchHasUpstream', () => { } throw new Error(`unexpected git args: ${args.join(' ')}`) }) - expect(await branchHasUpstream(exec)).toBe(false) + expect(await probeBranchUpstream(exec)).toEqual({ outcome: 'no-upstream' }) }) - it('is true when a same-name origin tracking ref exists without configured upstream', async () => { + it('reports has-upstream when a same-name origin tracking ref exists without configured upstream', async () => { const exec: GitExec = vi.fn(async (args: string[]) => { if (args[0] === 'symbolic-ref') { return { stdout: 'feature\n', stderr: '' } @@ -55,12 +55,44 @@ describe('branchHasUpstream', () => { } throw new Error(`unexpected git args: ${args.join(' ')}`) }) - expect(await branchHasUpstream(exec)).toBe(true) + expect(await probeBranchUpstream(exec)).toEqual({ outcome: 'has-upstream' }) }) - it('is conservatively true on an unexpected failure', async () => { + it('reports probe-failed on an unexpected failure', async () => { const exec: GitExec = vi.fn().mockRejectedValue(new Error('fatal: not a git repository')) - expect(await branchHasUpstream(exec)).toBe(true) + expect(await probeBranchUpstream(exec)).toEqual({ + outcome: 'probe-failed', + message: 'fatal: not a git repository' + }) + }) + + it('scrubs credential-bearing URLs from the probe-failed message', async () => { + // The message surfaces on the worktree card, so an embedded remote URL + // must not leak a token or password into the UI. + const exec: GitExec = vi + .fn() + .mockRejectedValue( + new Error('fatal: unable to access https://user:hunter2@example.com/repo.git/: timed out') + ) + expect(await probeBranchUpstream(exec)).toEqual({ + outcome: 'probe-failed', + message: 'fatal: unable to access https://example.com/repo.git/: timed out' + }) + }) + + it('reports probe-failed, not has-upstream, for localized git diagnostics (issue #7808)', async () => { + // A gettext-enabled git under de_DE translates even the `fatal:` prefix. + const exec: GitExec = vi.fn(async (args: string[]) => { + if (args[0] === 'symbolic-ref') { + return { stdout: 'feature\n', stderr: '' } + } + throw new Error( + 'Command failed: git rev-parse --abbrev-ref HEAD@{u}\n' + + "Schwerwiegend: Kein Upstream-Branch für Branch 'feature' konfiguriert." + ) + }) + const probe = await probeBranchUpstream(exec) + expect(probe.outcome).toBe('probe-failed') }) }) diff --git a/src/main/git/branch-rename.ts b/src/main/git/branch-rename.ts index 061f585f3b76..1237b82cf5ab 100644 --- a/src/main/git/branch-rename.ts +++ b/src/main/git/branch-rename.ts @@ -1,4 +1,4 @@ -import { isNoUpstreamError } from '../../shared/git-remote-error' +import { isNoUpstreamError, stripCredentialsFromMessage } from '../../shared/git-remote-error' import { resolveEffectiveGitUpstream, type GitCommandRunner @@ -11,22 +11,31 @@ import { */ export type GitExec = GitCommandRunner +export type BranchUpstreamProbe = + | { outcome: 'has-upstream' } + | { outcome: 'no-upstream' } + | { outcome: 'probe-failed'; message: string } + /** - * True when the branch has a configured upstream — i.e. it has been pushed or - * is tracking a remote. Auto-rename refuses to touch such a branch because - * `git branch -m` would orphan the remote branch and break any open PR. + * Whether the branch has an upstream — i.e. it has been pushed or is tracking + * a remote. Auto-rename refuses to touch such a branch because `git branch -m` + * would orphan the remote branch and break any open PR. */ -export async function branchHasUpstream(exec: GitExec): Promise { +export async function probeBranchUpstream(exec: GitExec): Promise { try { - return (await resolveEffectiveGitUpstream(exec)) !== null + const upstream = await resolveEffectiveGitUpstream(exec) + return { outcome: upstream !== null ? 'has-upstream' : 'no-upstream' } } catch (error) { if (isNoUpstreamError(error)) { - return false + return { outcome: 'no-upstream' } + } + // Why: an unexpected failure is not proof either way — report it as its own + // outcome so callers skip the rename but stay retryable (issue #7808). + // The message surfaces in the UI, so scrub credential-bearing remote URLs. + return { + outcome: 'probe-failed', + message: stripCredentialsFromMessage(error instanceof Error ? error.message : String(error)) } - // Why: an unexpected failure (detached HEAD, corruption, transport error) - // is not proof there's no upstream. Stay conservative and report "has - // upstream" so the caller skips the rename rather than risk a published branch. - return true } } diff --git a/src/main/git/check-ignored-paths.test.ts b/src/main/git/check-ignored-paths.test.ts index 3338ee230273..398d7c186506 100644 --- a/src/main/git/check-ignored-paths.test.ts +++ b/src/main/git/check-ignored-paths.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { checkIgnoredPaths } from './check-ignored-paths' import { gitExecFileAsync } from './runner' +import { GIT_CHECK_IGNORE_TIMEOUT_MS } from '../../shared/git-check-ignore-stdio' vi.mock('./runner', () => ({ gitExecFileAsync: vi.fn() @@ -14,29 +15,43 @@ describe('checkIgnoredPaths', () => { }) it('returns ignored paths from git check-ignore output', async () => { - gitExecFileAsyncMock.mockResolvedValue({ stdout: 'dist/bundle.js\n.env\n', stderr: '' }) + gitExecFileAsyncMock.mockResolvedValue({ stdout: 'dist/bundle.js\0.env\0', stderr: '' }) await expect( checkIgnoredPaths('/repo', ['dist/bundle.js', 'src/index.ts', '.env']) ).resolves.toEqual(['dist/bundle.js', '.env']) expect(gitExecFileAsyncMock).toHaveBeenCalledWith( - [ - '-c', - 'core.quotePath=false', - 'check-ignore', - '--', - 'dist/bundle.js', - 'src/index.ts', - '.env' - ], - { cwd: '/repo' } + ['-c', 'core.quotePath=false', 'check-ignore', '-z', '--stdin'], + { + cwd: '/repo', + stdin: 'dist/bundle.js\0src/index.ts\0.env\0', + timeout: GIT_CHECK_IGNORE_TIMEOUT_MS + } ) }) + it('checks ten thousand paths with one bounded subprocess', async () => { + gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + const paths = Array.from({ length: 10_000 }, (_, index) => `generated/file-${index}.js`) + + await expect(checkIgnoredPaths('/repo', paths)).resolves.toEqual([]) + + expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) + expect(gitExecFileAsyncMock.mock.calls[0]?.[1]).toMatchObject({ + timeout: GIT_CHECK_IGNORE_TIMEOUT_MS + }) + expect(gitExecFileAsyncMock.mock.calls[0]?.[1].stdin?.split('\0')).toHaveLength(10_001) + }) + it('treats exit code 1 as no ignored paths', async () => { gitExecFileAsyncMock.mockRejectedValue(Object.assign(new Error('no matches'), { code: 1 })) await expect(checkIgnoredPaths('/repo', ['src/index.ts'])).resolves.toEqual([]) }) + + it('skips the subprocess for an empty path list', async () => { + await expect(checkIgnoredPaths('/repo', [])).resolves.toEqual([]) + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) }) diff --git a/src/main/git/check-ignored-paths.ts b/src/main/git/check-ignored-paths.ts index 4a03bbb3127f..65e2a88f73dc 100644 --- a/src/main/git/check-ignored-paths.ts +++ b/src/main/git/check-ignored-paths.ts @@ -1,30 +1,32 @@ import type { GitRuntimeOptions } from './git-runtime-options' import { gitOptionsForWorktree } from './git-runtime-options' import { gitExecFileAsync } from './runner' - -const CHECK_IGNORE_CHUNK_SIZE = 100 +import { + encodeGitCheckIgnorePaths, + GIT_CHECK_IGNORE_STDIN_ARGS, + GIT_CHECK_IGNORE_TIMEOUT_MS, + parseGitCheckIgnorePaths, + splitGitCheckIgnorePathsByStdinBytes +} from '../../shared/git-check-ignore-stdio' type GitExecError = Error & { stdout?: string; code?: number | string } -function parseCheckIgnoreOutput(stdout: string): string[] { - return stdout.split(/\r?\n/).filter(Boolean) -} - -async function runCheckIgnoreChunk( +async function runCheckIgnoredPaths( worktreePath: string, relativePaths: string[], - options: GitRuntimeOptions = {} + options: GitRuntimeOptions ): Promise { try { - const { stdout } = await gitExecFileAsync( - ['-c', 'core.quotePath=false', 'check-ignore', '--', ...relativePaths], - gitOptionsForWorktree(worktreePath, options) - ) - return parseCheckIgnoreOutput(stdout) + const { stdout } = await gitExecFileAsync([...GIT_CHECK_IGNORE_STDIN_ARGS], { + ...gitOptionsForWorktree(worktreePath, options), + stdin: encodeGitCheckIgnorePaths(relativePaths), + timeout: GIT_CHECK_IGNORE_TIMEOUT_MS + }) + return parseGitCheckIgnorePaths(stdout) } catch (error) { const gitError = error as GitExecError if (gitError.code === 1) { - return parseCheckIgnoreOutput(gitError.stdout ?? '') + return parseGitCheckIgnorePaths(gitError.stdout ?? '') } throw error } @@ -35,10 +37,12 @@ export async function checkIgnoredPaths( relativePaths: string[], options: GitRuntimeOptions = {} ): Promise { + if (relativePaths.length === 0) { + return [] + } const ignored = new Set() - for (let i = 0; i < relativePaths.length; i += CHECK_IGNORE_CHUNK_SIZE) { - const chunk = relativePaths.slice(i, i + CHECK_IGNORE_CHUNK_SIZE) - for (const ignoredPath of await runCheckIgnoreChunk(worktreePath, chunk, options)) { + for (const chunk of splitGitCheckIgnorePathsByStdinBytes(relativePaths)) { + for (const ignoredPath of await runCheckIgnoredPaths(worktreePath, chunk, options)) { ignored.add(ignoredPath) } } diff --git a/src/main/git/git-capability-state.test.ts b/src/main/git/git-capability-state.test.ts new file mode 100644 index 000000000000..0d499aea1632 --- /dev/null +++ b/src/main/git/git-capability-state.test.ts @@ -0,0 +1,37 @@ +import { beforeEach, describe, expect, it } from 'vitest' +import { + clearGitCapabilityStateForTests, + getLocalGitCapabilityCache, + getSshGitCapabilityCache +} from './git-capability-state' + +describe('Git capability execution-host state', () => { + beforeEach(() => { + clearGitCapabilityStateForTests() + }) + + it('shares native state while isolating each WSL distro', () => { + expect(getLocalGitCapabilityCache({ cwd: '/repo-a' })).toBe( + getLocalGitCapabilityCache({ cwd: '/repo-b' }) + ) + expect(getLocalGitCapabilityCache({ wslDistro: 'Ubuntu' })).toBe( + getLocalGitCapabilityCache({ cwd: '\\\\wsl.localhost\\Ubuntu\\home\\repo' }) + ) + expect(getLocalGitCapabilityCache({ wslDistro: 'Ubuntu' })).not.toBe( + getLocalGitCapabilityCache({ wslDistro: 'Debian' }) + ) + expect(getLocalGitCapabilityCache()).not.toBe( + getLocalGitCapabilityCache({ wslDistro: 'Ubuntu' }) + ) + }) + + it('shares one SSH provider lifetime without leaking into a replacement provider', () => { + const provider = {} + const replacementProvider = {} + + expect(getSshGitCapabilityCache(provider)).toBe(getSshGitCapabilityCache(provider)) + expect(getSshGitCapabilityCache(provider)).not.toBe( + getSshGitCapabilityCache(replacementProvider) + ) + }) +}) diff --git a/src/main/git/git-capability-state.ts b/src/main/git/git-capability-state.ts new file mode 100644 index 000000000000..aec7a369a265 --- /dev/null +++ b/src/main/git/git-capability-state.ts @@ -0,0 +1,44 @@ +import { GitCapabilityCache } from '../../shared/git-capability-cache' +import { parseWslUncPath } from '../../shared/wsl-paths' + +type LocalGitCapabilityTarget = { + cwd?: string + wslDistro?: string +} + +const localCapabilitiesByExecutionHost = new Map() +// Why: reconnecting creates a new provider, while concurrent IPC/runtime users +// of one SSH connection must share the same remote Git capability results. +let sshCapabilitiesByProvider = new WeakMap() + +function getLocalGitExecutionHostKey(target: LocalGitCapabilityTarget): string { + const wslDistro = + target.wslDistro ?? (target.cwd ? parseWslUncPath(target.cwd)?.distro : undefined) + return wslDistro ? `wsl:${wslDistro}` : 'local' +} + +export function getLocalGitCapabilityCache( + target: LocalGitCapabilityTarget = {} +): GitCapabilityCache { + const executionHost = getLocalGitExecutionHostKey(target) + let cache = localCapabilitiesByExecutionHost.get(executionHost) + if (!cache) { + cache = new GitCapabilityCache() + localCapabilitiesByExecutionHost.set(executionHost, cache) + } + return cache +} + +export function getSshGitCapabilityCache(provider: object): GitCapabilityCache { + let cache = sshCapabilitiesByProvider.get(provider) + if (!cache) { + cache = new GitCapabilityCache() + sshCapabilitiesByProvider.set(provider, cache) + } + return cache +} + +export function clearGitCapabilityStateForTests(): void { + localCapabilitiesByExecutionHost.clear() + sshCapabilitiesByProvider = new WeakMap() +} diff --git a/src/main/git/remote.test.ts b/src/main/git/remote.test.ts index 4e7b27639f04..166db56079d0 100644 --- a/src/main/git/remote.test.ts +++ b/src/main/git/remote.test.ts @@ -270,6 +270,35 @@ describe('git remote operations', () => { await expect(gitPush('/repo', false)).rejects.toThrow('fatal: something obscure happened') }) + it('preserves redacted pre-push hook output from failed pushes', async () => { + gitExecFileAsyncMock + .mockRejectedValueOnce(new Error('no branch')) + .mockRejectedValueOnce( + new Error( + [ + 'Command failed: git push https://x-access-token:ghp_secret@github.com/acme/repo.git HEAD', + 'husky - pre-push hook failed', + 'eslint found 2 errors', + "error: failed to push some refs to 'https://ghp_tailSecret@github.com/acme/repo.git'" + ].join('\n') + ) + ) + + let caught: Error | undefined + try { + await gitPush('/repo', false) + } catch (error) { + caught = error as Error + } + + expect(caught).toBeInstanceOf(Error) + expect(caught?.message).toContain('husky - pre-push hook failed') + expect(caught?.message).toContain('eslint found 2 errors') + expect(caught?.message).not.toContain('x-access-token') + expect(caught?.message).not.toContain('ghp_secret') + expect(caught?.message).not.toContain('ghp_tailSecret') + }) + it('strips embedded credentials from push error messages', async () => { gitExecFileAsyncMock .mockRejectedValueOnce(new Error('no branch')) diff --git a/src/main/git/remove-worktree.test.ts b/src/main/git/remove-worktree.test.ts index f2f356a87348..5c3a07693662 100644 --- a/src/main/git/remove-worktree.test.ts +++ b/src/main/git/remove-worktree.test.ts @@ -32,6 +32,8 @@ vi.mock('fs/promises', async () => { return { ...actual, stat: statMock } }) +import { clearGitCapabilityStateForTests } from './git-capability-state' + import { addSparseWorktree, assertWorktreeCleanForRemoval, @@ -40,6 +42,10 @@ import { removeWorktree } from './worktree' +beforeEach(() => { + clearGitCapabilityStateForTests() +}) + type MockResult = { error?: Error stdout?: string @@ -247,7 +253,7 @@ branch refs/heads/main ]) }) - it('passes --force before the worktree path when forced removal is requested', async () => { + it('passes one --force before the worktree path for dirty-file removal', async () => { mockGitCommands({ 'git worktree list --porcelain': { stdout: `worktree /repo @@ -272,6 +278,48 @@ branch refs/heads/main expect(getGitCalls()).toContain('git worktree remove --force /repo-feature') }) + it('rejects a locked worktree with stable app-owned copy before invoking remove', async () => { + mockGitCommands({ + 'git worktree list --porcelain': { + stdout: `worktree /repo +HEAD abc123 +branch refs/heads/main + +worktree /repo-feature +HEAD def456 +branch refs/heads/feature/test +locked active agent session +` + } + }) + + await expect(removeWorktree('/repo', '/repo-feature', true)).rejects.toThrow( + 'Worktree is locked by Git. Lock reason: active agent session.' + ) + expect(getGitCalls()).not.toContain('git worktree remove /repo-feature') + }) + + it('does not treat dirty-file force as permission to override a lock', async () => { + mockGitCommands({ + 'git worktree list --porcelain': { + stdout: `worktree /repo +HEAD abc123 +branch refs/heads/main + +worktree /repo-feature +HEAD def456 +branch refs/heads/feature/test +locked active agent session +` + } + }) + + await expect(removeWorktree('/repo', '/repo-feature', true)).rejects.toThrow( + 'Worktree is locked by Git. Lock reason: active agent session.' + ) + expect(getGitCalls()).not.toContain('git worktree remove --force /repo-feature') + }) + it('matches Windows worktree paths before deleting the branch', async () => { mockGitCommands({ 'git worktree list --porcelain': { diff --git a/src/main/git/repo-search-ref-compat.test.ts b/src/main/git/repo-search-ref-compat.test.ts index 9e9659a11b23..7c29357f55d2 100644 --- a/src/main/git/repo-search-ref-compat.test.ts +++ b/src/main/git/repo-search-ref-compat.test.ts @@ -9,10 +9,12 @@ vi.mock('./runner', () => ({ gitExecFileSync: vi.fn() })) +import { clearGitCapabilityStateForTests } from './git-capability-state' import { searchBaseRefs } from './repo' describe('searchBaseRefs git compatibility', () => { afterEach(() => { + clearGitCapabilityStateForTests() gitExecFileAsyncMock.mockReset() }) @@ -35,13 +37,15 @@ describe('searchBaseRefs git compatibility', () => { } }) + await expect(searchBaseRefs('/repo', '', 1)).resolves.toEqual(['origin/main']) await expect(searchBaseRefs('/repo', '', 1)).resolves.toEqual(['origin/main']) const forEachRefCalls = gitExecFileAsyncMock.mock.calls.filter( (call) => (call[0] as string[])[0] === 'for-each-ref' ) - expect(forEachRefCalls).toHaveLength(2) + expect(forEachRefCalls).toHaveLength(3) expect(forEachRefCalls[0][0]).toContain('--exclude=refs/remotes/**/HEAD') expect(forEachRefCalls[1][0]).not.toContain('--exclude=refs/remotes/**/HEAD') expect(forEachRefCalls[1][0]).toContain('--count=104') + expect(forEachRefCalls[2][0]).not.toContain('--exclude=refs/remotes/**/HEAD') }) }) diff --git a/src/main/git/repo.ts b/src/main/git/repo.ts index 68900f810bf5..f649017cdebe 100644 --- a/src/main/git/repo.ts +++ b/src/main/git/repo.ts @@ -5,9 +5,11 @@ import { gitExecFileSync, gitExecFileAsync } from './runner' import type { BaseRefSearchResult } from '../../shared/types' import { parseGitRevListAheadBehindCounts } from '../../shared/git-rev-list-output' import { normalizeRuntimePathSeparators } from '../../shared/cross-platform-path' +import { isForEachRefExcludeUnsupportedError } from '../../shared/git-ref-command-capabilities' import { parseWslUncPath } from '../../shared/wsl-paths' import { toWindowsWslPath } from '../wsl' import { buildHostedRemoteCommitUrl, buildHostedRemoteFileUrl } from './hosted-remote-url' +import { getLocalGitCapabilityCache } from './git-capability-state' type LocalGitExecOptions = { wslDistro?: string @@ -788,27 +790,27 @@ async function runSearchBaseRefsGit( limit: number, options: { remoteNames: readonly string[]; patternGroup?: RefSearchPatternGroup } ): Promise<{ stdout: string }> { - try { - return await gitExecFileAsync( - buildSearchBaseRefsArgv(normalizedQuery, limit, { - remoteNames: options.remoteNames, - patternGroup: options.patternGroup - }), - { cwd: path } - ) - } catch (err) { - if (!isForEachRefExcludeUnsupportedError(err)) { - throw err - } - return gitExecFileAsync( - buildSearchBaseRefsArgv(normalizedQuery, limit, { - excludeRemoteHead: false, - remoteNames: options.remoteNames, - patternGroup: options.patternGroup - }), - { cwd: path } - ) - } + return getLocalGitCapabilityCache({ cwd: path }).runWithFallback( + 'for-each-ref-exclude', + () => + gitExecFileAsync( + buildSearchBaseRefsArgv(normalizedQuery, limit, { + remoteNames: options.remoteNames, + patternGroup: options.patternGroup + }), + { cwd: path } + ), + () => + gitExecFileAsync( + buildSearchBaseRefsArgv(normalizedQuery, limit, { + excludeRemoteHead: false, + remoteNames: options.remoteNames, + patternGroup: options.patternGroup + }), + { cwd: path } + ), + isForEachRefExcludeUnsupportedError + ) } export function mergeBaseRefSearchResultGroups( @@ -834,17 +836,7 @@ export function mergeBaseRefSearchResultGroups( return merged } -export function isForEachRefExcludeUnsupportedError(error: unknown): boolean { - if (!error || typeof error !== 'object') { - return false - } - const maybe = error as { message?: unknown; stderr?: unknown; stdout?: unknown } - const text = [maybe.message, maybe.stderr, maybe.stdout] - .filter((value): value is string => typeof value === 'string') - .join('\n') - .toLowerCase() - return text.includes('unknown option') && text.includes('exclude') -} +export { isForEachRefExcludeUnsupportedError } from '../../shared/git-ref-command-capabilities' /** * Resolve the default push remote for a repo. diff --git a/src/main/git/runner-wsl-gh-fallback.test.ts b/src/main/git/runner-wsl-gh-fallback.test.ts index 3aae182432ca..c77108588389 100644 --- a/src/main/git/runner-wsl-gh-fallback.test.ts +++ b/src/main/git/runner-wsl-gh-fallback.test.ts @@ -352,6 +352,29 @@ describe('ghExecFileAsync WSL fallback', () => { ) }) + it('does not wake the default WSL distro for host-only GitLab diagnostics', async () => { + getDefaultWslDistroMock.mockReturnValue('Ubuntu') + execFileMock + .mockImplementationOnce((_binary, _args, _options, callback) => { + callback(Object.assign(new Error('spawn glab ENOENT'), { code: 'ENOENT' })) + }) + .mockImplementationOnce((_binary, _args, _options, callback) => { + callback(null, { stdout: 'Logged in to gitlab.com', stderr: '' }) + }) + + await expect( + glabExecFileAsync(['auth', 'status'], { allowDefaultWslFallback: false }) + ).rejects.toThrow('spawn glab ENOENT') + + expect(execFileMock).toHaveBeenCalledTimes(1) + expect(execFileMock).toHaveBeenCalledWith( + 'glab', + ['auth', 'status'], + expect.objectContaining({ cwd: undefined }), + expect.any(Function) + ) + }) + it('still retries idempotent glab transient failures', async () => { execFileMock .mockImplementationOnce((_binary, _args, _options, callback) => { diff --git a/src/main/git/runner.test.ts b/src/main/git/runner.test.ts index 57b04831acc6..df0392c3c10e 100644 --- a/src/main/git/runner.test.ts +++ b/src/main/git/runner.test.ts @@ -9,7 +9,8 @@ import { nonInteractiveGitEnv, parseRetryAfterMs, promptGuardGitEnv, - redirectPortedHostnameToEnv + redirectPortedHostnameToEnv, + untranslatedGitOutputEnv } from './runner' // Reads git config injected via the GIT_CONFIG_COUNT/KEY/VALUE env protocol @@ -218,3 +219,25 @@ describe('nonInteractiveGitEnv credential-interactivity disable (STA-1292)', () expect(env.GIT_SSH_COMMAND).toBe('ssh -o BatchMode=yes') }) }) + +describe('git env forces untranslated diagnostics (issue #7808)', () => { + it('overrides an inherited non-English locale so stderr parsers keep working', () => { + // A gettext-enabled git under de_DE translates even the `fatal:` prefix, + // breaking isNoUpstreamError and every other stderr phrase match. + const env = promptGuardGitEnv({ PATH: '/usr/bin', LC_ALL: 'de_DE.UTF-8' }) + expect(env.LC_ALL).toBe('en_US.UTF-8') + expect(env.LANG).toBe('en_US.UTF-8') + }) + + it('pins LANGUAGE, which outranks LC_ALL in gettext lookups', () => { + const env = untranslatedGitOutputEnv({ PATH: '/usr/bin', LANGUAGE: 'de:en' }) + expect(env.LANGUAGE).toBe('en') + expect(env.LC_ALL).toBe('en_US.UTF-8') + }) + + it('applies to nonInteractiveGitEnv as well', () => { + const env = nonInteractiveGitEnv({ PATH: '/usr/bin', LANG: 'fr_FR.UTF-8' }) + expect(env.LC_ALL).toBe('en_US.UTF-8') + expect(env.LANGUAGE).toBe('en') + }) +}) diff --git a/src/main/git/runner.ts b/src/main/git/runner.ts index c90098453693..29990ad9c644 100644 --- a/src/main/git/runner.ts +++ b/src/main/git/runner.ts @@ -35,9 +35,18 @@ import { escapeWslShCommandForWindows, quotePosixShell } from '../../shared/wsl-login-shell-command' +import { UNTRANSLATED_GIT_OUTPUT_ENV } from '../../shared/git-output-locale' +import { endSubprocessStdin } from '../../shared/subprocess-stdin-write' // ─── Core resolution ──────────────────────────────────────────────── +// `LANGUAGE=en LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8` — env-assignment prefix for +// WSL-routed git, where spawn env cannot cross the wsl.exe boundary. Values are +// shell-safe unquoted (alnum, dot, dash, underscore only). +const GIT_OUTPUT_LOCALE_SHELL_PREFIX = Object.entries(UNTRANSLATED_GIT_OUTPUT_ENV) + .map(([key, value]) => `${key}=${value}`) + .join(' ') + type ResolvedCommand = { binary: string args: string[] @@ -202,6 +211,10 @@ function resolveCommand( } const translatedArgs = translateArgsForWsl(args) + // Why: env set on wsl.exe stays on the Windows side (WSLENV forwards only + // named vars), so the untranslated-output locale must ride the command + // string for git stderr parsers to work inside the distro (issue #7808). + const localePrefix = command === 'git' ? `${GIT_OUTPUT_LOCALE_SHELL_PREFIX} ` : '' const escapedCommand = quotePosixShell(command) // Why: shell-escape each argument to prevent word splitting / glob expansion // inside the bash -c string. Single quotes are safe for all chars except @@ -214,8 +227,8 @@ function resolveCommand( // doesn't need a particular cwd for global calls like `api rate_limit`. const linuxCwd = cwdWsl?.linuxPath ?? (cwd && wslDistroOverride ? translateArgForWsl(cwd) : null) const shellCmd = linuxCwd - ? `cd ${quotePosixShell(linuxCwd)} && ${escapedCommand} ${escapedArgs.join(' ')}` - : `${escapedCommand} ${escapedArgs.join(' ')}` + ? `cd ${quotePosixShell(linuxCwd)} && ${localePrefix}${escapedCommand} ${escapedArgs.join(' ')}` + : `${localePrefix}${escapedCommand} ${escapedArgs.join(' ')}` if (options.useWslLoginShell) { return { @@ -418,7 +431,7 @@ function execFileCapture( child.once('error', (error) => finish(error)) if (options.stdin !== undefined) { - child.stdin?.end(options.stdin) + endSubprocessStdin(child.stdin, options.stdin) } // Why: Node's native execFile timeout waits for the child to exit after @@ -560,10 +573,21 @@ export function appendGitConfigEnv( return next } +/** + * Pin Orca-spawned git to untranslated English output so stderr/progress + * parsers keep working under any user locale (issue #7808; see + * UNTRANSLATED_GIT_OUTPUT_ENV for the full rationale). Terminal git is + * untouched. Injected by every git runner in this module; WSL-routed spawns + * get the same values via GIT_OUTPUT_LOCALE_SHELL_PREFIX instead. + */ +export function untranslatedGitOutputEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv { + return { ...env, ...UNTRANSLATED_GIT_OUTPUT_ENV } +} + export function promptGuardGitEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv { return appendGitConfigEnv( { - ...env, + ...untranslatedGitOutputEnv(env), GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: env.GIT_ASKPASS ?? '', SSH_ASKPASS: env.SSH_ASKPASS ?? '', @@ -870,7 +894,8 @@ export async function gitExecFileAsyncBuffer( const { stdout } = (await execFileCapture(resolved.binary, resolved.args, { cwd: resolved.cwd, encoding: 'buffer', - maxBuffer: options.maxBuffer + maxBuffer: options.maxBuffer, + env: untranslatedGitOutputEnv() })) as { stdout: Buffer } return { stdout } } @@ -1051,6 +1076,7 @@ export function gitExecFileSync( return execFileSync(resolved.binary, resolved.args, { cwd: resolved.cwd, encoding: options.encoding ?? 'utf-8', + env: untranslatedGitOutputEnv(), stdio: options.stdio ?? ['pipe', 'pipe', 'pipe'], timeout: options.timeout ?? GIT_EXEC_SYNC_TIMEOUT_MS }) as string @@ -1076,6 +1102,7 @@ export function gitSpawn( const spawnStartedAt = performance.now() const child = spawn(resolved.binary, resolved.args, { ...spawnOptions, + env: untranslatedGitOutputEnv(spawnOptions.env ?? process.env), cwd: resolved.cwd }) recordSubprocessSpawn(resolved.binary, resolved.args, performance.now() - spawnStartedAt) @@ -1480,6 +1507,7 @@ type GlabExecOptions = Omit & { cwd?: string wslDistro?: string idempotent?: boolean + allowDefaultWslFallback?: boolean } /** @@ -1544,6 +1572,7 @@ export async function glabExecFileAsync( resolved.wsl === null && !options.cwd && !options.wslDistro && + options.allowDefaultWslFallback !== false && isHostCommandMissing(err, 'glab') ) { const wslResolved = resolveDefaultWslCli('glab', args) diff --git a/src/main/git/status-wsl-pathspecs.test.ts b/src/main/git/status-wsl-pathspecs.test.ts new file mode 100644 index 000000000000..e802fb72b5bb --- /dev/null +++ b/src/main/git/status-wsl-pathspecs.test.ts @@ -0,0 +1,87 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { gitExecFileAsyncMock } = vi.hoisted(() => ({ + gitExecFileAsyncMock: vi.fn() +})) + +vi.mock('./runner', () => ({ + gitExecFileAsync: gitExecFileAsyncMock, + gitExecFileAsyncBuffer: vi.fn(), + gitOptionalLocksDisabledEnv: (env: NodeJS.ProcessEnv = process.env) => env, + gitStreamStdout: vi.fn() +})) + +import { + bulkDiscardChanges, + bulkStageFiles, + bulkUnstageFiles, + discardChanges, + stageFile, + unstageFile +} from './status' + +const worktreePath = path.resolve('repo') +const windowsRelativePath = 'tests\\breakgit' +const wslOptions = { wslDistro: 'Ubuntu' } + +describe('WSL git pathspecs', () => { + beforeEach(() => { + gitExecFileAsyncMock.mockReset() + gitExecFileAsyncMock.mockResolvedValue({ stdout: 'tests/breakgit\0', stderr: '' }) + }) + + it('uses POSIX separators for tracked file mutations executed inside WSL', async () => { + await stageFile(worktreePath, windowsRelativePath, wslOptions) + await unstageFile(worktreePath, windowsRelativePath, wslOptions) + await bulkStageFiles(worktreePath, [windowsRelativePath], wslOptions) + await bulkUnstageFiles(worktreePath, [windowsRelativePath], wslOptions) + await discardChanges(worktreePath, windowsRelativePath, wslOptions) + await bulkDiscardChanges(worktreePath, [windowsRelativePath], wslOptions) + + const pathspecs = gitExecFileAsyncMock.mock.calls.flatMap(([args]) => + (args as string[]).filter((arg) => arg.startsWith(':(literal)')) + ) + expect(pathspecs).toEqual(Array(8).fill(':(literal)tests/breakgit')) + }) + + it('uses POSIX separators when discarding untracked files inside WSL', async () => { + const repo = await mkdtemp(path.join(tmpdir(), 'orca-wsl-pathspec-')) + const targetPath = path.resolve(repo, windowsRelativePath) + await mkdir(path.dirname(targetPath), { recursive: true }) + await writeFile(targetPath, 'untracked') + + try { + gitExecFileAsyncMock + .mockRejectedValueOnce(new Error('not tracked')) + .mockResolvedValue({ stdout: '', stderr: '' }) + await discardChanges(repo, windowsRelativePath, wslOptions) + + expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([ + ['ls-files', '--error-unmatch', '--', ':(literal)tests/breakgit'], + ['clean', '-ffdx', '--', ':(literal)tests/breakgit'] + ]) + + gitExecFileAsyncMock.mockReset() + gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + await bulkDiscardChanges(repo, [windowsRelativePath], wslOptions) + + expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([ + ['ls-files', '-z', '--', ':(literal)tests/breakgit'], + ['clean', '-ffdx', '--', ':(literal)tests/breakgit'] + ]) + } finally { + await rm(repo, { recursive: true, force: true }) + } + }) + + it('preserves backslashes for host Git where they can be literal filename characters', async () => { + await stageFile(worktreePath, windowsRelativePath) + + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['add', '--', ':(literal)tests\\breakgit'], { + cwd: worktreePath + }) + }) +}) diff --git a/src/main/git/status.ts b/src/main/git/status.ts index 862c8c9b76b2..6ec73ef8a3b0 100644 --- a/src/main/git/status.ts +++ b/src/main/git/status.ts @@ -1837,7 +1837,7 @@ export async function stageFile( clearGitReadInvalidationState() try { await gitExecFileAsync( - ['add', '--', literalPathspec(filePath)], + ['add', '--', literalPathspec(filePath, options)], gitOptionsForWorktree(worktreePath, options) ) } finally { @@ -1855,7 +1855,7 @@ export async function unstageFile( ): Promise { clearGitReadInvalidationState() try { - await gitExecFileAsync(['restore', '--staged', '--', literalPathspec(filePath)], { + await gitExecFileAsync(['restore', '--staged', '--', literalPathspec(filePath, options)], { ...gitOptionsForWorktree(worktreePath, options) }) } finally { @@ -1961,9 +1961,12 @@ export async function discardChanges( let tracked = false try { - await gitExecFileAsync(['ls-files', '--error-unmatch', '--', literalPathspec(filePath)], { - ...gitOptionsForWorktree(worktreePath, options) - }) + await gitExecFileAsync( + ['ls-files', '--error-unmatch', '--', literalPathspec(filePath, options)], + { + ...gitOptionsForWorktree(worktreePath, options) + } + ) tracked = true } catch { // File is not tracked by git @@ -1971,7 +1974,7 @@ export async function discardChanges( if (tracked) { await gitExecFileAsync( - ['restore', '--worktree', '--source=HEAD', '--', literalPathspec(filePath)], + ['restore', '--worktree', '--source=HEAD', '--', literalPathspec(filePath, options)], { ...gitOptionsForWorktree(worktreePath, options) } @@ -1991,9 +1994,11 @@ function normalizeGitPathForCompare(filePath: string): string { return filePath.replace(/\\/g, '/').replace(/\/+$/, '') } -function literalPathspec(filePath: string): string { - // Why: source-control selections are concrete paths, not user-authored Git globs. - return `:(literal)${filePath}` +function literalPathspec(filePath: string, options: GitRuntimeOptions): string { + // Why: Windows validation produces backslashes, but Git running inside WSL + // needs POSIX paths. Host paths stay untouched so POSIX filenames remain literal. + const runtimePath = options.wslDistro ? filePath.replace(/\\/g, '/') : filePath + return `:(literal)${runtimePath}` } function isTrackedPathSpec(filePath: string, trackedPaths: readonly string[]): boolean { @@ -2013,7 +2018,7 @@ async function listTrackedPathSpecs( for (let i = 0; i < filePaths.length; i += BULK_CHUNK_SIZE) { const chunk = filePaths.slice(i, i + BULK_CHUNK_SIZE) const { stdout } = await gitExecFileAsync( - ['ls-files', '-z', '--', ...chunk.map(literalPathspec)], + ['ls-files', '-z', '--', ...chunk.map((filePath) => literalPathspec(filePath, options))], { ...gitOptionsForWorktree(worktreePath, options) } @@ -2038,9 +2043,12 @@ async function cleanUntrackedPaths( const chunk = filePaths.slice(i, i + BULK_CHUNK_SIZE) if (chunk.length > 0) { // Why: Git pathspec cleanup avoids raw recursive deletion through symlinked parents. - await gitExecFileAsync(['clean', '-ffdx', '--', ...chunk.map(literalPathspec)], { - ...gitOptionsForWorktree(worktreePath, options) - }) + await gitExecFileAsync( + ['clean', '-ffdx', '--', ...chunk.map((filePath) => literalPathspec(filePath, options))], + { + ...gitOptionsForWorktree(worktreePath, options) + } + ) } } } @@ -2082,7 +2090,13 @@ export async function bulkDiscardChanges( for (let i = 0; i < trackedPaths.length; i += BULK_CHUNK_SIZE) { const chunk = trackedPaths.slice(i, i + BULK_CHUNK_SIZE) await gitExecFileAsync( - ['restore', '--worktree', '--source=HEAD', '--', ...chunk.map(literalPathspec)], + [ + 'restore', + '--worktree', + '--source=HEAD', + '--', + ...chunk.map((filePath) => literalPathspec(filePath, options)) + ], { ...gitOptionsForWorktree(worktreePath, options) } @@ -2125,7 +2139,7 @@ export async function bulkStageFiles( for (let i = 0; i < filePaths.length; i += BULK_CHUNK_SIZE) { const chunk = filePaths.slice(i, i + BULK_CHUNK_SIZE) await gitExecFileAsync( - ['add', '--', ...chunk.map(literalPathspec)], + ['add', '--', ...chunk.map((filePath) => literalPathspec(filePath, options))], gitOptionsForWorktree(worktreePath, options) ) } @@ -2149,9 +2163,17 @@ export async function bulkUnstageFiles( try { for (let i = 0; i < filePaths.length; i += BULK_CHUNK_SIZE) { const chunk = filePaths.slice(i, i + BULK_CHUNK_SIZE) - await gitExecFileAsync(['restore', '--staged', '--', ...chunk.map(literalPathspec)], { - ...gitOptionsForWorktree(worktreePath, options) - }) + await gitExecFileAsync( + [ + 'restore', + '--staged', + '--', + ...chunk.map((filePath) => literalPathspec(filePath, options)) + ], + { + ...gitOptionsForWorktree(worktreePath, options) + } + ) } } finally { clearGitReadInvalidationState() diff --git a/src/main/git/worktree-git-capabilities.test.ts b/src/main/git/worktree-git-capabilities.test.ts new file mode 100644 index 000000000000..c6d7cdfc6cef --- /dev/null +++ b/src/main/git/worktree-git-capabilities.test.ts @@ -0,0 +1,138 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { gitExecFileAsyncMock } = vi.hoisted(() => ({ + gitExecFileAsyncMock: vi.fn() +})) + +vi.mock('./runner', () => ({ + gitExecFileAsync: gitExecFileAsyncMock, + gitExecFileSync: vi.fn(), + translateWslOutputPaths: (output: string) => output +})) + +import { clearGitCapabilityStateForTests } from './git-capability-state' +import { listWorktrees } from './worktree' + +const WORKTREE_LIST_OUTPUT = `worktree /repo +HEAD abc123 +branch refs/heads/main +` + +describe('worktree Git capabilities', () => { + beforeEach(() => { + clearGitCapabilityStateForTests() + gitExecFileAsyncMock.mockReset() + }) + + it('does not repeat a known-unsupported -z probe on later scans', async () => { + gitExecFileAsyncMock.mockImplementation((args: string[]) => { + if (args.includes('-z')) { + return Promise.reject( + Object.assign(new Error('git usage error'), { + code: 129, + stderr: 'usage: git worktree list []\n' + }) + ) + } + return Promise.resolve({ stdout: WORKTREE_LIST_OUTPUT }) + }) + + await listWorktrees('/repo') + await listWorktrees('/repo') + + expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([ + ['worktree', 'list', '--porcelain', '-z'], + ['worktree', 'list', '--porcelain'], + ['worktree', 'list', '--porcelain'] + ]) + }) + + it('keeps native and WSL Git capability results separate', async () => { + gitExecFileAsyncMock.mockImplementation( + (args: string[], options: { cwd: string; wslDistro?: string }) => { + if (args.includes('-z') && !options.wslDistro) { + return Promise.reject( + Object.assign(new Error('git usage error'), { + code: 129, + stderr: 'usage: git worktree list []\n' + }) + ) + } + return Promise.resolve({ + stdout: `worktree ${options.cwd}\nHEAD abc123\nbranch refs/heads/main\n` + }) + } + ) + + await listWorktrees('/native-repo') + await listWorktrees('/wsl-repo', { wslDistro: 'Ubuntu' }) + + expect( + gitExecFileAsyncMock.mock.calls.map(([args, options]) => ({ + args, + wslDistro: options.wslDistro + })) + ).toEqual([ + { args: ['worktree', 'list', '--porcelain', '-z'], wslDistro: undefined }, + { args: ['worktree', 'list', '--porcelain'], wslDistro: undefined }, + { args: ['worktree', 'list', '--porcelain', '-z'], wslDistro: 'Ubuntu' } + ]) + }) + + it('does not repeat a known-unsupported rev-parse --path-format probe', async () => { + gitExecFileAsyncMock.mockImplementation((args: string[]) => { + if (args[0] === 'worktree') { + return Promise.resolve({ + stdout: 'worktree /git-store/project.git\nHEAD abc123\nbranch refs/heads/main\n' + }) + } + if (args.includes('--path-format=absolute')) { + return Promise.reject( + Object.assign(new Error('unknown option: --path-format=absolute'), { + stderr: 'error: unknown option `path-format=absolute`\n' + }) + ) + } + return Promise.resolve({ stdout: '/repo\n/git-store/project.git\n' }) + }) + + await listWorktrees('/repo') + await listWorktrees('/repo') + + const revParseCalls = gitExecFileAsyncMock.mock.calls.filter( + ([args]) => (args as string[])[0] === 'rev-parse' + ) + expect(revParseCalls.map(([args]) => args)).toEqual([ + ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'], + ['rev-parse', '--show-toplevel', '--git-common-dir'], + ['rev-parse', '--show-toplevel', '--git-common-dir'] + ]) + }) + + it('remembers old Git that echoes --path-format while exiting successfully', async () => { + gitExecFileAsyncMock.mockImplementation((args: string[]) => { + if (args[0] === 'worktree') { + return Promise.resolve({ + stdout: 'worktree /git-store/project.git\nHEAD abc123\nbranch refs/heads/main\n' + }) + } + if (args.includes('--path-format=absolute')) { + return Promise.resolve({ + stdout: '--path-format=absolute\n/repo\n/git-store/project.git\n' + }) + } + return Promise.resolve({ stdout: '/repo\n/git-store/project.git\n' }) + }) + + await listWorktrees('/repo') + await listWorktrees('/repo') + + const revParseCalls = gitExecFileAsyncMock.mock.calls.filter( + ([args]) => (args as string[])[0] === 'rev-parse' + ) + expect(revParseCalls.map(([args]) => args)).toEqual([ + ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'], + ['rev-parse', '--show-toplevel', '--git-common-dir'] + ]) + }) +}) diff --git a/src/main/git/worktree-list-paths.test.ts b/src/main/git/worktree-list-paths.test.ts index dc7927120773..df83417e7cb4 100644 --- a/src/main/git/worktree-list-paths.test.ts +++ b/src/main/git/worktree-list-paths.test.ts @@ -33,6 +33,39 @@ async function createRepoWithNewlineWorktree(): Promise<{ } } +async function createRepoWithLockedDeletedWorktree(): Promise<{ + repoPath: string + worktreePath: string +}> { + const root = await mkdtemp(path.join(tmpdir(), 'orca-worktree-locked-delete-')) + tempRoots.push(root) + const repoPath = path.join(root, 'repo') + const requestedWorktreePath = path.join(root, 'locked deleted worktree') + + execFileSync('git', ['init', '--quiet', repoPath]) + git(repoPath, ['symbolic-ref', 'HEAD', 'refs/heads/main']) + git(repoPath, ['config', 'user.email', 'test@example.com']) + git(repoPath, ['config', 'user.name', 'Test User']) + git(repoPath, ['commit', '--allow-empty', '--quiet', '-m', 'initial']) + git(repoPath, [ + 'worktree', + 'add', + '--quiet', + '-b', + 'feature/locked-delete', + requestedWorktreePath + ]) + git(repoPath, ['worktree', 'lock', '--reason', 'orca locked stale repro', requestedWorktreePath]) + + const worktreePath = await realpath(requestedWorktreePath) + await rm(worktreePath, { recursive: true, force: true }) + + return { + repoPath: await realpath(repoPath), + worktreePath + } +} + function branchExists(repoPath: string, branchName: string): boolean { try { git(repoPath, ['show-ref', '--verify', '--quiet', `refs/heads/${branchName}`]) @@ -68,4 +101,17 @@ describe('git worktree paths', () => { expect(branchExists(repoPath, 'feature/newline')).toBe(false) } ) + + it('preserves a locked worktree whose directory was deleted manually', async () => { + const { repoPath, worktreePath } = await createRepoWithLockedDeletedWorktree() + + await expect(removeWorktree(repoPath, worktreePath, true)).rejects.toThrow( + 'Worktree is locked by Git' + ) + + expect(git(repoPath, ['worktree', 'list', '--porcelain'])).toContain( + worktreePath.replaceAll('\\', '/') + ) + expect(branchExists(repoPath, 'feature/locked-delete')).toBe(true) + }) }) diff --git a/src/main/git/worktree.test.ts b/src/main/git/worktree.test.ts index 43269a065a19..858b7c2bfd61 100644 --- a/src/main/git/worktree.test.ts +++ b/src/main/git/worktree.test.ts @@ -18,6 +18,8 @@ vi.mock('./runner', () => ({ translateWslOutputPaths: translateWslOutputPathsMock })) +import { clearGitCapabilityStateForTests } from './git-capability-state' + import { addSparseWorktree, addWorktree, @@ -29,6 +31,10 @@ import { WORKTREE_ADD_TIMEOUT_MS } from './worktree' +beforeEach(() => { + clearGitCapabilityStateForTests() +}) + describe('listWorktrees in-flight sharing', () => { beforeEach(() => { gitExecFileAsyncMock.mockReset() @@ -98,6 +104,47 @@ describe('listWorktrees in-flight sharing', () => { }) describe('parseWorktreeList', () => { + it('preserves a locked marker and its reason', () => { + expect( + parseWorktreeList( + 'worktree /repo\nHEAD abc\nbranch refs/heads/main\n\nworktree /locked\nHEAD def\nbranch refs/heads/feature\nlocked active agent session\n' + )[1] + ).toMatchObject({ + path: '/locked', + locked: true, + lockReason: 'active agent session' + }) + }) + + it('decodes C-quoted lock reasons from legacy line porcelain output', () => { + const output = + 'worktree /repo\nHEAD abc\nbranch refs/heads/main\n\nworktree /locked\nHEAD def\nbranch refs/heads/feature\nlocked "first line\\nsecond line \\303\\251"\n' + + expect(parseWorktreeList(output)[1]).toMatchObject({ + locked: true, + lockReason: 'first line\nsecond line é' + }) + }) + + it('keeps NUL-delimited lock reasons raw', () => { + const output = [ + 'worktree /repo', + 'HEAD abc', + 'branch refs/heads/main', + '', + 'worktree /locked', + 'HEAD def', + 'branch refs/heads/feature', + 'locked "literal\\nquote"', + '' + ].join('\0') + + expect(parseWorktreeList(output, { nulDelimited: true })[1]).toMatchObject({ + locked: true, + lockReason: '"literal\\nquote"' + }) + }) + it('parses regular and bare worktree blocks from porcelain output', () => { const output = ` worktree /repo diff --git a/src/main/git/worktree.ts b/src/main/git/worktree.ts index eb30e13ad0a9..19b84a7b3eae 100644 --- a/src/main/git/worktree.ts +++ b/src/main/git/worktree.ts @@ -13,8 +13,16 @@ import type { LocalBaseRefUpdateSuggestion, RemoveWorktreeResult } from '../../shared/types' +import { assertWorktreeUnlockedForRemoval } from '../../shared/worktree-removal' +import { decodeGitCQuotedPath } from '../../shared/git-cquoted-path' import { parseGitRevListAheadBehindCounts } from '../../shared/git-rev-list-output' import { parseWslUncPath } from '../../shared/wsl-paths' +import { + hasUnsupportedRevParsePathFormatEcho, + isUnsupportedRevParsePathFormatError, + isUnsupportedWorktreeListZError +} from '../../shared/git-worktree-command-capabilities' +import { getLocalGitCapabilityCache } from './git-capability-state' import { gitExecFileAsync, translateWslOutputPaths } from './runner' import { resolveGitDir } from './status' import { hasWorktreeBaseCommitRef } from './worktree-base-ref-probe' @@ -46,7 +54,7 @@ export type AddWorktreeOptions = GitWorktreeExecOptions & { export type RemoveWorktreeOptions = GitWorktreeExecOptions & { deleteBranch?: boolean forceBranchDelete?: boolean - knownRemovedWorktree?: Pick + knownRemovedWorktree?: Pick } type LocalBaseRefRefreshability = @@ -109,22 +117,6 @@ function isNotGitRepositoryError(error: unknown): boolean { return /not a git repository/i.test(getErrorText(error)) } -function isUnsupportedWorktreeListZError(error: unknown): boolean { - // `-z` is this command's only flag older Git (<2.36) lacks, so its usage - // exit 129 signals the rejection in any locale; stderr match is a fallback. - if (getErrorCode(error) === '129') { - return true - } - - return /(?:unknown|invalid|unrecognized) (?:switch|option).*`?-?z'?/i.test(getErrorText(error)) -} - -function isUnsupportedRevParsePathFormatError(error: unknown): boolean { - return /(?:unknown|invalid|unrecognized).*(?:--path-format|path-format)/i.test( - getErrorText(error) - ) -} - function isBranchCheckedOutInWorktreeError(error: unknown): boolean { return /cannot delete branch .*(?:used by worktree|checked out)|branch .*is checked out/i.test( getErrorText(error) @@ -408,24 +400,34 @@ async function readRepoLocation( resolveBasePath: string, options: GitWorktreeExecOptions = {} ): Promise { + const capabilities = getLocalGitCapabilityCache({ + cwd: repoPath, + wslDistro: options.wslDistro + }) try { - const { stdout } = await gitExecFileAsync( - ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'], - gitExecOptions(repoPath, options) - ) - return parseRepoLocation(resolveBasePath, stdout) - } catch (error) { - if (!isUnsupportedRevParsePathFormatError(error)) { - return undefined - } - } - - try { - const { stdout } = await gitExecFileAsync( - ['rev-parse', '--show-toplevel', '--git-common-dir'], - gitExecOptions(repoPath, options) + return await capabilities.runWithFallback( + 'rev-parse-path-format', + async () => { + const { stdout } = await gitExecFileAsync( + ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'], + gitExecOptions(repoPath, options) + ) + if (hasUnsupportedRevParsePathFormatEcho(stdout)) { + // Why: some old Git versions echo the unknown option and exit zero; + // remember that compatibility signal even though parsing can recover. + capabilities.rememberUnsupported('rev-parse-path-format') + } + return parseRepoLocation(resolveBasePath, stdout) + }, + async () => { + const { stdout } = await gitExecFileAsync( + ['rev-parse', '--show-toplevel', '--git-common-dir'], + gitExecOptions(repoPath, options) + ) + return parseRepoLocation(resolveBasePath, stdout) + }, + isUnsupportedRevParsePathFormatError ) - return parseRepoLocation(resolveBasePath, stdout) } catch { return undefined } @@ -487,6 +489,8 @@ export function parseWorktreeList( let branch = '' let isBare = false let isSparse = false + let locked = false + let lockReason = '' for (const line of lines) { if (line.startsWith('worktree ')) { @@ -499,6 +503,10 @@ export function parseWorktreeList( isBare = true } else if (line === 'sparse') { isSparse = true + } else if (line === 'locked' || line.startsWith('locked ')) { + locked = true + const rawReason = line.slice('locked'.length).trim() + lockReason = options.nulDelimited ? rawReason : decodeGitCQuotedPath(rawReason) } } @@ -510,6 +518,8 @@ export function parseWorktreeList( branch, isBare, ...(isSparse ? { isSparse } : {}), + ...(locked ? { locked: true } : {}), + ...(lockReason ? { lockReason } : {}), isMainWorktree: worktrees.length === 0 }) } @@ -555,29 +565,34 @@ async function readWorktreeList( repoPath: string, options: GitWorktreeExecOptions = {} ): Promise { - try { - const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain', '-z'], { - cwd: repoPath, - ...options - }) - return normalizeMainWorktreePath( - repoPath, - parseWorktreeList(stdout, { nulDelimited: true }), - options - ) - } catch (error) { - if (!isUnsupportedWorktreeListZError(error)) { - throw error - } - } - - // Why: `-z` is required to preserve worktree paths containing newlines, but - // Git <2.36 rejects it. Keep the old parser as a compatibility fallback. - const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain'], { + const capabilities = getLocalGitCapabilityCache({ cwd: repoPath, - ...options + wslDistro: options.wslDistro }) - return normalizeMainWorktreePath(repoPath, parseWorktreeList(stdout), options) + return capabilities.runWithFallback( + 'worktree-list-z', + async () => { + const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain', '-z'], { + cwd: repoPath, + ...options + }) + return normalizeMainWorktreePath( + repoPath, + parseWorktreeList(stdout, { nulDelimited: true }), + options + ) + }, + async () => { + // Why: `-z` is required to preserve worktree paths containing newlines, + // but Git <2.36 rejects it. Keep the line parser as the fallback. + const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain'], { + cwd: repoPath, + ...options + }) + return normalizeMainWorktreePath(repoPath, parseWorktreeList(stdout), options) + }, + isUnsupportedWorktreeListZError + ) } async function readTranslatedWorktreeGraph( @@ -1074,6 +1089,10 @@ async function performRemoveWorktree( const branchName = normalizeLocalBranchRef(removedWorktree?.branch ?? '') const branchHead = removedWorktree?.head ?? '' + // Why: callers outside the IPC/runtime preflight must not bypass Git's lock + // contract or depend on localized stderr to discover it after side effects. + assertWorktreeUnlockedForRemoval(removedWorktree) + const args = ['worktree', 'remove'] if (force) { args.push('--force') @@ -1196,7 +1215,14 @@ async function deleteAlreadyMergedBranchAfterSafeDeleteFailure( // Why: squash merges rewrite commit IDs, so `branch -d` can reject a branch // whose changes are already on the base ref. Delete only when Git can prove // the branch contributes no tree changes to that base. - if (!(await branchHasNoUnmergedChangesOnAnyTarget(runGit, branchName, targetRefs))) { + if ( + !(await branchHasNoUnmergedChangesOnAnyTarget( + runGit, + branchName, + targetRefs, + getLocalGitCapabilityCache({ cwd: repoPath, wslDistro: options.wslDistro }) + )) + ) { return false } await forceDeleteLocalBranch(repoPath, branchName, branchHead, (args, cwd) => diff --git a/src/main/github/client.test.ts b/src/main/github/client.test.ts index 2138ba0aad05..5363cb56c60b 100644 --- a/src/main/github/client.test.ts +++ b/src/main/github/client.test.ts @@ -122,7 +122,7 @@ import { _resetMergeQueueCacheForTests, __resetTrackedUpstreamBranchCacheForTests } from './client' -import { __resetPRConflictSummaryGitCapabilityCacheForTests } from './conflict-summary' +import { __resetPRConflictSummaryCachesForTests } from './conflict-summary' import { resetMergedPRCommitMembershipCacheForTest } from './merged-pr-commit-membership' describe('checkOrcaStarred', () => { @@ -194,7 +194,7 @@ describe('getPRForBranch', () => { _resetOwnerRepoCache() _resetMergeQueueCacheForTests() __resetTrackedUpstreamBranchCacheForTests() - __resetPRConflictSummaryGitCapabilityCacheForTests() + __resetPRConflictSummaryCachesForTests() resetMergedPRCommitMembershipCacheForTest() }) @@ -2987,11 +2987,16 @@ describe('getPRForBranch', () => { baseRefOid: 'base-oid', headRefOid: 'head-oid' } + // Why a second head OID: identical inputs now hit the summary result + // cache outright; a pushed head re-derives and must still skip the + // unsupported --merge-base retry via the capability cache. + const pushedBranchLookup = { ...branchLookup, head: { ref: 'feature/test', sha: 'head-oid-2' } } + const pushedExactLookup = { ...exactLookup, headRefOid: 'head-oid-2' } ghExecFileAsyncMock .mockResolvedValueOnce({ stdout: JSON.stringify([branchLookup]) }) .mockResolvedValueOnce({ stdout: JSON.stringify(exactLookup) }) - .mockResolvedValueOnce({ stdout: JSON.stringify([branchLookup]) }) - .mockResolvedValueOnce({ stdout: JSON.stringify(exactLookup) }) + .mockResolvedValueOnce({ stdout: JSON.stringify([pushedBranchLookup]) }) + .mockResolvedValueOnce({ stdout: JSON.stringify(pushedExactLookup) }) gitExecFileAsyncMock .mockResolvedValueOnce({ stdout: '' }) .mockResolvedValueOnce({ stdout: 'latest-base-oid\n' }) @@ -2999,8 +3004,6 @@ describe('getPRForBranch', () => { .mockResolvedValueOnce({ stdout: '2\n' }) .mockRejectedValueOnce({ stderr: "error: unknown option `merge-base'" }) .mockRejectedValueOnce({ stdout: 'result-tree-oid\u0000src/conflict.ts\u0000' }) - .mockResolvedValueOnce({ stdout: '' }) - .mockResolvedValueOnce({ stdout: 'latest-base-oid\n' }) .mockResolvedValueOnce({ stdout: 'merge-base-oid\n' }) .mockResolvedValueOnce({ stdout: '2\n' }) .mockRejectedValueOnce({ stdout: 'result-tree-oid\u0000src/conflict.ts\u0000' }) @@ -3567,6 +3570,7 @@ describe('GitHub GraphQL rate-limit guard', () => { acquireMock.mockResolvedValue(undefined) _resetOwnerRepoCache() _resetMergeQueueCacheForTests() + __resetPRConflictSummaryCachesForTests() }) it('skips PR review-thread GraphQL fetch while preserving REST comments', async () => { diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 3a308a3adfba..6e4005421a47 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -848,6 +848,43 @@ async function fetchIssueWorkItem( return mapIssueWorkItem(JSON.parse(stdout) as Record) } +// REST /pulls/{n} has requested_reviewers but not latestReviews. When the JSON +// `gh pr view` path fails, still pull review fields from gh so mobile/desktop +// reviewer lists (CodeRabbit COMMENTED, etc.) are not silently empty. +const WORK_ITEM_PR_REVIEW_JSON_FIELDS = 'reviewRequests,latestReviews' + +async function fetchPullRequestReviewFields( + number: number, + ownerRepo: OwnerRepo | null, + ghOptions: GhExecOptions +): Promise> { + try { + const args = ownerRepo + ? [ + 'pr', + 'view', + String(number), + '--repo', + `${ownerRepo.owner}/${ownerRepo.repo}`, + '--json', + WORK_ITEM_PR_REVIEW_JSON_FIELDS + ] + : ['pr', 'view', String(number), '--json', WORK_ITEM_PR_REVIEW_JSON_FIELDS] + const { stdout } = await ghExecFileAsync(args, ghOptions) + const item = JSON.parse(stdout) as Record + return { + ...(item.reviewRequests !== undefined + ? { reviewRequests: usersFromUnknown(item.reviewRequests) } + : {}), + ...(item.latestReviews !== undefined + ? { latestReviews: latestReviewsFromUnknown(item.latestReviews) } + : {}) + } + } catch { + return {} + } +} + async function fetchPullRequestWorkItem( repoPath: string, ownerRepo: OwnerRepo | null, @@ -872,24 +909,36 @@ async function fetchPullRequestWorkItem( ) const item = JSON.parse(stdout) as Record const mapped = mapPullRequestWorkItem(item, ownerRepo) + // Why: merge-metadata GraphQL is best-effort. A failure here must not fall + // through to the REST path below — that path drops latestReviews and blanks + // the mobile/desktop reviewer list for bots that only left a review. const baseRefName = typeof item.baseRefName === 'string' ? item.baseRefName : undefined - const mergeMetadata = await detectRepositoryMergeMetadata(ownerRepo, baseRefName, ghOptions) - return { - ...mapped, - mergeQueueRequired: mergeMetadata.mergeQueueRequired, - ...(mergeMetadata.autoMergeAllowed !== null - ? { autoMergeAllowed: mergeMetadata.autoMergeAllowed } - : {}), - ...(mergeMetadata.mergeMethodSettings - ? { mergeMethodSettings: mergeMetadata.mergeMethodSettings } - : {}) + try { + const mergeMetadata = await detectRepositoryMergeMetadata(ownerRepo, baseRefName, ghOptions) + return { + ...mapped, + mergeQueueRequired: mergeMetadata.mergeQueueRequired, + ...(mergeMetadata.autoMergeAllowed !== null + ? { autoMergeAllowed: mergeMetadata.autoMergeAllowed } + : {}), + ...(mergeMetadata.mergeMethodSettings + ? { mergeMethodSettings: mergeMetadata.mergeMethodSettings } + : {}) + } + } catch { + return mapped } } catch { const { stdout } = await ghExecFileAsync( ['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${number}`], ghOptions ) - return mapPullRequestWorkItem(JSON.parse(stdout) as Record, ownerRepo) + const mapped = mapPullRequestWorkItem( + JSON.parse(stdout) as Record, + ownerRepo + ) + const reviewFields = await fetchPullRequestReviewFields(number, ownerRepo, ghOptions) + return { ...mapped, ...reviewFields } } } diff --git a/src/main/github/conflict-summary-cache.ts b/src/main/github/conflict-summary-cache.ts new file mode 100644 index 000000000000..99a2715ce6dc --- /dev/null +++ b/src/main/github/conflict-summary-cache.ts @@ -0,0 +1,150 @@ +import type { PRConflictSummary } from '../../shared/types' + +// Why 60s: the hottest coordinator cadences that re-derive a CONFLICTING PR +// (10s mergeability-pending, 2.5s manual-pending) previously each ran a +// network fetch; one fetch per base branch per minute matches the 60s minimum +// background refresh cadence, so the tracked base tip is never staler than the +// PR data around it. Manual refresh intentionally shares the window: GitHub's +// own mergeability recompute is async too, and the card self-corrects within +// a minute. +export const CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS = 60_000 + +// Why bounded: the main process is long-lived; cap the maps so repos and PRs +// that stop refreshing can't accumulate entries forever. +const BASE_OID_CACHE_MAX = 64 +const SUMMARY_CACHE_MAX = 128 + +export type FreshBaseTipResolution = + | { kind: 'resolved'; oid: string } + | { kind: 'fallback-unresolved' } + +type CachedBaseTipResolution = { + oid: string | null + resolvedAt: number +} + +type CachedSummary = { + value: PRConflictSummary | undefined + // Why: a successful summary is a pure function of two immutable commit OIDs + // and never goes stale; a failed derivation depends on which objects exist + // locally, which the next fetch window can change, so it carries an expiry. + staleAt: number | null +} + +const baseOidCache = new Map() +const summaryCache = new Map() +const inFlightBaseOidResolves = new Map>() +const inFlightSummaryDerivations = new Map>() + +// Why: WSL distros have their own git binary, filesystem view, and remote +// access, so cached state must never leak across the host/distro boundary. +export function getConflictSummaryGitRuntimeKey(wslDistro: string | undefined): string { + return wslDistro ? `wsl:${wslDistro}` : 'local:host' +} + +// Why JSON: repo paths and git ref names may contain any printable joiner +// character (git allows `|` in branch names), so a delimiter-joined key could +// alias distinct identities onto one cache entry. +export function buildConflictSummaryCacheKey(...parts: string[]): string { + return JSON.stringify(parts) +} + +export function readFreshBaseTipResolution(baseKey: string): FreshBaseTipResolution | null { + const entry = baseOidCache.get(baseKey) + if (!entry) { + return null + } + if (Date.now() - entry.resolvedAt >= CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS) { + baseOidCache.delete(baseKey) + return null + } + return entry.oid ? { kind: 'resolved', oid: entry.oid } : { kind: 'fallback-unresolved' } +} + +export function storeResolvedBaseTip(baseKey: string, oid: string): void { + setBoundedMapEntry(baseOidCache, baseKey, { oid, resolvedAt: Date.now() }, BASE_OID_CACHE_MAX) +} + +export function rememberUnresolvedBaseTip(baseKey: string): void { + setBoundedMapEntry( + baseOidCache, + baseKey, + { oid: null, resolvedAt: Date.now() }, + BASE_OID_CACHE_MAX + ) +} + +export function readCachedSummary(summaryKey: string): CachedSummary | null { + const entry = summaryCache.get(summaryKey) + if (!entry) { + return null + } + if (entry.staleAt !== null && Date.now() >= entry.staleAt) { + summaryCache.delete(summaryKey) + return null + } + return entry +} + +export function storeCachedSummary(summaryKey: string, value: PRConflictSummary | undefined): void { + setBoundedMapEntry( + summaryCache, + summaryKey, + { + value, + staleAt: value === undefined ? Date.now() + CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS : null + }, + SUMMARY_CACHE_MAX + ) +} + +export function dedupeBaseOidResolve( + key: string, + factory: () => Promise +): Promise { + return dedupeInFlight(inFlightBaseOidResolves, key, factory) +} + +export function dedupeSummaryDerivation( + key: string, + factory: () => Promise +): Promise { + return dedupeInFlight(inFlightSummaryDerivations, key, factory) +} + +function dedupeInFlight( + map: Map>, + key: string, + factory: () => Promise +): Promise { + const existing = map.get(key) + if (existing) { + return existing + } + const promise = factory().finally(() => { + map.delete(key) + }) + map.set(key, promise) + return promise +} + +function setBoundedMapEntry(map: Map, key: K, value: V, maxEntries: number): void { + if (map.has(key)) { + map.delete(key) + } + map.set(key, value) + while (map.size > maxEntries) { + const oldest = map.keys().next() + if (oldest.done) { + return + } + map.delete(oldest.value) + } +} + +export function __resetPRConflictSummaryDerivationCachesForTests(): void { + baseOidCache.clear() + summaryCache.clear() + inFlightBaseOidResolves.clear() + inFlightSummaryDerivations.clear() +} diff --git a/src/main/github/conflict-summary.test.ts b/src/main/github/conflict-summary.test.ts new file mode 100644 index 000000000000..506b1c9f9ea3 --- /dev/null +++ b/src/main/github/conflict-summary.test.ts @@ -0,0 +1,348 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +// Why these tests exist: the conflict-summary derivation used to re-run a +// network `git fetch` plus a four-subprocess chain on every PR refresh tick +// (measured ~490 full derivations in 2.1h on one machine). They pin the +// regression contract by counting subprocess spawns: unchanged inputs must +// cost zero subprocesses, and the base fetch must run at most once per +// throttle window. + +const gitExecFileAsyncMock = vi.hoisted(() => vi.fn()) + +vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) + +import { CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS } from './conflict-summary-cache' +import { __resetPRConflictSummaryCachesForTests, getPRConflictSummary } from './conflict-summary' + +type GitResult = { stdout: string } +type GitHandler = (argv: string[]) => Promise + +const defaultHandlers: Record = { + fetch: async () => ({ stdout: '' }), + 'rev-parse': async () => ({ stdout: 'base-tip-1\n' }), + 'merge-base': async () => ({ stdout: 'merge-base-1\n' }), + 'rev-list': async () => ({ stdout: '3\n' }), + 'merge-tree': async () => ({ stdout: 'tree-oid\u0000src/conflict.ts\u0000' }) +} + +function mockGitDispatch(overrides: Record = {}): void { + gitExecFileAsyncMock.mockImplementation((argv: string[]) => { + const handler = overrides[argv[0]] ?? defaultHandlers[argv[0]] + if (!handler) { + return Promise.reject(new Error(`unexpected git command: ${argv.join(' ')}`)) + } + return handler(argv) + }) +} + +function spawnCount(command?: string): number { + const calls = gitExecFileAsyncMock.mock.calls + if (!command) { + return calls.length + } + return calls.filter(([argv]) => Array.isArray(argv) && argv[0] === command).length +} + +const expectedSummary = { + baseRef: 'main', + baseCommit: 'base-ti', + commitsBehind: 3, + files: ['src/conflict.ts'] +} + +function deriveSummary(headRefOid = 'head-oid-1', wslDistro?: string) { + return getPRConflictSummary( + '/repo-root', + 'main', + 'github-base-oid', + headRefOid, + wslDistro ? { wslDistro } : {} + ) +} + +describe('getPRConflictSummary caching', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(1_750_000_000_000) + gitExecFileAsyncMock.mockReset() + __resetPRConflictSummaryCachesForTests() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('runs exactly one fetch and one derivation chain, then zero subprocesses on repeat calls', async () => { + mockGitDispatch() + + const first = await deriveSummary() + expect(first).toEqual(expectedSummary) + expect(spawnCount('fetch')).toBe(1) + expect(spawnCount()).toBe(5) + + const second = await deriveSummary() + const third = await deriveSummary() + expect(second).toEqual(expectedSummary) + expect(third).toEqual(expectedSummary) + expect(spawnCount()).toBe(5) + }) + + it('re-derives when headRefOid changes without re-fetching inside the throttle window', async () => { + mockGitDispatch() + + await deriveSummary('head-oid-1') + const afterPush = await deriveSummary('head-oid-2') + + expect(afterPush).toEqual(expectedSummary) + expect(spawnCount('fetch')).toBe(1) + expect(spawnCount('rev-parse')).toBe(1) + expect(spawnCount('merge-base')).toBe(2) + expect(spawnCount('rev-list')).toBe(2) + expect(spawnCount('merge-tree')).toBe(2) + }) + + it('fetches again after the throttle window and skips derivation when the base tip is unchanged', async () => { + mockGitDispatch() + + await deriveSummary() + vi.setSystemTime(1_750_000_000_000 + CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS + 1_000) + const afterExpiry = await deriveSummary() + + expect(afterExpiry).toEqual(expectedSummary) + expect(spawnCount('fetch')).toBe(2) + expect(spawnCount('rev-parse')).toBe(2) + // Why: same (headRefOid, latestBaseOid) pair — the summary cache still hits. + expect(spawnCount('merge-base')).toBe(1) + expect(spawnCount('rev-list')).toBe(1) + expect(spawnCount('merge-tree')).toBe(1) + }) + + it('re-derives after the throttle window when the base tip moved', async () => { + mockGitDispatch() + await deriveSummary() + + vi.setSystemTime(1_750_000_000_000 + CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS + 1_000) + mockGitDispatch({ + 'rev-parse': async () => ({ stdout: 'base-tip-2\n' }), + 'rev-list': async () => ({ stdout: '5\n' }) + }) + const afterBaseMove = await deriveSummary() + + expect(afterBaseMove).toEqual({ ...expectedSummary, baseCommit: 'base-ti', commitsBehind: 5 }) + expect(spawnCount('fetch')).toBe(2) + expect(spawnCount('merge-base')).toBe(2) + expect(spawnCount('rev-list')).toBe(2) + expect(spawnCount('merge-tree')).toBe(2) + }) + + it('dedupes concurrent identical calls onto one in-flight subprocess chain', async () => { + let releaseFetch: ((value: GitResult) => void) | undefined + mockGitDispatch({ + fetch: () => + new Promise((resolve) => { + releaseFetch = resolve + }) + }) + + const firstCall = deriveSummary() + const secondCall = deriveSummary() + releaseFetch?.({ stdout: '' }) + const [first, second] = await Promise.all([firstCall, secondCall]) + + expect(first).toEqual(expectedSummary) + expect(second).toEqual(expectedSummary) + expect(spawnCount()).toBe(5) + }) + + it('dedupes overlapping derivations after resolving the same live base tip', async () => { + let releaseFetch: ((value: GitResult) => void) | undefined + mockGitDispatch({ + fetch: () => + new Promise((resolve) => { + releaseFetch = resolve + }) + }) + + const backgroundRefresh = getPRConflictSummary( + '/repo-root', + 'main', + 'older-github-base-oid', + 'head-oid-1', + {} + ) + const manualRefresh = getPRConflictSummary( + '/repo-root', + 'main', + 'newer-github-base-oid', + 'head-oid-1', + {} + ) + releaseFetch?.({ stdout: '' }) + const [backgroundSummary, manualSummary] = await Promise.all([backgroundRefresh, manualRefresh]) + + expect(backgroundSummary).toEqual(expectedSummary) + expect(manualSummary).toEqual(expectedSummary) + expect(spawnCount('fetch')).toBe(1) + expect(spawnCount('rev-parse')).toBe(1) + expect(spawnCount('merge-base')).toBe(1) + expect(spawnCount('rev-list')).toBe(1) + expect(spawnCount('merge-tree')).toBe(1) + }) + + it('shares one base fetch across concurrent PRs on the same base branch', async () => { + let releaseFetch: ((value: GitResult) => void) | undefined + mockGitDispatch({ + fetch: () => + new Promise((resolve) => { + releaseFetch = resolve + }) + }) + + const prA = deriveSummary('head-oid-a') + const prB = deriveSummary('head-oid-b') + releaseFetch?.({ stdout: '' }) + const [summaryA, summaryB] = await Promise.all([prA, prB]) + + expect(summaryA).toEqual(expectedSummary) + expect(summaryB).toEqual(expectedSummary) + expect(spawnCount('fetch')).toBe(1) + expect(spawnCount('rev-parse')).toBe(1) + expect(spawnCount('merge-base')).toBe(2) + }) + + it('keeps concurrent fallback base OIDs isolated per PR when the base ref is unavailable', async () => { + let releaseFetch: ((value: GitResult) => void) | undefined + mockGitDispatch({ + fetch: () => + new Promise((resolve) => { + releaseFetch = resolve + }), + 'rev-parse': () => Promise.reject(new Error('missing remote-tracking ref')), + 'rev-list': async (argv) => ({ + stdout: argv[2]?.includes('bbbb2222-base') ? '7\n' : '4\n' + }), + 'merge-tree': async (argv) => ({ + stdout: argv.includes('bbbb2222-base') + ? 'tree-oid\u0000src/b.ts\u0000' + : 'tree-oid\u0000src/a.ts\u0000' + }) + }) + + const prA = getPRConflictSummary('/repo-root', 'main', 'aaaa1111-base', 'head-oid-a', {}) + const prB = getPRConflictSummary('/repo-root', 'main', 'bbbb2222-base', 'head-oid-b', {}) + releaseFetch?.({ stdout: '' }) + const [summaryA, summaryB] = await Promise.all([prA, prB]) + + expect(summaryA).toEqual({ + baseRef: 'main', + baseCommit: 'aaaa111', + commitsBehind: 4, + files: ['src/a.ts'] + }) + expect(summaryB).toEqual({ + baseRef: 'main', + baseCommit: 'bbbb222', + commitsBehind: 7, + files: ['src/b.ts'] + }) + expect(spawnCount('fetch')).toBe(1) + expect(spawnCount('merge-base')).toBe(2) + }) + + it('falls back to the local remote-tracking ref when fetch fails', async () => { + mockGitDispatch({ + fetch: () => Promise.reject(new Error('offline')) + }) + + const summary = await deriveSummary() + + expect(summary).toEqual(expectedSummary) + expect(spawnCount('fetch')).toBe(1) + + // Why: a failed fetch attempt must also be throttled — offline machines + // were the worst case, paying the 10s fetch timeout on every tick. + const repeat = await deriveSummary() + expect(repeat).toEqual(expectedSummary) + expect(spawnCount('fetch')).toBe(1) + expect(spawnCount()).toBe(5) + }) + + it("falls back to GitHub's baseRefOid when fetch and remote-tracking refs are unavailable", async () => { + mockGitDispatch({ + fetch: () => Promise.reject(new Error('offline')), + 'rev-parse': () => Promise.reject(new Error('unknown revision')) + }) + + const summary = await deriveSummary() + + expect(summary).toEqual({ ...expectedSummary, baseCommit: 'github-' }) + expect( + gitExecFileAsyncMock.mock.calls.some( + ([argv]) => argv[0] === 'merge-base' && argv.includes('github-base-oid') + ) + ).toBe(true) + }) + + it('keeps WSL-distro derivations isolated from host derivations', async () => { + mockGitDispatch() + + await deriveSummary() + await deriveSummary('head-oid-1', 'Ubuntu') + + expect(spawnCount('fetch')).toBe(2) + expect( + gitExecFileAsyncMock.mock.calls.filter( + ([argv, options]) => + argv[0] === 'fetch' && (options as { wslDistro?: string })?.wslDistro === 'Ubuntu' + ) + ).toHaveLength(1) + }) + + it('keeps identities distinct when paths or ref names contain a joiner character', async () => { + mockGitDispatch() + + // Why: these two calls alias under naive pipe-joined keys — the segment + // boundary shifts between repoPath and baseRefName. + await getPRConflictSummary('/repo|x', 'main', 'github-base-oid', 'head-oid-1', {}) + await getPRConflictSummary('/repo', 'x|main', 'github-base-oid', 'head-oid-1', {}) + + expect(spawnCount('fetch')).toBe(2) + expect(spawnCount('merge-base')).toBe(2) + }) + + it('caches failed derivations only until the throttle window expires', async () => { + mockGitDispatch({ + 'merge-base': () => Promise.reject(new Error('bad object')) + }) + + await expect(deriveSummary()).resolves.toBeUndefined() + const failureSpawns = spawnCount() + + // Within the window the failure is negative-cached: zero subprocesses. + await expect(deriveSummary()).resolves.toBeUndefined() + expect(spawnCount()).toBe(failureSpawns) + + // After expiry the derivation retries (a fetch may have brought objects in). + vi.setSystemTime(1_750_000_000_000 + CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS + 1_000) + mockGitDispatch() + await expect(deriveSummary()).resolves.toEqual(expectedSummary) + expect(spawnCount('merge-base')).toBe(2) + }) + + it('does not repeat merge-tree --write-tree after an old-Git rejection', async () => { + mockGitDispatch({ + 'merge-tree': () => + Promise.reject( + Object.assign(new Error('unknown option'), { + stdout: 'usage: git merge-tree ' + }) + ) + }) + + await expect(deriveSummary('head-oid-1')).resolves.toBeUndefined() + await expect(deriveSummary('head-oid-2')).resolves.toBeUndefined() + + expect(spawnCount('merge-base')).toBe(2) + expect(spawnCount('merge-tree')).toBe(1) + }) +}) diff --git a/src/main/github/conflict-summary.ts b/src/main/github/conflict-summary.ts index ce0c4b361b78..73ec657977cf 100644 --- a/src/main/github/conflict-summary.ts +++ b/src/main/github/conflict-summary.ts @@ -1,14 +1,33 @@ import type { PRConflictSummary } from '../../shared/types' +import { + isUnsupportedMergeTreeMergeBaseError, + isUnsupportedMergeTreeWriteTreeError +} from '../../shared/git-merge-tree-capability' import { gitExecFileAsync } from '../git/runner' +import { + clearGitCapabilityStateForTests, + getLocalGitCapabilityCache +} from '../git/git-capability-state' +import { + __resetPRConflictSummaryDerivationCachesForTests, + buildConflictSummaryCacheKey, + dedupeBaseOidResolve, + dedupeSummaryDerivation, + getConflictSummaryGitRuntimeKey, + readCachedSummary, + readFreshBaseTipResolution, + rememberUnresolvedBaseTip, + storeResolvedBaseTip, + storeCachedSummary +} from './conflict-summary-cache' type LocalGitExecOptions = { wslDistro?: string } -const mergeTreeMergeBaseUnsupportedRuntimes = new Set() - -export function __resetPRConflictSummaryGitCapabilityCacheForTests(): void { - mergeTreeMergeBaseUnsupportedRuntimes.clear() +export function __resetPRConflictSummaryCachesForTests(): void { + clearGitCapabilityStateForTests() + __resetPRConflictSummaryDerivationCachesForTests() } export async function getPRConflictSummary( @@ -18,45 +37,122 @@ export async function getPRConflictSummary( headRefOid: string, localGitOptions: LocalGitExecOptions = {} ): Promise { - try { - // Why: the renderer only needs a read-only merge-conflict snapshot. We - // derive it from local git state so the PR card can show GitHub-style - // detail without spending additional gh API calls on every refresh. We use - // GitHub's head OID directly because the registered repo path may not have - // a matching local branch name for the PR head. For the base side, prefer a - // freshly-fetched remote-tracking ref so Orca matches GitHub's portal, - // which compares against the latest base branch tip rather than the PR's - // older pinned baseRefOid snapshot. - const latestBaseOid = await resolveLatestBaseOid( + // Why: the renderer only needs a read-only merge-conflict snapshot. We + // derive it from local git state so the PR card can show GitHub-style + // detail without spending additional gh API calls on every refresh. We use + // GitHub's head OID directly because the registered repo path may not have + // a matching local branch name for the PR head. For the base side, prefer a + // freshly-fetched remote-tracking ref so Orca matches GitHub's portal, + // which compares against the latest base branch tip rather than the PR's + // older pinned baseRefOid snapshot. + const latestBaseOid = await resolveLatestBaseOidThrottled( + repoPath, + baseRefName, + baseRefOid, + localGitOptions + ) + // Why: the summary is a pure function of the two commit OIDs, so a key hit + // can skip the whole merge-base/rev-list/merge-tree subprocess chain. + const runtimeKey = getConflictSummaryGitRuntimeKey(localGitOptions.wslDistro) + const summaryKey = buildConflictSummaryCacheKey( + runtimeKey, + repoPath, + baseRefName, + headRefOid, + latestBaseOid + ) + const cached = readCachedSummary(summaryKey) + if (cached) { + return cached.value + } + + // Why: different GitHub reads can report different pinned baseRefOid values + // while still resolving to the same live base tip; dedupe the expensive + // local derivation on the actual summary identity. + return dedupeSummaryDerivation(summaryKey, () => + derivePRConflictSummary( repoPath, baseRefName, - baseRefOid, + headRefOid, + latestBaseOid, + summaryKey, localGitOptions ) + ) +} + +async function derivePRConflictSummary( + repoPath: string, + baseRefName: string, + headRefOid: string, + latestBaseOid: string, + summaryKey: string, + localGitOptions: LocalGitExecOptions +): Promise { + const cached = readCachedSummary(summaryKey) + if (cached) { + return cached.value + } + + try { const mergeBase = await resolveMergeBase(repoPath, headRefOid, latestBaseOid, localGitOptions) const [commitsBehind, files] = await Promise.all([ countCommits(repoPath, `${headRefOid}..${latestBaseOid}`, localGitOptions), loadConflictingFiles(repoPath, mergeBase, headRefOid, latestBaseOid, localGitOptions) ]) - return { + const summary = { baseRef: baseRefName, baseCommit: latestBaseOid.slice(0, 7), commitsBehind, files, ...(files.length === 0 ? { localMergeState: 'clean' as const } : {}) } + storeCachedSummary(summaryKey, summary) + return summary } catch { + storeCachedSummary(summaryKey, undefined) return undefined } } -async function resolveLatestBaseOid( +async function resolveLatestBaseOidThrottled( repoPath: string, baseRefName: string, fallbackBaseOid: string, localGitOptions: LocalGitExecOptions ): Promise { + const runtimeKey = getConflictSummaryGitRuntimeKey(localGitOptions.wslDistro) + const baseKey = buildConflictSummaryCacheKey(runtimeKey, repoPath, baseRefName) + const cachedResolution = readFreshBaseTipResolution(baseKey) + if (cachedResolution) { + return cachedResolution.kind === 'resolved' ? cachedResolution.oid : fallbackBaseOid + } + return dedupeBaseOidResolve(baseKey, async () => { + // Why re-check inside the dedupe slot: a sibling caller may have finished + // resolving between our cache read and this factory starting. + const freshResolution = readFreshBaseTipResolution(baseKey) + if (freshResolution) { + return freshResolution + } + const oid = await resolveLatestBaseOid(repoPath, baseRefName, localGitOptions) + if (oid) { + storeResolvedBaseTip(baseKey, oid) + return { kind: 'resolved', oid } + } + // Why cache the unresolved probe, not the caller fallback: the fetch + // attempt is branch-wide expensive work, but GitHub's baseRefOid is + // PR-specific and must not leak to sibling PRs on the same base branch. + rememberUnresolvedBaseTip(baseKey) + return { kind: 'fallback-unresolved' } + }).then((resolution) => (resolution.kind === 'resolved' ? resolution.oid : fallbackBaseOid)) +} + +async function resolveLatestBaseOid( + repoPath: string, + baseRefName: string, + localGitOptions: LocalGitExecOptions +): Promise { const remoteName = 'origin' try { @@ -88,7 +184,7 @@ async function resolveLatestBaseOid( } } - return fallbackBaseOid + return null } async function resolveMergeBase( @@ -123,7 +219,10 @@ async function loadConflictingFiles( baseOid: string, localGitOptions: LocalGitExecOptions ): Promise { - const capabilityKey = getMergeTreeCapabilityKey(localGitOptions) + const capabilities = getLocalGitCapabilityCache({ + cwd: repoPath, + wslDistro: localGitOptions.wslDistro + }) const modernArgs = [ 'merge-tree', '--write-tree', @@ -145,32 +244,41 @@ async function loadConflictingFiles( baseOid ] - if (mergeTreeMergeBaseUnsupportedRuntimes.has(capabilityKey)) { - return loadConflictingFilesWithLegacyMergeTree(repoPath, legacyArgs, localGitOptions) - } - - try { - const result = await gitExecFileAsync(modernArgs, { - cwd: repoPath, - ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}) - }) - return parseMergeTreeNameOnlyOutput(result.stdout) - } catch (error) { - // Why: `git merge-tree --write-tree` exits with status 1 when it finds - // conflicts, but still writes the conflicted file list to stdout. Treat - // that stdout as the useful result instead of dropping the summary. - const stdoutFromError = getGitErrorOutput(error, 'stdout') - if (stdoutFromError) { - return parseMergeTreeNameOnlyOutput(stdoutFromError) - } - - if (!isUnsupportedMergeBaseOption(error)) { - throw error - } - - mergeTreeMergeBaseUnsupportedRuntimes.add(capabilityKey) - return loadConflictingFilesWithLegacyMergeTree(repoPath, legacyArgs, localGitOptions) - } + return capabilities.runWithFallback( + 'merge-tree-write-tree', + () => + capabilities.runWithFallback( + 'merge-tree-merge-base', + async () => { + try { + const result = await gitExecFileAsync(modernArgs, { + cwd: repoPath, + ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}) + }) + return parseMergeTreeNameOnlyOutput(result.stdout) + } catch (error) { + if (isUnsupportedMergeTreeWriteTreeError(error)) { + throw error + } + // Why: `git merge-tree --write-tree` exits 1 for conflicts but still + // writes the useful file list; only option rejection reaches fallback. + const stdoutFromError = getGitErrorOutput(error, 'stdout') + if (stdoutFromError) { + return parseMergeTreeNameOnlyOutput(stdoutFromError) + } + throw error + } + }, + () => loadConflictingFilesWithLegacyMergeTree(repoPath, legacyArgs, localGitOptions), + isUnsupportedMergeTreeMergeBaseError + ), + async () => { + // Why: Git before 2.38 cannot derive a reliable real-merge conflict list; + // fail closed without respawning the same rejected command every refresh. + throw new Error('Git merge-tree --write-tree is unavailable on this execution host.') + }, + isUnsupportedMergeTreeWriteTreeError + ) } async function loadConflictingFilesWithLegacyMergeTree( @@ -193,10 +301,6 @@ async function loadConflictingFilesWithLegacyMergeTree( } } -function getMergeTreeCapabilityKey(localGitOptions: LocalGitExecOptions): string { - return localGitOptions.wslDistro ? `wsl:${localGitOptions.wslDistro}` : 'local:host' -} - function parseMergeTreeNameOnlyOutput(stdout: string): string[] { const entries = stdout.split('\0').filter(Boolean) if (entries.length === 0) { @@ -214,12 +318,3 @@ function getGitErrorOutput(error: unknown, key: 'stdout' | 'stderr'): string { const output = (error as Partial>)[key] return typeof output === 'string' ? output : '' } - -function isUnsupportedMergeBaseOption(error: unknown): boolean { - const output = `${getGitErrorOutput(error, 'stderr')}\n${ - error instanceof Error ? error.message : '' - }` - return /(?:unknown|unrecognized) option(?::|\s+)[`']?(?:--?)?merge-base[`']?(?:\s|$)/i.test( - output - ) -} diff --git a/src/main/github/pr-refresh-coordinator.test.ts b/src/main/github/pr-refresh-coordinator.test.ts index 76bd24603077..3e53d0116d1c 100644 --- a/src/main/github/pr-refresh-coordinator.test.ts +++ b/src/main/github/pr-refresh-coordinator.test.ts @@ -3,14 +3,19 @@ request timestamps, and follow-up scheduling against shared module state. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { GitHubPRRefreshCandidate, PRInfo } from '../../shared/types' -const { sendMock, getAllWebContentsMock, getPRForBranchOutcomeMock, getRateLimitMock } = vi.hoisted( - () => ({ - sendMock: vi.fn(), - getAllWebContentsMock: vi.fn(), - getPRForBranchOutcomeMock: vi.fn(), - getRateLimitMock: vi.fn() - }) -) +const { + sendMock, + getAllWebContentsMock, + getPRForBranchOutcomeMock, + getRateLimitMock, + rateLimitGuardMock +} = vi.hoisted(() => ({ + sendMock: vi.fn(), + getAllWebContentsMock: vi.fn(), + getPRForBranchOutcomeMock: vi.fn(), + getRateLimitMock: vi.fn(), + rateLimitGuardMock: vi.fn() +})) vi.mock('electron', () => ({ webContents: { @@ -25,7 +30,7 @@ vi.mock('./client', () => ({ vi.mock('./rate-limit', () => ({ getRateLimit: getRateLimitMock, noteRateLimitSpend: vi.fn(), - rateLimitGuard: vi.fn(() => ({ blocked: false })) + rateLimitGuard: rateLimitGuardMock })) function makeCandidate( @@ -80,6 +85,8 @@ describe('pr-refresh-coordinator', () => { getAllWebContentsMock.mockReset() getPRForBranchOutcomeMock.mockReset() getRateLimitMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) getAllWebContentsMock.mockReturnValue([ { id: 1, @@ -505,13 +512,45 @@ describe('pr-refresh-coordinator', () => { expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(5) }) + it('proceeds with background refreshes when the budget probe fails (fail open)', async () => { + const { enqueuePRRefresh } = await import('./pr-refresh-coordinator') + // Why: regression for #7553 — GHES with rate limiting disabled 404s every + // probe; an unreadable budget must not pause refreshes. + getRateLimitMock.mockResolvedValue({ + ok: false, + error: 'HTTP 404: Rate limiting is not enabled.' + }) + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'no-pr', + fetchedAt: Date.now() + }) + + enqueuePRRefresh(makeCandidate(), 'active', 80, 1) + + await vi.advanceTimersByTimeAsync(0) + + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + const pausedEvents = sendMock.mock.calls + .map(([, event]) => event) + .filter((event) => event.status === 'paused' && event.skippedReason === 'rate-limit') + expect(pausedEvents).toHaveLength(0) + }) + it('does not consume active burst slots for rate-limit pauses', async () => { const { enqueuePRRefresh } = await import('./pr-refresh-coordinator') - getRateLimitMock - .mockResolvedValueOnce({ ok: false }) - .mockResolvedValueOnce({ ok: false }) - .mockResolvedValueOnce({ ok: false }) - .mockResolvedValue({ ok: true }) + // Why: keyed on drained items (one getRateLimit call each) rather than + // guard-call counts, so the guard's per-bucket evaluation order stays free + // to change without breaking the slot-accounting assertion. + let drainedItems = 0 + getRateLimitMock.mockImplementation(async () => { + drainedItems += 1 + return { ok: true } + }) + rateLimitGuardMock.mockImplementation(() => + drainedItems <= 3 + ? { blocked: true, remaining: 0, limit: 5000, resetAt: 61 } + : { blocked: false } + ) getPRForBranchOutcomeMock.mockResolvedValue({ kind: 'upstream-error', errorType: 'unknown', diff --git a/src/main/github/pr-refresh-coordinator.ts b/src/main/github/pr-refresh-coordinator.ts index a2576e4805e7..8065fbb81455 100644 --- a/src/main/github/pr-refresh-coordinator.ts +++ b/src/main/github/pr-refresh-coordinator.ts @@ -708,20 +708,11 @@ async function drainQueue(): Promise { ) if (isBackground(next.reason)) { - const rateLimit = await getRateLimit() - if (!rateLimit.ok) { - const retryAt = Date.now() + 30_000 - queue.set(next.key, { ...next, dueAt: retryAt }) - broadcast({ - aliases, - reason: next.reason, - status: 'paused', - pausedUntil: retryAt, - skippedReason: 'rate-limit' - }) - scheduleDrain(30_000) - continue - } + // Why: the probe only warms rateLimitGuard's cached snapshot, so a + // failed probe must fail open — GHES with rate limiting disabled 404s + // every probe (#7553). A genuinely broken gh surfaces per-key as typed + // fetch outcomes instead (visible keys additionally back off). + await getRateLimit() const buckets = backgroundRefreshBuckets() const blockedGuard = buckets .map((bucket) => rateLimitGuard(bucket)) diff --git a/src/main/github/rate-limit.test.ts b/src/main/github/rate-limit.test.ts new file mode 100644 index 000000000000..ab1373a70f08 --- /dev/null +++ b/src/main/github/rate-limit.test.ts @@ -0,0 +1,138 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { ghExecFileAsyncMock } = vi.hoisted(() => ({ + ghExecFileAsyncMock: vi.fn() +})) + +vi.mock('../git/runner', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('./gh-utils', () => ({ + acquire: vi.fn(), + release: vi.fn() +})) + +import { getRateLimit, rateLimitGuard, _resetRateLimitCache } from './rate-limit' + +const PAYLOAD = JSON.stringify({ + resources: { + core: { limit: 5000, remaining: 4200, reset: 1_700_000_000 }, + search: { limit: 30, remaining: 28, reset: 1_700_000_000 }, + graphql: { limit: 5000, remaining: 4900, reset: 1_700_000_000 } + } +}) + +describe('getRateLimit', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + ghExecFileAsyncMock.mockReset() + _resetRateLimitCache() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('parses bucket counts from gh api rate_limit', async () => { + ghExecFileAsyncMock.mockResolvedValue({ stdout: PAYLOAD }) + + const result = await getRateLimit() + + expect(result).toEqual({ + ok: true, + snapshot: { + core: { limit: 5000, remaining: 4200, resetAt: 1_700_000_000 }, + search: { limit: 30, remaining: 28, resetAt: 1_700_000_000 }, + graphql: { limit: 5000, remaining: 4900, resetAt: 1_700_000_000 }, + fetchedAt: 1_000 + } + }) + }) + + it('caches a failed probe for the TTL instead of re-spawning gh', async () => { + // Why: regression for #7553 — GHES with rate limiting disabled fails every + // probe. Refreshes fail open past the failure, so without a negative cache + // each queued refresh would spawn its own doomed gh subprocess. + ghExecFileAsyncMock.mockRejectedValue(new Error('HTTP 404: Rate limiting is not enabled.')) + + const first = await getRateLimit() + const second = await getRateLimit() + + expect(first).toEqual({ ok: false, error: 'HTTP 404: Rate limiting is not enabled.' }) + expect(second).toEqual(first) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + }) + + it('re-probes after the failure TTL elapses and recovers on success', async () => { + ghExecFileAsyncMock.mockRejectedValueOnce(new Error('boom')) + ghExecFileAsyncMock.mockResolvedValue({ stdout: PAYLOAD }) + + expect((await getRateLimit()).ok).toBe(false) + expect((await getRateLimit()).ok).toBe(false) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + + vi.setSystemTime(1_000 + 30_000) + + expect((await getRateLimit()).ok).toBe(true) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) + }) + + it('bypasses the failure cache when forced', async () => { + ghExecFileAsyncMock.mockRejectedValueOnce(new Error('boom')) + ghExecFileAsyncMock.mockResolvedValue({ stdout: PAYLOAD }) + + expect((await getRateLimit()).ok).toBe(false) + expect((await getRateLimit({ force: true })).ok).toBe(true) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) + }) +}) + +describe('rateLimitGuard', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + ghExecFileAsyncMock.mockReset() + _resetRateLimitCache() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + async function cacheExhaustedSnapshot(resetEpochSeconds: number): Promise { + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ + resources: { + core: { limit: 5000, remaining: 3, reset: resetEpochSeconds }, + search: { limit: 30, remaining: 28, reset: resetEpochSeconds }, + graphql: { limit: 5000, remaining: 4900, reset: resetEpochSeconds } + } + }) + }) + expect((await getRateLimit()).ok).toBe(true) + } + + it('blocks below the floor while resetAt is in the future', async () => { + await cacheExhaustedSnapshot(61) + + expect(rateLimitGuard('core')).toEqual({ + blocked: true, + remaining: 3, + limit: 5000, + resetAt: 61 + }) + }) + + it('fails open once the blocking bucket resetAt has elapsed', async () => { + // Why: probes can fail indefinitely (sleep past resetAt, network blip), so + // a stale exhausted snapshot must not block once GitHub has already reset + // the budget — a past-due pause would spin the coordinator drain loop. + await cacheExhaustedSnapshot(61) + + vi.setSystemTime(61_000) + + expect(rateLimitGuard('core')).toEqual({ blocked: false }) + }) +}) diff --git a/src/main/github/rate-limit.ts b/src/main/github/rate-limit.ts index ad140422488e..f4a1ba562484 100644 --- a/src/main/github/rate-limit.ts +++ b/src/main/github/rate-limit.ts @@ -35,6 +35,11 @@ import { // 1-per-second "is it safe now?" polling pattern UIs tend to fall into. const RATE_LIMIT_CACHE_TTL_MS = 30_000 let cached: GitHubRateLimitSnapshot | null = null +// Why: failed probes are cached for the same TTL as successes. Refreshes fail +// open past a failed probe, so on a host that can never report a budget (GHES +// with rate limiting disabled 404s every probe) an uncached failure would cost +// a gh subprocess per queued refresh. +let probeFailure: { at: number; error: string } | null = null type GhRateLimitPayload = { resources?: { @@ -66,6 +71,7 @@ function parseBucket( /** @internal — test-only */ export function _resetRateLimitCache(): void { cached = null + probeFailure = null } // Why: hard-stop thresholds for the circuit breaker. We refuse to issue a new @@ -196,6 +202,9 @@ export async function getRateLimit(options?: { force?: boolean }): Promise { fetchedAt: Date.now() } cached = snapshot + probeFailure = null return { ok: true, snapshot } } catch (err) { const message = err instanceof Error ? err.message : String(err) + probeFailure = { at: Date.now(), error: message } return { ok: false, error: message } } finally { release() diff --git a/src/main/gitlab/client-mr.test.ts b/src/main/gitlab/client-mr.test.ts index 21747de6a26c..a090ec7963bb 100644 --- a/src/main/gitlab/client-mr.test.ts +++ b/src/main/gitlab/client-mr.test.ts @@ -245,6 +245,9 @@ describe('gitlab client — MR operations', () => { hosts: ['gitlab.com'], activeHost: 'gitlab.com' }) + expect(glabExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], { + allowDefaultWslFallback: false + }) }) }) diff --git a/src/main/gitlab/client.ts b/src/main/gitlab/client.ts index ec4a178ea64e..b6b32dfb8c37 100644 --- a/src/main/gitlab/client.ts +++ b/src/main/gitlab/client.ts @@ -97,7 +97,10 @@ export async function diagnoseAuth(): Promise { ? 'GLAB_TOKEN' : null try { - const { stdout, stderr } = await glabExecFileAsync(['auth', 'status']) + // Why: a host-global diagnostic must not wake an unrelated default WSL distro. + const { stdout, stderr } = await glabExecFileAsync(['auth', 'status'], { + allowDefaultWslFallback: false + }) const output = `${stdout}\n${stderr}` const hosts = parseGlabAuthStatusHosts(output) return { diff --git a/src/main/grok-accounts/status.test.ts b/src/main/grok-accounts/status.test.ts new file mode 100644 index 000000000000..fccf5dfd7191 --- /dev/null +++ b/src/main/grok-accounts/status.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { getGrokAccountStatus } from './status' +import { isGrokAccessTokenFresh, readGrokAuthSession } from '../rate-limits/grok-auth' + +vi.mock('../rate-limits/grok-auth', () => ({ + isGrokAccessTokenFresh: vi.fn(), + readGrokAuthSession: vi.fn() +})) + +describe('getGrokAccountStatus', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(isGrokAccessTokenFresh).mockReturnValue(true) + }) + + it('reports unsigned status when the Grok auth file is missing', () => { + vi.mocked(readGrokAuthSession).mockReturnValue({ status: 'missing' }) + + expect(getGrokAccountStatus()).toEqual({ + signedIn: false, + email: null, + teamId: null, + tokenFresh: false, + error: null + }) + }) + + it('reports auth read errors without exposing token fields', () => { + vi.mocked(readGrokAuthSession).mockReturnValue({ + status: 'error', + error: 'Grok auth file is invalid' + }) + + expect(getGrokAccountStatus()).toEqual({ + signedIn: false, + email: null, + teamId: null, + tokenFresh: false, + error: 'Grok auth file is invalid' + }) + }) + + it('returns non-secret signed-in metadata and freshness', () => { + vi.mocked(readGrokAuthSession).mockReturnValue({ + status: 'ok', + session: { + accessToken: 'secret-token', + email: 'dev@example.com', + teamId: 'team-1', + userId: 'user-1', + expiresAtMs: null, + oidcClientId: 'client-1' + } + }) + vi.mocked(isGrokAccessTokenFresh).mockReturnValue(false) + + const status = getGrokAccountStatus() + + expect(status).toEqual({ + signedIn: true, + email: 'dev@example.com', + teamId: 'team-1', + tokenFresh: false, + error: null + }) + expect(JSON.stringify(status)).not.toContain('secret-token') + expect(JSON.stringify(status)).not.toContain('client-1') + }) +}) diff --git a/src/main/grok-accounts/status.ts b/src/main/grok-accounts/status.ts new file mode 100644 index 000000000000..021483e47221 --- /dev/null +++ b/src/main/grok-accounts/status.ts @@ -0,0 +1,32 @@ +import type { GrokAccountStatus } from '../../shared/rate-limit-types' +import { isGrokAccessTokenFresh, readGrokAuthSession } from '../rate-limits/grok-auth' + +export function getGrokAccountStatus(): GrokAccountStatus { + const readResult = readGrokAuthSession() + if (readResult.status === 'missing') { + return { + signedIn: false, + email: null, + teamId: null, + tokenFresh: false, + error: null + } + } + if (readResult.status === 'error') { + return { + signedIn: false, + email: null, + teamId: null, + tokenFresh: false, + error: readResult.error + } + } + const session = readResult.session + return { + signedIn: true, + email: session.email, + teamId: session.teamId, + tokenFresh: isGrokAccessTokenFresh(session), + error: null + } +} diff --git a/src/main/grok/hook-service.test.ts b/src/main/grok/hook-service.test.ts index 23cc2eeaf5fd..c6f89509e16e 100644 --- a/src/main/grok/hook-service.test.ts +++ b/src/main/grok/hook-service.test.ts @@ -15,7 +15,7 @@ vi.mock('os', async () => { } }) -import { GrokHookService } from './hook-service' +import { getGrokToolEventMatcherForTests, GrokHookService } from './hook-service' const GROK_SCRIPT_FILE_NAME = process.platform === 'win32' ? 'grok-hook.cmd' : 'grok-hook.sh' const WINDOWS_POWERSHELL_LAUNCHER = @@ -55,12 +55,25 @@ describe('GrokHookService', () => { 'SessionEnd', 'SessionStart', 'Stop', + 'StopFailure', 'UserPromptSubmit' ].sort() ) - expect(config.hooks.PreToolUse[0].matcher).toBe('*') - expect(config.hooks.PostToolUseFailure[0].matcher).toBe('*') + // Why: Grok matchers are real regexes; bare `*` does not match-all. + expect(config.hooks.PreToolUse[0].matcher).toBe('.*') + expect(config.hooks.PostToolUseFailure[0].matcher).toBe('.*') + expect(config.hooks.PostToolUse[0].matcher).toBe('.*') + // Why: StopFailure must not carry a tool matcher — lifecycle-only event. + expect(config.hooks.StopFailure[0].matcher).toBeUndefined() expect(config.hooks.Notification[0].matcher).toBeUndefined() + // Why: assert the shipped helper still matches what install wrote (regression + // guard if GROK_TOOL_EVENT_MATCHER drifts from install). + expect(getGrokToolEventMatcherForTests()).toBe('.*') + expect(getGrokToolEventMatcherForTests()).not.toBe('*') + expect(new RegExp(getGrokToolEventMatcherForTests()).test('run_terminal_command')).toBe(true) + // Why: build the invalid pattern at runtime so static lint does not flag it. + const bareStar = ['*', ''].join('') + expect(() => new RegExp(bareStar)).toThrow() expect(config.hooks.PreToolUse[0].hooks[0].command).toMatch( process.platform === 'win32' ? WINDOWS_POWERSHELL_LAUNCHER : /grok-hook/ ) @@ -75,12 +88,20 @@ describe('GrokHookService', () => { expect(script).toContain('/hook/grok') if (process.platform === 'win32') { expect(script).toContain('%SystemRoot%\\System32\\curl.exe') + expect(script).toContain('set "ORCA_GROK_HOME=%GROK_HOME%"') + expect(script).toContain('%GROK_HOME:~4096,1%') + expect(script).toContain( + 'if "%ORCA_GROK_HOME:~-1%"=="\\" set "ORCA_GROK_HOME=%ORCA_GROK_HOME%."' + ) + expect(script).toContain('--data-urlencode "grokHome=%ORCA_GROK_HOME%"') } else { // Why: payload is piped to curl via stdin (`payload@-`) so it never lands // on the curl command line (EDR oversized-command-line false positive). expect(script).toContain('payload=$(cat)') expect(script).toContain('printf \'%s\' "$payload" | curl') expect(script).toContain('--data-urlencode "payload@-"') + expect(script).toContain('${#GROK_HOME}" -le 4096') + expect(script).toContain('--data-urlencode "grokHome=${grok_home}"') expect(script).not.toContain('--data-urlencode "payload=${payload}"') } }) @@ -112,6 +133,31 @@ describe('GrokHookService', () => { } ) + it('installs hooks under GROK_HOME when set', () => { + const grokHome = mkdtempSync(join(tmpdir(), 'orca-grok-home-env-')) + const previous = process.env.GROK_HOME + process.env.GROK_HOME = grokHome + try { + const status = new GrokHookService().install() + expect(status.state).toBe('installed') + expect(status.configPath).toBe(join(grokHome, 'hooks', 'orca-status.json')) + expect(readFileSync(join(grokHome, 'hooks', 'orca-status.json'), 'utf8')).toContain( + 'SessionStart' + ) + // Why: must not also write into the mocked ~/.grok when GROK_HOME wins. + expect(() => + readFileSync(join(homeDir, '.grok', 'hooks', 'orca-status.json'), 'utf8') + ).toThrow() + } finally { + if (previous === undefined) { + delete process.env.GROK_HOME + } else { + process.env.GROK_HOME = previous + } + rmSync(grokHome, { recursive: true, force: true }) + } + }) + it('preserves user-authored hook entries in the Orca Grok config file', () => { const configPath = join(homeDir, '.grok', 'hooks', 'orca-status.json') mkdirSync(dirname(configPath), { recursive: true }) diff --git a/src/main/grok/hook-service.ts b/src/main/grok/hook-service.ts index 6fbbacadbc71..c88e1254febf 100644 --- a/src/main/grok/hook-service.ts +++ b/src/main/grok/hook-service.ts @@ -1,7 +1,7 @@ -import { homedir } from 'node:os' import { join } from 'node:path' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' +import { resolveGrokHomeDir } from '../../shared/grok-session-paths' import { buildManagedCommandHook, createManagedCommandMatcher, @@ -21,33 +21,80 @@ import { writeManagedScriptRemote } from '../agent-hooks/installer-utils-remote' +// Why: Grok's tool-event matcher is a real regex (see Grok hooks docs). Bare +// `*` is not a valid "match all" pattern and can fail to load/match, so tool +// lifecycle hooks never fire. `.*` matches every tool name (same as Command +// Code's managed hooks). +const GROK_TOOL_EVENT_MATCHER = '.*' +const GROK_HOME_ENVELOPE_MAX_LENGTH = 4096 +const WINDOWS_HOOK_PAYLOAD_FORM_LINE = ' --data-urlencode "payload@-" >nul 2>nul' + const GROK_EVENTS = [ { eventName: 'SessionStart', definition: { hooks: [{ type: 'command', command: '' }] } }, { eventName: 'UserPromptSubmit', definition: { hooks: [{ type: 'command', command: '' }] } }, { eventName: 'Stop', definition: { hooks: [{ type: 'command', command: '' }] } }, + // Why: Grok can end a turn on API error without a normal Stop; without this + // the sidebar can stick on working (same rationale as Claude StopFailure). + { eventName: 'StopFailure', definition: { hooks: [{ type: 'command', command: '' }] } }, { eventName: 'SessionEnd', definition: { hooks: [{ type: 'command', command: '' }] } }, { eventName: 'PreToolUse', - definition: { matcher: '*', hooks: [{ type: 'command', command: '' }] } + definition: { matcher: GROK_TOOL_EVENT_MATCHER, hooks: [{ type: 'command', command: '' }] } }, { eventName: 'PostToolUse', - definition: { matcher: '*', hooks: [{ type: 'command', command: '' }] } + definition: { matcher: GROK_TOOL_EVENT_MATCHER, hooks: [{ type: 'command', command: '' }] } }, { eventName: 'PostToolUseFailure', - definition: { matcher: '*', hooks: [{ type: 'command', command: '' }] } + definition: { matcher: GROK_TOOL_EVENT_MATCHER, hooks: [{ type: 'command', command: '' }] } }, { eventName: 'Notification', definition: { hooks: [{ type: 'command', command: '' }] } } ] as const +/** Test seam: the matcher string written for Pre/Post tool lifecycle hooks. */ +export function getGrokToolEventMatcherForTests(): string { + return GROK_TOOL_EVENT_MATCHER +} + function getConfigPath(): string { - // Why: Grok loads trusted global hook files from ~/.grok/hooks/*.json. Keep - // Orca's managed entries in a dedicated file so user-authored hook files stay - // untouched and project-level trust is not required for status reporting. - return join(homedir(), '.grok', 'hooks', 'orca-status.json') + // Why: Grok loads trusted global hook files from $GROK_HOME/hooks/*.json + // (or ~/.grok when unset). Honor GROK_HOME so install/status match the same + // home Grok and transcript lookup use; keep Orca entries in a dedicated file + // so user-authored hook files stay untouched. + return join(resolveGrokHomeDir(), 'hooks', 'orca-status.json') +} + +/** Validated guest Grok home with a login-home fallback. */ +function getRemoteGrokHome(remoteHome: string, remoteGrokHome?: string): string { + // Why: SFTP paths are always POSIX — never use host path.join here. + const home = remoteHome.replace(/\/+$/, '') || remoteHome + const candidate = remoteGrokHome?.trim() + if ( + candidate && + candidate === remoteGrokHome && + candidate.startsWith('/') && + !candidate.includes('\\') && + candidate.length <= GROK_HOME_ENVELOPE_MAX_LENGTH && + !hasControlCharacter(candidate) + ) { + return candidate.replace(/\/+$/, '') || '/' + } + return `${home}/.grok` +} + +function hasControlCharacter(value: string): boolean { + return Array.from(value).some((character) => { + const code = character.charCodeAt(0) + return code <= 0x1f || code === 0x7f + }) } +const WINDOWS_GROK_HOOK_POST_COMMAND = buildWindowsAgentHookPostCommand('grok').replace( + WINDOWS_HOOK_PAYLOAD_FORM_LINE, + ` --data-urlencode "grokHome=%ORCA_GROK_HOME%" ^\r\n${WINDOWS_HOOK_PAYLOAD_FORM_LINE}` +) + function getManagedScriptFileName(): string { return process.platform === 'win32' ? 'grok-hook.cmd' : 'grok-hook.sh' } @@ -71,7 +118,12 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string { 'if "%ORCA_AGENT_HOOK_PORT%"=="" exit /b 0', 'if "%ORCA_AGENT_HOOK_TOKEN%"=="" exit /b 0', 'if "%ORCA_PANE_KEY%"=="" exit /b 0', - buildWindowsAgentHookPostCommand('grok'), + 'set "ORCA_GROK_HOME=%GROK_HOME%"', + `if not "%GROK_HOME:~${GROK_HOME_ENVELOPE_MAX_LENGTH},1%"=="" set "ORCA_GROK_HOME="`, + // Why: a trailing backslash escapes curl's closing argv quote on Windows, + // merging the payload option into grokHome and dropping the hook body. + 'if "%ORCA_GROK_HOME:~-1%"=="\\" set "ORCA_GROK_HOME=%ORCA_GROK_HOME%."', + WINDOWS_GROK_HOOK_POST_COMMAND, 'exit /b 0', '' ].join('\r\n') @@ -89,6 +141,10 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string { 'if [ -z "$payload" ]; then', ' exit 0', 'fi', + 'grok_home=', + `if [ -n "\${GROK_HOME:-}" ] && [ "\${#GROK_HOME}" -le ${GROK_HOME_ENVELOPE_MAX_LENGTH} ]; then`, + ' grok_home=$GROK_HOME', + 'fi', // Timeout caps best-effort hook posts if the local listener stalls. // Why: pipe payload to curl's stdin (`payload@-`) instead of an inline // `payload=$VALUE` arg, so tens-of-KB tool output stays off the curl @@ -103,6 +159,7 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string { ' --data-urlencode "worktreeId=${ORCA_WORKTREE_ID}" \\', ' --data-urlencode "env=${ORCA_AGENT_HOOK_ENV}" \\', ' --data-urlencode "version=${ORCA_AGENT_HOOK_VERSION}" \\', + ' --data-urlencode "grokHome=${grok_home}" \\', ' --data-urlencode "payload@-" >/dev/null 2>&1 || true', 'exit 0', '' @@ -213,9 +270,15 @@ export class GrokHookService { return this.getStatus() } - async installRemote(sftp: SFTPWrapper, remoteHome: string): Promise { + async installRemote( + sftp: SFTPWrapper, + remoteHome: string, + remoteGrokHome?: string + ): Promise { const home = remoteHome.replace(/\/$/, '') - const remoteConfigPath = `${home}/.grok/hooks/orca-status.json` + // Why: only a guest-resolved path can describe remote Grok; never apply the + // host process's GROK_HOME to SFTP paths. + const remoteConfigPath = `${getRemoteGrokHome(home, remoteGrokHome)}/hooks/orca-status.json` const remoteScriptPath = `${home}/.orca/agent-hooks/grok-hook.sh` try { const config = await readHooksJsonRemote(sftp, remoteConfigPath) diff --git a/src/main/index.ts b/src/main/index.ts index 251ea69e67d5..975e3a4596b7 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -14,6 +14,7 @@ import { getCanonicalUserDataPath, migrateMobilePairingDataToCanonicalUserDataPath } from './persistence' +import { ensureActiveOrcaProfile, initOrcaProfilePaths } from './orca-profiles/profile-index-store' import { applyAppIcon } from './app-icon' import { StatsCollector, initStatsPath } from './stats/collector' import { ClaudeUsageStore, initClaudeUsagePath } from './claude-usage/store' @@ -27,7 +28,8 @@ import { registerCoreHandlers } from './ipc/register-core-handlers' import { initObservability, shutdownObservability } from './observability' import { startSpan } from './observability/tracer' import { registerMobileHandlers } from './ipc/mobile' -import { initTelemetry, shutdownTelemetry, trackAppOpenedOnce } from './telemetry/client' +import { initTelemetry, shutdownTelemetry, trackAppOpenedOnce, track } from './telemetry/client' +import { classifyError } from './telemetry/classify-error' import { runManagedHookInstallers } from './agent-hooks/install-telemetry' import { isAgentStatusHooksEnabled, @@ -49,6 +51,7 @@ import { rebuildAppMenu } from './menu/register-app-menu' import { checkForUpdatesFromMenu, isQuittingForUpdate } from './updater' +import { recordUpdaterLifecycle } from './updater-lifecycle-diagnostics' import { configureElectronNetworkCompatibility, configureDevUserDataPath, @@ -109,8 +112,9 @@ import { ensureAutoUpdaterConfigured } from './window/attach-main-window-services' import { createMainWindow, loadMainWindow } from './window/createMainWindow' -import { createSystemTray, destroySystemTray } from './tray/system-tray' +import { createSystemTray, destroySystemTray, setTrayAttention } from './tray/system-tray' import { focusExistingMainWindow } from './window/focus-existing-window' +import { notifyMainWindowBecameVisible } from './window/main-window-visibility' import { CodexAccountService } from './codex-accounts/service' import { CodexRuntimeHomeService } from './codex-accounts/runtime-home-service' import { @@ -119,6 +123,7 @@ import { } from './codex-accounts/runtime-selection' import { normalizeClaudeRuntimeSelection } from './claude-accounts/runtime-selection' import { codexHookService } from './codex/hook-service' +import { getDefaultWslDistro } from './wsl' import { ClaudeAccountService } from './claude-accounts/service' import { ClaudeRuntimeAuthService } from './claude-accounts/runtime-auth-service' import { @@ -127,6 +132,7 @@ import { } from './claude-accounts/live-pty-gate' import { StarNagService } from './star-nag/service' import { agentHookServer } from './agent-hooks/server' +import { wslHookRelayManager } from './agent-hooks/wsl-hook-relay-manager' import { maybeAutoRenameBranchOnFirstWork } from './agent-hooks/first-work-branch-rename' import { renameWorktreeFolderOnFirstWork } from './agent-hooks/first-work-folder-rename' import { moveWorktree } from './git/worktree' @@ -151,6 +157,7 @@ import { AutomationService } from './automations/service' import { createHeadlessAutomationOutputSnapshotBuffer } from './automations/headless-dispatch' import { buildHeadlessAutomationWorktreeCreateArgs } from './automations/headless-workspace-create' import { AgentAwakeService } from './agent-awake-service' +import { registerSystemResumeBroadcast } from './system-resume-broadcast' import { getCrashBreadcrumbSnapshot, recordCoalescedCrashBreadcrumb, @@ -172,6 +179,7 @@ import { type SyntheticTitleSpinnerEntry } from './synthetic-title-spinner' import { shouldSendSyntheticTitleFrame } from './synthetic-title-visibility' +import { shouldCopySyntheticTitleFrameToPtyData } from './synthetic-title-frame-routing' import { isCrashReportReason } from '../shared/crash-reporting' import { getSyntheticAgentTitleProfile, @@ -180,6 +188,7 @@ import { } from '../shared/synthetic-agent-title' import type { AgentStatusState } from '../shared/agent-status-types' import { resolveTuiAgentPermissionMode } from '../shared/tui-agent-permissions' +import type { TerminalSideEffectBatch } from '../shared/terminal-side-effect-facts' import { KeybindingService } from './keybindings/keybinding-service' import { applyElectronProxySettings } from './network/proxy-settings' import { preserveAgentAuthBeforeRestart } from './agent-auth-restart-preservation' @@ -212,6 +221,7 @@ let starNag: StarNagService | null = null let agentAwakeService: AgentAwakeService | null = null let crashReports: CrashReportStore | null = null let unsubscribeAgentAwakeStatusChanges: (() => void) | null = null +let unsubscribeSystemResumeBroadcast: (() => void) | null = null let watcherShutdownPromise: Promise | null = null let watcherShutdownDone = false let automations: AutomationService | null = null @@ -578,6 +588,7 @@ if (hasSingleInstanceLock) { // orca-dev in dev mode) but before app.setName('Orca') inside whenReady // (which would change the resolved path on case-sensitive filesystems). initDataPath() + initOrcaProfilePaths() // Why: same timing constraint as initDataPath — capture the userData path // before app.setName changes it. See persistence.ts:20-28. initStatsPath() @@ -641,7 +652,16 @@ function startDesktopFirstWindowStartupServices(): Promise { logStartupMilestone('startup-service-done', { service: 'agent-hook-server' }) }, onDaemonError: (error) => { - console.error('[daemon] Failed to start daemon PTY provider, falling back to local:', error) + // Why: daemon startup failure silently dropped terminals onto the local + // provider (killed on quit, no persistence) — the v1.4.129-rc.1 outage was + // invisible in the field. Log loudly (error.message carries the captured + // daemon stderr tail from the fork) and emit a low-cardinality telemetry + // signal so a fleet-wide daemon failure is observable without a bug report. + const reason = error instanceof Error ? error.message : String(error) + console.error( + `[daemon] STARTUP FAILED — falling back to local PTYs; terminals will not persist across quit. Reason: ${reason}` + ) + track('daemon_start_failed', classifyError(error)) }, onAgentHookServerError: (error) => { // Why: Claude/Codex/Gemini/OpenCode/Cursor hook callbacks are sidebar @@ -679,13 +699,22 @@ async function startServeAgentHookServer(): Promise { function prepareCodexRuntimeHomeForLaunch(target?: CodexAccountSelectionTarget): string | null { const runtimeHomePath = codexRuntimeHome!.prepareForCodexLaunch(target) + const hookTarget = + target?.runtime === 'wsl' + ? { + runtime: 'wsl' as const, + wslDistro: target.wslDistro?.trim() || getDefaultWslDistro() + } + : target const hooksEnabled = isAgentStatusHooksEnabled(store?.getSettings()) try { // Why: launch prep is reachable after startup via PTY/runtime paths; honor // the persisted off switch so those launches cannot reinstall removed hooks. const status = hooksEnabled - ? codexHookService.install() - : codexHookService.refreshRuntimeUserHooks() + ? (codexHookService.installForRuntimeHome(runtimeHomePath, hookTarget) ?? + codexHookService.install()) + : (codexHookService.refreshRuntimeUserHooksForRuntimeHome(runtimeHomePath, hookTarget) ?? + codexHookService.refreshRuntimeUserHooks()) if (status.state === 'error') { console.warn( `[codex-hook-service] failed to ${ @@ -984,6 +1013,15 @@ function openMainWindow(): BrowserWindow { window.on('restore', resumeSyntheticTitleSpinnerTimer) window.on('hide', stopSyntheticTitleSpinnerTimer) window.on('minimize', stopSyntheticTitleSpinnerTimer) + // Why: visibility-gated main-process pollers (SSH port scanner) park while + // hidden and rely on this signal to resume; re-wired per window because + // macOS dock re-activation recreates the BrowserWindow. + window.on('show', notifyMainWindowBecameVisible) + window.on('restore', notifyMainWindowBecameVisible) + // Why: showing/restoring the window means the user is back, so clear the + // tray attention dot set while it was minimized/hidden (see notifications.ts). + window.on('show', () => setTrayAttention(false)) + window.on('restore', () => setTrayAttention(false)) agentHookServer.setListener( ({ paneKey, @@ -1468,7 +1506,17 @@ function sendSyntheticTitle(ptyId: string, data: string, options: { force?: bool ) { return } - mainWindow.webContents.send('pty:data', { id: ptyId, data }) + // Why: feed the per-PTY tracker directly (never onPtyData — emulator state, + // tails, transcripts, and stats must not see fabricated bytes) so synthetic + // titles/BELs reach pty:sideEffect consumers when main holds side-effect + // authority. + runtime?.ingestSyntheticTitleFrame(ptyId, data) + // Why: only the kill-switch-off renderer still byte-parses synthetic frames; + // under main authority the copy would just mint phantom ACKs for unmetered + // bytes (see synthetic-title-frame-routing.ts). + if (shouldCopySyntheticTitleFrameToPtyData(store?.getSettings())) { + mainWindow.webContents.send('pty:data', { id: ptyId, data }) + } } function isSyntheticTitleWindowVisible(): boolean { @@ -1624,7 +1672,8 @@ app.whenReady().then(async () => { electronApp.setAppUserModelId(devInstanceIdentity.appUserModelId) app.setName(devInstanceIdentity.name) - store = new Store() + const activeOrcaProfile = ensureActiveOrcaProfile() + store = new Store({ dataFile: activeOrcaProfile.dataFile }) logStartupMilestone('store-loaded') // Why: must run before ClaudeRuntimeAuthService's constructor sync — a Claude // CLI that survived the restart inside the daemon still holds the current @@ -1652,7 +1701,11 @@ app.whenReady().then(async () => { } // Why: browser sessions are used by desktop webviews and runtime profile // commands, so initialize them at app startup instead of a renderer IPC path. - initializeBrowserSessionsForApp() + initializeBrowserSessionsForApp({ + orcaProfileId: activeOrcaProfile.profile.id, + profileDirectory: activeOrcaProfile.profileDirectory + }) + unsubscribeSystemResumeBroadcast = registerSystemResumeBroadcast() agentAwakeService = new AgentAwakeService() agentAwakeService.setEnabled(store.getSettings().keepComputerAwakeWhileAgentsRun) // Why: disk-hydrated status rows are UI continuity only. The service starts @@ -1764,9 +1817,28 @@ app.whenReady().then(async () => { onTerminalAgentStatus: (event) => { agentHookServer.ingestTerminalStatus(event) }, + // Why: derived title/bell/agent facts ride one batched main→renderer + // channel (terminal-side-effect-authority.md). The renderer's authority + // kill switch decides whether to consume. Headless serve never creates a + // window, so the dep is omitted entirely — the runtime then skips fact + // batch construction and the per-chunk bell walk. + ...(isServeMode + ? {} + : { + onTerminalSideEffects: (batch: TerminalSideEffectBatch) => { + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.webContents.send('pty:sideEffect', batch) + } + } + }), // Why: hook-reported agent status is the same source the desktop sidebar // reads. worktree.ps pulls it at query time so mobile shows the same agents. getAgentStatusSnapshot: () => agentHookServer.getStatusSnapshot(), + // Why: source codex-home here (runs in BOTH window and serve modes) so the + // aiVault.listSessions RPC includes managed-Codex sessions on remote/SSH + // hosts; the window-only registerCoreHandlers path never runs under serve. + getAdditionalAiVaultCodexHomePaths: () => + codexRuntimeHome ? [codexRuntimeHome.getHostRuntimeHomePath()] : [], buildAgentHookPtyEnv: () => isAgentStatusHooksEnabled(store?.getSettings()) ? agentHookServer.buildPtyEnv() : {} }) @@ -2018,7 +2090,9 @@ app.whenReady().then(async () => { // a random OS-assigned port — breaking deterministic mobile pairing/repro // scripts against the dev instance. Pin the first dev instance to 6769 so // ws://127.0.0.1:6769 is stable; a second dev instance still falls back via - // ws-transport's EADDRINUSE handler. + // ws-transport's EADDRINUSE handler. Note: once an instance has ever fallen + // back, the persisted fallback port is re-bound in preference to 6769 + // (STA-1511) until mobile-ws-fallback-port.json is removed from userData. const devWsPort = is.dev && !isE2E ? 6769 : undefined let serveOptions: ServeOptions | null = null try { @@ -2169,7 +2243,14 @@ app.whenReady().then(async () => { }) app.on('before-quit', () => { + if (isQuittingForUpdate()) { + recordUpdaterLifecycle('before_quit_allowed', undefined, { + message: 'before-quit allowed for update install' + }) + } isQuitting = true + unsubscribeSystemResumeBroadcast?.() + unsubscribeSystemResumeBroadcast = null unsubscribeAgentAwakeStatusChanges?.() unsubscribeAgentAwakeStatusChanges = null agentAwakeService?.dispose() @@ -2188,6 +2269,14 @@ app.on('before-quit', () => { // async work and let Electron exit. let daemonDisconnectDone = false app.on('will-quit', (e) => { + const updateQuitInProgress = isQuittingForUpdate() + if (updateQuitInProgress) { + recordUpdaterLifecycle( + 'will_quit_cleanup_started', + { daemonTeardown: 'disconnect' }, + { message: 'will-quit cleanup for update install; daemonTeardown=disconnect' } + ) + } // Why: before-quit can still be aborted by renderer beforeunload; wait until // the committed quit path before removing the Windows notification icon. destroySystemTray() @@ -2200,6 +2289,9 @@ app.on('will-quit', (e) => { automations?.stop() setUnreadDockBadgeCount(0) agentHookServer.stop() + // Why: cancels relay restart/reinstall timers and kills wsl.exe children + // deterministically instead of relying on stdio-pipe teardown. + wslHookRelayManager.disposeAll() stats?.flush() // Why: agent-browser daemon processes would otherwise linger after Orca quits, // holding ports and leaving stale session state on disk. diff --git a/src/main/ipc/ai-vault.test.ts b/src/main/ipc/ai-vault.test.ts index 9cc8060eee2a..8d4ba30dbd56 100644 --- a/src/main/ipc/ai-vault.test.ts +++ b/src/main/ipc/ai-vault.test.ts @@ -1,3 +1,5 @@ +import { homedir } from 'node:os' +import { join, sep } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { AiVaultListResult, AiVaultSession } from '../../shared/ai-vault-types' import type { IFilesystemProvider } from '../providers/types' @@ -6,6 +8,8 @@ import { getRemoteHostPlatform } from '../ssh/ssh-remote-platform' const mocks = vi.hoisted(() => ({ scanAiVaultSessions: vi.fn(), scanRemoteAiVaultSessions: vi.fn(), + listClaudeSubagentSessions: vi.fn(), + scanRuntimeAiVaultSessions: vi.fn(), getAiVaultWslHomeDirs: vi.fn(), getSshFilesystemProvider: vi.fn(), getActiveSshAiVaultHostInfo: vi.fn(), @@ -25,6 +29,10 @@ vi.mock('../ai-vault/remote-session-scanner', () => ({ scanRemoteAiVaultSessions: mocks.scanRemoteAiVaultSessions })) +vi.mock('../ai-vault/session-scanner-claude-subagents', () => ({ + listClaudeSubagentSessions: mocks.listClaudeSubagentSessions +})) + vi.mock('../wsl', () => ({ getWslHomeAsync: mocks.getAiVaultWslHomeDirs, listWslDistrosAsync: vi.fn().mockResolvedValue([]) @@ -41,7 +49,7 @@ vi.mock('./ssh', () => ({ getActiveSshAiVaultHostInfos: mocks.getActiveSshAiVaultHostInfos })) -const { _internals } = await import('./ai-vault') +const { _internals, registerAiVaultHandlers } = await import('./ai-vault') const provider = {} as IFilesystemProvider @@ -52,6 +60,10 @@ beforeEach(() => { mocks.scanRemoteAiVaultSessions.mockResolvedValue( result([session('ssh:dev-box', 'remote-session')]) ) + mocks.listClaudeSubagentSessions.mockResolvedValue({ sessions: [], issues: [] }) + mocks.scanRuntimeAiVaultSessions.mockResolvedValue( + result([session('runtime:remote-server', 'runtime-session')]) + ) mocks.getSshFilesystemProvider.mockReturnValue(provider) mocks.getActiveSshAiVaultHostInfo.mockReturnValue(hostInfo('dev-box')) mocks.getActiveSshAiVaultHostInfos.mockReturnValue([hostInfo('dev-box')]) @@ -96,6 +108,77 @@ describe('listAiVaultSessions host routing', () => { expect(result.sessions.map((entry) => entry.executionHostId)).toEqual(['ssh:dev-box', 'local']) }) + it('merges paired runtime servers for all hosts', async () => { + registerAiVaultHandlers({ + getActiveRuntimeAiVaultHostInfos: () => [ + { + environmentId: 'remote-server', + executionHostId: 'runtime:remote-server' + } + ], + scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions + }) + + const result = await _internals.listAiVaultSessions({ executionHostScope: 'all' }) + + expect(mocks.scanRuntimeAiVaultSessions).toHaveBeenCalledWith( + 'remote-server', + { + executionHostScope: 'runtime:remote-server' + }, + expect.objectContaining({ timeoutMs: expect.any(Number) }) + ) + expect(result.sessions.map((entry) => entry.executionHostId)).toEqual([ + 'runtime:remote-server', + 'ssh:dev-box', + 'local' + ]) + }) + + it('keeps local and SSH results when runtime host discovery fails', async () => { + registerAiVaultHandlers({ + getActiveRuntimeAiVaultHostInfos: () => { + throw new Error('runtime store is invalid') + }, + scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions + }) + + const result = await _internals.listAiVaultSessions({ executionHostScope: 'all' }) + + expect(mocks.scanAiVaultSessions).toHaveBeenCalledTimes(1) + expect(mocks.scanRemoteAiVaultSessions).toHaveBeenCalledTimes(1) + expect(mocks.scanRuntimeAiVaultSessions).not.toHaveBeenCalled() + expect(result.sessions.map((entry) => entry.executionHostId)).toEqual(['ssh:dev-box', 'local']) + expect(result.issues).toEqual([ + expect.objectContaining({ + agent: 'codex', + path: 'runtime environments', + message: 'runtime store is invalid' + }) + ]) + }) + + it('keeps direct runtime host scans on the normal runtime timeout', async () => { + registerAiVaultHandlers({ + getActiveRuntimeAiVaultHostInfos: () => [], + scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions + }) + + await _internals.listAiVaultSessions({ + executionHostScope: 'runtime:remote-server', + force: true + }) + + expect(mocks.scanRuntimeAiVaultSessions).toHaveBeenCalledWith( + 'remote-server', + { + executionHostScope: 'runtime:remote-server', + force: true + }, + {} + ) + }) + it('returns a scan issue for a disconnected SSH target', async () => { mocks.getActiveSshAiVaultHostInfo.mockReturnValue(null) mocks.getSshFilesystemProvider.mockReturnValue(undefined) @@ -123,6 +206,82 @@ describe('listAiVaultSessions host routing', () => { }) }) +describe('listAiVaultSubagentSessions gating', () => { + const claudeRoot = join(homedir(), '.claude', 'projects') + + it('lists subagents for a local Claude session inside the projects root', async () => { + const parentFilePath = join(claudeRoot, 'proj', 'sess.jsonl') + + await _internals.listAiVaultSubagentSessions({ + agent: 'claude', + parentFilePath, + executionHostId: 'local' + }) + + expect(mocks.listClaudeSubagentSessions).toHaveBeenCalledWith({ parentFilePath }) + }) + + it('returns empty for a remote Claude session without reading the filesystem', async () => { + const result = await _internals.listAiVaultSubagentSessions({ + agent: 'claude', + parentFilePath: join(claudeRoot, 'proj', 'sess.jsonl'), + executionHostId: 'ssh:dev-box' + }) + + expect(result).toEqual({ sessions: [], issues: [] }) + expect(mocks.listClaudeSubagentSessions).not.toHaveBeenCalled() + }) + + it('rejects a path outside the Claude projects root', async () => { + const result = await _internals.listAiVaultSubagentSessions({ + agent: 'claude', + parentFilePath: '/etc/secrets/subagents', + executionHostId: 'local' + }) + + expect(result).toEqual({ sessions: [], issues: [] }) + expect(mocks.listClaudeSubagentSessions).not.toHaveBeenCalled() + }) + + it('rejects a dot-segment traversal out of the Claude projects root', async () => { + // Built with sep (not join) so the `..` segments survive into the arg. + const traversal = [claudeRoot, '..', '..', '..', 'etc', 'passwd.jsonl'].join(sep) + + const result = await _internals.listAiVaultSubagentSessions({ + agent: 'claude', + parentFilePath: traversal, + executionHostId: 'local' + }) + + expect(result).toEqual({ sessions: [], issues: [] }) + expect(mocks.listClaudeSubagentSessions).not.toHaveBeenCalled() + }) + + it('resolves empty for malformed IPC payloads instead of throwing', async () => { + const missing = await _internals.listAiVaultSubagentSessions(undefined) + const badPath = await _internals.listAiVaultSubagentSessions({ + agent: 'claude', + parentFilePath: 42 as unknown as string, + executionHostId: 'local' + }) + + expect(missing).toEqual({ sessions: [], issues: [] }) + expect(badPath).toEqual({ sessions: [], issues: [] }) + expect(mocks.listClaudeSubagentSessions).not.toHaveBeenCalled() + }) + + it('returns empty for a non-Claude agent', async () => { + const result = await _internals.listAiVaultSubagentSessions({ + agent: 'codex', + parentFilePath: join(claudeRoot, 'proj', 'sess.jsonl'), + executionHostId: 'local' + }) + + expect(result).toEqual({ sessions: [], issues: [] }) + expect(mocks.listClaudeSubagentSessions).not.toHaveBeenCalled() + }) +}) + function hostInfo(targetId: string) { return { targetId, @@ -153,11 +312,18 @@ function session( codexHome: null, createdAt: null, updatedAt: - sessionId === 'remote-session' ? '2026-07-04T02:00:00.000Z' : '2026-07-04T01:00:00.000Z', + sessionId === 'runtime-session' + ? '2026-07-04T03:00:00.000Z' + : sessionId === 'remote-session' + ? '2026-07-04T02:00:00.000Z' + : '2026-07-04T01:00:00.000Z', modifiedAt: '2026-07-04T00:00:00.000Z', messageCount: 1, totalTokens: 0, previewMessages: [], - resumeCommand: `codex resume ${sessionId}` + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: `codex resume ${sessionId}`, + subagent: null } } diff --git a/src/main/ipc/ai-vault.ts b/src/main/ipc/ai-vault.ts index 4551379afde8..5a5dbe0c6ea8 100644 --- a/src/main/ipc/ai-vault.ts +++ b/src/main/ipc/ai-vault.ts @@ -1,18 +1,28 @@ import { app, ipcMain } from 'electron' -import { join } from 'node:path' +import { resolve } from 'node:path' +import { + configureAiVaultSessionSources, + getAiVaultWslHomeDirs, + listAiVaultSessions as listCachedLocalAiVaultSessions, + resetAiVaultSessionListCacheForTests, + type AiVaultSessionSources +} from '../ai-vault/cached-session-list' import { scanRemoteAiVaultSessions } from '../ai-vault/remote-session-scanner' -import { scanAiVaultSessions } from '../ai-vault/session-scanner' -import { sessionSortTime } from '../ai-vault/session-scanner-accumulator' -import { getWslHomeAsync, listWslDistrosAsync } from '../wsl' +import { listClaudeSubagentSessions } from '../ai-vault/session-scanner-claude-subagents' +import { claudeProjectsRootDirs } from '../ai-vault/session-scanner-source-discovery' +import { isPathInsideOrEqual } from '../../shared/cross-platform-path' +import { aiVaultScanIssueResult, mergeAiVaultListResults } from '../ai-vault/session-list-results' import type { AiVaultListArgs, AiVaultListResult, - AiVaultScanIssue + AiVaultSubagentListArgs, + AiVaultSubagentListResult } from '../../shared/ai-vault-types' import { LOCAL_EXECUTION_HOST_ID, normalizeExecutionHostScope, parseExecutionHostId, + toRuntimeExecutionHostId, toSshExecutionHostId, type ExecutionHostScope } from '../../shared/execution-host' @@ -23,9 +33,19 @@ import { import { getActiveSshAiVaultHostInfo, getActiveSshAiVaultHostInfos } from './ssh' const AI_VAULT_CACHE_TTL_MS = 15_000 +const AI_VAULT_ALL_HOST_RUNTIME_TIMEOUT_MS = 3_000 + +type AiVaultHandlerOptions = AiVaultSessionSources & { + getActiveRuntimeAiVaultHostInfos?: () => readonly RuntimeAiVaultHostInfo[] + scanRuntimeAiVaultSessions?: ( + environmentId: string, + args: AiVaultListArgs, + options?: RuntimeAiVaultScanOptions + ) => Promise +} -type AiVaultHandlerOptions = { - getAdditionalCodexHomePaths?: () => readonly string[] +type RuntimeAiVaultScanOptions = { + timeoutMs?: number } type CachedAiVaultList = { @@ -34,6 +54,11 @@ type CachedAiVaultList = { expiresAt: number } +type RuntimeAiVaultHostInfo = { + environmentId: string + executionHostId: `runtime:${string}` +} + let cachedList: CachedAiVaultList | null = null let inflightList: Promise | null = null let inflightKey: string | null = null @@ -43,6 +68,13 @@ async function listAiVaultSessions(args?: AiVaultListArgs): Promise { - if (executionHostScope === LOCAL_EXECUTION_HOST_ID) { - return scanLocalAiVaultSessions(args) - } - if (executionHostScope === 'all') { + const runtimeHosts = getActiveRuntimeAiVaultHostInfosResult() + const runtimeResults = runtimeHosts.issue ? [runtimeHosts.issue] : [] return mergeAiVaultListResults( await Promise.all([ scanLocalAiVaultSessions(args), ...getActiveSshAiVaultHostInfos().map((hostInfo) => scanSshAiVaultSessions(hostInfo.targetId, args) - ) + ), + ...runtimeHosts.hostInfos.map((hostInfo) => + scanRuntimeAiVaultSessions(hostInfo, args, { + timeoutMs: AI_VAULT_ALL_HOST_RUNTIME_TIMEOUT_MS + }) + ), + ...runtimeResults ]), args?.limit ) @@ -104,31 +140,98 @@ async function scanAiVaultSessionsByHostScope( if (parsed?.kind === 'ssh') { return scanSshAiVaultSessions(parsed.targetId, args) } - - return { - sessions: [], - issues: [ + if (parsed?.kind === 'runtime') { + return scanRuntimeAiVaultSessions( { - executionHostId: executionHostScope, - agent: 'codex', - path: executionHostScope, - message: 'Agent Session History is not available for this execution host.' - } - ], - scannedAt: new Date().toISOString() + environmentId: parsed.environmentId, + executionHostId: toRuntimeExecutionHostId(parsed.environmentId) + }, + args + ) + } + + return aiVaultScanIssueResult({ + executionHostId: executionHostScope, + path: executionHostScope, + message: 'Agent Session History is not available for this execution host.' + }) +} + +function getActiveRuntimeAiVaultHostInfos(): readonly RuntimeAiVaultHostInfo[] { + return handlerOptions.getActiveRuntimeAiVaultHostInfos?.() ?? [] +} + +function getActiveRuntimeAiVaultHostInfosResult(): { + hostInfos: readonly RuntimeAiVaultHostInfo[] + issue?: AiVaultListResult +} { + try { + return { hostInfos: getActiveRuntimeAiVaultHostInfos() } + } catch (error) { + return { + hostInfos: [], + issue: runtimeHostDiscoveryIssueResult( + error instanceof Error ? error.message : 'Runtime hosts are unavailable.' + ) + } + } +} + +async function scanRuntimeAiVaultSessions( + hostInfo: RuntimeAiVaultHostInfo, + args?: AiVaultListArgs, + options: RuntimeAiVaultScanOptions = {} +): Promise { + const scanner = handlerOptions.scanRuntimeAiVaultSessions + if (!scanner) { + return runtimeScanIssueResult( + hostInfo, + 'Agent Session History is not available for this execution host.' + ) + } + const scanArgs: AiVaultListArgs = { executionHostScope: hostInfo.executionHostId } + if (args?.limit !== undefined) { + scanArgs.limit = args.limit + } + if (args?.force !== undefined) { + scanArgs.force = args.force + } + if (args?.scopePaths !== undefined) { + scanArgs.scopePaths = args.scopePaths } + try { + return await scanner(hostInfo.environmentId, scanArgs, options) + } catch (error) { + return runtimeScanIssueResult( + hostInfo, + error instanceof Error ? error.message : 'Remote Orca server is unavailable.' + ) + } +} + +function runtimeScanIssueResult( + hostInfo: RuntimeAiVaultHostInfo, + message: string +): AiVaultListResult { + return aiVaultScanIssueResult({ + executionHostId: hostInfo.executionHostId, + path: hostInfo.environmentId, + message + }) +} + +function runtimeHostDiscoveryIssueResult(message: string): AiVaultListResult { + return aiVaultScanIssueResult({ path: 'runtime environments', message }) } async function scanLocalAiVaultSessions(args?: AiVaultListArgs): Promise { - const additionalCodexSessionsDirs = - handlerOptions.getAdditionalCodexHomePaths?.().map((homePath) => join(homePath, 'sessions')) ?? - [] - return scanAiVaultSessions({ + // Why: the shared cache module owns codex-home/WSL sourcing and the local + // scan cache, so the desktop IPC path and the runtime RPC method (mobile) + // share one cache instance and one source of managed-Codex homes. + return listCachedLocalAiVaultSessions({ limit: args?.limit, - scopePaths: args?.scopePaths, - additionalCodexSessionsDirs, - wslHomeDirs: await getAiVaultWslHomeDirs(), - executionHostId: LOCAL_EXECUTION_HOST_ID + force: args?.force, + scopePaths: args?.scopePaths }) } @@ -161,47 +264,28 @@ function sshScanIssueResult(args: { targetId: string message: string }): AiVaultListResult { - return { - sessions: [], - issues: [ - { - executionHostId: args.executionHostId, - agent: 'codex', - path: args.targetId, - message: args.message - } - ], - scannedAt: new Date().toISOString() - } -} - -function mergeAiVaultListResults( - results: readonly AiVaultListResult[], - rawLimit: number | undefined -): AiVaultListResult { - const limit = rawLimit && rawLimit > 0 ? Math.floor(rawLimit) : 1000 - const byId = new Map() - const issues: AiVaultScanIssue[] = [] - for (const result of results) { - for (const session of result.sessions) { - byId.set(session.id, session) - } - issues.push(...result.issues) - } - return { - sessions: [...byId.values()] - .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)) - .slice(0, limit), - issues, - scannedAt: new Date().toISOString() - } + return aiVaultScanIssueResult({ + executionHostId: args.executionHostId, + path: args.targetId, + message: args.message + }) } export function registerAiVaultHandlers(options: AiVaultHandlerOptions = {}): void { handlerOptions = options + // Why: configure the SAME shared cache module the runtime RPC method uses so + // there is exactly one cache instance and neither caller drops codex-home or + // WSL injection. The runtime also configures these sources from its deps + // (serve-mode reachable); this desktop path supplies the same source. + configureAiVaultSessionSources(options) ipcMain.handle('aiVault:listSessions', (_event, args?: AiVaultListArgs) => listAiVaultSessions(args) ) + ipcMain.handle( + 'aiVault:listSubagentSessions', + (_event, args?: AiVaultSubagentListArgs): Promise => + listAiVaultSubagentSessions(args) + ) // DOM focus/visibility events don't fire in the renderer on macOS app // activation, so refresh-on-refocus needs this main-process signal. app.on('browser-window-focus', (_event, window) => { @@ -211,24 +295,52 @@ export function registerAiVaultHandlers(options: AiVaultHandlerOptions = {}): vo }) } +// Provider-gated: only Claude materializes Task subagent transcripts as +// sibling files today; other agents resolve to an empty list. +async function listAiVaultSubagentSessions( + args?: AiVaultSubagentListArgs +): Promise { + // IPC payloads are untyped at runtime; malformed input resolves empty like + // every other rejected input instead of throwing. + if ( + !args || + args.agent !== 'claude' || + typeof args.parentFilePath !== 'string' || + !args.parentFilePath.trim() + ) { + return { sessions: [], issues: [] } + } + // Why: subagent transcripts are read from the local filesystem. The UI + // skips remote sessions (their transcripts live on the remote host); return + // empty defensively rather than reading local paths for a remote session. + const executionHostId = args.executionHostId ?? LOCAL_EXECUTION_HOST_ID + if (executionHostId !== LOCAL_EXECUTION_HOST_ID) { + return { sessions: [], issues: [] } + } + // Why: the path is renderer-supplied; only list files under a known Claude + // projects root so a crafted path can't readdir/preview arbitrary dirs. + // resolve() collapses `..` segments first — isPathInsideOrEqual compares + // textually and would otherwise pass `/../../etc/x.jsonl`. + const parentFilePath = resolve(args.parentFilePath) + const roots = claudeProjectsRootDirs({ wslHomeDirs: await getAiVaultWslHomeDirs() }) + if (!roots.some((root) => isPathInsideOrEqual(resolve(root), parentFilePath))) { + return { sessions: [], issues: [] } + } + return listClaudeSubagentSessions({ parentFilePath }) +} + function resetAiVaultCacheForTests(): void { cachedList = null inflightList = null inflightKey = null handlerOptions = {} + // The local leg delegates to the shared cache module; reset it too so tests + // never see a scan cached by an earlier case. + resetAiVaultSessionListCacheForTests() } export const _internals = { listAiVaultSessions, + listAiVaultSubagentSessions, resetAiVaultCacheForTests } - -async function getAiVaultWslHomeDirs(): Promise { - if (process.platform !== 'win32') { - return [] - } - const homes = await Promise.all( - (await listWslDistrosAsync()).map((distro) => getWslHomeAsync(distro)) - ) - return homes.filter((homeDir): homeDir is string => Boolean(homeDir)) -} diff --git a/src/main/ipc/app.test.ts b/src/main/ipc/app.test.ts index e1149d1b6d17..1eb9bbb17a2a 100644 --- a/src/main/ipc/app.test.ts +++ b/src/main/ipc/app.test.ts @@ -1,3 +1,4 @@ +import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -5,7 +6,7 @@ const { appExitMock, appQuitMock, appRelaunchMock, - execFileMock, + spawnMock, destroySystemTrayMock, showOpenDialogMock, grantFloatingWorkspaceDirectoryMock @@ -14,16 +15,53 @@ const { appExitMock: vi.fn(), appQuitMock: vi.fn(), appRelaunchMock: vi.fn(), - execFileMock: vi.fn(), + spawnMock: vi.fn(), destroySystemTrayMock: vi.fn(), showOpenDialogMock: vi.fn(), grantFloatingWorkspaceDirectoryMock: vi.fn() })) vi.mock('node:child_process', () => ({ - execFile: execFileMock + spawn: spawnMock })) +// Fakes the detached `spawn` child: a stdout EventEmitter plus close/error +// events, so tests drive the async command lifecycle readCommandStdout expects. +function createFakeSpawnChild(options: { + stdout?: string + code?: number + error?: Error + pid?: number + hang?: boolean +}): EventEmitter & { pid: number; kill: ReturnType; stdout: EventEmitter } { + const { stdout, code = 0, error, pid = 4242, hang = false } = options + const child = new EventEmitter() as EventEmitter & { + pid: number + kill: ReturnType + stdout: EventEmitter & { setEncoding: ReturnType } + } + child.pid = pid + child.kill = vi.fn() + const stdoutStream = new EventEmitter() as EventEmitter & { + setEncoding: ReturnType + } + stdoutStream.setEncoding = vi.fn() + child.stdout = stdoutStream + if (!hang) { + queueMicrotask(() => { + if (error) { + child.emit('error', error) + return + } + if (stdout !== undefined) { + stdoutStream.emit('data', stdout) + } + child.emit('close', code) + }) + } + return child +} + vi.mock('electron', () => ({ app: { exit: appExitMock, @@ -63,6 +101,9 @@ import { registerAppHandlers } from './app' describe('registerAppHandlers', () => { const originalPlatform = process.platform + // Why: readCommandStdout process-group-kills on timeout; stub the real signal + // so a fake child pid can never target a live process group during tests. + let processKillSpy: ReturnType beforeEach(() => { vi.useFakeTimers() @@ -70,14 +111,16 @@ describe('registerAppHandlers', () => { appExitMock.mockReset() appQuitMock.mockReset() appRelaunchMock.mockReset() - execFileMock.mockReset() + spawnMock.mockReset() destroySystemTrayMock.mockReset() showOpenDialogMock.mockReset() grantFloatingWorkspaceDirectoryMock.mockReset() + processKillSpy = vi.spyOn(process, 'kill').mockReturnValue(true) Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) }) afterEach(() => { + processKillSpy.mockRestore() vi.useRealTimers() Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) }) @@ -177,10 +220,9 @@ describe('registerAppHandlers', () => { it('returns the selected macOS input mode before the keyboard layout fallback', async () => { Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) - execFileMock.mockImplementation((_command, _args, _options, callback) => { - callback( - null, - JSON.stringify([ + spawnMock.mockImplementation(() => + createFakeSpawnChild({ + stdout: JSON.stringify([ { 'Bundle ID': 'com.apple.PressAndHold', InputSourceKind: 'Non Keyboard Input Method' }, { 'Bundle ID': 'com.apple.inputmethod.SCIM', @@ -188,60 +230,96 @@ describe('registerAppHandlers', () => { InputSourceKind: 'Input Mode' } ]) - ) - return { kill: vi.fn() } - }) + }) + ) registerAppHandlers({} as never) await expect(handlers.get('app:getKeyboardInputSourceId')?.(null)).resolves.toBe( 'com.apple.inputmethod.SCIM.ITABC' ) - expect(execFileMock).toHaveBeenCalledTimes(1) - expect(execFileMock).toHaveBeenCalledWith( - '/usr/bin/plutil', - expect.arrayContaining(['AppleSelectedInputSources']), - expect.any(Object), - expect.any(Function) + expect(spawnMock).toHaveBeenCalledTimes(1) + // Why: macOS 15's `plutil -extract json` aborts on the input-source + // array, so the probe reads live cfprefsd via `defaults export` and dodges + // the bug with an xml1 extract before converting the clean subtree to JSON. + // Pin the exact pipeline (absolute paths, stdin markers) so dropping any + // stage silently regressing CJK detection to the fallback fails the test. + expect(spawnMock).toHaveBeenCalledWith( + '/bin/sh', + [ + '-c', + '/usr/bin/defaults export com.apple.HIToolbox - | ' + + '/usr/bin/plutil -extract AppleSelectedInputSources xml1 -o - - | ' + + '/usr/bin/plutil -convert json -o - -' + ], + expect.objectContaining({ detached: true, stdio: ['ignore', 'pipe', 'ignore'] }) ) }) it('falls back to the keyboard layout when no keyboard input mode is selected', async () => { Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) - execFileMock - .mockImplementationOnce((_command, _args, _options, callback) => { - callback( - null, - JSON.stringify([ + spawnMock + .mockImplementationOnce(() => + createFakeSpawnChild({ + stdout: JSON.stringify([ { 'Bundle ID': 'com.apple.PressAndHold', InputSourceKind: 'Non Keyboard Input Method' } ]) - ) - return { kill: vi.fn() } - }) - .mockImplementationOnce((_command, _args, _options, callback) => { - callback(null, 'com.apple.keylayout.ABC\n') - return { kill: vi.fn() } - }) + }) + ) + .mockImplementationOnce(() => createFakeSpawnChild({ stdout: 'com.apple.keylayout.ABC\n' })) + registerAppHandlers({} as never) + + await expect(handlers.get('app:getKeyboardInputSourceId')?.(null)).resolves.toBe( + 'com.apple.keylayout.ABC' + ) + expect(spawnMock).toHaveBeenCalledTimes(2) + expect(spawnMock).toHaveBeenLastCalledWith( + '/usr/bin/defaults', + ['read', 'com.apple.HIToolbox', 'AppleCurrentKeyboardLayoutInputSourceID'], + expect.objectContaining({ detached: true }) + ) + }) + + it('falls back to the keyboard layout when the selected input source probe exits non-zero', async () => { + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + // Why: reproduces macOS 15's `plutil` abort — the pipeline exits non-zero, so + // the probe rejects on the `close` branch and the handler falls back. + spawnMock + .mockImplementationOnce(() => createFakeSpawnChild({ code: 1 })) + .mockImplementationOnce(() => createFakeSpawnChild({ stdout: 'com.apple.keylayout.ABC\n' })) registerAppHandlers({} as never) await expect(handlers.get('app:getKeyboardInputSourceId')?.(null)).resolves.toBe( 'com.apple.keylayout.ABC' ) - expect(execFileMock).toHaveBeenCalledTimes(2) - expect(execFileMock).toHaveBeenLastCalledWith( + expect(spawnMock).toHaveBeenCalledTimes(2) + expect(spawnMock).toHaveBeenLastCalledWith( '/usr/bin/defaults', ['read', 'com.apple.HIToolbox', 'AppleCurrentKeyboardLayoutInputSourceID'], - expect.any(Object), - expect.any(Function) + expect.objectContaining({ detached: true }) + ) + }) + + it('falls back to the keyboard layout when the selected input source probe fails to spawn', async () => { + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + // Why: a spawn-level failure (ENOENT/EACCES) emits 'error'; the handler must + // still fall back rather than reject out of the IPC call. + spawnMock + .mockImplementationOnce(() => createFakeSpawnChild({ error: new Error('spawn ENOENT') })) + .mockImplementationOnce(() => createFakeSpawnChild({ stdout: 'com.apple.keylayout.ABC\n' })) + registerAppHandlers({} as never) + + await expect(handlers.get('app:getKeyboardInputSourceId')?.(null)).resolves.toBe( + 'com.apple.keylayout.ABC' ) + expect(spawnMock).toHaveBeenCalledTimes(2) }) it('falls back when macOS keyboard input source probes never report completion', async () => { Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) - const killMock = vi.fn() - execFileMock.mockImplementation(() => ({ kill: killMock })) + spawnMock.mockImplementation(() => createFakeSpawnChild({ pid: 4242, hang: true })) registerAppHandlers({} as never) const handler = handlers.get('app:getKeyboardInputSourceId') @@ -256,7 +334,10 @@ describe('registerAppHandlers', () => { expect(settled).toBe(true) await expect(resultPromise).resolves.toBeNull() - expect(killMock).toHaveBeenCalledTimes(2) + // Why: both wedged probes get a process-group SIGKILL (negative pid) so the + // shell and any orphaned `defaults`/`plutil` stages are reaped on timeout. + expect(processKillSpy).toHaveBeenCalledTimes(2) + expect(processKillSpy).toHaveBeenCalledWith(-4242, 'SIGKILL') }) it('picks an existing floating workspace directory without enabling native directory creation', async () => { diff --git a/src/main/ipc/app.ts b/src/main/ipc/app.ts index 276c3ba5f71a..2dc3c81f91b4 100644 --- a/src/main/ipc/app.ts +++ b/src/main/ipc/app.ts @@ -1,6 +1,5 @@ -import { execFile } from 'node:child_process' +import { spawn } from 'node:child_process' import { existsSync } from 'node:fs' -import { homedir } from 'node:os' import path from 'node:path' import { pathToFileURL } from 'node:url' import { app, BrowserWindow, dialog, ipcMain, type IpcMainInvokeEvent } from 'electron' @@ -24,12 +23,15 @@ import { isMarkdownDocumentName, markdownDocumentFromFilePath } from './markdown const KEYBOARD_INPUT_SOURCE_TIMEOUT_MS = 500 const MAC_HITOOLBOX_DOMAIN = 'com.apple.HIToolbox' -const MAC_HITOOLBOX_PREFERENCES_PATH = path.join( - homedir(), - 'Library', - 'Preferences', - `${MAC_HITOOLBOX_DOMAIN}.plist` -) +// Why: macOS 15's `plutil -extract json` aborts on the (pure-string) +// input-source array and the on-disk plist lags cfprefsd; read live prefs via +// `defaults export`, extract as xml1 (dodges the json bug), then convert to JSON. +// Absolute paths so a GUI-launched app's minimal PATH can't shadow the tools. +const MAC_SELECTED_INPUT_SOURCES_JSON_COMMAND = [ + `/usr/bin/defaults export ${MAC_HITOOLBOX_DOMAIN} -`, + '/usr/bin/plutil -extract AppleSelectedInputSources xml1 -o - -', + '/usr/bin/plutil -convert json -o - -' +].join(' | ') type RegisterAppHandlersOptions = { onBeforeRelaunch?: () => void | Promise @@ -118,13 +120,32 @@ function readCommandStdout( ): Promise { return new Promise((resolve, reject) => { let settled = false - let child: ReturnType | undefined + let child: ReturnType | undefined + + // Why: the probe runs a `/bin/sh -c` pipeline, so signaling only the shell + // orphans wedged `defaults`/`plutil` stages on a stuck cfprefsd. Spawning + // detached makes the child a process-group leader, so one negative-pid + // SIGKILL reaps the shell and every stage; child.kill() covers the fallback. + const killTree = (): void => { + if (!child?.pid) { + return + } + try { + process.kill(-child.pid, 'SIGKILL') + } catch { + child.kill() + } + } + + // Why: short timeout so a wedged macOS preference probe (corporate-managed + // config, sandbox policy, ...) never holds the handle indefinitely. This + // manual timer is the only timeout guard, so it owns the process-group kill. const timer = setTimeout(() => { if (settled) { return } settled = true - child?.kill() + killTree() reject(new Error(timeoutMessage)) }, KEYBOARD_INPUT_SOURCE_TIMEOUT_MS) @@ -137,24 +158,32 @@ function readCommandStdout( callback() } - // Why: execFile's timeout only signals `defaults`; if the callback - // never arrives, window-focus keyboard probes would remain pending. try { - child = execFile( - command, - args, - // Why: short timeout so a wedged macOS preference probe (corporate-managed - // config, sandbox policy, ...) never holds the handle indefinitely. - // Fall through to the fingerprint on timeout. - { encoding: 'utf8', timeout: KEYBOARD_INPUT_SOURCE_TIMEOUT_MS }, - (error, stdout) => { - if (error) { - settle(() => reject(error)) - return - } - settle(() => resolve(String(stdout ?? ''))) - } - ) + child = spawn(command, args, { detached: true, stdio: ['ignore', 'pipe', 'ignore'] }) + let stdout = '' + child.stdout?.setEncoding('utf8') + child.stdout?.on('data', (chunk: string) => { + stdout += chunk + }) + const failWith = (error: Error): void => { + killTree() + settle(() => reject(error)) + } + // Why: an unhandled Readable 'error' would crash the main process; treat a + // stdout read failure the same as a child spawn error. + child.stdout?.on('error', failWith) + child.on('error', failWith) + child.on('close', (code, signal) => { + settle(() => + code === 0 + ? resolve(stdout) + : reject( + new Error( + `${command} exited with ${signal ? `signal ${signal}` : `code ${code ?? 'unknown'}`}` + ) + ) + ) + }) } catch (error) { settle(() => reject(error)) } @@ -196,8 +225,8 @@ function readSelectedInputSourceIdFromJson(stdout: string): string | null { async function readSelectedKeyboardInputSourceId(): Promise { try { const stdout = await readCommandStdout( - '/usr/bin/plutil', - ['-extract', 'AppleSelectedInputSources', 'json', '-o', '-', MAC_HITOOLBOX_PREFERENCES_PATH], + '/bin/sh', + ['-c', MAC_SELECTED_INPUT_SOURCES_JSON_COMMAND], 'Selected keyboard input source probe timed out' ) return readSelectedInputSourceIdFromJson(stdout) diff --git a/src/main/ipc/filesystem-list-files-git-directory-expansion.test.ts b/src/main/ipc/filesystem-list-files-git-directory-expansion.test.ts new file mode 100644 index 000000000000..5d5cf1637465 --- /dev/null +++ b/src/main/ipc/filesystem-list-files-git-directory-expansion.test.ts @@ -0,0 +1,103 @@ +import { EventEmitter } from 'node:events' +import type { ChildProcess } from 'node:child_process' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +const { gitSpawnMock } = vi.hoisted(() => ({ + gitSpawnMock: vi.fn() +})) + +vi.mock('../git/runner', () => ({ + gitSpawn: gitSpawnMock +})) + +import { listFilesWithGit } from './filesystem-list-files-git-fallback' +import { isFileListingCancellation } from '../../shared/file-listing-cancellation' + +const tempDirs: string[] = [] +const SHA1 = '0123456789abcdef0123456789abcdef01234567' + +function createMockProcess(): ChildProcess { + const process = new EventEmitter() as unknown as ChildProcess + ;(process as unknown as Record).stdout = new EventEmitter() + ;( + (process as unknown as Record).stdout as EventEmitter & { + setEncoding: () => void + } + ).setEncoding = vi.fn() + ;(process as unknown as Record).stderr = new EventEmitter() + ;(process as unknown as Record).kill = vi.fn() + ;(process as unknown as Record).exitCode = null + ;(process as unknown as Record).signalCode = null + return process +} + +async function writeRel(root: string, relPath: string): Promise { + const absPath = join(root, ...relPath.split('/')) + await mkdir(dirname(absPath), { recursive: true }) + await writeFile(absPath, 'x') +} + +afterEach(async () => { + vi.clearAllMocks() + await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))) +}) + +describe('main Quick Open git directory expansion', () => { + it('expands placeholders emitted by both directory-collapsing passes', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-main-git-ignored-dir-')) + tempDirs.push(root) + await writeRel(root, 'dist/generated.js') + await writeRel(root, 'scratch/notes.txt') + + const revParse = createMockProcess() + const primary = createMockProcess() + const ignored = createMockProcess() + gitSpawnMock + .mockReturnValueOnce(revParse) + .mockReturnValueOnce(primary) + .mockReturnValueOnce(ignored) + + const promise = listFilesWithGit(root, [], {}) + revParse.emit('close', 0, null) + await vi.waitFor(() => expect(gitSpawnMock).toHaveBeenCalledTimes(3)) + ;(primary.stdout as unknown as EventEmitter).emit( + 'data', + `100644 ${SHA1} 0\tsrc/index.ts\0scratch/\0` + ) + primary.emit('close', 0, null) + ;(ignored.stdout as unknown as EventEmitter).emit('data', 'dist/\0') + ignored.emit('close', 0, null) + + await expect(promise).resolves.toEqual([ + 'dist/generated.js', + 'scratch/notes.txt', + 'src/index.ts' + ]) + expect(gitSpawnMock.mock.calls[2][0]).toContain('--directory') + }) + + it('cancels both local Git passes when Quick Open abandons the request', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-main-git-cancel-')) + tempDirs.push(root) + const revParse = createMockProcess() + const primary = createMockProcess() + const ignored = createMockProcess() + gitSpawnMock + .mockReturnValueOnce(revParse) + .mockReturnValueOnce(primary) + .mockReturnValueOnce(ignored) + + const controller = new AbortController() + const promise = listFilesWithGit(root, [], {}, controller.signal) + revParse.emit('close', 0, null) + await vi.waitFor(() => expect(gitSpawnMock).toHaveBeenCalledTimes(3)) + controller.abort() + + await expect(promise).rejects.toSatisfy(isFileListingCancellation) + expect(primary.kill).toHaveBeenCalled() + expect(ignored.kill).toHaveBeenCalled() + }) +}) diff --git a/src/main/ipc/filesystem-list-files-git-fallback.ts b/src/main/ipc/filesystem-list-files-git-fallback.ts index 3b77ac28131d..616a9a10c932 100644 --- a/src/main/ipc/filesystem-list-files-git-fallback.ts +++ b/src/main/ipc/filesystem-list-files-git-fallback.ts @@ -3,9 +3,10 @@ import { gitSpawn } from '../git/runner' import { buildGitLsFilesArgsForQuickOpen } from '../../shared/quick-open-filter' import { createQuickOpenReaddirBudget, - expandQuickOpenGitFilesWithNestedRepos, + expandQuickOpenGitFileListing, listQuickOpenFilesWithReaddir } from '../../shared/quick-open-readdir-walk' +import { fileListingCancellationError } from '../../shared/file-listing-cancellation' /** * Fallback file lister using git ls-files. Used when rg is not available. @@ -16,9 +17,13 @@ import { */ async function isInsideGitWorkTree( rootPath: string, - localGitOptions: { wslDistro?: string } + localGitOptions: { wslDistro?: string }, + signal?: AbortSignal ): Promise { - return new Promise((resolve) => { + if (signal?.aborted) { + throw fileListingCancellationError(signal) + } + return new Promise((resolve, reject) => { const child = gitSpawn(['rev-parse', '--is-inside-work-tree'], { cwd: rootPath, ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}), @@ -26,22 +31,37 @@ async function isInsideGitWorkTree( }) let done = false let timer: ReturnType + const cleanup = (): void => { + clearTimeout(timer) + child.off('error', handleError) + child.off('close', handleClose) + signal?.removeEventListener('abort', handleAbort) + } const finish = (isGitRepo: boolean): void => { if (done) { return } done = true - clearTimeout(timer) - child.off('error', handleError) - child.off('close', handleClose) + cleanup() resolve(isGitRepo) } + const cancel = (): void => { + if (done) { + return + } + done = true + child.kill() + cleanup() + reject(fileListingCancellationError(signal)) + } const handleError = (): void => finish(false) const handleClose = (code: number | null, signal: NodeJS.Signals | null): void => finish(code === 0 && signal === null) + const handleAbort = (): void => cancel() child.once('error', handleError) child.once('close', handleClose) + signal?.addEventListener('abort', handleAbort, { once: true }) timer = setTimeout(() => { child.kill() finish(false) @@ -52,16 +72,23 @@ async function isInsideGitWorkTree( export async function listFilesWithGit( rootPath: string, excludePathPrefixes: readonly string[], - localGitOptions: { wslDistro?: string } + localGitOptions: { wslDistro?: string }, + signal?: AbortSignal ): Promise { - if (!(await isInsideGitWorkTree(rootPath, localGitOptions))) { + const isGitWorkTree = await isInsideGitWorkTree(rootPath, localGitOptions, signal) + if (signal?.aborted) { + throw fileListingCancellationError(signal) + } + if (!isGitWorkTree) { return listQuickOpenFilesWithReaddir(rootPath, { excludePathPrefixes, - budget: createQuickOpenReaddirBudget() + budget: createQuickOpenReaddirBudget(), + signal }) } const gitPaths = new Set() + const directoryPaths = new Set() const { primary, ignoredPass } = buildGitLsFilesArgsForQuickOpen(excludePathPrefixes) const children: { child: ChildProcess @@ -78,7 +105,11 @@ export async function listFilesWithGit( if (!path) { return } - gitPaths.add(path) + if (path.endsWith('/')) { + directoryPaths.add(path) + } else { + gitPaths.add(path) + } } // Why: git ls-files outputs paths relative to cwd, so we set cwd to @@ -168,7 +199,7 @@ export async function listFilesWithGit( }) } - const killSurvivors = (): void => { + const killSurvivors = (reason = 'git ls-files canceled after sibling failure'): void => { // Why: Promise.all rejects on the first failed pass; cancel the sibling so // a stuck git process cannot keep scanning after Quick Open has failed. for (const entry of children) { @@ -178,20 +209,44 @@ export async function listFilesWithGit( if (entry.child.exitCode === null && entry.child.signalCode === null) { entry.child.kill() } - entry.reject(new Error('git ls-files canceled after sibling failure')) + entry.reject(new Error(reason)) } } + const onAbort = (): void => killSurvivors('git ls-files cancelled') + signal?.addEventListener('abort', onAbort, { once: true }) try { - await Promise.all([runGitLsFiles(primary), runGitLsFiles(ignoredPass)]) + await Promise.all([ + runGitLsFiles(primary), + // Why: ignored files are supplementary — a failed or timed-out ignored + // pass must not discard the primary listing the user actually needs + // (#7719 root cause: the all-or-nothing failure showed zero files). + // Entries streamed before the failure are kept; a cancelled scan still + // rejects via the primary pass or the expansion's cancellation check. + runGitLsFiles(ignoredPass).catch((err: Error) => { + if (!signal?.aborted) { + console.warn('[quick-open] git ignored-file pass failed; keeping primary results:', err) + } + }) + ]) } catch (err) { killSurvivors() + if (signal?.aborted) { + throw fileListingCancellationError(signal) + } throw err + } finally { + signal?.removeEventListener('abort', onAbort) } - return expandQuickOpenGitFilesWithNestedRepos({ + const files = await expandQuickOpenGitFileListing({ rootPath, gitPaths, - excludePathPrefixes + directoryPaths, + excludePathPrefixes, + signal }) + // Why: directory placeholders are expanded after Git exits; restore Git's + // path order so empty queries and fuzzy-score ties remain stable. + return files.sort() } diff --git a/src/main/ipc/filesystem-list-files.test.ts b/src/main/ipc/filesystem-list-files.test.ts index 638775a4811a..ba535a258681 100644 --- a/src/main/ipc/filesystem-list-files.test.ts +++ b/src/main/ipc/filesystem-list-files.test.ts @@ -365,6 +365,9 @@ describe('filesystem-list-files', () => { expect(gitCalls.length).toBe(2) expect(gitCalls[0][1]).toContain('ls-files') expect(gitCalls[0][1]).toContain('-s') + expect(gitCalls[0][1]).toContain('--directory') + expect(gitCalls[1][1]).toContain('--directory') + expect(gitCalls[1][1]).toContain('--no-empty-directory') // Should include valid files and filter node_modules expect(result).toContain('src/index.ts') @@ -472,6 +475,60 @@ describe('filesystem-list-files', () => { } }) + it('keeps primary results when only the ignored pass times out', async () => { + checkRgAvailableMock.mockResolvedValue(false) + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.useFakeTimers() + + try { + const revParseProc = createMockProcess() + const gitP1 = createMockProcess() + const gitP2 = createMockProcess() + let callIndex = 0 + + spawnMock.mockImplementation((cmd: string, args: string[]) => { + if (cmd === 'git' && args.includes('rev-parse')) { + return revParseProc + } + if (cmd === 'git' && args.includes('ls-files')) { + callIndex++ + return callIndex === 1 ? gitP1 : gitP2 + } + return createMockProcess() + }) + + const storeMock = {} as unknown as Store + const promise = listQuickOpenFiles('/mock/root', storeMock) + + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + revParseProc.emit('close', 0, null) + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + + ;(gitP1.stdout as unknown as EventEmitter).emit( + 'data', + `${staged('100644', 'src/index.ts')}\0` + ) + gitP1.emit('close', 0, null) + // Ignored entries streamed before the timeout are kept. + ;(gitP2.stdout as unknown as EventEmitter).emit('data', 'dist/generated.js\0') + + await vi.advanceTimersByTimeAsync(10000) + + await expect(promise).resolves.toEqual( + expect.arrayContaining(['src/index.ts', 'dist/generated.js']) + ) + expect(gitP2.kill).toHaveBeenCalled() + expect(warnSpy).toHaveBeenCalled() + } finally { + vi.useRealTimers() + warnSpy.mockRestore() + } + }) + it('does not fall back to git when rg is available', async () => { checkRgAvailableMock.mockResolvedValue(true) diff --git a/src/main/ipc/filesystem-list-files.ts b/src/main/ipc/filesystem-list-files.ts index 363762273052..9dcd2c450382 100644 --- a/src/main/ipc/filesystem-list-files.ts +++ b/src/main/ipc/filesystem-list-files.ts @@ -19,7 +19,8 @@ import { listFilesWithGit } from './filesystem-list-files-git-fallback' export async function listQuickOpenFiles( rootPath: string, store: Store, - excludePaths?: string[] + excludePaths?: string[], + signal?: AbortSignal ): Promise { const authorizedRootPath = await resolveAuthorizedPath(rootPath, store) const localGitOptions = getLocalGitOptionsForRegisteredWorktree( @@ -40,7 +41,7 @@ export async function listQuickOpenFiles( // can run. const rgAvailable = await checkRgAvailable(authorizedRootPath, localGitOptions.wslDistro) if (!rgAvailable) { - return listFilesWithGit(authorizedRootPath, excludePathPrefixes, localGitOptions) + return listFilesWithGit(authorizedRootPath, excludePathPrefixes, localGitOptions, signal) } const files = new Set() diff --git a/src/main/ipc/filesystem-watcher-ignore.test.ts b/src/main/ipc/filesystem-watcher-ignore.test.ts index 6a3ab329fefc..28f90a53a04d 100644 --- a/src/main/ipc/filesystem-watcher-ignore.test.ts +++ b/src/main/ipc/filesystem-watcher-ignore.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { MACOS_FSEVENTS_EXCLUSION_PATH_LIMIT, WATCHER_IGNORE_DIRS, - buildParcelWatcherIgnoreOption + buildParcelWatcherIgnoreOptions } from './filesystem-watcher-ignore' const realPlatform = process.platform @@ -11,39 +11,45 @@ function setPlatform(platform: NodeJS.Platform): void { Object.defineProperty(process, 'platform', { value: platform }) } -describe('buildParcelWatcherIgnoreOption', () => { +describe('buildParcelWatcherIgnoreOptions', () => { afterEach(() => { setPlatform(realPlatform) }) it('keeps at most 8 plain paths on macOS so FSEventStreamSetExclusionPaths succeeds', () => { setPlatform('darwin') - const option = buildParcelWatcherIgnoreOption(WATCHER_IGNORE_DIRS) + const options = buildParcelWatcherIgnoreOptions(WATCHER_IGNORE_DIRS) + const option = options.ignore ?? [] // @parcel/watcher passes non-glob entries to FSEventStreamSetExclusionPaths, // which rejects the WHOLE set past 8 paths — silently disabling daemon-side // exclusion of node_modules/.git churn. const plainPaths = option.filter((entry) => !entry.includes('*')) expect(plainPaths.length).toBeLessThanOrEqual(MACOS_FSEVENTS_EXCLUSION_PATH_LIMIT) - // Every ignore dir must still be covered, as a path or as a glob. - for (const dir of WATCHER_IGNORE_DIRS) { - expect( - option.some((entry) => entry === dir || entry === `**/${dir}` || entry === `**/${dir}/**`) - ).toBe(true) + expect(option).toEqual(WATCHER_IGNORE_DIRS.slice(0, MACOS_FSEVENTS_EXCLUSION_PATH_LIMIT)) + const fallbackRegex = new RegExp(options.ignoreGlobs?.[0] ?? '(?!)') + for (const dir of WATCHER_IGNORE_DIRS.slice(MACOS_FSEVENTS_EXCLUSION_PATH_LIMIT)) { + expect(fallbackRegex.test(`packages/app/${dir}/file.ts`)).toBe(true) } + expect(options.ignoreGlobs?.[0]).not.toContain('?!') }) - it('expands to nested globs on Linux/Windows so nested node_modules/.git are excluded', () => { + it('uses one lookahead-free native regex for nested ignores on Linux/Windows', () => { for (const platform of ['linux', 'win32'] as const) { setPlatform(platform) - const option = buildParcelWatcherIgnoreOption(WATCHER_IGNORE_DIRS) - // @parcel/watcher resolves plain names to top-level-only absolute paths on - // these platforms, so nested dirs must be matched via depth-agnostic globs. + const options = buildParcelWatcherIgnoreOptions(WATCHER_IGNORE_DIRS) + expect(options.ignore).toBeUndefined() + expect(options.ignoreGlobs).toHaveLength(1) + const source = options.ignoreGlobs![0] + expect(source).not.toContain('?!') + const regex = new RegExp(source) for (const dir of WATCHER_IGNORE_DIRS) { - expect(option).toContain(`**/${dir}`) - expect(option).toContain(`**/${dir}/**`) + expect(regex.test(dir)).toBe(true) + expect(regex.test(`packages/app/${dir}`)).toBe(true) + expect(regex.test(`packages\\app\\${dir}\\nested\\file.ts`)).toBe(platform === 'win32') } - // No plain (glob-free) entries — those would only exclude the top level. - expect(option.every((entry) => entry.includes('*'))).toBe(true) + expect(regex.test('packages/app/.github/workflows')).toBe(false) + expect(regex.test('packages/app/node_modules-cache/file.ts')).toBe(false) + expect(regex.test('project\\node_modules/file.ts')).toBe(platform === 'win32') } }) }) diff --git a/src/main/ipc/filesystem-watcher-ignore.ts b/src/main/ipc/filesystem-watcher-ignore.ts index 9828f4a59119..7c483814c30e 100644 --- a/src/main/ipc/filesystem-watcher-ignore.ts +++ b/src/main/ipc/filesystem-watcher-ignore.ts @@ -23,19 +23,42 @@ export const WATCHER_IGNORE_DIRS: string[] = [ // therefore meaningful: the first 8 get true daemon-side exclusion on macOS. export const MACOS_FSEVENTS_EXCLUSION_PATH_LIMIT = 8 -export function buildParcelWatcherIgnoreOption(ignoreDirs: readonly string[]): string[] { +export type ParcelWatcherIgnoreOptions = { + ignore?: string[] + // @parcel/watcher's wrapper preserves this native option even though its + // public TypeScript declaration omits it. See parcel-bundler/watcher#244. + ignoreGlobs?: string[] +} + +function escapeRegex(value: string): string { + return value.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') +} + +function buildNestedDirectoryRegex(ignoreDirs: readonly string[]): string { + const alternatives = ignoreDirs.map(escapeRegex).join('|') + if (process.platform === 'win32') { + return `^(?:[^\\\\/]+[\\\\/])*(?:${alternatives})(?:[\\\\/].*)?$` + } + // Why: backslash is a legal POSIX filename character, not a path separator. + return `^(?:[^/]+/)*(?:${alternatives})(?:/.*)?$` +} + +export function buildParcelWatcherIgnoreOptions( + ignoreDirs: readonly string[] +): ParcelWatcherIgnoreOptions { + if (ignoreDirs.length === 0) { + return {} + } if (process.platform !== 'darwin') { - // Linux/Windows: @parcel/watcher resolves plain names to top-level-only - // absolute paths, so nested node_modules/.git/build/etc. (monorepos) get - // fully watched — on Linux that means one inotify watch per nested dir, - // exhausting fs.inotify.max_user_watches. Nested globs match at any depth - // (and **/dir still matches the top-level dir), pruning those subtrees. - return ignoreDirs.flatMap((dir) => [`**/${dir}`, `**/${dir}/**`]) + // Why: Parcel 2.5.6 turns leading-** globs into nested-lookahead regexes + // that are pathological in native std::regex (10-17x slower upstream). + // One component-aware regex preserves nested pruning without that CPU cost. + return { ignoreGlobs: [buildNestedDirectoryRegex(ignoreDirs)] } + } + const daemonExcludedDirs = ignoreDirs.slice(0, MACOS_FSEVENTS_EXCLUSION_PATH_LIMIT) + const remainingDirs = ignoreDirs.slice(MACOS_FSEVENTS_EXCLUSION_PATH_LIMIT) + return { + ignore: [...daemonExcludedDirs], + ...(remainingDirs.length > 0 ? { ignoreGlobs: [buildNestedDirectoryRegex(remainingDirs)] } : {}) } - return [ - ...ignoreDirs.slice(0, MACOS_FSEVENTS_EXCLUSION_PATH_LIMIT), - ...ignoreDirs - .slice(MACOS_FSEVENTS_EXCLUSION_PATH_LIMIT) - .flatMap((dir) => [`**/${dir}`, `**/${dir}/**`]) - ] } diff --git a/src/main/ipc/filesystem-watcher.ts b/src/main/ipc/filesystem-watcher.ts index 51cbfbaefc6b..224c348b8716 100644 --- a/src/main/ipc/filesystem-watcher.ts +++ b/src/main/ipc/filesystem-watcher.ts @@ -13,11 +13,12 @@ import { createWslWatcher } from './filesystem-watcher-wsl' import type { WatchedRoot } from './filesystem-watcher-wsl' import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' import { MAX_BATCHED_WATCHER_EVENTS, queueWatcherEvents } from './filesystem-watcher-event-batch' +import { disposeWatcherProcess, subscribeViaWatcherProcess } from './parcel-watcher-process' // Why: high-churn directories are suppressed at the native watcher level so // events never leave the OS/daemon. This list is separate from the File // Explorer display filter (which only hides rows). Directories like `dist` // and `build` remain visible in the tree but will not auto-refresh. -import { WATCHER_IGNORE_DIRS, buildParcelWatcherIgnoreOption } from './filesystem-watcher-ignore' +import { WATCHER_IGNORE_DIRS, buildParcelWatcherIgnoreOptions } from './filesystem-watcher-ignore' // ── Debounce helpers ───────────────────────────────────────────────── @@ -278,10 +279,6 @@ function scheduleBatchFlush(rootKey: string, root: WatchedRoot): void { // ── Watcher creation ───────────────────────────────────────────────── async function createWatcher(rootKey: string, rootPath: string): Promise { - // Why: @parcel/watcher is a native module that may not load in all - // environments. Dynamic import keeps the require() lazy. - const watcher = await import('@parcel/watcher') - const root: WatchedRoot = { subscription: null!, listeners: new Map(), @@ -296,14 +293,18 @@ async function createWatcher(rootKey: string, rootPath: string): Promise { if (err) { @@ -334,7 +335,13 @@ async function createWatcher(rootKey: string, rootPath: string): Promise { + // The watcher process crashed and this root was resubscribed; events + // during the gap are lost, so hand the renderer an overflow refresh. + root.batch.overflowed = true + scheduleBatchFlush(rootKey, root) + } ) // Why: if the error callback already fired and cleaned up watchedRoots @@ -929,6 +936,10 @@ export async function closeAllWatchers(): Promise { } watchedRoots.clear() await Promise.allSettled(Array.from(pendingLocalUnsubscribes)) + // Why: with every local subscription released, drop the forked watcher + // process outright — process death frees any remaining native handles + // without running watcher.node's crash-prone async teardown in this process. + disposeWatcherProcess() // Why: remote watchers are tracked separately from local @parcel/watcher // subscriptions. Without cleaning them up here, their unwatch callbacks diff --git a/src/main/ipc/filesystem.test.ts b/src/main/ipc/filesystem.test.ts index 25894ffb7231..072f8239dcb8 100644 --- a/src/main/ipc/filesystem.test.ts +++ b/src/main/ipc/filesystem.test.ts @@ -2316,4 +2316,39 @@ describe('registerFilesystemHandlers', () => { excludePaths: ['/home/user/repo/worktrees/feature'] }) }) + + // Why #7721: without a cancel path, every workspace switch left the previous + // workspace's full-tree SSH scan running, stacking scans on the relay until + // interactive fs.readDir/fs.stat starved past their 30s timeout. + it('fs:cancelListFiles aborts an in-flight SSH listing by request token (#7721)', async () => { + let capturedSignal: AbortSignal | undefined + const listFilesMock = vi.fn( + (_rootPath: string, options: { signal?: AbortSignal }) => + new Promise((_resolve, reject) => { + capturedSignal = options.signal + options.signal?.addEventListener('abort', () => reject(new Error('listing cancelled')), { + once: true + }) + }) + ) + getSshFilesystemProviderMock.mockReturnValue({ listFiles: listFilesMock }) + + registerFilesystemHandlers(store as never) + + const pending = handlers.get('fs:listFiles')!(null, { + rootPath: '/home/user/repo', + connectionId: 'conn-1', + requestToken: 'token-1' + }) as Promise + + expect(capturedSignal?.aborted).toBe(false) + await handlers.get('fs:cancelListFiles')!(null, { requestToken: 'token-1' }) + expect(capturedSignal?.aborted).toBe(true) + await expect(pending).rejects.toThrow('listing cancelled') + + // Unknown or already-settled tokens are a no-op, not an error. + expect(() => + handlers.get('fs:cancelListFiles')!(null, { requestToken: 'unknown' }) + ).not.toThrow() + }) }) diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts index 85c0ce56e311..100245dca8b1 100644 --- a/src/main/ipc/filesystem.ts +++ b/src/main/ipc/filesystem.ts @@ -1026,30 +1026,57 @@ export function registerFilesystemHandlers( ) // ─── List all files (for quick-open) ───────────────────── + // Why #7721: keyed by renderer-generated token so a workspace switch can + // abort the previous workspace's full-tree scan (SSH relays otherwise stack + // scans that starve interactive fs.readDir/fs.stat past their 30s timeout). + const listFilesCancellations = new Map() ipcMain.handle( 'fs:listFiles', async ( _event, - args: { rootPath: string; connectionId?: string; excludePaths?: string[] } + args: { + rootPath: string + connectionId?: string + excludePaths?: string[] + requestToken?: string + } ): Promise => { - if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - // Why: when the SSH connection is not yet established (cold start) or - // temporarily disconnected, return [] so quick-open shows "No matching - // files" instead of an error banner. The file list will repopulate when - // the user re-opens quick-open after the connection is restored. - if (!provider) { - return [] + const controller = args.requestToken ? new AbortController() : null + if (controller && args.requestToken) { + listFilesCancellations.set(args.requestToken, controller) + } + try { + if (args.connectionId) { + const provider = getSshFilesystemProvider(args.connectionId) + // Why: when the SSH connection is not yet established (cold start) or + // temporarily disconnected, return [] so quick-open shows "No matching + // files" instead of an error banner. The file list will repopulate when + // the user re-opens quick-open after the connection is restored. + if (!provider) { + return [] + } + // Why: forward excludePaths through to the remote provider. + // Dropping it here would silently double-scan nested linked worktrees + // over SSH and contribute to timeout-induced partial results. + return await provider.listFiles(args.rootPath, { + excludePaths: args.excludePaths, + signal: controller?.signal + }) + } + return await listQuickOpenFiles(args.rootPath, store, args.excludePaths, controller?.signal) + } finally { + if (args.requestToken) { + listFilesCancellations.delete(args.requestToken) } - // Why: forward excludePaths through to the remote provider. - // Dropping it here would silently double-scan nested linked worktrees - // over SSH and contribute to timeout-induced partial results. - return provider.listFiles(args.rootPath, { excludePaths: args.excludePaths }) } - return listQuickOpenFiles(args.rootPath, store, args.excludePaths) } ) + ipcMain.handle('fs:cancelListFiles', (_event, args: { requestToken: string }): void => { + // Why: best-effort — the entry is gone once the listing settles. + listFilesCancellations.get(args.requestToken)?.abort() + }) + // ─── Git operations ───────────────────────────────────── ipcMain.handle( 'git:status', diff --git a/src/main/ipc/grok-accounts.ts b/src/main/ipc/grok-accounts.ts new file mode 100644 index 000000000000..8b0aa69f2a3c --- /dev/null +++ b/src/main/ipc/grok-accounts.ts @@ -0,0 +1,6 @@ +import { ipcMain } from 'electron' +import { getGrokAccountStatus } from '../grok-accounts/status' + +export function registerGrokAccountHandlers(): void { + ipcMain.handle('grokAccounts:getStatus', () => getGrokAccountStatus()) +} diff --git a/src/main/ipc/jira.ts b/src/main/ipc/jira.ts index e8ed17f9bfe1..e4a0e7ff8950 100644 --- a/src/main/ipc/jira.ts +++ b/src/main/ipc/jira.ts @@ -6,6 +6,7 @@ import { createIssue, getIssue, getIssueComments, + getProjectStatusOrder, listAssignableUsers, listCreateFields, listIssueTypes, @@ -259,4 +260,14 @@ export function registerJiraHandlers(): void { } return listTransitions(args.key.trim(), normalizeSiteId(args.siteId)) }) + + ipcMain.handle( + 'jira:getProjectStatusOrder', + async (_event, args: { projectKey: string; siteId?: string }) => { + if (typeof args?.projectKey !== 'string' || !args.projectKey.trim()) { + return { statusIdsByColumn: [] } + } + return getProjectStatusOrder(args.projectKey.trim(), normalizeSiteId(args.siteId)) + } + ) } diff --git a/src/main/ipc/linear.test.ts b/src/main/ipc/linear.test.ts index 1f52cb08265c..d022497486b2 100644 --- a/src/main/ipc/linear.test.ts +++ b/src/main/ipc/linear.test.ts @@ -97,7 +97,43 @@ describe('registerLinearHandlers', () => { workspaceId: 'workspace-1' }) - expect(listIssuesMock).toHaveBeenCalledWith('all', 216, 'workspace-1') + expect(listIssuesMock).toHaveBeenCalledWith('all', 216, 'workspace-1', { + attributeFilter: undefined + }) + }) + + it('parses attribute filters and rejects malformed payloads before listIssues', async () => { + listIssuesMock.mockResolvedValue({ items: [], hasMore: false }) + registerLinearHandlers() + + await handlers['linear:listIssues'](null, { + filter: 'all', + limit: 20, + workspaceId: 'workspace-1', + attributeFilter: { + stateIds: ['state-1'], + priorities: [1], + assignee: { kind: 'unassigned' }, + labelIds: [] + } + }) + expect(listIssuesMock).toHaveBeenCalledWith('all', 20, 'workspace-1', { + attributeFilter: { + stateIds: ['state-1'], + priorities: [1], + assignee: { kind: 'unassigned' }, + labelIds: [] + } + }) + + listIssuesMock.mockClear() + await expect( + handlers['linear:listIssues'](null, { + filter: 'all', + attributeFilter: { stateIds: [] } + }) + ).rejects.toThrow(/required/) + expect(listIssuesMock).not.toHaveBeenCalled() }) it('forwards expanded Linear project issue limits through local IPC', async () => { diff --git a/src/main/ipc/linear.ts b/src/main/ipc/linear.ts index 1cf04dbb5581..2e70cd0564d0 100644 --- a/src/main/ipc/linear.ts +++ b/src/main/ipc/linear.ts @@ -25,6 +25,7 @@ import { import { listTeams, getTeamStates, getTeamLabels, getTeamMembers } from '../linear/teams' import type { LinearListFilter } from '../linear/issues' import { clampLinearIssueListLimit } from '../../shared/linear-issue-read-limits' +import { optionalParsedLinearIssueAttributeFilter } from '../../shared/linear-issue-attribute-filter' import type { LinearCustomViewModel, LinearIssueUpdate, @@ -131,13 +132,26 @@ export function registerLinearHandlers(): void { 'linear:listIssues', async ( _event, - args?: { filter?: LinearListFilter; limit?: number; workspaceId?: LinearWorkspaceSelection } + args?: { + filter?: LinearListFilter + limit?: number + workspaceId?: LinearWorkspaceSelection + attributeFilter?: unknown + } ) => { const filter = VALID_FILTERS.has(args?.filter as LinearListFilter) ? (args!.filter as LinearListFilter) : undefined const limit = clampLinearIssueListLimit(args?.limit) - return listIssues(filter, limit, normalizeWorkspaceSelection(args?.workspaceId)) + // Why: reject malformed filters at the trust boundary instead of + // normalizing them to empty (which would silently broaden results). + const attributeFilter = + args && 'attributeFilter' in args && args.attributeFilter !== undefined + ? optionalParsedLinearIssueAttributeFilter(args.attributeFilter) + : undefined + return listIssues(filter, limit, normalizeWorkspaceSelection(args?.workspaceId), { + attributeFilter + }) } ) diff --git a/src/main/ipc/notification-authorization-status.ts b/src/main/ipc/notification-authorization-status.ts new file mode 100644 index 000000000000..d51f97ede17b --- /dev/null +++ b/src/main/ipc/notification-authorization-status.ts @@ -0,0 +1,92 @@ +import { execFile } from 'node:child_process' +import { existsSync } from 'node:fs' +import { dirname, join } from 'node:path' + +export type NotificationAuthorizationStatus = 'authorized' | 'denied' | 'not-determined' | 'unknown' + +const HELPER_EXECUTABLE = 'orca-notification-status' +const HELPER_TIMEOUT_MS = 4000 + +let cachedHelperPath: string | null | undefined + +/** + * Resolves the bundled notification-status helper binary. + * + * Why: the helper must live in Contents/MacOS next to the Electron executable + * — NSBundle resolves the process's bundle by walking up from the executable + * path, macOS keys notification records to that identity, and macOS 26 aborts + * UNUserNotificationCenter for executables run from Contents/Resources + * (#7929). Dev copies and packaged builds (extraFiles) both place it there. + */ +function resolveHelperPath(): string | null { + if (cachedHelperPath !== undefined) { + return cachedHelperPath + } + if (process.platform !== 'darwin') { + cachedHelperPath = null + return cachedHelperPath + } + const candidate = join(dirname(process.execPath), HELPER_EXECUTABLE) + cachedHelperPath = existsSync(candidate) ? candidate : null + return cachedHelperPath +} + +/** + * Reads the app's real macOS notification authorization via a helper binary + * calling UNUserNotificationCenter.getNotificationSettings. Returns null when + * the helper is unavailable or fails, so callers can fall back to weaker + * delivery-probe evidence. + * + * Why a helper at all: Electron exposes no API for notification authorization + * (scheduling silently succeeds even while macOS is suppressing display), so + * the only truthful signal is the native settings read. + */ +let readInFlight: Promise | null = null + +export function readNotificationAuthorizationStatus(): Promise { + const helperPath = resolveHelperPath() + if (!helperPath) { + return Promise.resolve(null) + } + // Why: simultaneous agent completions across worktrees each consult the + // readout — one in-flight helper run answers all of them. + if (readInFlight) { + return readInFlight + } + readInFlight = runStatusHelper(helperPath).finally(() => { + readInFlight = null + }) + return readInFlight +} + +function runStatusHelper(helperPath: string): Promise { + return new Promise((resolve) => { + execFile(helperPath, [], { timeout: HELPER_TIMEOUT_MS }, (error, stdout) => { + if (error) { + resolve(null) + return + } + try { + const parsed = JSON.parse(String(stdout).trim()) as { authorization?: string } + switch (parsed.authorization) { + case 'authorized': + case 'provisional': + case 'ephemeral': + resolve('authorized') + return + case 'denied': + resolve('denied') + return + case 'not-determined': + resolve('not-determined') + return + case undefined: + default: + resolve('unknown') + } + } catch { + resolve(null) + } + }) + }) +} diff --git a/src/main/ipc/notifications.test.ts b/src/main/ipc/notifications.test.ts index 3ada1917185e..8fb5566a8955 100644 --- a/src/main/ipc/notifications.test.ts +++ b/src/main/ipc/notifications.test.ts @@ -70,6 +70,25 @@ vi.mock('electron', () => ({ } })) +const { readAuthorizationStatusMock } = vi.hoisted(() => ({ + readAuthorizationStatusMock: vi.fn( + (): Promise<'authorized' | 'denied' | 'not-determined' | 'unknown' | null> => + Promise.resolve(null) + ) +})) + +vi.mock('./notification-authorization-status', () => ({ + readNotificationAuthorizationStatus: readAuthorizationStatusMock +})) + +// Why: notifications.ts pulls in the tray module (for the minimized attention +// dot), which transitively loads app-icon/electron-toolkit; stub it so this +// suite stays focused on notification dispatch and avoids that import chain. +const setTrayAttentionMock = vi.hoisted(() => vi.fn()) +vi.mock('../tray/system-tray', () => ({ + setTrayAttention: setTrayAttentionMock +})) + import { registerNotificationHandlers, triggerStartupNotificationRegistration @@ -98,9 +117,12 @@ describe('registerNotificationHandlers', () => { notificationRemoveListenerMock.mockClear() notificationIsSupportedMock.mockReset() notificationIsSupportedMock.mockReturnValue(true) + readAuthorizationStatusMock.mockReset() + readAuthorizationStatusMock.mockResolvedValue(null) getAllWindowsMock.mockReset() getAllWindowsMock.mockReturnValue([]) shellOpenExternalMock.mockClear() + setTrayAttentionMock.mockClear() }) afterEach(() => { @@ -167,7 +189,7 @@ describe('registerNotificationHandlers', () => { return call[1] as () => void } - it('registers the IPC handler', () => { + it('registers the IPC handler', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -183,7 +205,7 @@ describe('registerNotificationHandlers', () => { expect(handleMock).toHaveBeenCalledWith('notifications:dispatch', expect.any(Function)) }) - it('opens the current macOS app notification settings entry', () => { + it('opens the current macOS app notification settings entry', async () => { const originalPlatform = process.platform const originalBundleId = process.env.ORCA_DEV_MACOS_BUNDLE_ID Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) @@ -216,7 +238,7 @@ describe('registerNotificationHandlers', () => { } }) - it('opens Windows notification settings', () => { + it('opens Windows notification settings', async () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) try { @@ -240,7 +262,7 @@ describe('registerNotificationHandlers', () => { } }) - it('suppresses notifications when disabled in settings', () => { + it('suppresses notifications when disabled in settings', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -253,14 +275,14 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getDispatchHandler() - expect(handler({}, { source: 'agent-task-complete' })).toEqual({ + expect(await handler({}, { source: 'agent-task-complete' })).toEqual({ delivered: false, reason: 'disabled' }) expect(notificationCtorMock).not.toHaveBeenCalled() }) - it('suppresses active-worktree notifications while Orca is focused', () => { + it('suppresses active-worktree notifications while Orca is focused', async () => { getAllWindowsMock.mockReturnValue([ { isDestroyed: () => false, @@ -280,14 +302,73 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getDispatchHandler() - expect(handler({}, { source: 'agent-task-complete', isActiveWorktree: true })).toEqual({ + expect(await handler({}, { source: 'agent-task-complete', isActiveWorktree: true })).toEqual({ delivered: false, reason: 'suppressed-focus' }) expect(notificationCtorMock).not.toHaveBeenCalled() }) - it('delivers a notification when the event is allowed', () => { + describe('minimized tray attention dot', () => { + function registerEnabledNotifications(): void { + registerNotificationHandlers({ + getSettings: () => ({ + notifications: { + enabled: true, + agentTaskComplete: true, + terminalBell: true, + suppressWhenFocused: true + } + }) + } as never) + } + + it('lights the tray dot for an agent completion while the window is hidden', () => { + getAllWindowsMock.mockReturnValue([ + { isDestroyed: () => false, isVisible: () => false, isMinimized: () => false } as never + ]) + registerEnabledNotifications() + + getDispatchHandler()({}, { source: 'agent-task-complete' }) + + expect(setTrayAttentionMock).toHaveBeenCalledWith(true) + }) + + it('lights the tray dot for a terminal bell while the window is minimized', () => { + getAllWindowsMock.mockReturnValue([ + { isDestroyed: () => false, isVisible: () => true, isMinimized: () => true } as never + ]) + registerEnabledNotifications() + + getDispatchHandler()({}, { source: 'terminal-bell' }) + + expect(setTrayAttentionMock).toHaveBeenCalledWith(true) + }) + + it('does not light the tray dot while the window is visible', () => { + getAllWindowsMock.mockReturnValue([ + { isDestroyed: () => false, isVisible: () => true, isMinimized: () => false } as never + ]) + registerEnabledNotifications() + + getDispatchHandler()({}, { source: 'agent-task-complete' }) + + expect(setTrayAttentionMock).not.toHaveBeenCalled() + }) + + it('does not light the tray dot for non-bell/completion sources', () => { + getAllWindowsMock.mockReturnValue([ + { isDestroyed: () => false, isVisible: () => false, isMinimized: () => false } as never + ]) + registerEnabledNotifications() + + getDispatchHandler()({}, { source: 'test' }) + + expect(setTrayAttentionMock).not.toHaveBeenCalled() + }) + }) + + it('delivers a notification when the event is allowed', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -301,7 +382,10 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() expect( - handler({}, { source: 'agent-task-complete', repoLabel: 'orca', worktreeLabel: 'feat/notis' }) + await handler( + {}, + { source: 'agent-task-complete', repoLabel: 'orca', worktreeLabel: 'feat/notis' } + ) ).toEqual({ delivered: true }) expect(notificationCtorMock).toHaveBeenCalledWith( expectedNativeNotificationOptions({ @@ -312,7 +396,7 @@ describe('registerNotificationHandlers', () => { expect(notificationShowMock).toHaveBeenCalledTimes(1) }) - it('uses the macOS default notification sound when no custom sound is configured', () => { + it('uses the macOS default notification sound when no custom sound is configured', async () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) try { @@ -329,7 +413,7 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getDispatchHandler() - expect(handler({}, { source: 'test' })).toEqual({ delivered: true }) + expect(await handler({}, { source: 'test' })).toEqual({ delivered: true }) expect(notificationCtorMock).toHaveBeenCalledWith({ title: 'Orca notifications are on', body: 'This is a test notification from Orca.', @@ -340,7 +424,7 @@ describe('registerNotificationHandlers', () => { } }) - it('does not request a native macOS sound when a custom sound is configured', () => { + it('does not request a native macOS sound when a custom sound is configured', async () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) try { @@ -357,7 +441,7 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getDispatchHandler() - expect(handler({}, { source: 'test' })).toEqual({ delivered: true }) + expect(await handler({}, { source: 'test' })).toEqual({ delivered: true }) expect(notificationCtorMock).toHaveBeenCalledWith({ title: 'Orca notifications are on', body: 'This is a test notification from Orca.', @@ -368,7 +452,7 @@ describe('registerNotificationHandlers', () => { } }) - it('focuses the originating terminal pane when a notification with paneKey is clicked', () => { + it('focuses the originating terminal pane when a notification with paneKey is clicked', async () => { const webContentsSend = vi.fn() const restore = vi.fn() const focus = vi.fn() @@ -396,7 +480,7 @@ describe('registerNotificationHandlers', () => { const paneKey = 'tab-1:11111111-1111-4111-8111-111111111111' const handler = getDispatchHandler() expect( - handler({}, { source: 'agent-task-complete', worktreeId: 'repo::wt1', paneKey }) + await handler({}, { source: 'agent-task-complete', worktreeId: 'repo::wt1', paneKey }) ).toEqual({ delivered: true }) expect(vi.getTimerCount()).toBe(1) @@ -420,7 +504,7 @@ describe('registerNotificationHandlers', () => { }) }) - it('clears the retained notification fallback timer when the native notification closes', () => { + it('clears the retained notification fallback timer when the native notification closes', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -433,7 +517,7 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getDispatchHandler() - expect(handler({}, { source: 'agent-task-complete' })).toEqual({ delivered: true }) + expect(await handler({}, { source: 'agent-task-complete' })).toEqual({ delivered: true }) expect(vi.getTimerCount()).toBe(1) const closeHandler = getNotificationEventHandler('close') @@ -443,7 +527,7 @@ describe('registerNotificationHandlers', () => { expect(notificationRemoveListenerMock).toHaveBeenCalledWith('close', closeHandler) }) - it('releases retained notifications when native delivery fails', () => { + it('releases retained notifications when native delivery fails', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) try { registerNotificationHandlers({ @@ -458,7 +542,7 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getDispatchHandler() - expect(handler({}, { source: 'agent-task-complete' })).toEqual({ delivered: true }) + expect(await handler({}, { source: 'agent-task-complete' })).toEqual({ delivered: true }) expect(vi.getTimerCount()).toBe(1) const failedHandler = getNotificationEventHandler('failed') @@ -474,7 +558,7 @@ describe('registerNotificationHandlers', () => { } }) - it('formats agent-task-complete with the agent response when a status snapshot is present', () => { + it('formats agent-task-complete with the agent response when a status snapshot is present', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -488,7 +572,7 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() expect( - handler( + await handler( {}, { source: 'agent-task-complete', @@ -512,7 +596,7 @@ describe('registerNotificationHandlers', () => { ) }) - it('includes the repo name when multiple repos are active', () => { + it('includes the repo name when multiple repos are active', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -526,7 +610,7 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() expect( - handler( + await handler( {}, { source: 'agent-task-complete', @@ -549,7 +633,7 @@ describe('registerNotificationHandlers', () => { ) }) - it('keeps a readable body when no assistant response was captured', () => { + it('keeps a readable body when no assistant response was captured', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -563,7 +647,7 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() expect( - handler( + await handler( {}, { source: 'agent-task-complete', @@ -586,7 +670,7 @@ describe('registerNotificationHandlers', () => { ) }) - it('formats blocked and interrupted agent snapshots distinctly', () => { + it('formats blocked and interrupted agent snapshots distinctly', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -600,7 +684,7 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() expect( - handler( + await handler( {}, { source: 'agent-task-complete', @@ -614,7 +698,7 @@ describe('registerNotificationHandlers', () => { ).toEqual({ delivered: true }) vi.advanceTimersByTime(5001) expect( - handler( + await handler( {}, { source: 'agent-task-complete', @@ -644,7 +728,7 @@ describe('registerNotificationHandlers', () => { ) }) - it('normalizes custom agent labels and re-bounds multiline assistant previews', () => { + it('normalizes custom agent labels and re-bounds multiline assistant previews', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -659,7 +743,7 @@ describe('registerNotificationHandlers', () => { const longAssistantMessage = `Line one\n\n${'x'.repeat(400)}` const handler = getDispatchHandler() expect( - handler( + await handler( {}, { source: 'agent-task-complete', @@ -686,7 +770,7 @@ describe('registerNotificationHandlers', () => { expect(options.body.length).toBeLessThanOrEqual(180) }) - it('uses tool context before falling back when no prompt or assistant preview exists', () => { + it('uses tool context before falling back when no prompt or assistant preview exists', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -700,7 +784,7 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() expect( - handler( + await handler( {}, { source: 'agent-task-complete', @@ -722,7 +806,7 @@ describe('registerNotificationHandlers', () => { ) }) - it('uses rich formatter output for mobile notifications before the native support guard', () => { + it('uses rich formatter output for mobile notifications before the native support guard', async () => { notificationIsSupportedMock.mockReturnValue(false) const dispatchMobileNotification = vi.fn() registerNotificationHandlers( @@ -741,7 +825,7 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() expect( - handler( + await handler( {}, { source: 'agent-task-complete', @@ -765,7 +849,7 @@ describe('registerNotificationHandlers', () => { expect(notificationCtorMock).not.toHaveBeenCalled() }) - it('does not dispatch mobile notifications when notifications are disabled', () => { + it('does not dispatch mobile notifications when notifications are disabled', async () => { const dispatchMobileNotification = vi.fn() registerNotificationHandlers( { @@ -782,7 +866,7 @@ describe('registerNotificationHandlers', () => { ) const handler = getDispatchHandler() - expect(handler({}, { source: 'agent-task-complete', worktreeId: 'repo::wt1' })).toEqual({ + expect(await handler({}, { source: 'agent-task-complete', worktreeId: 'repo::wt1' })).toEqual({ delivered: false, reason: 'disabled' }) @@ -790,7 +874,7 @@ describe('registerNotificationHandlers', () => { expect(dispatchMobileNotification).not.toHaveBeenCalled() }) - it('does not dispatch mobile notifications when the source is disabled', () => { + it('does not dispatch mobile notifications when the source is disabled', async () => { const dispatchMobileNotification = vi.fn() registerNotificationHandlers( { @@ -807,7 +891,7 @@ describe('registerNotificationHandlers', () => { ) const handler = getDispatchHandler() - expect(handler({}, { source: 'agent-task-complete', worktreeId: 'repo::wt1' })).toEqual({ + expect(await handler({}, { source: 'agent-task-complete', worktreeId: 'repo::wt1' })).toEqual({ delivered: false, reason: 'source-disabled' }) @@ -815,7 +899,7 @@ describe('registerNotificationHandlers', () => { expect(dispatchMobileNotification).not.toHaveBeenCalled() }) - it('does not dispatch mobile notifications for focused active-worktree notifications', () => { + it('does not dispatch mobile notifications for focused active-worktree notifications', async () => { getAllWindowsMock.mockReturnValue([ { isDestroyed: () => false, @@ -839,7 +923,7 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() expect( - handler( + await handler( {}, { source: 'agent-task-complete', worktreeId: 'repo::wt1', isActiveWorktree: true } ) @@ -851,7 +935,7 @@ describe('registerNotificationHandlers', () => { expect(dispatchMobileNotification).not.toHaveBeenCalled() }) - it('does not dispatch mobile notifications for cooldown-suppressed bursts', () => { + it('does not dispatch mobile notifications for cooldown-suppressed bursts', async () => { const dispatchMobileNotification = vi.fn() registerNotificationHandlers( { @@ -868,10 +952,10 @@ describe('registerNotificationHandlers', () => { ) const handler = getDispatchHandler() - expect(handler({}, { source: 'agent-task-complete', worktreeId: 'repo::wt1' })).toEqual({ + expect(await handler({}, { source: 'agent-task-complete', worktreeId: 'repo::wt1' })).toEqual({ delivered: true }) - expect(handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ + expect(await handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ delivered: false, reason: 'cooldown' }) @@ -882,7 +966,7 @@ describe('registerNotificationHandlers', () => { ) }) - it('does not forward explicit desktop test notifications to mobile clients', () => { + it('does not forward explicit desktop test notifications to mobile clients', async () => { const dispatchMobileNotification = vi.fn() registerNotificationHandlers( { @@ -899,12 +983,12 @@ describe('registerNotificationHandlers', () => { ) const handler = getDispatchHandler() - expect(handler({}, { source: 'test' })).toEqual({ delivered: true }) + expect(await handler({}, { source: 'test' })).toEqual({ delivered: true }) expect(dispatchMobileNotification).not.toHaveBeenCalled() }) - it('dismisses active native notifications and fans out mobile dismissal once per id', () => { + it('dismisses active native notifications and fans out mobile dismissal once per id', async () => { const dispatchMobileNotification = vi.fn() const dismissMobileNotification = vi.fn() registerNotificationHandlers( @@ -923,7 +1007,7 @@ describe('registerNotificationHandlers', () => { const dispatchHandler = getDispatchHandler() expect( - dispatchHandler({}, { source: 'agent-task-complete', notificationId: 'agent:one' }) + await dispatchHandler({}, { source: 'agent-task-complete', notificationId: 'agent:one' }) ).toEqual({ delivered: true }) const dismissHandler = getDismissHandler() @@ -935,7 +1019,7 @@ describe('registerNotificationHandlers', () => { expect(dismissMobileNotification).toHaveBeenCalledWith('agent:one') }) - it('fans out mobile dismissal even when there is no active native notification', () => { + it('fans out mobile dismissal even when there is no active native notification', async () => { const dismissMobileNotification = vi.fn() registerNotificationHandlers( { @@ -958,7 +1042,7 @@ describe('registerNotificationHandlers', () => { expect(dismissMobileNotification).toHaveBeenCalledWith('agent:missing') }) - it('closes the previous native notification when replacing the same id', () => { + it('closes the previous native notification when replacing the same id', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -972,18 +1056,18 @@ describe('registerNotificationHandlers', () => { const dispatchHandler = getDispatchHandler() expect( - dispatchHandler({}, { source: 'agent-task-complete', notificationId: 'agent:replace' }) + await dispatchHandler({}, { source: 'agent-task-complete', notificationId: 'agent:replace' }) ).toEqual({ delivered: true }) vi.advanceTimersByTime(5001) expect( - dispatchHandler({}, { source: 'agent-task-complete', notificationId: 'agent:replace' }) + await dispatchHandler({}, { source: 'agent-task-complete', notificationId: 'agent:replace' }) ).toEqual({ delivered: true }) expect(notificationCloseMock).toHaveBeenCalledTimes(1) expect(notificationShowMock).toHaveBeenCalledTimes(2) }) - it('silences the native notification when a custom sound is configured', () => { + it('silences the native notification when a custom sound is configured', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -997,7 +1081,7 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getDispatchHandler() - expect(handler({}, { source: 'test' })).toEqual({ delivered: true }) + expect(await handler({}, { source: 'test' })).toEqual({ delivered: true }) expect(notificationCtorMock).toHaveBeenCalledWith({ title: 'Orca notifications are on', body: 'This is a test notification from Orca.', @@ -1005,7 +1089,7 @@ describe('registerNotificationHandlers', () => { }) }) - it('returns source-disabled when the specific source toggle is off', () => { + it('returns source-disabled when the specific source toggle is off', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -1018,13 +1102,13 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getDispatchHandler() - expect(handler({}, { source: 'agent-task-complete' })).toEqual({ + expect(await handler({}, { source: 'agent-task-complete' })).toEqual({ delivered: false, reason: 'source-disabled' }) }) - it('deduplicates repeated notifications for the same worktree', () => { + it('deduplicates repeated notifications for the same worktree', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -1037,23 +1121,23 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getDispatchHandler() - expect(handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ + expect(await handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ delivered: true }) - expect(handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ + expect(await handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ delivered: false, reason: 'cooldown' }) vi.advanceTimersByTime(5001) - expect(handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ + expect(await handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ delivered: true }) expect(notificationShowMock).toHaveBeenCalledTimes(2) }) - it('bounds notification cooldown keys during unique worktree bursts', () => { + it('bounds notification cooldown keys during unique worktree bursts', async () => { notificationIsSupportedMock.mockReturnValue(false) registerNotificationHandlers({ getSettings: () => ({ @@ -1068,24 +1152,24 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() for (let i = 0; i < 75; i++) { - expect(handler({}, { source: 'terminal-bell', worktreeId: `repo::wt-${i}` })).toEqual({ + expect(await handler({}, { source: 'terminal-bell', worktreeId: `repo::wt-${i}` })).toEqual({ delivered: false, reason: 'not-supported' }) } - expect(handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt-0' })).toEqual({ + expect(await handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt-0' })).toEqual({ delivered: false, reason: 'not-supported' }) - expect(handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt-74' })).toEqual({ + expect(await handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt-74' })).toEqual({ delivered: false, reason: 'cooldown' }) expect(notificationCtorMock).not.toHaveBeenCalled() }) - it('deduplicates agent-task-complete and terminal-bell for the same worktree', () => { + it('deduplicates agent-task-complete and terminal-bell for the same worktree', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -1099,17 +1183,46 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() - expect(handler({}, { source: 'agent-task-complete', worktreeId: 'repo::wt1' })).toEqual({ + expect(await handler({}, { source: 'agent-task-complete', worktreeId: 'repo::wt1' })).toEqual({ delivered: true }) - expect(handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ + expect(await handler({}, { source: 'terminal-bell', worktreeId: 'repo::wt1' })).toEqual({ delivered: false, reason: 'cooldown' }) expect(notificationShowMock).toHaveBeenCalledTimes(1) }) - it('does not cooldown explicit test notifications', () => { + it('skips native delivery and reports blocked-by-system when macOS would swallow it', async () => { + const originalPlatform = process.platform + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + try { + registerNotificationHandlers({ + getSettings: () => ({ + notifications: { + enabled: true, + agentTaskComplete: true, + terminalBell: true, + suppressWhenFocused: false + } + }) + } as never) + readAuthorizationStatusMock.mockResolvedValue('denied') + + const handler = getDispatchHandler() + expect(await handler({}, { source: 'agent-task-complete' })).toEqual({ + delivered: false, + reason: 'blocked-by-system' + }) + // Why: a swallowed native notification would still pile up in the + // Notification Center delivered list — skip creating it entirely. + expect(notificationCtorMock).not.toHaveBeenCalled() + } finally { + Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) + } + }) + + it('does not cooldown explicit test notifications', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -1123,8 +1236,8 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() - expect(handler({}, { source: 'test' })).toEqual({ delivered: true }) - expect(handler({}, { source: 'test' })).toEqual({ delivered: true }) + expect(await handler({}, { source: 'test' })).toEqual({ delivered: true }) + expect(await handler({}, { source: 'test' })).toEqual({ delivered: true }) expect(notificationShowMock).toHaveBeenCalledTimes(2) }) @@ -1143,6 +1256,9 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() const result = handler({}, { source: 'test', requireDisplayConfirmation: true }) + // Why: the darwin authorization gate resolves before the notification is + // created, so flush microtasks before grabbing its event listeners. + await vi.advanceTimersByTimeAsync(0) const showHandler = getNotificationOnceEventHandler('show') const failedHandler = getNotificationOnceEventHandler('failed') showHandler() @@ -1168,6 +1284,7 @@ describe('registerNotificationHandlers', () => { const handler = getDispatchHandler() const result = handler({}, { source: 'test', requireDisplayConfirmation: true }) + await vi.advanceTimersByTimeAsync(0) const showHandler = getNotificationOnceEventHandler('show') const failedHandler = getNotificationOnceEventHandler('failed') await vi.advanceTimersByTimeAsync(2501) @@ -1217,13 +1334,13 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getLoadSoundHandler() - await expect(handler({})).resolves.toEqual({ + expect(await handler({})).toEqual({ ok: false, reason: 'unsupported-type' }) }) - it('resolves the sound path without reading the file', () => { + it('resolves the sound path without reading the file', async () => { const soundPath = join(tempDir, 'sound.ogg') writeFileSync(soundPath, Buffer.from([1, 2, 3])) registerNotificationHandlers({ @@ -1239,10 +1356,10 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getResolveSoundPathHandler() - expect(handler({})).toEqual({ ok: true, path: soundPath }) + expect(await handler({})).toEqual({ ok: true, path: soundPath }) }) - it('rejects unsupported types from resolveSoundPath without touching the disk', () => { + it('rejects unsupported types from resolveSoundPath without touching the disk', async () => { registerNotificationHandlers({ getSettings: () => ({ notifications: { @@ -1256,7 +1373,203 @@ describe('registerNotificationHandlers', () => { } as never) const handler = getResolveSoundPathHandler() - expect(handler({})).toEqual({ ok: false, reason: 'unsupported-type' }) + expect(await handler({})).toEqual({ ok: false, reason: 'unsupported-type' }) + }) +}) + +describe('notifications:probeDelivery', () => { + const originalPlatform = process.platform + + function getProbeDeliveryHandler(): (event: unknown, args?: { force?: boolean }) => unknown { + const call = handleMock.mock.calls.find( + (c: unknown[]) => c[0] === 'notifications:probeDelivery' + ) + if (!call) { + throw new Error('notifications:probeDelivery handler not registered') + } + return call[1] as (event: unknown, args?: { force?: boolean }) => unknown + } + + function getProbeOnceEventHandler(eventName: string): (...args: unknown[]) => void { + // Why: findLast — a test may run several probes, and only the newest + // probe's listeners can settle the pending promise. + const call = notificationOnceMock.mock.calls.findLast((c: unknown[]) => c[0] === eventName) + if (!call) { + throw new Error(`Probe notification ${eventName} once handler not registered`) + } + return call[1] as (...args: unknown[]) => void + } + + function createStore(ui: Record = {}): { + getSettings: () => unknown + getUI: () => Record + updateUI: ReturnType + } { + const state = { ...ui } + return { + getSettings: () => ({ + notifications: { + enabled: true, + agentTaskComplete: true, + terminalBell: true, + suppressWhenFocused: false + } + }), + getUI: () => state, + updateUI: vi.fn((updates: Record) => { + Object.assign(state, updates) + }) + } + } + + beforeEach(() => { + vi.useFakeTimers() + handleMock.mockReset() + removeHandlerMock.mockReset() + notificationCtorMock.mockClear() + notificationShowMock.mockClear() + notificationCloseMock.mockClear() + notificationOnMock.mockClear() + notificationOnceMock.mockClear() + notificationRemoveListenerMock.mockClear() + notificationIsSupportedMock.mockReset() + notificationIsSupportedMock.mockReturnValue(true) + readAuthorizationStatusMock.mockReset() + readAuthorizationStatusMock.mockResolvedValue(null) + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + }) + + afterEach(() => { + Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) + }) + + it('reports unsupported on non-darwin platforms without probing', async () => { + Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }) + const store = createStore() + registerNotificationHandlers(store as never) + + await expect(getProbeDeliveryHandler()({})).resolves.toEqual({ + state: 'unsupported', + authoritative: false + }) + expect(notificationCtorMock).not.toHaveBeenCalled() + expect(store.updateUI).not.toHaveBeenCalled() + }) + + it('reports authoritative states straight from the authorization readout', async () => { + const store = createStore() + registerNotificationHandlers(store as never) + const handler = getProbeDeliveryHandler() + + readAuthorizationStatusMock.mockResolvedValue('authorized') + expect(await handler({})).toEqual({ state: 'delivered', authoritative: true }) + + readAuthorizationStatusMock.mockResolvedValue('denied') + expect(await handler({})).toEqual({ state: 'blocked', authoritative: true }) + + // No probe notifications were needed for either readout. + expect(notificationCtorMock).not.toHaveBeenCalled() + }) + + it('fires one dialog-trigger probe per session while the decision is pending', async () => { + const store = createStore() + registerNotificationHandlers(store as never) + const handler = getProbeDeliveryHandler() + readAuthorizationStatusMock.mockResolvedValue('not-determined') + + expect(await handler({})).toEqual({ + state: 'awaiting-decision', + authoritative: true + }) + expect(notificationCtorMock).toHaveBeenCalledTimes(1) + + // Polling again while pending must not spam more probe notifications. + expect(await handler({}, { force: true })).toEqual({ + state: 'awaiting-decision', + authoritative: true + }) + expect(notificationCtorMock).toHaveBeenCalledTimes(1) + }) + + it('marks the one-shot permission registration as done so startup cannot re-prompt', async () => { + const store = createStore() + registerNotificationHandlers(store as never) + + const result = getProbeDeliveryHandler()({}) as Promise + await vi.advanceTimersByTimeAsync(0) + expect(store.updateUI).toHaveBeenCalledWith({ notificationPermissionRequested: true }) + + getProbeOnceEventHandler('failed')({}, 'not allowed') + await expect(result).resolves.toEqual({ state: 'blocked', authoritative: false }) + }) + + it('falls back to delivery probes when the readout is unavailable', async () => { + const store = createStore() + registerNotificationHandlers(store as never) + + const result = getProbeDeliveryHandler()({}) as Promise + await vi.advanceTimersByTimeAsync(0) + expect(notificationShowMock).toHaveBeenCalledTimes(1) + + getProbeOnceEventHandler('show')() + await expect(result).resolves.toEqual({ state: 'delivered', authoritative: false }) + // No persisted confirmation on purpose: OS permission changes between runs. + expect(store.updateUI).not.toHaveBeenCalledWith({ notificationDeliveryConfirmed: true }) + }) + + it('serves session evidence without probing again until forced', async () => { + const store = createStore() + registerNotificationHandlers(store as never) + const handler = getProbeDeliveryHandler() + + const probeResult = handler({}) as Promise + await vi.advanceTimersByTimeAsync(0) + getProbeOnceEventHandler('show')() + await expect(probeResult).resolves.toEqual({ state: 'delivered', authoritative: false }) + expect(notificationCtorMock).toHaveBeenCalledTimes(1) + + // Cached session evidence answers non-force calls with no new probe. + expect(await handler({})).toEqual({ state: 'delivered', authoritative: false }) + expect(notificationCtorMock).toHaveBeenCalledTimes(1) + + // Force bypasses the cache and schedules a fresh probe. + const forced = handler({}, { force: true }) as Promise + await vi.advanceTimersByTimeAsync(0) + expect(notificationCtorMock).toHaveBeenCalledTimes(2) + getProbeOnceEventHandler('show')() + await expect(forced).resolves.toEqual({ state: 'delivered', authoritative: false }) + }) + + it('serves cached failure evidence after a rejected probe', async () => { + const store = createStore() + registerNotificationHandlers(store as never) + const handler = getProbeDeliveryHandler() + + const probeResult = handler({}, { force: true }) as Promise + await vi.advanceTimersByTimeAsync(0) + getProbeOnceEventHandler('failed')({}, 'Notifications are not allowed for this application') + await expect(probeResult).resolves.toEqual({ state: 'blocked', authoritative: false }) + + expect(await handler({})).toEqual({ state: 'blocked', authoritative: false }) + expect(notificationCtorMock).toHaveBeenCalledTimes(1) + }) + + it('resolves blocked on timeout without recording a definitive failure', async () => { + const store = createStore() + registerNotificationHandlers(store as never) + const handler = getProbeDeliveryHandler() + + const probeResult = handler({}) as Promise + await vi.advanceTimersByTimeAsync(3001) + await expect(probeResult).resolves.toEqual({ state: 'blocked', authoritative: false }) + expect(notificationCloseMock).toHaveBeenCalledTimes(1) + + // A timeout is ambiguous evidence, so the next non-force call probes again. + const secondResult = handler({}) as Promise + await vi.advanceTimersByTimeAsync(0) + expect(notificationCtorMock).toHaveBeenCalledTimes(2) + getProbeOnceEventHandler('show')() + await expect(secondResult).resolves.toEqual({ state: 'delivered', authoritative: false }) }) }) @@ -1288,7 +1601,7 @@ describe('triggerStartupNotificationRegistration', () => { Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) }) - it('shows welcome notification when not yet requested', () => { + it('shows welcome notification when not yet requested', async () => { const store = { getUI: () => ({ notificationPermissionRequested: undefined }), updateUI: vi.fn() @@ -1304,7 +1617,7 @@ describe('triggerStartupNotificationRegistration', () => { expect(notificationShowMock).toHaveBeenCalledTimes(1) }) - it('does not fire when notificationPermissionRequested flag is set', () => { + it('does not fire when notificationPermissionRequested flag is set', async () => { const store = { getUI: () => ({ notificationPermissionRequested: true }), updateUI: vi.fn() @@ -1315,7 +1628,7 @@ describe('triggerStartupNotificationRegistration', () => { expect(notificationCtorMock).not.toHaveBeenCalled() }) - it('does nothing on non-darwin platforms', () => { + it('does nothing on non-darwin platforms', async () => { Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }) const store = { getUI: () => ({ notificationPermissionRequested: undefined }), @@ -1327,7 +1640,7 @@ describe('triggerStartupNotificationRegistration', () => { expect(notificationCtorMock).not.toHaveBeenCalled() }) - it('clears startup notification timers when the notification is clicked', () => { + it('clears startup notification timers when the notification is clicked', async () => { const store = { getUI: () => ({ notificationPermissionRequested: undefined }), updateUI: vi.fn() @@ -1345,7 +1658,7 @@ describe('triggerStartupNotificationRegistration', () => { expect(notificationRemoveListenerMock).toHaveBeenCalledWith('show', expect.any(Function)) }) - it('cleans up startup notification registration when native delivery fails', () => { + it('cleans up startup notification registration when native delivery fails', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) try { const store = { diff --git a/src/main/ipc/notifications.ts b/src/main/ipc/notifications.ts index b9490da86317..47baa7e77251 100644 --- a/src/main/ipc/notifications.ts +++ b/src/main/ipc/notifications.ts @@ -13,6 +13,7 @@ import thumpSoundPath from '../../../resources/notification-sounds/thump.mp3?ass import twoToneSoundPath from '../../../resources/notification-sounds/two-tone.mp3?asset' import type { Store } from '../persistence' import type { + NotificationDeliveryProbeResult, NotificationDispatchRequest, NotificationDispatchResult, NotificationDismissResult, @@ -23,7 +24,10 @@ import type { import { getRepoIdFromWorktreeId } from '../../shared/worktree-id' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { buildNotificationOptions } from './notification-options' +import { readNotificationAuthorizationStatus } from './notification-authorization-status' import { parsePaneKey } from '../../shared/stable-pane-id' +import { setTrayAttention } from '../tray/system-tray' +import { isMainWindowVisible } from '../window/main-window-visibility' const NOTIFICATION_COOLDOWN_MS = 5000 const MAX_RECENT_NOTIFICATION_KEYS = 50 @@ -96,6 +100,113 @@ function retainNotificationUntilRelease( return release } +const NOTIFICATION_PROBE_RESULT_TIMEOUT_MS = 3000 +const NOTIFICATION_PROBE_BANNER_CLOSE_DELAY_MS = 4000 + +// Why: Electron has no API to read macOS UNUserNotificationCenter +// authorization, so the freshest signal we have is what happened to the last +// notification we scheduled. Session-scoped on purpose: OS-level permission +// can change between runs, and a stale positive renders a false green card. +let lastObservedDeliveryOutcome: 'delivered' | 'failed' | null = null +let deliveryProbeInFlight: Promise | null = null +// Why: firing one probe notification is what instantiates Electron's +// presenter and pops the macOS permission dialog. Once per session is enough +// while the authorization readout reports the decision as pending. +let permissionDialogTriggeredThisSession = false + +/** + * Fallback signal for hosts without the native helper. Schedules a silent + * probe notification and reports whether macOS accepted it. 'failed' means + * the request was rejected (permission denied, or an unsigned build). On a + * fresh install the probe also instantiates Electron's notification + * presenter, which is what makes macOS pop the "Allow notifications?" dialog. + * + * Known ambiguity with no public API to resolve it (verified on macOS 26): + * while the dialog is unanswered — and when notifications are toggled off in + * System Settings after being authorized — macOS still accepts requests and + * silently swallows them, so 'delivered' can over-report. 'failed' fires for + * hard rejections (unsigned builds, dialog-level denial). The bundled + * notification-status helper exists precisely to avoid this ambiguity. + */ +function probeNotificationDelivery(): Promise { + if (deliveryProbeInFlight) { + return deliveryProbeInFlight + } + permissionDialogTriggeredThisSession = true + + const probe = new Notification({ + title: 'Orca notifications are on', + body: 'Orca will alert you when agents finish or terminals need attention.', + silent: true + }) + activeNotifications.add(probe) + + deliveryProbeInFlight = new Promise((resolve) => { + let settled = false + let timeoutTimer: ReturnType | null = null + + function releaseProbe(): void { + activeNotifications.delete(probe) + probe.removeListener('show', onShow) + probe.removeListener('failed', onFailed) + probe.close() + } + + function settle(state: 'delivered' | 'blocked'): void { + if (settled) { + return + } + settled = true + if (timeoutTimer) { + clearTimeout(timeoutTimer) + timeoutTimer = null + } + lastObservedDeliveryOutcome = state === 'delivered' ? 'delivered' : 'failed' + resolve({ state, authoritative: false }) + } + + function onShow(): void { + settle('delivered') + // Why: when delivery works the probe banner is visible, so it doubles + // as the user-facing confirmation — let it linger briefly instead of + // vanishing the instant it appears. + const closeTimer = setTimeout(releaseProbe, NOTIFICATION_PROBE_BANNER_CLOSE_DELAY_MS) + if (typeof closeTimer.unref === 'function') { + closeTimer.unref() + } + } + + function onFailed(_event: unknown, _error?: string): void { + // Why: a rejected probe is an expected outcome (denied permission), not + // an anomaly — logging it would spam the console on every poll while + // the onboarding card waits for the user to allow notifications. + settle('blocked') + releaseProbe() + } + + probe.once('show', onShow) + probe.once('failed', onFailed) + // Why: don't record a 'failed' outcome on timeout — a missing callback is + // ambiguous, while the 'failed' event is a definitive rejection. + timeoutTimer = setTimeout(() => { + if (!settled) { + settled = true + resolve({ state: 'blocked', authoritative: false }) + releaseProbe() + } + }, NOTIFICATION_PROBE_RESULT_TIMEOUT_MS) + if (typeof timeoutTimer.unref === 'function') { + timeoutTimer.unref() + } + + probe.show() + }).finally(() => { + deliveryProbeInFlight = null + }) + + return deliveryProbeInFlight +} + function getMacNotificationSettingsUrl(): string { const bundleId = process.env.ORCA_DEV_MACOS_BUNDLE_ID ?? MACOS_PACKAGED_BUNDLE_ID return `${MACOS_NOTIFICATION_SETTINGS_URL}?id=${encodeURIComponent(bundleId)}` @@ -203,10 +314,15 @@ function pruneRecentNotifications(recentNotifications: Map, now: export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntimeService): void { const recentNotifications = new Map() + // Why: handler registration marks a fresh session — permission evidence + // from a previous registration must not leak into the new one. + lastObservedDeliveryOutcome = null + deliveryProbeInFlight = null + permissionDialogTriggeredThisSession = false ipcMain.removeHandler('notifications:openSystemSettings') ipcMain.removeHandler('notifications:getPermissionStatus') - ipcMain.removeHandler('notifications:requestPermission') + ipcMain.removeHandler('notifications:probeDelivery') ipcMain.handle('notifications:openSystemSettings', (): void => { openNotificationSystemSettings() }) @@ -225,10 +341,52 @@ export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntime }) ipcMain.handle('notifications:getPermissionStatus', getPermissionStatus) - ipcMain.handle('notifications:requestPermission', (): NotificationPermissionStatusResult => { - triggerStartupNotificationRegistration(store) - return getPermissionStatus() - }) + ipcMain.handle( + 'notifications:probeDelivery', + async (_event, args?: { force?: boolean }): Promise => { + // Why: macOS-only. Windows/Linux have no equivalent first-use permission + // dialog, so the onboarding card that consumes this never renders there. + if (process.platform !== 'darwin' || !Notification.isSupported()) { + return { state: 'unsupported', authoritative: false } + } + // Why: probes (and the native helper's first-launch path) surface the + // macOS permission dialog — mark the one-shot startup registration as + // done so it can't fire a second prompt later. + if (store.getUI().notificationPermissionRequested !== true) { + store.updateUI({ notificationPermissionRequested: true }) + } + // Preferred source: the bundled helper reads the real + // UNUserNotificationCenter authorization. Silent, so polling with it + // tracks System Settings changes live without flashing banners. + const authorization = await readNotificationAuthorizationStatus() + if (authorization === 'authorized') { + lastObservedDeliveryOutcome = 'delivered' + return { state: 'delivered', authoritative: true } + } + if (authorization === 'denied') { + lastObservedDeliveryOutcome = 'failed' + return { state: 'blocked', authoritative: true } + } + if (authorization === 'not-determined') { + // Why: the dialog only appears once something asks — fire a single + // probe per session to trigger it, then report the pending decision. + if (!permissionDialogTriggeredThisSession) { + void probeNotificationDelivery() + } + return { state: 'awaiting-decision', authoritative: true } + } + // Helper unavailable ('unknown' status is also unusable evidence): + // fall back to scheduling-based probes with session caching, which + // avoids repeated probe banners when delivery works. + if (!args?.force && lastObservedDeliveryOutcome !== null) { + return { + state: lastObservedDeliveryOutcome === 'delivered' ? 'delivered' : 'blocked', + authoritative: false + } + } + return probeNotificationDelivery() + } + ) ipcMain.removeHandler('notifications:dismiss') ipcMain.handle('notifications:dismiss', (_event, ids: string[]): NotificationDismissResult => { @@ -255,6 +413,22 @@ export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntime _event, args: NotificationDispatchRequest ): NotificationDispatchResult | Promise => { + // Why: a terminal bell or agent completion that arrives while the window + // is minimized/hidden lights the tray attention dot — a passive cue that + // clears on window show/restore (see index.ts). Placed before the + // focus-suppression, cooldown, and enabled gates below so those do not + // hold back the dot. It rides the notification dispatch, so it follows the + // renderer's per-source decision to notify: bells always reach here, while + // an agent completion is suppressed upstream when its notification is + // disabled. Tray exists only on Windows, so setTrayAttention no-ops + // elsewhere. + if (args.source === 'agent-task-complete' || args.source === 'terminal-bell') { + const activeWindow = BrowserWindow.getAllWindows().find((win) => !win.isDestroyed()) ?? null + if (!isMainWindowVisible(activeWindow)) { + setTrayAttention(true) + } + } + const settings = store.getSettings().notifications if (!settings.enabled) { return { delivered: false, reason: 'disabled' } @@ -317,116 +491,140 @@ export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntime return { delivered: false, reason: 'not-supported' } } - if (getEffectiveNotificationSoundId(settings) !== 'system') { - notificationOptions.silent = true - } else if (process.platform === 'darwin') { - // Why: macOS treats an unset notification sound as silent. When Orca is - // using the OS sound, ask Electron for the default notification sound. - notificationOptions.sound = 'default' - } - const notification = new Notification(notificationOptions) - if (args.notificationId) { - const previous = activeNotificationsById.get(args.notificationId) - if (previous) { - previous.notification.close() - previous.release() - } - } - - // Why: prevent GC from collecting the notification (and its click - // handler) while it's still visible in macOS Notification Center. - let clickHandler: (() => void) | null = null - let failedHandler: ((_event: unknown, error?: string) => void) | null = null - const entryForId: { notification: Notification; release: () => void } | null = - args.notificationId ? { notification, release: () => {} } : null - const release = retainNotificationUntilRelease(notification, () => { - if (clickHandler) { - notification.removeListener('click', clickHandler) - clickHandler = null + function deliverNativeNotification(): + | NotificationDispatchResult + | Promise { + if (getEffectiveNotificationSoundId(settings) !== 'system') { + notificationOptions.silent = true + } else if (process.platform === 'darwin') { + // Why: macOS treats an unset notification sound as silent. When Orca is + // using the OS sound, ask Electron for the default notification sound. + notificationOptions.sound = 'default' } - if (failedHandler) { - notification.removeListener('failed', failedHandler) - failedHandler = null - } - if ( - args.notificationId && - activeNotificationsById.get(args.notificationId) === entryForId - ) { - activeNotificationsById.delete(args.notificationId) + const notification = new Notification(notificationOptions) + if (args.notificationId) { + const previous = activeNotificationsById.get(args.notificationId) + if (previous) { + previous.notification.close() + previous.release() + } } - }) - if (entryForId && args.notificationId) { - entryForId.release = release - activeNotificationsById.set(args.notificationId, entryForId) - } - failedHandler = (_event, error) => { - // Why: Electron 42's macOS UNNotification backend reports unsigned - // apps and native delivery errors here; release immediately instead - // of retaining a dead notification until the fallback timer. - logNativeNotificationFailure(args.source, error) - release() - } - notification.on('failed', failedHandler) - - // Why: clicking a notification should bring Orca to the foreground and - // switch to the worktree/pane that triggered it. Worktree activation owns - // repo/sidebar state; the optional focusTerminal follow-up uses the stable - // pane leaf id so split-pane notifications land on the exact pane. - // Why: worktreeId is formatted as "repoId::worktreePath". If the - // separator is missing we cannot reliably extract a repoId, so skip - // the click-to-navigate binding — the notification still fires but - // clicking it will not attempt to switch to an unknown worktree. - if (args.worktreeId && args.worktreeId.includes('::')) { - const repoId = getRepoIdFromWorktreeId(args.worktreeId) - clickHandler = () => { - release() - const win = BrowserWindow.getAllWindows().find((w) => !w.isDestroyed()) - if (!win) { - return + // Why: prevent GC from collecting the notification (and its click + // handler) while it's still visible in macOS Notification Center. + let clickHandler: (() => void) | null = null + let failedHandler: ((_event: unknown, error?: string) => void) | null = null + const entryForId: { notification: Notification; release: () => void } | null = + args.notificationId ? { notification, release: () => {} } : null + const release = retainNotificationUntilRelease(notification, () => { + if (clickHandler) { + notification.removeListener('click', clickHandler) + clickHandler = null } - if (process.platform === 'darwin') { - app.focus({ steal: true }) + if (failedHandler) { + notification.removeListener('failed', failedHandler) + failedHandler = null } - if (win.isMinimized()) { - win.restore() + if ( + args.notificationId && + activeNotificationsById.get(args.notificationId) === entryForId + ) { + activeNotificationsById.delete(args.notificationId) } - win.focus() - win.webContents.send('ui:activateWorktree', { - repoId, - worktreeId: args.worktreeId - }) - const paneTarget = args.paneKey ? parsePaneKey(args.paneKey) : null - if (paneTarget) { - win.webContents.send('ui:focusTerminal', { - tabId: paneTarget.tabId, - worktreeId: args.worktreeId, - leafId: paneTarget.leafId, - ackPaneKeyOnSuccess: args.paneKey, - flashFocusedPane: true, - scrollToBottomIfOutputSinceLastView: true + }) + if (entryForId && args.notificationId) { + entryForId.release = release + activeNotificationsById.set(args.notificationId, entryForId) + } + + failedHandler = (_event, error) => { + // Why: Electron 42's macOS UNNotification backend reports unsigned + // apps and native delivery errors here; release immediately instead + // of retaining a dead notification until the fallback timer. + logNativeNotificationFailure(args.source, error) + // A definitive rejection — feeds the permission card's evidence. + lastObservedDeliveryOutcome = 'failed' + release() + } + notification.on('failed', failedHandler) + + // Why: clicking a notification should bring Orca to the foreground and + // switch to the worktree/pane that triggered it. Worktree activation owns + // repo/sidebar state; the optional focusTerminal follow-up uses the stable + // pane leaf id so split-pane notifications land on the exact pane. + // Why: worktreeId is formatted as "repoId::worktreePath". If the + // separator is missing we cannot reliably extract a repoId, so skip + // the click-to-navigate binding — the notification still fires but + // clicking it will not attempt to switch to an unknown worktree. + if (args.worktreeId && args.worktreeId.includes('::')) { + const repoId = getRepoIdFromWorktreeId(args.worktreeId) + clickHandler = () => { + release() + const win = BrowserWindow.getAllWindows().find((w) => !w.isDestroyed()) + if (!win) { + return + } + if (process.platform === 'darwin') { + app.focus({ steal: true }) + } + if (win.isMinimized()) { + win.restore() + } + win.focus() + win.webContents.send('ui:activateWorktree', { + repoId, + worktreeId: args.worktreeId }) + const paneTarget = args.paneKey ? parsePaneKey(args.paneKey) : null + if (paneTarget) { + win.webContents.send('ui:focusTerminal', { + tabId: paneTarget.tabId, + worktreeId: args.worktreeId, + leafId: paneTarget.leafId, + ackPaneKeyOnSuccess: args.paneKey, + flashFocusedPane: true, + scrollToBottomIfOutputSinceLastView: true + }) + } } + notification.on('click', clickHandler) } - notification.on('click', clickHandler) - } - const displayConfirmation = args.requireDisplayConfirmation - ? waitForNotificationDisplay(notification) - : null - notification.show() + const displayConfirmation = args.requireDisplayConfirmation + ? waitForNotificationDisplay(notification) + : null + notification.show() + + if (displayConfirmation) { + return displayConfirmation.then((displayed) => { + if (!displayed) { + release() + return { delivered: false, reason: 'not-displayed' } + } + lastObservedDeliveryOutcome = 'delivered' + return { delivered: true } + }) + } - if (displayConfirmation) { - return displayConfirmation.then((displayed) => { - if (!displayed) { - release() - return { delivered: false, reason: 'not-displayed' } - } - return { delivered: true } - }) + return { delivered: true } } - return { delivered: true } + if (process.platform !== 'darwin') { + return deliverNativeNotification() + } + // Why: macOS silently swallows accepted notifications while permission + // is denied or the permission dialog is unanswered (verified on macOS + // 26). Skip the doomed native notification and tell the caller, so the + // renderer can surface an in-app fallback pointing at System Settings. + // The mobile dispatch above is unaffected — paired devices have their + // own notification channel. + return readNotificationAuthorizationStatus().then((authorization) => { + if (authorization === 'denied' || authorization === 'not-determined') { + lastObservedDeliveryOutcome = 'failed' + return { delivered: false, reason: 'blocked-by-system' } + } + return deliverNativeNotification() + }) } ) @@ -564,6 +762,7 @@ export function triggerStartupNotificationRegistration(store: Store): void { // Why: Electron 42 requires code-signed macOS apps for UNNotification // delivery. Unsigned builds fail here instead of producing the permission UI. logNativeNotificationFailure('startup registration', error) + lastObservedDeliveryOutcome = 'failed' cleanup() } diff --git a/src/main/ipc/orca-profile-auth-handlers.test.ts b/src/main/ipc/orca-profile-auth-handlers.test.ts new file mode 100644 index 000000000000..73726dd2b52b --- /dev/null +++ b/src/main/ipc/orca-profile-auth-handlers.test.ts @@ -0,0 +1,171 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + handlers, + createCloudLinkedOrcaProfileMock, + connectCurrentOrcaProfileMock, + getCurrentOrcaProfileAuthStatusMock, + refreshCurrentOrcaProfileAuthMock, + selectCurrentOrcaProfileOrgMock, + signOutCurrentOrcaProfileMock +} = vi.hoisted(() => ({ + handlers: new Map unknown>(), + createCloudLinkedOrcaProfileMock: vi.fn(), + connectCurrentOrcaProfileMock: vi.fn(), + getCurrentOrcaProfileAuthStatusMock: vi.fn(), + refreshCurrentOrcaProfileAuthMock: vi.fn(), + selectCurrentOrcaProfileOrgMock: vi.fn(), + signOutCurrentOrcaProfileMock: vi.fn() +})) + +vi.mock('electron', () => ({ + app: { + exit: vi.fn(), + getPath: () => '/tmp/orca-user-data', + relaunch: vi.fn() + }, + ipcMain: { + handle: vi.fn((channel: string, handler: (_event: unknown, args?: unknown) => unknown) => { + handlers.set(channel, handler) + }) + } +})) + +vi.mock('../tray/system-tray', () => ({ + destroySystemTray: vi.fn() +})) + +vi.mock('../orca-profiles/profile-index-store', () => ({ + createLocalOrcaProfile: vi.fn(), + getOrcaProfileListState: vi.fn(), + seedNewOrcaProfileTelemetryConsent: vi.fn(), + setActiveOrcaProfile: vi.fn() +})) + +vi.mock('../orca-profiles/profile-project-transfer', () => ({ + transferOrcaProfileProject: vi.fn() +})) + +vi.mock('../orca-profiles/profile-cloud-service', () => ({ + createCloudLinkedOrcaProfile: createCloudLinkedOrcaProfileMock, + connectCurrentOrcaProfile: connectCurrentOrcaProfileMock, + getCurrentOrcaProfileAuthStatus: getCurrentOrcaProfileAuthStatusMock, + refreshCurrentOrcaProfileAuth: refreshCurrentOrcaProfileAuthMock, + selectCurrentOrcaProfileOrg: selectCurrentOrcaProfileOrgMock, + signOutCurrentOrcaProfile: signOutCurrentOrcaProfileMock +})) + +import { registerOrcaProfileHandlers } from './orca-profiles' + +describe('registerOrcaProfileHandlers auth channels', () => { + beforeEach(() => { + handlers.clear() + createCloudLinkedOrcaProfileMock.mockReset() + connectCurrentOrcaProfileMock.mockReset() + getCurrentOrcaProfileAuthStatusMock.mockReset() + refreshCurrentOrcaProfileAuthMock.mockReset() + selectCurrentOrcaProfileOrgMock.mockReset() + signOutCurrentOrcaProfileMock.mockReset() + }) + + it('returns auth status for the current profile', async () => { + const status = { + activeProfileId: 'local-default', + configured: false, + state: 'unconfigured', + persistence: 'none' + } + getCurrentOrcaProfileAuthStatusMock.mockReturnValue(status) + registerOrcaProfileHandlers({ + flush: vi.fn(), + freezeWrites: vi.fn(), + getSettings: () => ({}) + } as never) + + await expect(Promise.resolve(handlers.get('orcaProfiles:authStatus')?.(null))).resolves.toBe( + status + ) + expect(getCurrentOrcaProfileAuthStatusMock).toHaveBeenCalledWith('/tmp/orca-user-data') + }) + + it('connects and signs out the current profile through the cloud service', async () => { + const connectResult = { status: 'unconfigured', auth: { activeProfileId: 'local-default' } } + const signOutResult = { status: 'signed-out', auth: { activeProfileId: 'local-default' } } + connectCurrentOrcaProfileMock.mockResolvedValue(connectResult) + signOutCurrentOrcaProfileMock.mockResolvedValue(signOutResult) + registerOrcaProfileHandlers({ + flush: vi.fn(), + freezeWrites: vi.fn(), + getSettings: () => ({}) + } as never) + + await expect( + Promise.resolve(handlers.get('orcaProfiles:connectCurrent')?.(null)) + ).resolves.toBe(connectResult) + await expect( + Promise.resolve(handlers.get('orcaProfiles:signOutCurrent')?.(null)) + ).resolves.toBe(signOutResult) + expect(connectCurrentOrcaProfileMock).toHaveBeenCalledWith('/tmp/orca-user-data') + expect(signOutCurrentOrcaProfileMock).toHaveBeenCalledWith('/tmp/orca-user-data') + }) + + it('refreshes profile auth through the cloud service', async () => { + const refreshResult = { status: 'refreshed', auth: { activeProfileId: 'local-default' } } + refreshCurrentOrcaProfileAuthMock.mockResolvedValue(refreshResult) + registerOrcaProfileHandlers({ + flush: vi.fn(), + freezeWrites: vi.fn(), + getSettings: () => ({}) + } as never) + + await expect(Promise.resolve(handlers.get('orcaProfiles:refreshAuth')?.(null))).resolves.toBe( + refreshResult + ) + expect(refreshCurrentOrcaProfileAuthMock).toHaveBeenCalledWith('/tmp/orca-user-data') + }) + + it('validates organization selection before calling the cloud service', async () => { + const selectResult = { status: 'selected', auth: { activeProfileId: 'local-default' } } + selectCurrentOrcaProfileOrgMock.mockResolvedValue(selectResult) + registerOrcaProfileHandlers({ + flush: vi.fn(), + freezeWrites: vi.fn(), + getSettings: () => ({}) + } as never) + + await expect( + Promise.resolve(handlers.get('orcaProfiles:selectOrg')?.(null, { orgId: ' org-1 ' })) + ).resolves.toBe(selectResult) + expect(selectCurrentOrcaProfileOrgMock).toHaveBeenCalledWith('/tmp/orca-user-data', 'org-1') + + await expect( + Promise.resolve(handlers.get('orcaProfiles:selectOrg')?.(null, { orgId: ' ' })) + ).rejects.toThrow('invalid_orca_profile_org_selection') + }) + + it('creates cloud-linked profiles with trimmed optional args', async () => { + const createResult = { + status: 'created', + auth: { activeProfileId: 'local-default' }, + activeProfileId: 'local-default', + profiles: [], + profile: { id: 'cloud-1' } + } + createCloudLinkedOrcaProfileMock.mockResolvedValue(createResult) + registerOrcaProfileHandlers({ + flush: vi.fn(), + freezeWrites: vi.fn(), + getSettings: () => ({}) + } as never) + + await expect( + Promise.resolve( + handlers.get('orcaProfiles:createCloudLinked')?.(null, { orgId: ' org-1 ', name: ' Acme ' }) + ) + ).resolves.toBe(createResult) + expect(createCloudLinkedOrcaProfileMock).toHaveBeenCalledWith('/tmp/orca-user-data', { + orgId: 'org-1', + name: 'Acme' + }) + }) +}) diff --git a/src/main/ipc/orca-profile-org-members-handlers.test.ts b/src/main/ipc/orca-profile-org-members-handlers.test.ts new file mode 100644 index 000000000000..6dc6775a6383 --- /dev/null +++ b/src/main/ipc/orca-profile-org-members-handlers.test.ts @@ -0,0 +1,116 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + handlers, + listOrcaProfileOrgMembersMock, + inviteOrcaProfileOrgMemberMock, + revokeOrcaProfileOrgInviteMock, + changeOrcaProfileOrgMemberRoleMock, + removeOrcaProfileOrgMemberMock +} = vi.hoisted(() => ({ + handlers: new Map unknown>(), + listOrcaProfileOrgMembersMock: vi.fn(), + inviteOrcaProfileOrgMemberMock: vi.fn(), + revokeOrcaProfileOrgInviteMock: vi.fn(), + changeOrcaProfileOrgMemberRoleMock: vi.fn(), + removeOrcaProfileOrgMemberMock: vi.fn() +})) + +vi.mock('electron', () => ({ + ipcMain: { + handle: vi.fn((channel: string, handler: (_event: unknown, args?: unknown) => unknown) => { + handlers.set(channel, handler) + }) + } +})) + +vi.mock('../orca-profiles/profile-storage-paths', () => ({ + getProfileUserDataPath: () => '/tmp/orca-user-data' +})) + +vi.mock('../orca-profiles/profile-cloud-org-members-service', () => ({ + listOrcaProfileOrgMembers: listOrcaProfileOrgMembersMock, + inviteOrcaProfileOrgMember: inviteOrcaProfileOrgMemberMock, + revokeOrcaProfileOrgInvite: revokeOrcaProfileOrgInviteMock, + changeOrcaProfileOrgMemberRole: changeOrcaProfileOrgMemberRoleMock, + removeOrcaProfileOrgMember: removeOrcaProfileOrgMemberMock +})) + +import { registerOrcaProfileOrgMemberHandlers } from './orca-profile-org-members-handlers' + +function invoke(channel: string, args?: unknown): unknown { + const handler = handlers.get(channel) + if (!handler) { + throw new Error(`No handler for ${channel}`) + } + return handler({}, args) +} + +describe('registerOrcaProfileOrgMemberHandlers', () => { + beforeEach(() => { + handlers.clear() + listOrcaProfileOrgMembersMock.mockReset().mockResolvedValue({ status: 'ok', roster: {} }) + inviteOrcaProfileOrgMemberMock.mockReset().mockResolvedValue({ status: 'ok' }) + revokeOrcaProfileOrgInviteMock.mockReset().mockResolvedValue({ status: 'ok' }) + changeOrcaProfileOrgMemberRoleMock.mockReset().mockResolvedValue({ status: 'ok' }) + removeOrcaProfileOrgMemberMock.mockReset().mockResolvedValue({ status: 'ok' }) + registerOrcaProfileOrgMemberHandlers() + }) + + it('registers all five org-member channels', () => { + expect([...handlers.keys()].sort()).toEqual( + [ + 'orcaProfiles:orgInviteRevoke', + 'orcaProfiles:orgMemberChangeRole', + 'orcaProfiles:orgMemberInvite', + 'orcaProfiles:orgMemberRemove', + 'orcaProfiles:orgMembersList' + ].sort() + ) + }) + + it('forwards a valid invite to the service with a trimmed email', async () => { + await invoke('orcaProfiles:orgMemberInvite', { + orgId: 'org-1', + email: ' new@example.com ', + role: 'admin' + }) + expect(inviteOrcaProfileOrgMemberMock).toHaveBeenCalledWith('/tmp/orca-user-data', { + orgId: 'org-1', + email: 'new@example.com', + role: 'admin' + }) + }) + + it('rejects an invite with a missing org id', async () => { + await expect( + invoke('orcaProfiles:orgMemberInvite', { email: 'a@b.com', role: 'member' }) + ).rejects.toThrow('invalid_orca_profile_org_selection') + expect(inviteOrcaProfileOrgMemberMock).not.toHaveBeenCalled() + }) + + it('rejects an invite with an unknown role', async () => { + await expect( + invoke('orcaProfiles:orgMemberInvite', { orgId: 'org-1', email: 'a@b.com', role: 'root' }) + ).rejects.toThrow('invalid_orca_org_role') + }) + + it('rejects a role change with a blank user id', async () => { + await expect( + invoke('orcaProfiles:orgMemberChangeRole', { orgId: 'org-1', userId: ' ', role: 'admin' }) + ).rejects.toThrow('invalid_orca_org_member_user') + }) + + it('forwards remove and revoke with validated args', async () => { + await invoke('orcaProfiles:orgMemberRemove', { orgId: 'org-1', userId: 'user-2' }) + expect(removeOrcaProfileOrgMemberMock).toHaveBeenCalledWith('/tmp/orca-user-data', { + orgId: 'org-1', + userId: 'user-2' + }) + await invoke('orcaProfiles:orgInviteRevoke', { orgId: 'org-1', email: 'gone@b.com' }) + expect(revokeOrcaProfileOrgInviteMock).toHaveBeenCalledWith('/tmp/orca-user-data', { + orgId: 'org-1', + email: 'gone@b.com' + }) + }) +}) diff --git a/src/main/ipc/orca-profile-org-members-handlers.ts b/src/main/ipc/orca-profile-org-members-handlers.ts new file mode 100644 index 000000000000..40eab31b7d49 --- /dev/null +++ b/src/main/ipc/orca-profile-org-members-handlers.ts @@ -0,0 +1,128 @@ +import { ipcMain } from 'electron' +import type { + OrcaOrgRole, + OrcaProfileOrgInviteRevokeArgs, + OrcaProfileOrgMemberChangeRoleArgs, + OrcaProfileOrgMemberInviteArgs, + OrcaProfileOrgMemberMutationResult, + OrcaProfileOrgMemberRemoveArgs, + OrcaProfileOrgMembersListArgs, + OrcaProfileOrgMembersListResult +} from '../../shared/orca-profiles' +import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' +import { + changeOrcaProfileOrgMemberRole, + inviteOrcaProfileOrgMember, + listOrcaProfileOrgMembers, + removeOrcaProfileOrgMember, + revokeOrcaProfileOrgInvite +} from '../orca-profiles/profile-cloud-org-members-service' + +function orgMembersScopedArgs(args: unknown): { orgId: string; record: Record } { + if (!args || typeof args !== 'object') { + throw new Error('invalid_orca_profile_org_selection') + } + const record = args as Record + const orgId = typeof record.orgId === 'string' ? record.orgId.trim() : '' + if (!orgId) { + throw new Error('invalid_orca_profile_org_selection') + } + return { orgId, record } +} + +function orgRoleFromUnknown(value: unknown): OrcaOrgRole { + if (value === 'owner' || value === 'admin' || value === 'member') { + return value + } + throw new Error('invalid_orca_org_role') +} + +function orgEmailFromUnknown(value: unknown): string { + const email = typeof value === 'string' ? value.trim() : '' + if (!email) { + throw new Error('invalid_orca_org_member_email') + } + return email +} + +function orgUserIdFromUnknown(value: unknown): string { + const userId = typeof value === 'string' ? value.trim() : '' + if (!userId) { + throw new Error('invalid_orca_org_member_user') + } + return userId +} + +function orgMemberInviteArgsFromUnknown(args: unknown): OrcaProfileOrgMemberInviteArgs { + const { orgId, record } = orgMembersScopedArgs(args) + return { orgId, email: orgEmailFromUnknown(record.email), role: orgRoleFromUnknown(record.role) } +} + +function orgInviteRevokeArgsFromUnknown(args: unknown): OrcaProfileOrgInviteRevokeArgs { + const { orgId, record } = orgMembersScopedArgs(args) + return { orgId, email: orgEmailFromUnknown(record.email) } +} + +function orgMemberChangeRoleArgsFromUnknown(args: unknown): OrcaProfileOrgMemberChangeRoleArgs { + const { orgId, record } = orgMembersScopedArgs(args) + return { + orgId, + userId: orgUserIdFromUnknown(record.userId), + role: orgRoleFromUnknown(record.role) + } +} + +function orgMemberRemoveArgsFromUnknown(args: unknown): OrcaProfileOrgMemberRemoveArgs { + const { orgId, record } = orgMembersScopedArgs(args) + return { orgId, userId: orgUserIdFromUnknown(record.userId) } +} + +export function registerOrcaProfileOrgMemberHandlers(): void { + ipcMain.handle( + 'orcaProfiles:orgMembersList', + async ( + _event, + rawArgs: OrcaProfileOrgMembersListArgs + ): Promise => + listOrcaProfileOrgMembers(getProfileUserDataPath(), orgMembersScopedArgs(rawArgs).orgId) + ) + + ipcMain.handle( + 'orcaProfiles:orgMemberInvite', + async ( + _event, + rawArgs: OrcaProfileOrgMemberInviteArgs + ): Promise => + inviteOrcaProfileOrgMember(getProfileUserDataPath(), orgMemberInviteArgsFromUnknown(rawArgs)) + ) + + ipcMain.handle( + 'orcaProfiles:orgInviteRevoke', + async ( + _event, + rawArgs: OrcaProfileOrgInviteRevokeArgs + ): Promise => + revokeOrcaProfileOrgInvite(getProfileUserDataPath(), orgInviteRevokeArgsFromUnknown(rawArgs)) + ) + + ipcMain.handle( + 'orcaProfiles:orgMemberChangeRole', + async ( + _event, + rawArgs: OrcaProfileOrgMemberChangeRoleArgs + ): Promise => + changeOrcaProfileOrgMemberRole( + getProfileUserDataPath(), + orgMemberChangeRoleArgsFromUnknown(rawArgs) + ) + ) + + ipcMain.handle( + 'orcaProfiles:orgMemberRemove', + async ( + _event, + rawArgs: OrcaProfileOrgMemberRemoveArgs + ): Promise => + removeOrcaProfileOrgMember(getProfileUserDataPath(), orgMemberRemoveArgsFromUnknown(rawArgs)) + ) +} diff --git a/src/main/ipc/orca-profiles.test.ts b/src/main/ipc/orca-profiles.test.ts new file mode 100644 index 000000000000..291a3dfe2f26 --- /dev/null +++ b/src/main/ipc/orca-profiles.test.ts @@ -0,0 +1,321 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { + handlers, + appExitMock, + appQuitMock, + appRelaunchMock, + destroySystemTrayMock, + createLocalOrcaProfileMock, + getOrcaProfileListStateMock, + seedNewOrcaProfileTelemetryConsentMock, + setActiveOrcaProfileMock, + transferOrcaProfileProjectMock +} = vi.hoisted(() => ({ + handlers: new Map unknown>(), + appExitMock: vi.fn(), + appQuitMock: vi.fn(), + appRelaunchMock: vi.fn(), + destroySystemTrayMock: vi.fn(), + createLocalOrcaProfileMock: vi.fn(), + getOrcaProfileListStateMock: vi.fn(), + seedNewOrcaProfileTelemetryConsentMock: vi.fn(), + setActiveOrcaProfileMock: vi.fn(), + transferOrcaProfileProjectMock: vi.fn() +})) + +vi.mock('electron', () => ({ + app: { + exit: appExitMock, + quit: appQuitMock, + relaunch: appRelaunchMock, + getPath: () => '/tmp/orca-user-data' + }, + ipcMain: { + handle: vi.fn((channel: string, handler: (_event: unknown, args?: unknown) => unknown) => { + handlers.set(channel, handler) + }) + } +})) + +vi.mock('../tray/system-tray', () => ({ + destroySystemTray: destroySystemTrayMock +})) + +vi.mock('../orca-profiles/profile-index-store', () => ({ + createLocalOrcaProfile: createLocalOrcaProfileMock, + getOrcaProfileListState: getOrcaProfileListStateMock, + seedNewOrcaProfileTelemetryConsent: seedNewOrcaProfileTelemetryConsentMock, + setActiveOrcaProfile: setActiveOrcaProfileMock +})) + +function makeStoreMock(flush = vi.fn()): { + flush: typeof flush + freezeWrites: ReturnType + getSettings: () => Record +} { + return { flush, freezeWrites: vi.fn(), getSettings: () => ({}) } +} + +vi.mock('../orca-profiles/profile-project-transfer', () => ({ + transferOrcaProfileProject: transferOrcaProfileProjectMock +})) + +import { registerOrcaProfileHandlers } from './orca-profiles' + +describe('registerOrcaProfileHandlers', () => { + beforeEach(() => { + vi.useFakeTimers() + handlers.clear() + appExitMock.mockReset() + appQuitMock.mockReset() + appRelaunchMock.mockReset() + destroySystemTrayMock.mockReset() + createLocalOrcaProfileMock.mockReset() + getOrcaProfileListStateMock.mockReset() + seedNewOrcaProfileTelemetryConsentMock.mockReset() + setActiveOrcaProfileMock.mockReset() + transferOrcaProfileProjectMock.mockReset() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('registers list and create handlers', async () => { + const listState = { + activeProfileId: 'local-default', + profiles: [{ id: 'local-default', name: 'Personal' }] + } + const createState = { + ...listState, + profile: { id: 'local-work', name: 'Work' } + } + getOrcaProfileListStateMock.mockReturnValue(listState) + createLocalOrcaProfileMock.mockReturnValue(createState) + + registerOrcaProfileHandlers(makeStoreMock() as never) + + await expect(Promise.resolve(handlers.get('orcaProfiles:list')?.(null))).resolves.toEqual({ + ...listState, + multiProfileUi: false + }) + await expect( + Promise.resolve(handlers.get('orcaProfiles:createLocal')?.(null, { name: 'Work' })) + ).resolves.toBe(createState) + expect(createLocalOrcaProfileMock).toHaveBeenCalledWith({ name: 'Work' }) + }) + + it('reports multiProfileUi when the env flag is set', async () => { + const previous = process.env.ORCA_MULTI_PROFILE_UI + process.env.ORCA_MULTI_PROFILE_UI = '1' + try { + getOrcaProfileListStateMock.mockReturnValue({ + activeProfileId: 'local-default', + profiles: [] + }) + registerOrcaProfileHandlers(makeStoreMock() as never) + + await expect(Promise.resolve(handlers.get('orcaProfiles:list')?.(null))).resolves.toEqual({ + activeProfileId: 'local-default', + profiles: [], + multiProfileUi: true + }) + } finally { + if (previous === undefined) { + delete process.env.ORCA_MULTI_PROFILE_UI + } else { + process.env.ORCA_MULTI_PROFILE_UI = previous + } + } + }) + + it('marks the target profile active, flushes, and relaunches', async () => { + const flush = vi.fn() + const onBeforeRelaunch = vi.fn() + getOrcaProfileListStateMock.mockReturnValue({ + activeProfileId: 'local-default', + profiles: [] + }) + setActiveOrcaProfileMock.mockReturnValue({ + activeProfileId: 'local-work', + profiles: [] + }) + registerOrcaProfileHandlers(makeStoreMock(flush) as never, { onBeforeRelaunch }) + + const resultPromise = Promise.resolve( + handlers.get('orcaProfiles:switch')?.(null, { profileId: 'local-work' }) + ) + + await expect(resultPromise).resolves.toEqual({ status: 'relaunching' }) + expect(setActiveOrcaProfileMock).toHaveBeenCalledWith('local-work') + expect(flush).toHaveBeenCalledOnce() + expect(onBeforeRelaunch).toHaveBeenCalledOnce() + expect(flush.mock.invocationCallOrder[0]).toBeLessThan( + setActiveOrcaProfileMock.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY + ) + expect(appRelaunchMock).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(150) + + expect(appRelaunchMock).toHaveBeenCalledOnce() + // Why quit, not exit: before-quit/will-quit teardown (scrollback capture, + // PTY kill, daemon checkpoints) must run on a profile switch. + expect(appQuitMock).toHaveBeenCalledOnce() + expect(appExitMock).not.toHaveBeenCalled() + }) + + it('does not mark a profile active when current profile flush fails', async () => { + const flush = vi.fn(() => { + throw new Error('flush_failed') + }) + getOrcaProfileListStateMock.mockReturnValue({ + activeProfileId: 'local-default', + profiles: [] + }) + registerOrcaProfileHandlers(makeStoreMock(flush) as never) + + await expect( + Promise.resolve(handlers.get('orcaProfiles:switch')?.(null, { profileId: 'local-work' })) + ).rejects.toThrow('flush_failed') + + expect(setActiveOrcaProfileMock).not.toHaveBeenCalled() + expect(appRelaunchMock).not.toHaveBeenCalled() + }) + + it('does not relaunch when switching to the active profile', async () => { + getOrcaProfileListStateMock.mockReturnValue({ + activeProfileId: 'local-default', + profiles: [] + }) + registerOrcaProfileHandlers(makeStoreMock() as never) + + await expect( + Promise.resolve(handlers.get('orcaProfiles:switch')?.(null, { profileId: 'local-default' })) + ).resolves.toEqual({ status: 'already-active' }) + + expect(setActiveOrcaProfileMock).not.toHaveBeenCalled() + expect(appRelaunchMock).not.toHaveBeenCalled() + }) + + it('rejects invalid profile ids', async () => { + registerOrcaProfileHandlers(makeStoreMock() as never) + + await expect( + Promise.resolve(handlers.get('orcaProfiles:switch')?.(null, { profileId: ' ' })) + ).rejects.toThrow('invalid_orca_profile_id') + }) + + it('transfers projects between inactive profiles after flushing active state', async () => { + const flush = vi.fn() + const result = { + status: 'transferred', + mode: 'copy', + sourceProfileId: 'personal', + targetProfileId: 'work', + sourceRepoId: 'repo-1', + targetRepoId: 'repo-2', + targetProjectId: 'repo:repo-2' + } + getOrcaProfileListStateMock.mockReturnValue({ + activeProfileId: 'personal', + profiles: [] + }) + transferOrcaProfileProjectMock.mockReturnValue(result) + registerOrcaProfileHandlers(makeStoreMock(flush) as never) + + await expect( + Promise.resolve( + handlers.get('orcaProfiles:transferProject')?.(null, { + sourceProfileId: ' personal ', + targetProfileId: ' work ', + repoId: ' repo-1 ', + mode: 'copy' + }) + ) + ).resolves.toBe(result) + + expect(flush).toHaveBeenCalledOnce() + expect(transferOrcaProfileProjectMock).toHaveBeenCalledWith( + { + sourceProfileId: 'personal', + targetProfileId: 'work', + repoId: 'repo-1', + mode: 'copy' + }, + '/tmp/orca-user-data' + ) + }) + + it('moves a project out of the active profile and relaunches into the target profile', async () => { + const flush = vi.fn() + const onBeforeRelaunch = vi.fn() + const result = { + status: 'transferred', + mode: 'move', + sourceProfileId: 'personal', + targetProfileId: 'work', + sourceRepoId: 'repo-1', + targetRepoId: 'repo-1', + targetProjectId: 'repo:repo-1' + } + getOrcaProfileListStateMock.mockReturnValue({ + activeProfileId: 'personal', + profiles: [] + }) + transferOrcaProfileProjectMock.mockReturnValue(result) + registerOrcaProfileHandlers(makeStoreMock(flush) as never, { onBeforeRelaunch }) + + await expect( + Promise.resolve( + handlers.get('orcaProfiles:transferProject')?.(null, { + sourceProfileId: 'personal', + targetProfileId: 'work', + repoId: 'repo-1', + mode: 'move' + }) + ) + ).resolves.toEqual({ ...result, willRelaunch: true }) + + expect(onBeforeRelaunch).toHaveBeenCalledOnce() + expect(flush).toHaveBeenCalledOnce() + expect(transferOrcaProfileProjectMock).toHaveBeenCalledWith( + { + sourceProfileId: 'personal', + targetProfileId: 'work', + repoId: 'repo-1', + mode: 'move' + }, + '/tmp/orca-user-data' + ) + expect(setActiveOrcaProfileMock).toHaveBeenCalledWith('work') + expect(appRelaunchMock).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(150) + + expect(appRelaunchMock).toHaveBeenCalledOnce() + expect(appQuitMock).toHaveBeenCalledOnce() + expect(appExitMock).not.toHaveBeenCalled() + }) + + it('rejects transfers that would mutate the active target profile offline', async () => { + getOrcaProfileListStateMock.mockReturnValue({ + activeProfileId: 'work', + profiles: [] + }) + registerOrcaProfileHandlers(makeStoreMock() as never) + + await expect( + Promise.resolve( + handlers.get('orcaProfiles:transferProject')?.(null, { + sourceProfileId: 'personal', + targetProfileId: 'work', + repoId: 'repo-1', + mode: 'copy' + }) + ) + ).rejects.toThrow('active_target_orca_profile_transfer_requires_relaunch') + + expect(transferOrcaProfileProjectMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/ipc/orca-profiles.ts b/src/main/ipc/orca-profiles.ts new file mode 100644 index 000000000000..fa6a57859e92 --- /dev/null +++ b/src/main/ipc/orca-profiles.ts @@ -0,0 +1,291 @@ +import { app, ipcMain } from 'electron' +import type { Store } from '../persistence' +import type { + CreateLocalOrcaProfileArgs, + CreateLocalOrcaProfileResult, + CreateCloudLinkedOrcaProfileArgs, + CreateCloudLinkedOrcaProfileResult, + FindOrcaProfileProjectsByPathArgs, + FindOrcaProfileProjectsByPathResult, + OrcaProfileListResult, + RefreshCurrentOrcaProfileAuthResult, + SwitchOrcaProfileArgs, + SwitchOrcaProfileResult, + TransferOrcaProfileProjectArgs, + TransferOrcaProfileProjectResult, + ConnectCurrentOrcaProfileResult, + OrcaProfileAuthStatus, + SelectOrcaProfileOrgArgs, + SelectOrcaProfileOrgResult, + SignOutCurrentOrcaProfileResult +} from '../../shared/orca-profiles' +import { + createLocalOrcaProfile, + getOrcaProfileListState, + seedNewOrcaProfileTelemetryConsent, + setActiveOrcaProfile +} from '../orca-profiles/profile-index-store' +import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' +import { isMultiProfileUiEnabled } from '../orca-profiles/profile-ui-scope' +import { transferOrcaProfileProject } from '../orca-profiles/profile-project-transfer' +import { findOrcaProfileProjectsByPath } from '../orca-profiles/profile-project-presence' +import { normalizeExecutionHostId } from '../../shared/execution-host' +import { + createCloudLinkedOrcaProfile, + connectCurrentOrcaProfile, + getCurrentOrcaProfileAuthStatus, + refreshCurrentOrcaProfileAuth, + selectCurrentOrcaProfileOrg, + signOutCurrentOrcaProfile +} from '../orca-profiles/profile-cloud-service' +import { registerOrcaProfileOrgMemberHandlers } from './orca-profile-org-members-handlers' + +type RegisterOrcaProfileHandlersOptions = { + onBeforeRelaunch?: () => void | Promise +} + +function profileIdFromArgs(args: unknown): string { + if ( + !args || + typeof args !== 'object' || + typeof (args as SwitchOrcaProfileArgs).profileId !== 'string' + ) { + throw new Error('invalid_orca_profile_id') + } + const profileId = (args as SwitchOrcaProfileArgs).profileId.trim() + if (!profileId) { + throw new Error('invalid_orca_profile_id') + } + return profileId +} + +function transferProjectArgsFromUnknown(args: unknown): TransferOrcaProfileProjectArgs { + if (!args || typeof args !== 'object') { + throw new Error('invalid_orca_profile_project_transfer') + } + const candidate = args as TransferOrcaProfileProjectArgs + const sourceProfileId = candidate.sourceProfileId?.trim() + const targetProfileId = candidate.targetProfileId?.trim() + const repoId = candidate.repoId?.trim() + const mode = candidate.mode + if (!sourceProfileId || !targetProfileId || !repoId || (mode !== 'move' && mode !== 'copy')) { + throw new Error('invalid_orca_profile_project_transfer') + } + return { + sourceProfileId, + targetProfileId, + repoId, + mode + } +} + +function findProjectsByPathArgsFromUnknown(args: unknown): FindOrcaProfileProjectsByPathArgs { + if (!args || typeof args !== 'object') { + throw new Error('invalid_orca_profile_project_path') + } + const candidate = args as FindOrcaProfileProjectsByPathArgs + const path = typeof candidate.path === 'string' ? candidate.path.trim() : '' + if (!path) { + throw new Error('invalid_orca_profile_project_path') + } + let executionHostId: FindOrcaProfileProjectsByPathArgs['executionHostId'] = null + if (candidate.executionHostId !== null && candidate.executionHostId !== undefined) { + if (typeof candidate.executionHostId !== 'string') { + throw new Error('invalid_orca_profile_project_path') + } + executionHostId = normalizeExecutionHostId(candidate.executionHostId) + if (!executionHostId) { + throw new Error('invalid_orca_profile_project_path') + } + } + return { + path, + connectionId: + typeof candidate.connectionId === 'string' ? candidate.connectionId.trim() || null : null, + executionHostId, + excludeProfileId: + typeof candidate.excludeProfileId === 'string' + ? candidate.excludeProfileId.trim() || null + : null + } +} + +function orgIdFromUnknown(args: unknown): string { + if (!args || typeof args !== 'object') { + throw new Error('invalid_orca_profile_org_selection') + } + const orgId = (args as SelectOrcaProfileOrgArgs).orgId?.trim() + if (!orgId) { + throw new Error('invalid_orca_profile_org_selection') + } + return orgId +} + +function createCloudLinkedProfileArgsFromUnknown(args: unknown): CreateCloudLinkedOrcaProfileArgs { + if (!args || typeof args !== 'object') { + return {} + } + const candidate = args as CreateCloudLinkedOrcaProfileArgs + const orgId = typeof candidate.orgId === 'string' ? candidate.orgId.trim() : undefined + const name = typeof candidate.name === 'string' ? candidate.name.trim() : undefined + return { + ...(orgId ? { orgId } : {}), + ...(name ? { name } : {}) + } +} + +async function runBeforeProfileRelaunch( + onBeforeRelaunch?: () => void | Promise +): Promise { + try { + await onBeforeRelaunch?.() + } catch (error) { + console.warn( + '[orca-profiles] Pre-relaunch cleanup failed; continuing profile switch:', + error instanceof Error ? error.name : typeof error + ) + } +} + +function scheduleProfileRelaunch(): void { + setTimeout(() => { + app.relaunch() + // Why: app.quit() (not app.exit) so before-quit/will-quit still run — + // renderer scrollback capture, PTY kill, stats flush, and daemon final + // checkpoints must not be skipped on a profile switch. + app.quit() + }, 150) +} + +export function registerOrcaProfileHandlers( + store: Store, + options: RegisterOrcaProfileHandlersOptions = {} +): void { + ipcMain.handle( + 'orcaProfiles:list', + (): OrcaProfileListResult => ({ + ...getOrcaProfileListState(), + multiProfileUi: isMultiProfileUiEnabled() + }) + ) + + ipcMain.handle( + 'orcaProfiles:authStatus', + (): OrcaProfileAuthStatus => getCurrentOrcaProfileAuthStatus(getProfileUserDataPath()) + ) + + ipcMain.handle( + 'orcaProfiles:createLocal', + (_event, args?: CreateLocalOrcaProfileArgs): CreateLocalOrcaProfileResult => { + const result = createLocalOrcaProfile(args) + seedNewOrcaProfileTelemetryConsent(result.profile.id, store.getSettings().telemetry) + return result + } + ) + + ipcMain.handle( + 'orcaProfiles:switch', + async (_event, args: SwitchOrcaProfileArgs): Promise => { + const profileId = profileIdFromArgs(args) + const current = getOrcaProfileListState() + if (profileId === current.activeProfileId) { + return { status: 'already-active' } + } + + // Why: the current profile must be persisted before the global index + // points startup at the target profile. + await runBeforeProfileRelaunch(options.onBeforeRelaunch) + store.flush() + setActiveOrcaProfile(profileId) + + scheduleProfileRelaunch() + + return { status: 'relaunching' } + } + ) + + ipcMain.handle( + 'orcaProfiles:transferProject', + async ( + _event, + rawArgs: TransferOrcaProfileProjectArgs + ): Promise => { + const args = transferProjectArgsFromUnknown(rawArgs) + const current = getOrcaProfileListState() + if (args.targetProfileId === current.activeProfileId) { + throw new Error('active_target_orca_profile_transfer_requires_relaunch') + } + if (args.mode === 'move' && args.sourceProfileId === current.activeProfileId) { + // Why: transfer before any relaunch side effect so a duplicate-target + // or validation failure cannot strand the app in a quitting state. + // flush→transfer→freeze runs synchronously with no interleaving, and + // the freeze keeps late sync saves from resurrecting the moved + // project from stale memory before the relaunch. + store.flush() + const result = transferOrcaProfileProject(args, getProfileUserDataPath()) + if (result.status === 'transferred') { + store.freezeWrites() + await runBeforeProfileRelaunch(options.onBeforeRelaunch) + setActiveOrcaProfile(args.targetProfileId) + scheduleProfileRelaunch() + return { ...result, willRelaunch: true } + } + return result + } + store.flush() + return transferOrcaProfileProject(args, getProfileUserDataPath()) + } + ) + + ipcMain.handle( + 'orcaProfiles:findProjectProfiles', + (_event, rawArgs: FindOrcaProfileProjectsByPathArgs): FindOrcaProfileProjectsByPathResult => + findOrcaProfileProjectsByPath( + findProjectsByPathArgsFromUnknown(rawArgs), + getProfileUserDataPath() + ) + ) + + ipcMain.handle( + 'orcaProfiles:connectCurrent', + async (): Promise => + connectCurrentOrcaProfile(getProfileUserDataPath()) + ) + + ipcMain.handle( + 'orcaProfiles:createCloudLinked', + async ( + _event, + rawArgs?: CreateCloudLinkedOrcaProfileArgs + ): Promise => { + const result = await createCloudLinkedOrcaProfile( + getProfileUserDataPath(), + createCloudLinkedProfileArgsFromUnknown(rawArgs) + ) + if (result.status === 'created') { + seedNewOrcaProfileTelemetryConsent(result.profile.id, store.getSettings().telemetry) + } + return result + } + ) + + ipcMain.handle( + 'orcaProfiles:refreshAuth', + async (): Promise => + refreshCurrentOrcaProfileAuth(getProfileUserDataPath()) + ) + + ipcMain.handle( + 'orcaProfiles:signOutCurrent', + async (): Promise => + signOutCurrentOrcaProfile(getProfileUserDataPath()) + ) + + ipcMain.handle( + 'orcaProfiles:selectOrg', + async (_event, rawArgs: SelectOrcaProfileOrgArgs): Promise => + selectCurrentOrcaProfileOrg(getProfileUserDataPath(), orgIdFromUnknown(rawArgs)) + ) + + registerOrcaProfileOrgMemberHandlers() +} diff --git a/src/main/ipc/parcel-watcher-entry-path.test.ts b/src/main/ipc/parcel-watcher-entry-path.test.ts new file mode 100644 index 000000000000..f8b59becc78f --- /dev/null +++ b/src/main/ipc/parcel-watcher-entry-path.test.ts @@ -0,0 +1,40 @@ +import path from 'node:path' +import { describe, expect, it } from 'vitest' +import { resolveWatcherProcessEntryPath } from './parcel-watcher-entry-path' + +describe('resolveWatcherProcessEntryPath', () => { + it('uses an adjacent entry when electron-vite appPath is already out/main', () => { + const builtMainPath = path.join(process.cwd(), 'out', 'main') + const adjacentEntry = path.join(builtMainPath, 'parcel-watcher-process-entry.js') + + expect( + resolveWatcherProcessEntryPath( + builtMainPath, + false, + (candidate) => candidate === adjacentEntry + ) + ).toBe(adjacentEntry) + }) + + it('uses the nested build entry when appPath is the project root', () => { + expect(resolveWatcherProcessEntryPath(process.cwd(), false, () => false)).toBe( + path.join(process.cwd(), 'out', 'main', 'parcel-watcher-process-entry.js') + ) + }) + + it('uses the unpacked nested entry for packaged apps', () => { + const appPath = path.join('C:', 'Orca', 'resources', 'app.asar') + + expect(resolveWatcherProcessEntryPath(appPath, true, () => true)).toBe( + path.join( + 'C:', + 'Orca', + 'resources', + 'app.asar.unpacked', + 'out', + 'main', + 'parcel-watcher-process-entry.js' + ) + ) + }) +}) diff --git a/src/main/ipc/parcel-watcher-entry-path.ts b/src/main/ipc/parcel-watcher-entry-path.ts new file mode 100644 index 000000000000..901331467154 --- /dev/null +++ b/src/main/ipc/parcel-watcher-entry-path.ts @@ -0,0 +1,37 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' + +type ElectronAppPath = { getAppPath(): string; isPackaged: boolean } + +function loadElectronApp(): ElectronAppPath | null { + try { + return require('electron').app ?? null + } catch { + return null + } +} + +export function resolveWatcherProcessEntryPath( + appPath: string, + isPackaged: boolean, + pathExists: (candidate: string) => boolean = existsSync +): string { + // Why: ELECTRON_RUN_AS_NODE bypasses Electron's asar integration, so the + // packaged entry must be forked from app.asar.unpacked. + const basePath = isPackaged ? appPath.replace('app.asar', 'app.asar.unpacked') : appPath + const adjacentBuildEntry = join(basePath, 'parcel-watcher-process-entry.js') + // Why: electron-vite's unpackaged appPath is already out/main. Appending + // out/main again silently disables crash isolation in dev and E2E builds. + if (!isPackaged && pathExists(adjacentBuildEntry)) { + return adjacentBuildEntry + } + return join(basePath, 'out', 'main', 'parcel-watcher-process-entry.js') +} + +export function getWatcherProcessEntryPath(): string { + const app = loadElectronApp() + return resolveWatcherProcessEntryPath( + app?.getAppPath() ?? process.cwd(), + app?.isPackaged === true + ) +} diff --git a/src/main/ipc/parcel-watcher-process-entry.test.ts b/src/main/ipc/parcel-watcher-process-entry.test.ts new file mode 100644 index 000000000000..13f808ab650e --- /dev/null +++ b/src/main/ipc/parcel-watcher-process-entry.test.ts @@ -0,0 +1,218 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { subscribeMock, writeFileSyncMock } = vi.hoisted(() => ({ + subscribeMock: vi.fn(), + writeFileSyncMock: vi.fn() +})) + +vi.mock('node:fs', () => ({ + mkdtempSync: vi.fn(() => '/tmp/orca-watcher-canary-test'), + rmSync: vi.fn(), + writeFileSync: writeFileSyncMock +})) +vi.mock('@parcel/watcher', () => ({ subscribe: subscribeMock })) + +describe('parcel watcher process canary', () => { + let originalMessageListeners: ReturnType + let originalExitListeners: ReturnType + let originalDisconnectListeners: ReturnType + + beforeEach(() => { + vi.useFakeTimers() + vi.resetModules() + subscribeMock.mockReset() + writeFileSyncMock.mockReset() + originalMessageListeners = process.listeners('message') + originalExitListeners = process.listeners('exit') + originalDisconnectListeners = process.listeners('disconnect') + }) + + afterEach(() => { + for (const listener of process.listeners('message')) { + if (!originalMessageListeners.includes(listener)) { + process.off('message', listener) + } + } + for (const listener of process.listeners('exit')) { + if (!originalExitListeners.includes(listener)) { + process.off('exit', listener) + } + } + for (const listener of process.listeners('disconnect')) { + if (!originalDisconnectListeners.includes(listener)) { + process.off('disconnect', listener) + } + } + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('does not restart while a native subscription is still crawling', async () => { + subscribeMock + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + .mockReturnValueOnce(new Promise(() => undefined)) + const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never) + + await import('./parcel-watcher-process-entry') + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 1, dir: '/large-repo', opts: {} }) + + await vi.advanceTimersByTimeAsync(30_000) + + expect(writeFileSyncMock).not.toHaveBeenCalled() + expect(exitSpy).not.toHaveBeenCalled() + }) + + it('invalidates an outstanding probe when another subscription starts crawling', async () => { + subscribeMock + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + .mockReturnValueOnce(new Promise(() => undefined)) + const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never) + + await import('./parcel-watcher-process-entry') + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 1, dir: '/repo', opts: {} }) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(10_000) + expect(writeFileSyncMock).toHaveBeenCalledTimes(1) + + process.emit('message', { op: 'subscribe', id: 2, dir: '/large-repo', opts: {} }) + await vi.advanceTimersByTimeAsync(20_000) + + expect(writeFileSyncMock).toHaveBeenCalledTimes(1) + expect(exitSpy).not.toHaveBeenCalled() + }) + + it('still restarts when unsubscribe deadlocks while another root remains live', async () => { + subscribeMock + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + .mockResolvedValueOnce({ unsubscribe: vi.fn(() => new Promise(() => undefined)) }) + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never) + + await import('./parcel-watcher-process-entry') + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 1, dir: '/repo-a', opts: {} }) + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 2, dir: '/repo-b', opts: {} }) + await vi.advanceTimersByTimeAsync(0) + + process.emit('message', { op: 'unsubscribe', id: 1 }) + await vi.advanceTimersByTimeAsync(30_000) + + expect(writeFileSyncMock).toHaveBeenCalledTimes(3) + expect(exitSpy).toHaveBeenCalledWith(2) + }) + + it('drains active crawls before starting teardown deadlock detection', async () => { + let finishSecondCrawl: + | ((subscription: { unsubscribe: () => Promise }) => void) + | undefined + const deadlockedUnsubscribe = vi.fn(() => new Promise(() => undefined)) + subscribeMock + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + .mockResolvedValueOnce({ unsubscribe: deadlockedUnsubscribe }) + .mockReturnValueOnce( + new Promise((resolve) => { + finishSecondCrawl = resolve + }) + ) + const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never) + + await import('./parcel-watcher-process-entry') + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 1, dir: '/repo-a', opts: {} }) + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 2, dir: '/repo-b', opts: {} }) + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'unsubscribe', id: 1 }) + + await vi.advanceTimersByTimeAsync(30_000) + expect(deadlockedUnsubscribe).not.toHaveBeenCalled() + expect(writeFileSyncMock).not.toHaveBeenCalled() + + finishSecondCrawl?.({ unsubscribe: vi.fn().mockResolvedValue(undefined) }) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(30_000) + + expect(deadlockedUnsubscribe).toHaveBeenCalledTimes(1) + expect(exitSpy).toHaveBeenCalledWith(2) + }) + + it('keeps later crawls queued behind teardown deadlock detection', async () => { + const deadlockedUnsubscribe = vi.fn(() => new Promise(() => undefined)) + subscribeMock + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + .mockResolvedValueOnce({ unsubscribe: deadlockedUnsubscribe }) + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never) + + await import('./parcel-watcher-process-entry') + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 1, dir: '/repo-a', opts: {} }) + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 2, dir: '/repo-b', opts: {} }) + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'unsubscribe', id: 1 }) + await vi.advanceTimersByTimeAsync(0) + expect(deadlockedUnsubscribe).toHaveBeenCalledTimes(1) + + process.emit('message', { op: 'subscribe', id: 3, dir: '/repo-c', opts: {} }) + await vi.advanceTimersByTimeAsync(30_000) + + expect(subscribeMock).toHaveBeenCalledTimes(3) + expect(exitSpy).toHaveBeenCalledWith(2) + }) + + it('reserves teardown order while its subscription is still crawling', async () => { + let finishCrawl: ((subscription: { unsubscribe: () => Promise }) => void) | undefined + const deadlockedUnsubscribe = vi.fn(() => new Promise(() => undefined)) + subscribeMock + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + .mockReturnValueOnce( + new Promise((resolve) => { + finishCrawl = resolve + }) + ) + .mockResolvedValueOnce({ unsubscribe: vi.fn() }) + const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never) + + await import('./parcel-watcher-process-entry') + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 1, dir: '/live-repo', opts: {} }) + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 2, dir: '/crawling-repo', opts: {} }) + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'unsubscribe', id: 2 }) + process.emit('message', { op: 'subscribe', id: 3, dir: '/later-repo', opts: {} }) + + await vi.advanceTimersByTimeAsync(30_000) + expect(writeFileSyncMock).not.toHaveBeenCalled() + + finishCrawl?.({ unsubscribe: deadlockedUnsubscribe }) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(30_000) + + expect(deadlockedUnsubscribe).toHaveBeenCalledTimes(1) + expect(subscribeMock).toHaveBeenCalledTimes(3) + expect(exitSpy).toHaveBeenCalledWith(2) + }) + + it('still restarts after consecutive missed events once every subscription is live', async () => { + subscribeMock.mockResolvedValue({ unsubscribe: vi.fn() }) + const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never) + + await import('./parcel-watcher-process-entry') + await vi.advanceTimersByTimeAsync(0) + process.emit('message', { op: 'subscribe', id: 1, dir: '/repo', opts: {} }) + await vi.advanceTimersByTimeAsync(0) + + await vi.advanceTimersByTimeAsync(30_000) + + expect(writeFileSyncMock).toHaveBeenCalledTimes(3) + expect(exitSpy).toHaveBeenCalledWith(2) + }) +}) diff --git a/src/main/ipc/parcel-watcher-process-entry.ts b/src/main/ipc/parcel-watcher-process-entry.ts new file mode 100644 index 000000000000..6a296eb2af9f --- /dev/null +++ b/src/main/ipc/parcel-watcher-process-entry.ts @@ -0,0 +1,254 @@ +// Forked (ELECTRON_RUN_AS_NODE) child that hosts all local @parcel/watcher +// subscriptions. Why: watcher.node has native teardown races that fail-fast +// the hosting process (issue #7547, 0xc0000409 on Windows; same class as +// #5377/#6635). Running the native module here turns a watcher fault into a +// contained child crash the host can recover from, instead of killing the app +// and every agent session in it. +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type * as ParcelWatcher from '@parcel/watcher' + +export type WatcherProcessEvent = { + type: 'create' | 'update' | 'delete' + path: string +} + +export type WatcherProcessSubscribeOptions = { + ignore?: string[] + ignoreGlobs?: string[] + backend?: string +} + +export type HostToWatcherMessage = + | { op: 'subscribe'; id: number; dir: string; opts: WatcherProcessSubscribeOptions } + | { op: 'unsubscribe'; id: number } + +export type WatcherToHostMessage = + | { op: 'subscribed'; id: number } + | { op: 'subscribe-failed'; id: number; message: string } + | { op: 'events'; id: number; events: WatcherProcessEvent[] } + | { op: 'watch-error'; id: number; message: string } + | { op: 'unsubscribed'; id: number } + +function errorMessage(err: unknown): string { + return err instanceof Error ? err.message : String(err) +} + +// Canary self-check. Why: @parcel/watcher can wedge silently — a lock-order +// inversion between Debounce::notify (debounce mutex → watcher mutex) and +// Watcher teardown (watcher mutex → debounce mutex in ~Watcher) deadlocks the +// single process-wide debounce thread, after which every subscription still +// acks but no events are ever delivered. The canary watches a private temp +// dir and touches a file in it; consecutive missed deliveries mean event +// delivery is dead, so exit and let the host respawn a fresh process. +const CANARY_INTERVAL_MS = 10_000 +const CANARY_EVENT_TIMEOUT_MS = 5_000 +const CANARY_MAX_MISSES = 2 + +async function startCanary(getStableActivityRevision: () => number | null): Promise { + let canaryDir: string + let lastEventAt = 0 + try { + canaryDir = mkdtempSync(join(tmpdir(), 'orca-watcher-canary-')) + const watcher = await import('@parcel/watcher') + // Why: pin the Windows backend like the main subscriptions do, so the + // canary never probes for Watchman. + const opts = ( + process.platform === 'win32' ? { backend: 'windows' } : {} + ) as ParcelWatcher.Options + await watcher.subscribe( + canaryDir, + (err) => { + if (!err) { + lastEventAt = Date.now() + } + }, + opts + ) + } catch (err) { + process.stderr.write(`[parcel-watcher-process] canary unavailable: ${errorMessage(err)}\n`) + return + } + process.on('exit', () => { + try { + rmSync(canaryDir, { recursive: true, force: true }) + } catch { + // Temp dir cleanup is best-effort. + } + }) + + let misses = 0 + setInterval(() => { + // Why: Parcel holds its shared backend mutex throughout each initial tree + // crawl, which legitimately starves canary delivery. Only apply the 5 s + // event SLA after every requested subscription has finished crawling. + const activityRevision = getStableActivityRevision() + if (activityRevision === null) { + misses = 0 + return + } + const probedAt = Date.now() + try { + writeFileSync(join(canaryDir, 'canary.txt'), String(probedAt)) + } catch { + return + } + setTimeout(() => { + // A root may start crawling after this probe was written. Invalidate the + // probe instead of misclassifying lifecycle work as a delivery deadlock. + if (getStableActivityRevision() !== activityRevision) { + misses = 0 + return + } + if (lastEventAt >= probedAt) { + misses = 0 + return + } + misses++ + if (misses >= CANARY_MAX_MISSES) { + process.stderr.write( + '[parcel-watcher-process] event delivery wedged (canary starved); restarting watcher process\n' + ) + process.exit(2) + } + }, CANARY_EVENT_TIMEOUT_MS) + }, CANARY_INTERVAL_MS) +} + +function main(): void { + const send = (message: WatcherToHostMessage): void => { + try { + process.send?.(message) + } catch { + // Host is gone; the disconnect handler below exits this process. + } + } + + // Subscribe promises are kept (not just subscriptions) so an unsubscribe + // that races a still-crawling subscribe awaits it instead of leaking the + // native handle — on Windows a leaked handle keeps the worktree dir locked. + const subscriptions = new Map>() + const liveSubscriptionIds = new Set() + let pendingSubscriptionCrawls = 0 + let subscriptionActivityRevision = 0 + let nativeLifecycleTail = Promise.resolve() + + const beginSubscriptionCrawl = (): void => { + pendingSubscriptionCrawls++ + subscriptionActivityRevision++ + } + + const finishSubscriptionCrawl = (): void => { + pendingSubscriptionCrawls-- + subscriptionActivityRevision++ + } + + const runNativeWatcherLifecycleExclusive = (operation: () => Promise): Promise => { + const ready = nativeLifecycleTail + let release: () => void + nativeLifecycleTail = new Promise((resolve) => { + release = resolve + }) + return ready.then(operation).finally(() => release()) + } + + const handleSubscribe = async ( + id: number, + dir: string, + opts: WatcherProcessSubscribeOptions + ): Promise => { + try { + const subscription = await runNativeWatcherLifecycleExclusive(async () => { + beginSubscriptionCrawl() + try { + const watcher = await import('@parcel/watcher') + return await watcher.subscribe( + dir, + (err, events) => { + if (err) { + send({ op: 'watch-error', id, message: errorMessage(err) }) + return + } + if (events.length > 0) { + send({ + op: 'events', + id, + events: events.map((event) => ({ type: event.type, path: event.path })) + }) + } + }, + opts as ParcelWatcher.Options + ) + } finally { + finishSubscriptionCrawl() + } + }) + // An unsubscribe can remove the record while subscribe() is crawling. + // Only advertise it as live if it is still owned by this process. + if (subscriptions.has(id)) { + liveSubscriptionIds.add(id) + } + send({ op: 'subscribed', id }) + return subscription + } catch (err) { + subscriptions.delete(id) + liveSubscriptionIds.delete(id) + send({ op: 'subscribe-failed', id, message: errorMessage(err) }) + return null + } + } + + const handleUnsubscribe = async (id: number): Promise => { + // Why: invalidate a probe already in flight, but keep future probes active. + // A native teardown deadlock is the failure the canary exists to recover. + subscriptionActivityRevision++ + const pending = subscriptions.get(id) + subscriptions.delete(id) + liveSubscriptionIds.delete(id) + try { + // Why: Parcel already serializes crawl and teardown on one backend mutex. + // Mirror that ordering here so neither operation can mask a canary miss. + await runNativeWatcherLifecycleExclusive(async () => { + const subscription = await pending + await subscription?.unsubscribe() + }) + } catch (err) { + process.stderr.write( + `[parcel-watcher-process] unsubscribe ${id} failed: ${errorMessage(err)}\n` + ) + } finally { + subscriptionActivityRevision++ + } + send({ op: 'unsubscribed', id }) + } + + process.on('message', (message: HostToWatcherMessage) => { + if (!message || typeof message !== 'object') { + return + } + if (message.op === 'subscribe') { + subscriptions.set(message.id, handleSubscribe(message.id, message.dir, message.opts)) + return + } + if (message.op === 'unsubscribe') { + void handleUnsubscribe(message.id) + } + }) + + void startCanary(() => { + if (pendingSubscriptionCrawls > 0 || liveSubscriptionIds.size === 0) { + return null + } + return subscriptionActivityRevision + }) + + // Why: if the host dies (or kills us during shutdown), exit immediately — + // process death releases every native watcher handle without running the + // crash-prone napi teardown at all. + process.on('disconnect', () => { + process.exit(0) + }) +} + +main() diff --git a/src/main/ipc/parcel-watcher-process.test.ts b/src/main/ipc/parcel-watcher-process.test.ts new file mode 100644 index 000000000000..4df3b666fbbd --- /dev/null +++ b/src/main/ipc/parcel-watcher-process.test.ts @@ -0,0 +1,286 @@ +// Regression tests for issue #7547: local @parcel/watcher subscriptions run +// in a forked watcher process, and a native watcher crash must be contained — +// respawn, resubscribe, notify interruption — instead of killing the app. +import { EventEmitter } from 'node:events' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { forkMock, existsSyncMock, parcelSubscribeMock } = vi.hoisted(() => ({ + forkMock: vi.fn(), + existsSyncMock: vi.fn(), + parcelSubscribeMock: vi.fn() +})) + +vi.mock('node:child_process', () => ({ fork: forkMock })) +vi.mock('node:fs', () => ({ existsSync: existsSyncMock })) +vi.mock('@parcel/watcher', () => ({ subscribe: parcelSubscribeMock })) + +import { + disposeWatcherProcess, + resetWatcherProcessForTest, + subscribeViaWatcherProcess +} from './parcel-watcher-process' + +type SentMessage = { op: string; id: number; dir?: string } + +class FakeChild extends EventEmitter { + connected = true + sent: SentMessage[] = [] + stderr = new EventEmitter() + kill = vi.fn(() => { + this.connected = false + }) + send = vi.fn((message: SentMessage) => { + this.sent.push(message) + return true + }) +} + +function currentChild(): FakeChild { + const result = forkMock.mock.results.at(-1) + if (!result) { + throw new Error('fork was not called') + } + return result.value as FakeChild +} + +function ackSubscribe(child: FakeChild, index = -1): number { + const message = child.sent.filter((m) => m.op === 'subscribe').at(index) + if (!message) { + throw new Error('no subscribe message sent') + } + child.emit('message', { op: 'subscribed', id: message.id }) + return message.id +} + +describe('subscribeViaWatcherProcess', () => { + beforeEach(() => { + resetWatcherProcessForTest() + // Why: the client deliberately runs in-process under vitest; these tests + // exercise the forked-process mode, so hide the vitest marker. + vi.stubEnv('VITEST', '') + existsSyncMock.mockReturnValue(true) + forkMock.mockImplementation(() => new FakeChild()) + }) + + afterEach(() => { + disposeWatcherProcess() + vi.unstubAllEnvs() + vi.clearAllMocks() + }) + + it('subscribes through the watcher process and forwards events', async () => { + const callback = vi.fn() + const promise = subscribeViaWatcherProcess('/repo', callback, { ignore: ['**/.git'] }) + const child = currentChild() + expect(child.sent[0]).toMatchObject({ op: 'subscribe', dir: '/repo' }) + const id = ackSubscribe(child) + await promise + + const events = [{ type: 'update', path: '/repo/a.txt' }] + child.emit('message', { op: 'events', id, events }) + expect(callback).toHaveBeenCalledWith(null, events) + }) + + it('forwards watcher errors to the callback', async () => { + const callback = vi.fn() + const promise = subscribeViaWatcherProcess('/repo', callback, {}) + const child = currentChild() + const id = ackSubscribe(child) + await promise + + child.emit('message', { op: 'watch-error', id, message: 'boom' }) + expect(callback).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' }), []) + }) + + it('rejects the subscribe when the watcher process reports failure', async () => { + const promise = subscribeViaWatcherProcess('/gone', vi.fn(), {}) + const child = currentChild() + const id = child.sent[0].id + child.emit('message', { op: 'subscribe-failed', id, message: 'Error opening directory' }) + await expect(promise).rejects.toThrow('Error opening directory') + }) + + it('resolves unsubscribe on the child ack', async () => { + const promise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) + const child = currentChild() + const id = ackSubscribe(child, 0) + const subscription = await promise + // Why: hold a second subscription so this unsubscribe exercises the ack + // path instead of the last-subscriber idle kill. + const keepAlivePromise = subscribeViaWatcherProcess('/other', vi.fn(), {}) + ackSubscribe(child) + await keepAlivePromise + + const unsubPromise = subscription.unsubscribe() + expect(child.sent.at(-1)).toEqual({ op: 'unsubscribe', id }) + child.emit('message', { op: 'unsubscribed', id }) + await expect(unsubPromise).resolves.toBeUndefined() + }) + + it('resolves a pending unsubscribe when the child dies', async () => { + const promise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) + const child = currentChild() + ackSubscribe(child, 0) + const subscription = await promise + const keepAlivePromise = subscribeViaWatcherProcess('/other', vi.fn(), {}) + ackSubscribe(child) + await keepAlivePromise + + const unsubPromise = subscription.unsubscribe() + child.connected = false + child.emit('exit', 3221226505, null) + await expect(unsubPromise).resolves.toBeUndefined() + }) + + it('respawns after a crash, resubscribes, and reports the interruption', async () => { + const callback = vi.fn() + const onInterruption = vi.fn() + const promise = subscribeViaWatcherProcess('/repo', callback, {}, onInterruption) + const first = currentChild() + const id = ackSubscribe(first) + await promise + + // Simulate the 0xc0000409 fail-fast: the watcher process dies. + first.connected = false + first.emit('exit', 3221226505, null) + + const second = currentChild() + expect(second).not.toBe(first) + expect(second.sent[0]).toMatchObject({ op: 'subscribe', id, dir: '/repo' }) + expect(onInterruption).not.toHaveBeenCalled() + + second.emit('message', { op: 'subscribed', id }) + expect(onInterruption).toHaveBeenCalledTimes(1) + + const events = [{ type: 'create', path: '/repo/b.txt' }] + second.emit('message', { op: 'events', id, events }) + expect(callback).toHaveBeenCalledWith(null, events) + }) + + it('completes an in-flight subscribe across a crash-respawn', async () => { + const promise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) + const first = currentChild() + expect(first.sent[0].op).toBe('subscribe') + + first.connected = false + first.emit('exit', 3221226505, null) + + const second = currentChild() + ackSubscribe(second) + await expect(promise).resolves.toMatchObject({ unsubscribe: expect.any(Function) }) + }) + + it('disables watching after repeated crashes instead of fork-bombing', async () => { + const callback = vi.fn() + const promise = subscribeViaWatcherProcess('/repo', callback, {}) + ackSubscribe(currentChild()) + await promise + + for (let crash = 0; crash < 2; crash++) { + const child = currentChild() + child.connected = false + child.emit('exit', 3221226505, null) + ackSubscribe(currentChild()) + } + expect(forkMock).toHaveBeenCalledTimes(3) + + const last = currentChild() + last.connected = false + last.emit('exit', 3221226505, null) + + expect(forkMock).toHaveBeenCalledTimes(3) + expect(callback).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('crashed repeatedly') }), + [] + ) + }) + + it('kills the idle child after the last unsubscribe and respawns on the next subscribe', async () => { + const promise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) + const first = currentChild() + ackSubscribe(first) + const subscription = await promise + + await expect(subscription.unsubscribe()).resolves.toBeUndefined() + expect(first.kill).toHaveBeenCalledTimes(1) + + // Why: the deliberate idle kill must not count as a crash — no respawn + // and no crash-fuse advance when the killed child's exit event lands. + first.connected = false + first.emit('exit', null, 'SIGTERM') + expect(forkMock).toHaveBeenCalledTimes(1) + + const respawnPromise = subscribeViaWatcherProcess('/repo2', vi.fn(), {}) + expect(forkMock).toHaveBeenCalledTimes(2) + const second = currentChild() + expect(second).not.toBe(first) + expect(second.sent[0]).toMatchObject({ op: 'subscribe', dir: '/repo2' }) + ackSubscribe(second) + await expect(respawnPromise).resolves.toMatchObject({ unsubscribe: expect.any(Function) }) + }) + + it('kills the idle child when the last pending subscribe fails', async () => { + const promise = subscribeViaWatcherProcess('/gone', vi.fn(), {}) + const first = currentChild() + first.emit('message', { + op: 'subscribe-failed', + id: first.sent[0].id, + message: 'Error opening directory' + }) + await expect(promise).rejects.toThrow('Error opening directory') + expect(first.kill).toHaveBeenCalledTimes(1) + + const respawnPromise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) + expect(forkMock).toHaveBeenCalledTimes(2) + ackSubscribe(currentChild()) + await expect(respawnPromise).resolves.toMatchObject({ unsubscribe: expect.any(Function) }) + }) + + it('keeps the child alive when a subscribe fails while other subscriptions remain', async () => { + const firstPromise = subscribeViaWatcherProcess('/a', vi.fn(), {}) + const child = currentChild() + ackSubscribe(child) + await firstPromise + + const failingPromise = subscribeViaWatcherProcess('/gone', vi.fn(), {}) + child.emit('message', { op: 'subscribe-failed', id: child.sent.at(-1)!.id, message: 'boom' }) + await expect(failingPromise).rejects.toThrow('boom') + expect(child.kill).not.toHaveBeenCalled() + }) + + it('keeps the child alive while other subscriptions remain', async () => { + const firstPromise = subscribeViaWatcherProcess('/a', vi.fn(), {}) + const child = currentChild() + ackSubscribe(child) + const first = await firstPromise + const secondPromise = subscribeViaWatcherProcess('/b', vi.fn(), {}) + ackSubscribe(child) + const second = await secondPromise + + const firstUnsub = first.unsubscribe() + expect(child.kill).not.toHaveBeenCalled() + expect(child.sent.at(-1)).toMatchObject({ op: 'unsubscribe' }) + + // The last unsubscribe kills the idle child, which also completes the + // still-pending unsubscribe ack from the first record. + const secondUnsub = second.unsubscribe() + expect(child.kill).toHaveBeenCalledTimes(1) + await expect(firstUnsub).resolves.toBeUndefined() + await expect(secondUnsub).resolves.toBeUndefined() + }) + + it('uses the in-process watcher under vitest', async () => { + vi.stubEnv('VITEST', 'true') + const unsubscribe = vi.fn().mockResolvedValue(undefined) + parcelSubscribeMock.mockResolvedValue({ unsubscribe }) + const callback = vi.fn() + + const subscription = await subscribeViaWatcherProcess('/repo', callback, { + ignore: ['**/.git'] + }) + expect(forkMock).not.toHaveBeenCalled() + expect(parcelSubscribeMock).toHaveBeenCalledWith('/repo', callback, { ignore: ['**/.git'] }) + await subscription.unsubscribe() + expect(unsubscribe).toHaveBeenCalled() + }) +}) diff --git a/src/main/ipc/parcel-watcher-process.ts b/src/main/ipc/parcel-watcher-process.ts new file mode 100644 index 000000000000..72e2ccf58cef --- /dev/null +++ b/src/main/ipc/parcel-watcher-process.ts @@ -0,0 +1,329 @@ +// Host side of the out-of-process @parcel/watcher (see +// parcel-watcher-process-entry.ts). Why: native watcher teardown races +// fail-fast the hosting process (issue #7547), so local subscriptions live in +// a disposable forked child; when it crashes the host respawns it and +// resubscribes every live root, and callers are told via onInterruption so +// they can refresh state that changed during the gap. +import { fork, type ChildProcess } from 'node:child_process' +import { existsSync } from 'node:fs' +import type * as ParcelWatcher from '@parcel/watcher' +import { getWatcherProcessEntryPath } from './parcel-watcher-entry-path' +import type { + HostToWatcherMessage, + WatcherProcessEvent, + WatcherProcessSubscribeOptions, + WatcherToHostMessage +} from './parcel-watcher-process-entry' + +export type { WatcherProcessEvent, WatcherProcessSubscribeOptions } + +export type WatcherProcessCallback = (err: Error | null, events: WatcherProcessEvent[]) => void +export type WatcherProcessSubscription = { unsubscribe(): Promise } + +// Why: a crash loop (e.g. a root that faults the native watcher on every +// resubscribe) must degrade to "file watching disabled" rather than fork-bomb. +const CRASH_WINDOW_MS = 30_000 +const MAX_CRASHES_PER_WINDOW = 3 + +type SubscriptionRecord = { + id: number + dir: string + opts: WatcherProcessSubscribeOptions + callback: WatcherProcessCallback + onInterruption?: () => void + pendingSubscribe?: { resolve: () => void; reject: (err: Error) => void } +} + +let child: ChildProcess | null = null +let nextSubscriptionId = 1 +let crashTimes: number[] = [] +let shutdownRequested = false +let loggedInProcessFallback = false +const records = new Map() +const pendingUnsubscribes = new Map void>() + +function shouldRunInProcess(entryPath: string): boolean { + // Why: vitest suites mock '@parcel/watcher' at the module level; a forked + // child would bypass those mocks (and could execute a stale build output), + // so tests keep the historical in-process path. + if (process.env.VITEST) { + return true + } + if (existsSync(entryPath)) { + return false + } + if (!loggedInProcessFallback) { + loggedInProcessFallback = true + console.warn( + `[parcel-watcher-process] entry not found at ${entryPath}; using in-process watcher (no crash isolation)` + ) + } + return true +} + +async function subscribeInProcess( + dir: string, + callback: WatcherProcessCallback, + opts: WatcherProcessSubscribeOptions +): Promise { + const watcher = await import('@parcel/watcher') + const subscription = await watcher.subscribe( + dir, + callback as ParcelWatcher.SubscribeCallback, + opts as ParcelWatcher.Options + ) + return { unsubscribe: () => subscription.unsubscribe() } +} + +function inCrashCooldown(): boolean { + const now = Date.now() + crashTimes = crashTimes.filter((time) => now - time < CRASH_WINDOW_MS) + return crashTimes.length >= MAX_CRASHES_PER_WINDOW +} + +function sendToChild(proc: ChildProcess, message: HostToWatcherMessage): void { + try { + proc.send(message) + } catch { + // Channel already closed — the child's exit handler recovers. + } +} + +function ensureWatcherProcess(): ChildProcess | null { + if (shutdownRequested) { + return null + } + if (child?.connected) { + return child + } + if (inCrashCooldown()) { + return null + } + let proc: ChildProcess + try { + proc = fork(getWatcherProcessEntryPath(), [], { + stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, + ...(process.platform === 'win32' ? { windowsHide: true } : {}) + }) + } catch (err) { + console.error('[parcel-watcher-process] failed to fork watcher process:', err) + return null + } + proc.stderr?.on('data', (chunk: Buffer) => { + console.error('[parcel-watcher-process]', String(chunk).trimEnd()) + }) + proc.on('message', (message) => { + if (child === proc) { + handleChildMessage(message as WatcherToHostMessage) + } + }) + proc.on('error', () => handleChildGone(proc)) + proc.on('exit', (code, signal) => { + if (child === proc && (code !== 0 || signal)) { + console.error( + `[parcel-watcher-process] watcher process exited (code=${code}, signal=${signal})` + ) + } + handleChildGone(proc) + }) + child = proc + return proc +} + +function handleChildMessage(message: WatcherToHostMessage): void { + if (!message || typeof message !== 'object') { + return + } + if (message.op === 'unsubscribed') { + const resolve = pendingUnsubscribes.get(message.id) + pendingUnsubscribes.delete(message.id) + resolve?.() + return + } + const record = records.get(message.id) + if (!record) { + return + } + if (message.op === 'subscribed') { + const pending = record.pendingSubscribe + record.pendingSubscribe = undefined + if (pending) { + pending.resolve() + } else { + // Reached after a crash-respawn resubscribe: events emitted while the + // watcher process was down are lost, so let the caller refresh. + record.onInterruption?.() + } + return + } + if (message.op === 'subscribe-failed') { + records.delete(message.id) + const pending = record.pendingSubscribe + record.pendingSubscribe = undefined + if (pending) { + pending.reject(new Error(message.message)) + } else { + record.callback(new Error(message.message), []) + } + // Why: a failed last subscribe empties the records map without any + // unsubscribe ever being called — tear down the idle child here too. + killWatcherChildIfIdle() + return + } + if (message.op === 'events') { + record.callback(null, message.events) + return + } + if (message.op === 'watch-error') { + record.callback(new Error(message.message), []) + } +} + +function failAllSubscriptions(err: Error): void { + for (const record of records.values()) { + const pending = record.pendingSubscribe + record.pendingSubscribe = undefined + if (pending) { + pending.reject(err) + } else { + record.callback(err, []) + } + } + records.clear() +} + +function handleChildGone(proc: ChildProcess): void { + if (child !== proc) { + return + } + child = null + // Why: process death released every native handle, so a pending unsubscribe + // is complete by definition — resolve rather than hang worktree deletion. + for (const resolve of pendingUnsubscribes.values()) { + resolve() + } + pendingUnsubscribes.clear() + if (shutdownRequested || records.size === 0) { + return + } + crashTimes.push(Date.now()) + const replacement = ensureWatcherProcess() + if (!replacement) { + console.error( + '[parcel-watcher-process] watcher process crashed repeatedly; disabling file watching' + ) + failAllSubscriptions(new Error('file watcher process crashed repeatedly')) + return + } + console.error( + `[parcel-watcher-process] watcher process crashed; resubscribing ${records.size} root(s)` + ) + for (const record of records.values()) { + sendToChild(replacement, { + op: 'subscribe', + id: record.id, + dir: record.dir, + opts: record.opts + }) + } +} + +// Why: the last record gone leaves the child idle until app shutdown. Killing +// it releases native handles without running watcher.node's crash-prone async +// teardown (same rationale as disposeWatcherProcess) and reclaims the process; +// the next subscribe forks a fresh child. `child = null` before kill so the +// exit event neither counts as a crash nor respawns. Process death also +// completes any still-pending unsubscribe acks. +function killWatcherChildIfIdle(): void { + const proc = child + if (!proc || records.size > 0) { + return + } + child = null + for (const resolve of pendingUnsubscribes.values()) { + resolve() + } + pendingUnsubscribes.clear() + proc.kill() +} + +function makeSubscription(record: SubscriptionRecord): WatcherProcessSubscription { + return { + unsubscribe: (): Promise => { + if (!records.delete(record.id)) { + return Promise.resolve() + } + const proc = child + if (!proc?.connected) { + return Promise.resolve() + } + if (records.size === 0) { + killWatcherChildIfIdle() + return Promise.resolve() + } + return new Promise((resolve) => { + pendingUnsubscribes.set(record.id, resolve) + sendToChild(proc, { op: 'unsubscribe', id: record.id }) + }) + } + } +} + +/** Subscribe to a directory tree via the isolated watcher process. Falls back + * to an in-process @parcel/watcher subscription when the forked entry is not + * available (tests, unbuilt trees). `onInterruption` fires after the watcher + * process crashed and this subscription was transparently re-established — + * events in the gap were lost, so callers should refresh. */ +export function subscribeViaWatcherProcess( + dir: string, + callback: WatcherProcessCallback, + opts: WatcherProcessSubscribeOptions, + onInterruption?: () => void +): Promise { + if (shouldRunInProcess(getWatcherProcessEntryPath())) { + return subscribeInProcess(dir, callback, opts) + } + const record: SubscriptionRecord = { + id: nextSubscriptionId++, + dir, + opts, + callback, + onInterruption + } + return new Promise((resolve, reject) => { + const proc = ensureWatcherProcess() + if (!proc) { + reject(new Error('file watcher process unavailable')) + return + } + records.set(record.id, record) + record.pendingSubscribe = { + resolve: () => resolve(makeSubscription(record)), + reject + } + sendToChild(proc, { op: 'subscribe', id: record.id, dir, opts }) + }) +} + +/** Kill the watcher process at app shutdown. Process death releases native + * handles without running watcher.node's crash-prone async teardown. */ +export function disposeWatcherProcess(): void { + shutdownRequested = true + const proc = child + child = null + for (const resolve of pendingUnsubscribes.values()) { + resolve() + } + pendingUnsubscribes.clear() + records.clear() + proc?.kill() +} + +export function resetWatcherProcessForTest(): void { + disposeWatcherProcess() + shutdownRequested = false + crashTimes = [] + loggedInProcessFallback = false + nextSubscriptionId = 1 +} diff --git a/src/main/ipc/preflight-command-exec.test.ts b/src/main/ipc/preflight-command-exec.test.ts new file mode 100644 index 000000000000..204b8a5f6e16 --- /dev/null +++ b/src/main/ipc/preflight-command-exec.test.ts @@ -0,0 +1,56 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { buildPosixCommandPathLookupScript } from '../../shared/posix-command-path-lookup' + +const { runPreflightCommandInWslMock } = vi.hoisted(() => ({ + runPreflightCommandInWslMock: vi.fn() +})) + +vi.mock('./preflight-wsl-command', () => ({ + runPreflightCommandInWsl: runPreflightCommandInWslMock +})) + +import { isCommandOnPath } from './preflight-command-exec' + +describe('isCommandOnPath', () => { + const sentinel = '__ORCA_PREFLIGHT_COMMAND_PATH__' + + beforeEach(() => { + runPreflightCommandInWslMock.mockReset() + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('uses the shared literal lookup and accepts a sentinel-prefixed POSIX path', async () => { + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + runPreflightCommandInWslMock.mockResolvedValue({ + stdout: `shell startup chatter\n${sentinel}/home/user/.local/bin/codex\n`, + stderr: '' + }) + + const found = await isCommandOnPath('codex', { distro: 'Ubuntu' }) + + expect(found).toBe(true) + expect(runPreflightCommandInWslMock).toHaveBeenCalledOnce() + const [, command] = runPreflightCommandInWslMock.mock.calls[0] as [{ distro: string }, string] + expect(command).toContain( + buildPosixCommandPathLookupScript({ kind: 'literal', value: 'codex' }) + ) + expect(command).toContain( + ['if [ -n "$resolved" ]; then', `printf '${sentinel}%s\\n' "$resolved"`, 'fi'].join('\n') + ) + }) + + it.each([ + ['/absolute/startup/chatter', false], + [`${sentinel}relative/path`, false], + ['codex', false], + ["alias codex='codex --wrapped'", false] + ])('parses WSL lookup output %s as available: %s', async (stdout, expected) => { + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + runPreflightCommandInWslMock.mockResolvedValue({ stdout: `${stdout}\n`, stderr: '' }) + + await expect(isCommandOnPath('codex', { distro: 'Ubuntu' })).resolves.toBe(expected) + }) +}) diff --git a/src/main/ipc/preflight-command-exec.ts b/src/main/ipc/preflight-command-exec.ts index b3c3ac990b7e..b5fa8dee40aa 100644 --- a/src/main/ipc/preflight-command-exec.ts +++ b/src/main/ipc/preflight-command-exec.ts @@ -1,12 +1,14 @@ import { execFile } from 'node:child_process' import path from 'node:path' import { promisify } from 'node:util' +import { buildPosixCommandPathLookupScript } from '../../shared/posix-command-path-lookup' import { buildLocalPreflightEnv } from './preflight-local-env' import { runPreflightCommandInWsl } from './preflight-wsl-command' import type { WslPreflightTarget } from './preflight-wsl-agent-detection' const execFileAsync = promisify(execFile) export const PREFLIGHT_COMMAND_TIMEOUT_MS = 5000 +const WSL_COMMAND_PATH_SENTINEL = '__ORCA_PREFLIGHT_COMMAND_PATH__' export type PreflightCommandResult = { stdout: string; stderr: string } @@ -81,8 +83,27 @@ export async function isCommandOnPath( const finder = process.platform === 'win32' ? 'where' : 'which' try { const { stdout } = wslTarget - ? await execCommandInWsl(wslTarget, `command -v ${shellQuote(command)}`) + ? // Why: preflight must validate the executable on PATH, not a shell alias or function. + await execCommandInWsl( + wslTarget, + [ + buildPosixCommandPathLookupScript({ kind: 'literal', value: command }), + 'if [ -n "$resolved" ]; then', + `printf '${WSL_COMMAND_PATH_SENTINEL}%s\\n' "$resolved"`, + 'fi' + ].join('\n') + ) : await execLocalPreflightCommand(finder, [command]) + if (wslTarget) { + // Why: WSL startup chatter can contain unrelated absolute paths. + return stdout + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line.startsWith(WSL_COMMAND_PATH_SENTINEL)) + .map((line) => line.slice(WSL_COMMAND_PATH_SENTINEL.length)) + .some((line) => path.posix.isAbsolute(line)) + } + return stdout .split(/\r?\n/) .map((line) => line.trim()) diff --git a/src/main/ipc/preflight-wsl-agent-detection.test.ts b/src/main/ipc/preflight-wsl-agent-detection.test.ts index 5c544ef5c63f..a1f9d7cfda5f 100644 --- a/src/main/ipc/preflight-wsl-agent-detection.test.ts +++ b/src/main/ipc/preflight-wsl-agent-detection.test.ts @@ -16,6 +16,8 @@ vi.mock('child_process', () => { }) import { detectWslCommandsOnPath } from './preflight-wsl-agent-detection' +import { buildPosixCommandPathLookupScript } from '../../shared/posix-command-path-lookup' +import { escapeWslShCommandForWindows } from '../../shared/wsl-login-shell-command' function lastShCommandPayload(): string { const call = execFileAsyncMock.mock.calls.at(-1) @@ -47,6 +49,20 @@ describe('detectWslCommandsOnPath', () => { expect(payload).toContain('fi\ndone') }) + it('uses the shared alias- and function-neutral PATH lookup', async () => { + execFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + + await detectWslCommandsOnPath({ distro: 'Ubuntu' }, ['claude', 'codex']) + + const payload = lastShCommandPayload() + const lookupScript = buildPosixCommandPathLookupScript({ + kind: 'shell-variable', + name: 'cmd' + }) + expect(payload).toContain(escapeWslShCommandForWindows(lookupScript)) + expect(payload).not.toContain('type -P') + }) + it('parses detected commands from prefixed stdout', async () => { execFileAsyncMock.mockResolvedValue({ stdout: diff --git a/src/main/ipc/preflight-wsl-agent-detection.ts b/src/main/ipc/preflight-wsl-agent-detection.ts index ed7d3f5399be..be1f216ed9ca 100644 --- a/src/main/ipc/preflight-wsl-agent-detection.ts +++ b/src/main/ipc/preflight-wsl-agent-detection.ts @@ -1,6 +1,7 @@ import { execFile } from 'node:child_process' import { promisify } from 'node:util' import path from 'node:path' +import { buildPosixCommandPathLookupScript } from '../../shared/posix-command-path-lookup' import { buildWslLoginShellCommand, escapeWslShCommandForWindows @@ -24,13 +25,15 @@ export async function detectWslCommandsOnPath( } const commandList = uniqueCommands.map(shellQuote).join(' ') - // Why: join with newlines, not spaces. zsh treats `fi done` as a parse error - // (it needs a separator before `done`); the login shell may be zsh, so a - // space-joined script silently fails for every agent. Newlines are valid - // statement separators in every POSIX shell and zsh. + const lookupScript = buildPosixCommandPathLookupScript({ + kind: 'shell-variable', + name: 'cmd' + }) + // Newlines keep the loop valid in zsh and every POSIX shell used here. const script = [ `for cmd in ${commandList}; do`, - 'if resolved=$(command -v "$cmd" 2>/dev/null); then', + lookupScript, + 'if [ -n "$resolved" ]; then', `printf '${WSL_AGENT_DETECTION_PREFIX}%s\\t%s\\n' "$cmd" "$resolved";`, 'fi', 'done' diff --git a/src/main/ipc/preflight.test.ts b/src/main/ipc/preflight.test.ts index 944ee1b4418f..e1f391af79d6 100644 --- a/src/main/ipc/preflight.test.ts +++ b/src/main/ipc/preflight.test.ts @@ -492,6 +492,58 @@ describe('preflight', () => { await expect(detectInstalledAgents()).resolves.toEqual(['claude', 'cursor']) }) + it('does not report Claude Agent Teams when only the Orca shim is present', async () => { + execFileAsyncMock.mockImplementation(async (command, args) => { + if (command !== 'which') { + throw new Error(`unexpected command ${String(command)}`) + } + if (String(args[0]) === 'orca') { + return { stdout: '/Applications/Orca.app/Contents/MacOS/orca\n' } + } + throw new Error('not found') + }) + + await expect(detectInstalledAgents()).resolves.toEqual([]) + }) + + it('reports Claude Agent Teams when both Orca and Claude are present', async () => { + execFileAsyncMock.mockImplementation(async (command, args) => { + if (command !== 'which') { + throw new Error(`unexpected command ${String(command)}`) + } + if (String(args[0]) === 'claude') { + return { stdout: '/Users/test/.local/bin/claude\n' } + } + if (String(args[0]) === 'orca') { + return { stdout: '/Applications/Orca.app/Contents/MacOS/orca\n' } + } + throw new Error('not found') + }) + + await expect(detectInstalledAgents()).resolves.toEqual(['claude', 'claude-agent-teams']) + }) + + it('does not report Claude Agent Teams on native Windows', async () => { + Object.defineProperty(process, 'platform', { + configurable: true, + value: 'win32' + }) + execFileAsyncMock.mockImplementation(async (command, args) => { + if (command !== 'where') { + throw new Error(`unexpected command ${String(command)}`) + } + if (String(args[0]) === 'claude') { + return { stdout: '/mock/windows/npm/claude.cmd\n' } + } + if (String(args[0]) === 'orca') { + return { stdout: '/mock/windows/programs/orca.cmd\n' } + } + throw new Error('not found') + }) + + await expect(detectInstalledAgents()).resolves.toEqual(['claude']) + }) + it('detects agents via the install-dir resolver when which fails (stripped GUI PATH)', async () => { // Why: cold GUI launches can run detection before shell-PATH hydration // adds user install dirs, so `which` can miss runnable CLIs. @@ -634,6 +686,28 @@ describe('preflight', () => { expect(hydrateShellPathMock).not.toHaveBeenCalled() }) + it('does not report Claude Agent Teams from WSL agent detection', async () => { + Object.defineProperty(process, 'platform', { + configurable: true, + value: 'win32' + }) + execFileAsyncMock.mockImplementation(async (command, args) => { + if (command !== 'wsl.exe') { + throw new Error(`unexpected command ${String(command)}`) + } + const script = String(args[5]) + expect(script).not.toContain("'orca'") + expect(script).not.toContain("'orca-dev'") + expect(script).not.toContain("'orca-ide'") + if (script.includes("'claude'")) { + return { stdout: '__ORCA_AGENT_PATH__claude\t/home/test/.local/bin/claude\n' } + } + throw new Error('not found') + }) + + await expect(detectInstalledAgents({ wslDistro: 'Ubuntu' })).resolves.toEqual(['claude']) + }) + it('detects Mistral Vibe from the installed vibe executable', async () => { execFileAsyncMock.mockImplementation(async (command, args) => { if (command !== 'which') { diff --git a/src/main/ipc/preflight.ts b/src/main/ipc/preflight.ts index cc14ca490b66..6a33e112fa26 100644 --- a/src/main/ipc/preflight.ts +++ b/src/main/ipc/preflight.ts @@ -1,5 +1,4 @@ import { ipcMain } from 'electron' -import { getTuiAgentDetectCommands, TUI_AGENT_CONFIG } from '../../shared/tui-agent-config' import type { PathSource, ShellHydrationFailureReason } from '../../shared/types' import { hydrateShellPath, mergePathSegments } from '../startup/hydrate-shell-path' import { getAzureDevOpsAuthStatus } from '../azure-devops/client' @@ -22,6 +21,11 @@ import { detectRemoteWindowsTerminalCapabilities, type RemoteWindowsTerminalCapabilities } from './preflight-remote-windows-terminal-capabilities' +import { + getTuiAgentDetectionProbeCommands, + KNOWN_TUI_AGENT_DETECTION_COMMANDS, + resolveDetectedTuiAgentIds +} from './tui-agent-detection-commands' export type PreflightStatus = { git: { installed: boolean } @@ -60,13 +64,6 @@ export function _resetPreflightCache(): void { cached = null } -const KNOWN_AGENT_COMMANDS = Object.entries(TUI_AGENT_CONFIG).flatMap(([id, config]) => - getTuiAgentDetectCommands(config).map((cmd) => ({ - id, - cmd - })) -) - function uniqueAgentIds(ids: Iterable): string[] { return [...new Set(ids)] } @@ -92,16 +89,17 @@ export async function detectInstalledAgents(context?: PreflightRuntimeContext): if (wslTarget) { const foundCommands = await detectWslCommandsOnPath( wslTarget, - KNOWN_AGENT_COMMANDS.map(({ cmd }) => cmd) - ) - return uniqueAgentIds( - KNOWN_AGENT_COMMANDS.filter(({ cmd }) => foundCommands.has(cmd)).map(({ id }) => id) + getTuiAgentDetectionProbeCommands(KNOWN_TUI_AGENT_DETECTION_COMMANDS, 'wsl') ) + return resolveDetectedTuiAgentIds(KNOWN_TUI_AGENT_DETECTION_COMMANDS, foundCommands, 'wsl') } + const probeCommands = getTuiAgentDetectionProbeCommands( + KNOWN_TUI_AGENT_DETECTION_COMMANDS, + process.platform + ) const pathChecks = await Promise.all( - KNOWN_AGENT_COMMANDS.map(async ({ id, cmd }) => ({ - id, + probeCommands.map(async (cmd) => ({ cmd, installedOnPath: await isCommandOnPath(cmd) })) @@ -110,11 +108,16 @@ export async function detectInstalledAgents(context?: PreflightRuntimeContext): // Why: PATH may still be unhydrated on a cold GUI launch; bulk resolution // computes user install dirs once instead of blocking once per missed CLI. const installDirCommands = detectCommandsInInstallDirs(missedCommands) - const checks = pathChecks.map(({ id, cmd, installedOnPath }) => ({ - id, - installed: installedOnPath || installDirCommands.has(cmd) - })) - return uniqueAgentIds(checks.filter((c) => c.installed).map((c) => c.id)) + const foundCommands = new Set( + pathChecks + .filter(({ cmd, installedOnPath }) => installedOnPath || installDirCommands.has(cmd)) + .map(({ cmd }) => cmd) + ) + return resolveDetectedTuiAgentIds( + KNOWN_TUI_AGENT_DETECTION_COMMANDS, + foundCommands, + process.platform + ) } export async function detectInstalledAgentsWithShellPathHydration( @@ -181,7 +184,7 @@ export async function detectRemoteAgents(args: { connectionId: string }): Promis return [] } const result = (await mux.request('preflight.detectAgents', { - commands: KNOWN_AGENT_COMMANDS + commands: KNOWN_TUI_AGENT_DETECTION_COMMANDS })) as { agents: string[] } return uniqueAgentIds(result.agents) } diff --git a/src/main/ipc/pty-hidden-delivery-gate.test.ts b/src/main/ipc/pty-hidden-delivery-gate.test.ts new file mode 100644 index 000000000000..c85c4e2c8e08 --- /dev/null +++ b/src/main/ipc/pty-hidden-delivery-gate.test.ts @@ -0,0 +1,118 @@ +import { beforeEach, describe, expect, it } from 'vitest' +import { + _resetHiddenRendererPtyDeliveryGateForTest, + clearHiddenRendererPtyDeliveryState, + getHiddenRendererPtyDeliveryDebug, + isHiddenPtyDeliveryGateEnabled, + markHiddenRendererPty, + recordHiddenRendererPtyDataDrop, + resetRendererScopedHiddenPtyDeliveryState, + setRendererPtyDeliveryInterest, + shouldDropHiddenRendererPtyData, + unmarkHiddenRendererPty +} from './pty-hidden-delivery-gate' + +const PTY_ID = 'pty-1' + +describe('pty hidden delivery gate', () => { + beforeEach(() => { + _resetHiddenRendererPtyDeliveryGateForTest() + }) + + it('only operates when both kill switches are on (default on)', () => { + expect(isHiddenPtyDeliveryGateEnabled(undefined)).toBe(true) + expect(isHiddenPtyDeliveryGateEnabled({})).toBe(true) + expect(isHiddenPtyDeliveryGateEnabled({ terminalHiddenDeliveryGate: false })).toBe(false) + expect(isHiddenPtyDeliveryGateEnabled({ terminalMainSideEffectAuthority: false })).toBe(false) + }) + + it('drops only hidden PTYs without registered delivery interest', () => { + expect(shouldDropHiddenRendererPtyData(PTY_ID, {})).toBe(false) + + markHiddenRendererPty(PTY_ID) + expect(shouldDropHiddenRendererPtyData(PTY_ID, {})).toBe(true) + expect(shouldDropHiddenRendererPtyData(PTY_ID, { terminalHiddenDeliveryGate: false })).toBe( + false + ) + + setRendererPtyDeliveryInterest(PTY_ID, true) + expect(shouldDropHiddenRendererPtyData(PTY_ID, {})).toBe(false) + setRendererPtyDeliveryInterest(PTY_ID, false) + expect(shouldDropHiddenRendererPtyData(PTY_ID, {})).toBe(true) + }) + + it('requests the restore marker exactly once per drop episode, re-armed by unmark', () => { + markHiddenRendererPty(PTY_ID) + expect(recordHiddenRendererPtyDataDrop(PTY_ID, 10).shouldEmitRestoreMarker).toBe(true) + expect(recordHiddenRendererPtyDataDrop(PTY_ID, 10).shouldEmitRestoreMarker).toBe(false) + + // Why: unmark consumes the latch (and re-emits via its own return value); + // the next hidden period's first drop reports again. + unmarkHiddenRendererPty(PTY_ID) + markHiddenRendererPty(PTY_ID) + expect(recordHiddenRendererPtyDataDrop(PTY_ID, 10).shouldEmitRestoreMarker).toBe(true) + }) + + it('keeps drop memory when an already-dropped PTY is re-marked hidden', () => { + // Why: a hidden remount or renderer reload re-marks without an unhide in + // between — clearing the latch there would make reveal skip the restore. + markHiddenRendererPty(PTY_ID) + recordHiddenRendererPtyDataDrop(PTY_ID, 10) + markHiddenRendererPty(PTY_ID) + expect(unmarkHiddenRendererPty(PTY_ID).droppedWhileHidden).toBe(true) + }) + + it('reports drops on unhide so reveal can heal a replaced renderer view', () => { + markHiddenRendererPty(PTY_ID) + expect(unmarkHiddenRendererPty(PTY_ID).droppedWhileHidden).toBe(false) + + markHiddenRendererPty(PTY_ID) + recordHiddenRendererPtyDataDrop(PTY_ID, 10) + expect(unmarkHiddenRendererPty(PTY_ID).droppedWhileHidden).toBe(true) + expect(shouldDropHiddenRendererPtyData(PTY_ID, {})).toBe(false) + }) + + it('clears renderer-scoped state on reload while preserving drop memory', () => { + markHiddenRendererPty(PTY_ID) + recordHiddenRendererPtyDataDrop(PTY_ID, 10) + setRendererPtyDeliveryInterest('pty-2', true) + markHiddenRendererPty('pty-2') + + resetRendererScopedHiddenPtyDeliveryState() + + // Hidden marks and interest holds died with the old renderer process. + expect(shouldDropHiddenRendererPtyData(PTY_ID, {})).toBe(false) + expect(getHiddenRendererPtyDeliveryDebug()).toMatchObject({ + hiddenDeliveryGatedPtyCount: 0, + deliveryInterestPtyCount: 0 + }) + // pty-2's leaked interest is gone: re-marking gates it again. + markHiddenRendererPty('pty-2') + expect(shouldDropHiddenRendererPtyData('pty-2', {})).toBe(true) + // Drop memory survives so the new renderer's first unhide still restores. + markHiddenRendererPty(PTY_ID) + expect(unmarkHiddenRendererPty(PTY_ID).droppedWhileHidden).toBe(true) + }) + + it('clears all per-PTY state on teardown and tracks debug counters', () => { + markHiddenRendererPty(PTY_ID) + setRendererPtyDeliveryInterest('pty-2', true) + recordHiddenRendererPtyDataDrop(PTY_ID, 7) + recordHiddenRendererPtyDataDrop(PTY_ID, 5) + + expect(getHiddenRendererPtyDeliveryDebug()).toEqual({ + hiddenDeliveryGatedPtyCount: 1, + deliveryInterestPtyCount: 1, + hiddenDeliveryDroppedChars: 12, + hiddenDeliveryDroppedChunks: 2 + }) + + clearHiddenRendererPtyDeliveryState(PTY_ID) + clearHiddenRendererPtyDeliveryState('pty-2') + expect(getHiddenRendererPtyDeliveryDebug()).toMatchObject({ + hiddenDeliveryGatedPtyCount: 0, + deliveryInterestPtyCount: 0 + }) + expect(shouldDropHiddenRendererPtyData(PTY_ID, {})).toBe(false) + }) +}) diff --git a/src/main/ipc/pty-hidden-delivery-gate.ts b/src/main/ipc/pty-hidden-delivery-gate.ts new file mode 100644 index 000000000000..77230f7300c2 --- /dev/null +++ b/src/main/ipc/pty-hidden-delivery-gate.ts @@ -0,0 +1,154 @@ +/** + * Main-side hidden-delivery gate for renderer PTY byte delivery (Phase 4 of + * the terminal model/view architecture). + * + * The renderer marks a PTY hidden when no visible view consumes its bytes; + * main then drops renderer-bound delivery AFTER model ingestion — the runtime + * already parsed the chunk, and reveal restores from the model snapshot via + * the existing seq-guarded machinery. Any renderer party that still needs raw + * bytes (dispatcher sidecars) registers delivery + * interest, which suppresses the gate for that PTY. + * See docs/reference/terminal-side-effect-authority.md (Open Items). + */ +import type { GlobalSettings } from '../../shared/types' + +export type HiddenPtyDeliveryGateSettings = Pick< + GlobalSettings, + 'terminalMainSideEffectAuthority' | 'terminalHiddenDeliveryGate' +> + +const hiddenRendererPtys = new Set() +// Why: sidecar consumers (paste-draft pacing, background agent launches, +// automation observers, and the kill-switch-off parked 2031 responder) need +// live bytes even while no visible view exists. Any +// registered interest suppresses the gate for that PTY. +const deliveryInterestRendererPtys = new Set() +// Why: reveal must restore from the model only when bytes were actually +// dropped. Doubles as the one-shot marker latch: the first gated drop emits a +// restore marker, and the latch is consumed only by unmark (which re-emits) +// or full PTY teardown — never by re-marking hidden, so drop memory survives +// hidden remounts and renderer reloads. +const droppedSinceHiddenPtys = new Set() + +let droppedHiddenDeliveryChars = 0 +let droppedHiddenDeliveryChunks = 0 + +/** Gate kill switches, both read main-side: the gate only operates under main + * side-effect authority AND the gate-specific setting (both default on). */ +export function isHiddenPtyDeliveryGateEnabled( + settings: HiddenPtyDeliveryGateSettings | null | undefined +): boolean { + return ( + settings?.terminalMainSideEffectAuthority !== false && + settings?.terminalHiddenDeliveryGate !== false + ) +} + +/** Renderer-reported "no visible view needs bytes" bit. Never clears drop + * memory: a hidden remount or renderer reload re-marks an already-dropped + * PTY, and erasing the latch there would make the eventual reveal skip the + * restore. Unmark is the only consumer of the latch. */ +export function markHiddenRendererPty(id: string): void { + hiddenRendererPtys.add(id) +} + +/** Clears the hidden bit. Returns whether bytes were dropped while hidden so + * the caller can emit a restore marker to the now-visible renderer. */ +export function unmarkHiddenRendererPty(id: string): { droppedWhileHidden: boolean } { + hiddenRendererPtys.delete(id) + const droppedWhileHidden = droppedSinceHiddenPtys.delete(id) + return { droppedWhileHidden } +} + +export function isHiddenRendererPty(id: string): boolean { + return hiddenRendererPtys.has(id) +} + +/** For freeze diagnostics only: hidden ptys must appear in the per-pty report + * table even when the gate dropped every byte before any send/accounting. */ +export function getHiddenRendererPtyIds(): string[] { + return [...hiddenRendererPtys] +} + +/** Renderer-side ref-counted interest, surfaced as boolean transitions. */ +export function setRendererPtyDeliveryInterest(id: string, interested: boolean): void { + if (interested) { + deliveryInterestRendererPtys.add(id) + } else { + deliveryInterestRendererPtys.delete(id) + } +} + +export function shouldDropHiddenRendererPtyData( + id: string, + settings: HiddenPtyDeliveryGateSettings | null | undefined +): boolean { + return ( + isHiddenPtyDeliveryGateEnabled(settings) && + hiddenRendererPtys.has(id) && + !deliveryInterestRendererPtys.has(id) + ) +} + +/** Record one gated drop. Returns whether the caller should emit the one-shot + * empty restore-marker chunk (first drop since this PTY went hidden). */ +export function recordHiddenRendererPtyDataDrop( + id: string, + chars: number +): { shouldEmitRestoreMarker: boolean } { + droppedHiddenDeliveryChars += chars + droppedHiddenDeliveryChunks += 1 + if (droppedSinceHiddenPtys.has(id)) { + return { shouldEmitRestoreMarker: false } + } + droppedSinceHiddenPtys.add(id) + return { shouldEmitRestoreMarker: true } +} + +/** Renderer process replaced (reload / crash): its ref-counted interest + * holds and hidden marks died with it, so keeping them would gate (or + * force-feed) PTYs no live renderer party asked about. Drop memory is + * preserved — surviving daemon/SSH PTYs may have dropped bytes the old + * renderer never restored; the new renderer's first hidden/visible sync + * re-marks or unmarks and the unmark path re-emits the restore marker. */ +export function resetRendererScopedHiddenPtyDeliveryState(): void { + hiddenRendererPtys.clear() + deliveryInterestRendererPtys.clear() +} + +/** Full per-PTY teardown — wired into clearProviderPtyState so every exit + * path (local, daemon, SSH, connection teardown) releases gate state. */ +export function clearHiddenRendererPtyDeliveryState(id: string): void { + hiddenRendererPtys.delete(id) + deliveryInterestRendererPtys.delete(id) + droppedSinceHiddenPtys.delete(id) +} + +export type HiddenRendererPtyDeliveryDebug = { + hiddenDeliveryGatedPtyCount: number + deliveryInterestPtyCount: number + hiddenDeliveryDroppedChars: number + hiddenDeliveryDroppedChunks: number +} + +export function getHiddenRendererPtyDeliveryDebug(): HiddenRendererPtyDeliveryDebug { + return { + hiddenDeliveryGatedPtyCount: hiddenRendererPtys.size, + deliveryInterestPtyCount: deliveryInterestRendererPtys.size, + hiddenDeliveryDroppedChars: droppedHiddenDeliveryChars, + hiddenDeliveryDroppedChunks: droppedHiddenDeliveryChunks + } +} + +export function resetHiddenRendererPtyDeliveryDebugCounters(): void { + droppedHiddenDeliveryChars = 0 + droppedHiddenDeliveryChunks = 0 +} + +/** Test seam: reset all module state between tests. */ +export function _resetHiddenRendererPtyDeliveryGateForTest(): void { + hiddenRendererPtys.clear() + deliveryInterestRendererPtys.clear() + droppedSinceHiddenPtys.clear() + resetHiddenRendererPtyDeliveryDebugCounters() +} diff --git a/src/main/ipc/pty-producer-flow-control.test.ts b/src/main/ipc/pty-producer-flow-control.test.ts new file mode 100644 index 000000000000..ae7fcb6b6550 --- /dev/null +++ b/src/main/ipc/pty-producer-flow-control.test.ts @@ -0,0 +1,137 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + PRODUCER_FLOW_HIGH_WATERMARK_CHARS, + PRODUCER_FLOW_LOW_WATERMARK_CHARS, + PRODUCER_PAUSE_REASSERT_INTERVAL_MS, + PtyProducerFlowController +} from './pty-producer-flow-control' + +const HIGH = PRODUCER_FLOW_HIGH_WATERMARK_CHARS +const LOW = PRODUCER_FLOW_LOW_WATERMARK_CHARS + +describe('PtyProducerFlowController', () => { + let pauseProducer: ReturnType void>> + let resumeProducer: ReturnType void>> + let controller: PtyProducerFlowController + + beforeEach(() => { + vi.useFakeTimers() + pauseProducer = vi.fn<(id: string) => void>() + resumeProducer = vi.fn<(id: string) => void>() + controller = new PtyProducerFlowController({ + pauseProducer, + resumeProducer + }) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('does not pause at or below the high watermark', () => { + controller.update('pty-1', 0) + controller.update('pty-1', LOW) + controller.update('pty-1', HIGH) + expect(pauseProducer).not.toHaveBeenCalled() + expect(controller.isPaused('pty-1')).toBe(false) + }) + + it('pauses exactly once when pending crosses the high watermark, not per chunk', () => { + controller.update('pty-1', HIGH + 1) + controller.update('pty-1', HIGH + 64 * 1024) + controller.update('pty-1', HIGH + 128 * 1024) + expect(pauseProducer).toHaveBeenCalledTimes(1) + expect(pauseProducer).toHaveBeenCalledWith('pty-1') + expect(controller.isPaused('pty-1')).toBe(true) + }) + + it('resumes exactly once when pending drains below the low watermark', () => { + controller.update('pty-1', HIGH + 1) + controller.update('pty-1', LOW - 1) + expect(resumeProducer).toHaveBeenCalledTimes(1) + expect(resumeProducer).toHaveBeenCalledWith('pty-1') + expect(controller.isPaused('pty-1')).toBe(false) + // A second drain report on the now-unpaused pty must not resume again. + controller.update('pty-1', 0) + expect(resumeProducer).toHaveBeenCalledTimes(1) + }) + + it('holds hysteresis: no flapping while pending sits between the watermarks', () => { + controller.update('pty-1', HIGH + 1) + expect(pauseProducer).toHaveBeenCalledTimes(1) + // Draining but still above LOW: stay paused, no extra calls either way. + controller.update('pty-1', HIGH - 16 * 1024) + controller.update('pty-1', 128 * 1024) + controller.update('pty-1', LOW) + expect(pauseProducer).toHaveBeenCalledTimes(1) + expect(resumeProducer).not.toHaveBeenCalled() + expect(controller.isPaused('pty-1')).toBe(true) + // An unpaused pty hovering in the same band must not pause. + controller.update('pty-2', LOW + 1) + controller.update('pty-2', HIGH) + expect(pauseProducer).toHaveBeenCalledTimes(1) + }) + + it('re-asserts the pause after the failsafe interval while still flooded', () => { + controller.update('pty-1', HIGH + 1) + expect(pauseProducer).toHaveBeenCalledTimes(1) + + // Within the failsafe window: no re-assert even far above HIGH. + vi.advanceTimersByTime(PRODUCER_PAUSE_REASSERT_INTERVAL_MS - 1) + controller.update('pty-1', HIGH * 4) + expect(pauseProducer).toHaveBeenCalledTimes(1) + + // After the window (daemon failsafe has auto-resumed by now): re-pause. + vi.advanceTimersByTime(1) + controller.update('pty-1', HIGH * 4) + expect(pauseProducer).toHaveBeenCalledTimes(2) + + // The re-assert re-stamps the clock — no immediate third pause. + controller.update('pty-1', HIGH * 4) + expect(pauseProducer).toHaveBeenCalledTimes(2) + }) + + it('release resumes only ptys that are actually paused', () => { + controller.update('paused-pty', HIGH + 1) + controller.release('paused-pty') + controller.release('never-paused-pty') + expect(resumeProducer).toHaveBeenCalledTimes(1) + expect(resumeProducer).toHaveBeenCalledWith('paused-pty') + expect(controller.isPaused('paused-pty')).toBe(false) + }) + + it('releaseAll resumes every paused pty', () => { + controller.update('pty-1', HIGH + 1) + controller.update('pty-2', HIGH + 1) + controller.update('pty-3', LOW) + controller.releaseAll() + expect(resumeProducer).toHaveBeenCalledTimes(2) + expect(resumeProducer).toHaveBeenCalledWith('pty-1') + expect(resumeProducer).toHaveBeenCalledWith('pty-2') + expect(controller.isPaused('pty-1')).toBe(false) + expect(controller.isPaused('pty-2')).toBe(false) + }) + + it('keeps bookkeeping consistent when the transport throws', () => { + pauseProducer.mockImplementation(() => { + throw new Error('provider gone') + }) + resumeProducer.mockImplementation(() => { + throw new Error('provider gone') + }) + expect(() => controller.update('pty-1', HIGH + 1)).not.toThrow() + expect(controller.isPaused('pty-1')).toBe(true) + expect(() => controller.update('pty-1', 0)).not.toThrow() + expect(controller.isPaused('pty-1')).toBe(false) + }) + + it('tracks watermark state per pty independently', () => { + controller.update('pty-1', HIGH + 1) + controller.update('pty-2', HIGH + 1) + controller.update('pty-1', 0) + expect(pauseProducer).toHaveBeenCalledTimes(2) + expect(resumeProducer).toHaveBeenCalledTimes(1) + expect(controller.isPaused('pty-1')).toBe(false) + expect(controller.isPaused('pty-2')).toBe(true) + }) +}) diff --git a/src/main/ipc/pty-producer-flow-control.ts b/src/main/ipc/pty-producer-flow-control.ts new file mode 100644 index 000000000000..48a9fc0b678c --- /dev/null +++ b/src/main/ipc/pty-producer-flow-control.ts @@ -0,0 +1,105 @@ +// Producer-side PTY flow control (notes/terminal-performance-initiative.md §5). +// Main tracks per-PTY renderer-pending chars; past HIGH it asks the provider to +// pause the actual PTY read (node-pty pause() → kernel backpressure → the +// flooding shell blocks on write), and below LOW it resumes. The wide +// HIGH/LOW gap is deliberate hysteresis so a draining queue cannot flap +// pause/resume once per flush slice. + +export const PRODUCER_FLOW_HIGH_WATERMARK_CHARS = 256 * 1024 +export const PRODUCER_FLOW_LOW_WATERMARK_CHARS = 32 * 1024 +// Why: the daemon auto-resumes a pause after its 5s lost-resume failsafe. If +// pending is still above HIGH after that window, the pause must be re-asserted +// or a sustained flood would run unthrottled after the first failsafe fires. +export const PRODUCER_PAUSE_REASSERT_INTERVAL_MS = 5_000 + +export type ProducerFlowControlTransport = { + pauseProducer: (id: string) => void + resumeProducer: (id: string) => void +} + +export class PtyProducerFlowController { + private transport: ProducerFlowControlTransport + private highWatermarkChars: number + private lowWatermarkChars: number + private reassertIntervalMs: number + private pausedAtByPty = new Map() + + constructor( + transport: ProducerFlowControlTransport, + opts: { + highWatermarkChars?: number + lowWatermarkChars?: number + reassertIntervalMs?: number + } = {} + ) { + this.transport = transport + this.highWatermarkChars = opts.highWatermarkChars ?? PRODUCER_FLOW_HIGH_WATERMARK_CHARS + this.lowWatermarkChars = opts.lowWatermarkChars ?? PRODUCER_FLOW_LOW_WATERMARK_CHARS + this.reassertIntervalMs = opts.reassertIntervalMs ?? PRODUCER_PAUSE_REASSERT_INTERVAL_MS + } + + /** Reports the current pending chars for a PTY. Fires pause exactly once at + * the HIGH crossing (re-asserted only after the failsafe interval) and + * resume exactly once when pending drains below LOW. */ + update(id: string, pendingChars: number): void { + const pausedAt = this.pausedAtByPty.get(id) + if (pausedAt === undefined) { + if (pendingChars > this.highWatermarkChars) { + this.pausedAtByPty.set(id, Date.now()) + this.safePause(id) + } + return + } + if (pendingChars < this.lowWatermarkChars) { + this.pausedAtByPty.delete(id) + this.safeResume(id) + return + } + if ( + pendingChars > this.highWatermarkChars && + Date.now() - pausedAt >= this.reassertIntervalMs + ) { + this.pausedAtByPty.set(id, Date.now()) + this.safePause(id) + } + } + + /** Resumes a PTY if it was paused. For teardown paths (exit, kill) where + * the pending bookkeeping is being dropped rather than drained. */ + release(id: string): void { + if (this.pausedAtByPty.delete(id)) { + this.safeResume(id) + } + } + + /** Resumes every paused PTY. For wholesale bookkeeping wipes (window + * destroyed) — a local PTY left paused here would stay wedged forever. */ + releaseAll(): void { + // Deleting the visited entry during Map key iteration is spec-safe. + for (const id of this.pausedAtByPty.keys()) { + this.release(id) + } + } + + isPaused(id: string): boolean { + return this.pausedAtByPty.has(id) + } + + // Why swallow: pause/resume are optimizations riding the terminal data + // path — a provider throw must never break delivery or exit handling. + private safePause(id: string): void { + try { + this.transport.pauseProducer(id) + } catch { + /* best-effort */ + } + } + + private safeResume(id: string): void { + try { + this.transport.resumeProducer(id) + } catch { + /* best-effort */ + } + } +} diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index 60a8bb5da3aa..2b405685c455 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -9,6 +9,7 @@ import { TERMINAL_INPUT_MAX_BYTES } from '../../shared/terminal-input' import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../shared/clipboard-text' +import { redactPtyIdForDiagnostics } from '../../shared/pty-delivery-diagnostics' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../shared/constants' const isWindowsHost = process.platform === 'win32' @@ -18,11 +19,13 @@ const expectedOmpStatusExtension = posix.join( 'extensions', 'orca-agent-status.ts' ) -const expectedAttributionShimDir = join( - '/tmp/orca-user-data', - 'orca-terminal-attribution', - isWindowsHost ? 'win32' : 'posix' -) +function expectedAttributionShimDir(): string { + return join( + '/tmp/orca-user-data', + 'orca-terminal-attribution', + process.platform === 'win32' ? 'win32' : 'posix' + ) +} const { handleMock, @@ -91,7 +94,11 @@ const { vi.mock('electron', () => ({ app: { isPackaged: true, - getPath: getPathMock + getPath: getPathMock, + getVersion: () => '0.0.0-test' + }, + powerMonitor: { + on: vi.fn() }, nativeTheme: { shouldUseDarkColors: true @@ -190,6 +197,11 @@ import { unregisterSshPtyProvider, getLocalPtyProvider } from './pty' +import { + _resetHiddenRendererPtyDeliveryGateForTest, + isHiddenRendererPty +} from './pty-hidden-delivery-gate' +import { OrcaRuntimeService } from '../runtime/orca-runtime' import { hasLiveClaudePtys, markClaudePtySpawned } from '../claude-accounts/live-pty-gate' import * as livePtyGate from '../claude-accounts/live-pty-gate' import { @@ -235,10 +247,17 @@ describe('registerPtyHandlers', () => { const handlers = new Map unknown>() const mainWindow = { isDestroyed: () => false, + isFocused: () => true, + isVisible: () => true, + isMinimized: () => false, webContents: { on: vi.fn(), send: vi.fn(), - removeListener: vi.fn() + removeListener: vi.fn(), + // Why: the did-start-loading reset handler filters to main-frame loads via + // isLoadingMainFrame; default true so lifecycle-reset tests still reset. A + // subframe-load case overrides it to false. + isLoadingMainFrame: vi.fn(() => true) } } const mainWindowIpcEvent = { sender: mainWindow.webContents } @@ -259,6 +278,7 @@ describe('registerPtyHandlers', () => { const savedOrcaClaudeAgentStatusSettings = process.env.ORCA_CLAUDE_AGENT_STATUS_SETTINGS const savedProcessPlatform = Object.getOwnPropertyDescriptor(process, 'platform') const savedDisableMacosLoginShell = process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL + const savedOrcaUserDataPath = process.env.ORCA_USER_DATA_PATH beforeEach(() => { // Why: most PTY spawn tests assert POSIX shell behavior; Windows-specific @@ -317,6 +337,9 @@ describe('registerPtyHandlers', () => { mainWindow.webContents.on.mockReset() mainWindow.webContents.send.mockReset() mainWindow.webContents.removeListener.mockReset() + // Why: hidden-delivery gate state is module-level by design (PTY-keyed, + // not window-keyed); tests must not leak hidden bits across cases. + _resetHiddenRendererPtyDeliveryGateForTest() // Why: mirror real Electron — ipcMain.handle throws on a duplicate channel // unless removeHandler cleared it first. This catches a re-registration @@ -330,7 +353,26 @@ describe('registerPtyHandlers', () => { removeHandlerMock.mockImplementation((channel: string) => { handlers.delete(channel) }) + // Why: production holds PTY sends until the renderer's pty:data dispatcher + // registers and sends pty:rendererDispatcherReady (the §1b boot-window gate). + // These tests model a live page whose dispatcher is already listening, so + // fire the handshake as soon as it registers. Lifecycle-reset tests re-close + // the gate via did-start-loading and re-open it with an explicit handshake. + onMock.mockImplementation((channel: string, listener: (...args: unknown[]) => void) => { + if (channel === 'pty:rendererDispatcherReady') { + listener(mainWindowIpcEvent) + // Drain the empty flush the handshake schedules so it can't fire later + // (once real output is pending) and perturb send-timing assertions. + if (vi.isFakeTimers()) { + vi.advanceTimersByTime(0) + } + } + }) getPathMock.mockReturnValue('/tmp/orca-user-data') + // Why: shell-ready wrapper roots resolve from ORCA_USER_DATA_PATH (main + // canonicalizes it to app.getPath('userData') at startup before any spawn); + // mirror that here so ZDOTDIR/wrapper assertions match the mocked userData. + process.env.ORCA_USER_DATA_PATH = '/tmp/orca-user-data' existsSyncMock.mockReturnValue(true) statSyncMock.mockReturnValue({ isDirectory: () => true, mode: 0o755 }) readFileSyncMock.mockReturnValue('') @@ -375,7 +417,21 @@ describe('registerPtyHandlers', () => { afterEach(() => { _resetWslCachesForTests() vi.useRealTimers() - unregisterSshPtyProvider('ssh-1') + // Why: sshProviders is module-level state; any id left registered leaks + // into later tests (pty:listSessions sweeps every registered provider). + for (const leakedConnectionId of [ + 'ssh-1', + 'ssh-a', + 'ssh-b', + 'ssh-expired-runtime', + 'ssh-fresh-fail', + 'ssh-reattach-1', + 'ssh-reattach-fail', + 'ssh-reattach-ok', + 'ssh-runtime-env' + ]) { + unregisterSshPtyProvider(leakedConnectionId) + } setLocalPtyProvider(new LocalPtyProvider()) if (savedProcessPlatform) { Object.defineProperty(process, 'platform', savedProcessPlatform) @@ -385,6 +441,11 @@ describe('registerPtyHandlers', () => { } else { delete process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL } + if (savedOrcaUserDataPath !== undefined) { + process.env.ORCA_USER_DATA_PATH = savedOrcaUserDataPath + } else { + delete process.env.ORCA_USER_DATA_PATH + } if (savedOpenCodeConfigDir !== undefined) { process.env.OPENCODE_CONFIG_DIR = savedOpenCodeConfigDir } else { @@ -494,6 +555,7 @@ describe('registerPtyHandlers', () => { acknowledgeDataEvent: vi.fn(), hasChildProcesses: vi.fn(), getForegroundProcess: vi.fn(), + confirmForegroundProcess: vi.fn(), serialize: vi.fn(), revive: vi.fn(), onData: vi.fn(() => () => {}), @@ -511,12 +573,21 @@ describe('registerPtyHandlers', () => { const spawn = vi.fn(async (options: { sessionId?: string }) => ({ id: options.sessionId ?? 'daemon-pty' })) + const write = vi.fn() + const pauseProducer = vi.fn() + const resumeProducer = vi.fn() let dataHandler: ((payload: { id: string; data: string }) => void) | null = null let exitHandler: ((payload: { id: string; code: number }) => void) | null = null + let backgroundStreamHandler: + | ((payload: { id: string; kind: 'dataGap'; droppedChars: number }) => void) + | null = null + const getBufferSnapshot = vi.fn() setLocalPtyProvider({ spawn, - write: vi.fn(), + write, resize: vi.fn(), + pauseProducer, + resumeProducer, kill: vi.fn(), shutdown: vi.fn(), sendSignal: vi.fn(), @@ -526,6 +597,7 @@ describe('registerPtyHandlers', () => { acknowledgeDataEvent: vi.fn(), hasChildProcesses: vi.fn(), getForegroundProcess: vi.fn(), + confirmForegroundProcess: vi.fn(), serialize: vi.fn(), revive: vi.fn(), onData: vi.fn((handler: (payload: { id: string; data: string }) => void) => { @@ -533,6 +605,13 @@ describe('registerPtyHandlers', () => { return () => {} }), onReplay: vi.fn(() => () => {}), + onBackgroundStreamEvent: vi.fn( + (handler: (payload: { id: string; kind: 'dataGap'; droppedChars: number }) => void) => { + backgroundStreamHandler = handler + return () => {} + } + ), + getBufferSnapshot, onExit: vi.fn((handler: (payload: { id: string; code: number }) => void) => { exitHandler = handler return () => {} @@ -544,20 +623,29 @@ describe('registerPtyHandlers', () => { } as never) return { spawn, + write, + pauseProducer, + resumeProducer, + getBufferSnapshot, emitData: (id: string, data: string) => dataHandler?.({ id, data }), - emitExit: (id: string, code = 0) => exitHandler?.({ id, code }) + emitExit: (id: string, code = 0) => exitHandler?.({ id, code }), + emitDataGap: (id: string, droppedChars: number) => + backgroundStreamHandler?.({ id, kind: 'dataGap', droppedChars }) } } function getPtyAckDataListener(): ( event: unknown, - args: { id: string; charCount: number } + args: { id: string; charCount?: number; processedChars?: number } ) => void { const ackCall = onMock.mock.calls.find((call: unknown[]) => call[0] === 'pty:ackData') if (!ackCall) { throw new Error('missing pty:ackData listener') } - return ackCall[1] as (event: unknown, args: { id: string; charCount: number }) => void + return ackCall[1] as ( + event: unknown, + args: { id: string; charCount?: number; processedChars?: number } + ) => void } function getPtySetActiveRendererPtyListener(): ( @@ -586,6 +674,19 @@ describe('registerPtyHandlers', () => { return visibleCall[1] as (event: unknown, args: { id: string; visible: boolean }) => void } + function getPtyRendererDispatcherReadyListener(): () => void { + const readyCall = onMock.mock.calls.find( + (call: unknown[]) => call[0] === 'pty:rendererDispatcherReady' + ) + if (!readyCall) { + throw new Error('missing pty:rendererDispatcherReady listener') + } + const listener = readyCall[1] as (event: unknown) => void + // Why: the production handler sender-guards its destructive reconcile, so + // tests must present as the main window. + return () => listener(mainWindowIpcEvent) + } + function getMainWindowWebContentsListener(eventName: string): (...args: unknown[]) => void { const listenerCall = mainWindow.webContents.on.mock.calls.find( (call: unknown[]) => call[0] === eventName @@ -610,6 +711,32 @@ describe('registerPtyHandlers', () => { ) => void } + function getPtySetHiddenRendererPtyListener(): ( + event: unknown, + args: { id: string; hidden: boolean } + ) => void { + const hiddenCall = onMock.mock.calls.find( + (call: unknown[]) => call[0] === 'pty:setHiddenRendererPty' + ) + if (!hiddenCall) { + throw new Error('missing pty:setHiddenRendererPty listener') + } + return hiddenCall[1] as (event: unknown, args: { id: string; hidden: boolean }) => void + } + + function getPtySetDeliveryInterestListener(): ( + event: unknown, + args: { id: string; interested: boolean } + ) => void { + const interestCall = onMock.mock.calls.find( + (call: unknown[]) => call[0] === 'pty:setPtyDeliveryInterest' + ) + if (!interestCall) { + throw new Error('missing pty:setPtyDeliveryInterest listener') + } + return interestCall[1] as (event: unknown, args: { id: string; interested: boolean }) => void + } + /** Helper: trigger pty:spawn and return the env passed to node-pty. */ async function spawnAndGetEnv( argsEnv?: Record, @@ -1152,7 +1279,7 @@ describe('registerPtyHandlers', () => { expect(env.ORCA_GIT_COMMIT_TRAILER).toBe('Co-authored-by: Orca ') expect(env.ORCA_GH_PR_FOOTER).toBe('Made with [Orca](https://github.com/stablyai/orca) 🐋') expect(env.ORCA_GH_ISSUE_FOOTER).toBe('Made with [Orca](https://github.com/stablyai/orca) 🐋') - expect(env.PATH).toContain(expectedAttributionShimDir) + expect(env.PATH).toContain(expectedAttributionShimDir()) }) it('skips git/gh attribution shims when attribution is disabled', async () => { @@ -1164,7 +1291,7 @@ describe('registerPtyHandlers', () => { expect(env.ORCA_GIT_COMMIT_TRAILER).toBeUndefined() expect(env.ORCA_GH_PR_FOOTER).toBeUndefined() expect(env.ORCA_GH_ISSUE_FOOTER).toBeUndefined() - expect(env.PATH ?? '').not.toContain(expectedAttributionShimDir) + expect(env.PATH ?? '').not.toContain(expectedAttributionShimDir()) }) it('prepends git/gh attribution shims for daemon-backed local PTYs', async () => { @@ -1193,7 +1320,7 @@ describe('registerPtyHandlers', () => { const env = daemonSpawn.mock.calls.at(-1)![0].env expect(env.ORCA_ENABLE_GIT_ATTRIBUTION).toBe('1') - expect(env.PATH).toContain(expectedAttributionShimDir) + expect(env.PATH).toContain(expectedAttributionShimDir()) }) it('overrides ambient CODEX_HOME with the Orca-managed home for system default', async () => { @@ -1588,6 +1715,7 @@ describe('registerPtyHandlers', () => { const runtime = { setPtyController: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), onPtyData: vi.fn() @@ -1609,6 +1737,47 @@ describe('registerPtyHandlers', () => { expect(spawnOptions.env.ORCA_AGENT_HOOK_TOKEN).toBe('agent-token') }) + it('threads the validated pane identity into registerPty for a runtime-created daemon PTY (#7587)', async () => { + type RuntimeSpawnController = { + spawn(args: { + cols: number + rows: number + worktreeId?: string + tabId?: string + leafId?: string + env?: Record + }): Promise<{ id: string }> + } + const leafId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + setupDaemonAdapter() + const runtime = { + setPtyController: vi.fn(), + registerPty: vi.fn(), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn() + } + handlers.clear() + registerPtyHandlers(mainWindow as never, runtime as never) + const controller = runtime.setPtyController.mock.calls[0]?.[0] as RuntimeSpawnController + + await controller.spawn({ + cols: 80, + rows: 24, + worktreeId: 'wt-runtime', + tabId: 'tab-1', + leafId + }) + + // Why: runtime-created spawns (e.g. the mobile-create materialize path) + // must thread the same {tabId, leafId} so the catch-path rescue can find + // and keep their live PTY (#7587). + expect(runtime.registerPty).toHaveBeenCalledWith(expect.any(String), 'wt-runtime', null, { + tabId: 'tab-1', + leafId + }) + }) + it('uses the owning project WSL runtime for runtime-created daemon PTYs', async () => { await withWin32Platform(async () => { _setWslCachesForTests({ available: true, distros: ['Ubuntu'] }) @@ -1732,6 +1901,7 @@ describe('registerPtyHandlers', () => { const runtime = { setPtyController: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), onPtyData: vi.fn() @@ -1758,7 +1928,7 @@ describe('registerPtyHandlers', () => { const spawnOptions = daemonSpawn.mock.calls.at(-1)?.[0] as DaemonSpawnCall expect(spawnOptions.env.PATH.split(delimiter)[0]).toBe('/tmp/orca-agent-teams-bin') - expect(spawnOptions.env.PATH).toContain(expectedAttributionShimDir) + expect(spawnOptions.env.PATH).toContain(expectedAttributionShimDir()) expect(spawnOptions.env.TERM_PROGRAM).toBeUndefined() expect(spawnOptions.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined() expect(spawnOptions.envToDelete).toEqual( @@ -1788,7 +1958,7 @@ describe('registerPtyHandlers', () => { enableGitHubAttribution: true })) expect(env.ORCA_ENABLE_GIT_ATTRIBUTION).toBe('1') - expect(env.PATH).toContain(expectedAttributionShimDir) + expect(env.PATH).toContain(expectedAttributionShimDir()) }) it('keeps the Agent Teams tmux shim ahead of host PATH shims on daemon pty:spawn', async () => { @@ -1809,7 +1979,7 @@ describe('registerPtyHandlers', () => { ) expect(spawnOptions.env.PATH.split(delimiter)[0]).toBe('/tmp/orca-agent-teams-bin') - expect(spawnOptions.env.PATH).toContain(expectedAttributionShimDir) + expect(spawnOptions.env.PATH).toContain(expectedAttributionShimDir()) expect(spawnOptions.env.TERM_PROGRAM).toBeUndefined() expect(spawnOptions.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined() expect(spawnOptions.envToDelete).toEqual( @@ -1926,7 +2096,7 @@ describe('registerPtyHandlers', () => { enableGitHubAttribution: false })) expect(env.ORCA_ENABLE_GIT_ATTRIBUTION).toBeUndefined() - expect(env.PATH ?? '').not.toContain(expectedAttributionShimDir) + expect(env.PATH ?? '').not.toContain(expectedAttributionShimDir()) }) it('does not mutate the caller-provided args.env on the daemon path', async () => { @@ -3257,6 +3427,7 @@ describe('registerPtyHandlers', () => { const runtime = { setPtyController: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), onPtyData: vi.fn(() => 13), @@ -3290,11 +3461,16 @@ describe('registerPtyHandlers', () => { const result = await pendingSpawn daemon.emitData(result.id, 'daemon output') - vi.advanceTimersByTime(8) + vi.advanceTimersByTime(2) daemon.emitExit(result.id, 0) expect(daemon.spawn).toHaveBeenCalledTimes(1) - expect(runtime.onPtyData).toHaveBeenCalledWith(result.id, 'daemon output', expect.any(Number)) + expect(runtime.onPtyData).toHaveBeenCalledWith( + result.id, + 'daemon output', + expect.any(Number), + 'daemon output'.length + ) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: result.id, data: 'daemon output', @@ -3311,76 +3487,6 @@ describe('registerPtyHandlers', () => { } }) - // Why: the unsent main->renderer backlog was only bounded by renderer ACKs. A - // background-throttled/frozen renderer (Win/Linux) stops ACKing while a busy - // pane keeps producing, so the per-pty pending string grew at raw PTY rate - // (MB->GB). The cap trims it to the most-recent span and flags droppedBacklog - // exactly once so the renderer rebuilds the dropped span from the main snapshot. - it('caps the unsent pending backlog and flags droppedBacklog once when the renderer never acks', async () => { - vi.useFakeTimers() - let seq = 0 - const runtime = { - setPtyController: vi.fn(), - registerPty: vi.fn(), - onPtySpawned: vi.fn(), - onPtyExit: vi.fn(), - onPtyData: vi.fn((_id: string, data: string) => { - seq += data.length - return seq - }), - createPreAllocatedTerminalHandle: vi.fn(() => 'terminal-handle-cap'), - registerPreAllocatedHandleForPty: vi.fn() - } - try { - registerPtyHandlers( - mainWindow as never, - runtime as never, - undefined, - undefined, - undefined, - undefined, - { awaitLocalPtyStartup: () => Promise.resolve() } - ) - const pendingSpawn = handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - sessionId: 'backlog-cap-session' - }) as Promise<{ id: string }> - await Promise.resolve() - const daemon = installObservableDaemonTestProvider() - rebindLocalProviderListeners() - const result = await pendingSpawn - - // Never ack: in-flight pins at the high-water and the flush gates, so the - // unsent backlog would grow unbounded. Emit far more than the 2 MB cap. - const HUGE = 'x'.repeat(5 * 1024 * 1024) - daemon.emitData(result.id, HUGE) - await vi.advanceTimersByTimeAsync(50) - - const dataSends = mainWindow.webContents.send.mock.calls.filter( - (call) => call[0] === 'pty:data' && (call[1] as { id: string }).id === result.id - ) - expect(dataSends.length).toBeGreaterThan(0) - // Sanity bound only: with no acks the sent total is already gated by the - // pre-existing in-flight high-water caps, so this holds independent of the - // trim. The actual retained-backlog cap is proven by droppedBacklog below. - const totalChars = dataSends.reduce( - (sum, call) => sum + (call[1] as { data: string }).data.length, - 0 - ) - expect(totalChars).toBeLessThan(3 * 1024 * 1024) - // The trim signals the renderer exactly once, on the first emitted chunk. - expect((dataSends[0][1] as { droppedBacklog?: boolean }).droppedBacklog).toBe(true) - expect( - dataSends.filter( - (call) => (call[1] as { droppedBacklog?: boolean }).droppedBacklog === true - ) - ).toHaveLength(1) - } finally { - vi.useRealTimers() - } - }) - // Why: the cap and its flag must never fire in the common case (renderer keeps // up), so ordinary small output carries no droppedBacklog. it('does not flag droppedBacklog for ordinary small output under the cap', async () => { @@ -3434,6 +3540,7 @@ describe('registerPtyHandlers', () => { const runtime = { setPtyController: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), onPtyData: vi.fn() @@ -3868,6 +3975,7 @@ describe('registerPtyHandlers', () => { listProcesses: vi.fn(), hasChildProcesses: vi.fn(), getForegroundProcess: vi.fn(), + confirmForegroundProcess: vi.fn(), serialize: vi.fn(), revive: vi.fn(), getDefaultShell: vi.fn(), @@ -3929,6 +4037,7 @@ describe('registerPtyHandlers', () => { listProcesses: vi.fn(), hasChildProcesses: vi.fn(), getForegroundProcess: vi.fn(), + confirmForegroundProcess: vi.fn(), serialize: vi.fn(), revive: vi.fn(), getDefaultShell: vi.fn(), @@ -3945,8 +4054,12 @@ describe('registerPtyHandlers', () => { await expect( handlers.get('pty:getForegroundProcess')!(null, { id: 'remote-pty' }) ).resolves.toBeNull() + await expect( + handlers.get('pty:confirmForegroundProcess')!(null, { id: 'remote-pty' }) + ).resolves.toBeNull() expect(provider.hasChildProcesses).not.toHaveBeenCalled() expect(provider.getForegroundProcess).not.toHaveBeenCalled() + expect(provider.confirmForegroundProcess).not.toHaveBeenCalled() }) // Why: regression for the Claude-Code split-pane garbled-render desync. resize @@ -4131,6 +4244,7 @@ describe('registerPtyHandlers', () => { } as never) const runtime = { setPtyController: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), createPreAllocatedTerminalHandle: vi.fn(() => 'term_remote'), registerPreAllocatedHandleForPty: vi.fn() } @@ -4246,6 +4360,67 @@ describe('registerPtyHandlers', () => { ) }) + it('threads the validated pane identity into registerPty for a renderer PTY spawn (#7587)', async () => { + const leafId = '88888888-8888-4888-8888-888888888888' + const runtime = { + setPtyController: vi.fn(), + preAllocateHandleForPty: vi.fn(() => 'term_seam'), + registerPreAllocatedHandleForPty: vi.fn(), + registerPty: vi.fn(), + getDriver: vi.fn(() => ({ kind: 'host' })), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn() + } + handlers.clear() + registerPtyHandlers(mainWindow as never, runtime as never) + + await handlers.get('pty:spawn')!(mainWindowIpcEvent, { + cols: 80, + rows: 24, + cwd: '/repo', + tabId: 'tab-1', + leafId, + worktreeId: 'wt-1' + }) + + // Why: this is the load-bearing wiring for #7587 — the runtime can only back a + // stalled mobile create from a live spawn if the spawn threads {tabId, leafId}. + expect(runtime.registerPty).toHaveBeenCalledWith(expect.any(String), 'wt-1', null, { + tabId: 'tab-1', + leafId + }) + }) + + it('omits the pane identity from registerPty when the leafId is not a terminal leaf (#7587)', async () => { + const runtime = { + setPtyController: vi.fn(), + preAllocateHandleForPty: vi.fn(() => 'term_seam'), + registerPreAllocatedHandleForPty: vi.fn(), + registerPty: vi.fn(), + getDriver: vi.fn(() => ({ kind: 'host' })), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn() + } + handlers.clear() + registerPtyHandlers(mainWindow as never, runtime as never) + + await handlers.get('pty:spawn')!(mainWindowIpcEvent, { + cols: 80, + rows: 24, + cwd: '/repo', + tabId: 'tab-1', + leafId: 'pane:1', + worktreeId: 'wt-1' + }) + + // Why: legacy numeric pane ids (`pane:N`) are not terminal leaf ids, so the + // spawn seam must not fabricate a binding for them (registerPty would ignore + // it anyway); this pins that the seam passes a clean `undefined`. + expect(runtime.registerPty).toHaveBeenCalledWith(expect.any(String), 'wt-1', null, undefined) + }) + it('refreshes native Agent Teams env when captured teammate mode lives in launch args', async () => { const leafId = '11111111-1111-4111-8111-111111111111' const runtime = { @@ -4356,6 +4531,7 @@ describe('registerPtyHandlers', () => { preAllocateHandleForPty: vi.fn(() => 'term_wrong'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), getDriver: vi.fn(() => ({ kind: 'host' })), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), @@ -4407,6 +4583,7 @@ describe('registerPtyHandlers', () => { preAllocateHandleForPty: vi.fn(), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), getDriver: vi.fn(() => ({ kind: 'host' })), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), @@ -4446,6 +4623,7 @@ describe('registerPtyHandlers', () => { preAllocateHandleForPty: vi.fn(() => 'term_trusted'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), onPtyData: vi.fn() @@ -4893,6 +5071,7 @@ describe('registerPtyHandlers', () => { createPreAllocatedTerminalHandle: vi.fn(() => 'term_remote'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), getDriver: vi.fn(() => ({ kind: 'host' })), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), @@ -4964,6 +5143,7 @@ describe('registerPtyHandlers', () => { preAllocateHandleForPty: vi.fn(() => 'term_trusted'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), onPtyData: vi.fn() @@ -5050,6 +5230,7 @@ describe('registerPtyHandlers', () => { createPreAllocatedTerminalHandle: vi.fn(() => 'term_remote'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), onPtyData: vi.fn() @@ -5147,6 +5328,7 @@ describe('registerPtyHandlers', () => { createPreAllocatedTerminalHandle: vi.fn(() => 'term_remote'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), getDriver: vi.fn(() => ({ kind: 'host' })), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), @@ -5255,6 +5437,7 @@ describe('registerPtyHandlers', () => { createPreAllocatedTerminalHandle: vi.fn(() => 'term_remote'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), getDriver: vi.fn(() => ({ kind: 'host' })), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), @@ -5348,6 +5531,7 @@ describe('registerPtyHandlers', () => { createPreAllocatedTerminalHandle: vi.fn(() => 'term_remote'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), getDriver: vi.fn(() => ({ kind: 'host' })), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), @@ -5553,6 +5737,7 @@ describe('registerPtyHandlers', () => { createPreAllocatedTerminalHandle: vi.fn(() => 'term_remote'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), onPtyData: vi.fn() @@ -5611,6 +5796,7 @@ describe('registerPtyHandlers', () => { preAllocateHandleForPty: vi.fn(() => 'term_trusted'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), onPtyData: vi.fn() @@ -5658,6 +5844,7 @@ describe('registerPtyHandlers', () => { it('ignores renderer-provided ORCA_TERMINAL_HANDLE for local PTY spawns', async () => { const runtime = { setPtyController: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), preAllocateHandleForPty: vi.fn(() => 'term_trusted'), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), @@ -5685,6 +5872,7 @@ describe('registerPtyHandlers', () => { }) const runtime = { setPtyController: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), preAllocateHandleForPty: vi.fn(() => 'term_wsl'), onPtySpawned: vi.fn(), onPtyExit: vi.fn(), @@ -5708,9 +5896,11 @@ describe('registerPtyHandlers', () => { const env = spawnCall[2].env as Record expect(spawnCall[0]).toBe('wsl.exe') expect(env.ORCA_TERMINAL_HANDLE).toBe('term_wsl') + expect(env.ORCA_USER_DATA_PATH).toBe('/tmp/orca-user-data') expect(env.WSLENV?.split(':')).toEqual( expect.arrayContaining([ 'ORCA_TERMINAL_HANDLE/u', + 'ORCA_USER_DATA_PATH/p', 'ORCA_AGENT_HOOK_PORT/u', 'ORCA_AGENT_HOOK_TOKEN/u', 'ORCA_OMP_SOURCE_AGENT_DIR/p', @@ -5720,6 +5910,42 @@ describe('registerPtyHandlers', () => { ) }) + it('forces managed ORCA_USER_DATA_PATH for WSL spawns even when the caller provides a stale root', async () => { + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { + configurable: true, + value: 'win32' + }) + const runtime = { + setPtyController: vi.fn(), + preAllocateHandleForPty: vi.fn(() => 'term_wsl'), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn() + } + + try { + registerPtyHandlers(mainWindow as never, runtime as never) + await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + shellOverride: 'wsl.exe', + env: { + ORCA_USER_DATA_PATH: '/tmp/stale-orca-user-data' + } + }) + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + + const spawnCall = spawnMock.mock.calls.at(-1)! + const env = spawnCall[2].env as Record + expect(spawnCall[0]).toBe('wsl.exe') + expect(env.ORCA_USER_DATA_PATH).toBe('/tmp/orca-user-data') + }) + describe('Windows UTF-8 code page', () => { let originalPlatform: string let originalComspec: string | undefined @@ -6164,6 +6390,98 @@ describe('registerPtyHandlers', () => { expect(options.cwd).toBe('/tmp/floating-notes') }) + it('falls back to the worktree root when a saved local cwd no longer exists', async () => { + registerPtyHandlers(mainWindow as never) + // Why: issue #7239 reproduced in a Japanese-named worktree; the fallback + // must return the selected worktree path verbatim. + const worktreePath = '/Users/motoki/orca/workspaces/nakamuramotoki/Fableと議論' + const missingCwd = `${worktreePath}/deleted-folder` + statSyncMock.mockImplementation((target: string) => { + if (target === missingCwd) { + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) + } + return { isDirectory: () => true, mode: 0o755 } + }) + + const result = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: missingCwd, + cwdFallback: 'worktree', + worktreeId: `repo-1::${worktreePath}` + })) as { startupCwdFallback?: { kind: string; cwd: string } } + + const [, , options] = spawnMock.mock.calls.at(-1) as [string, string[], { cwd: string }] + expect(options.cwd).toBe(worktreePath) + expect(result.startupCwdFallback).toEqual({ kind: 'worktree', cwd: worktreePath }) + }) + + it('keeps a missing cwd unchanged without the fallback flag', async () => { + registerPtyHandlers(mainWindow as never) + existsSyncMock.mockImplementation((target: string) => target !== '/repo/app/deleted-folder') + statSyncMock.mockImplementation((target: string) => { + if (target === '/repo/app/deleted-folder') { + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) + } + return { isDirectory: () => true, mode: 0o755 } + }) + + // Why: without the renderer opt-in the provider still surfaces its normal + // missing-directory error — API/runtime callers keep exact cwd semantics. + await expect( + handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/repo/app/deleted-folder', + worktreeId: 'repo-1::/repo/app' + }) + ).rejects.toThrow('Working directory "/repo/app/deleted-folder" does not exist.') + + expect(spawnMock).not.toHaveBeenCalled() + }) + + it('spawns at an existing outside-worktree cwd without falling back (#7685)', async () => { + registerPtyHandlers(mainWindow as never) + + const result = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/repo/app-other', + cwdFallback: 'worktree', + worktreeId: 'repo-1::/repo/app' + })) as { startupCwdFallback?: unknown } + + const [, , options] = spawnMock.mock.calls.at(-1) as [string, string[], { cwd: string }] + expect(options.cwd).toBe('/repo/app-other') + expect(result.startupCwdFallback).toBeUndefined() + }) + + it('ignores the cwd fallback flag for session reattach spawns', async () => { + registerPtyHandlers(mainWindow as never) + existsSyncMock.mockImplementation((target: string) => target !== '/repo/app/deleted-folder') + statSyncMock.mockImplementation((target: string) => { + if (target === '/repo/app/deleted-folder') { + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) + } + return { isDirectory: () => true, mode: 0o755 } + }) + + // Why: a reattach must keep the session's exact cwd; remapping it would + // silently detach the restored terminal from its recorded state. + await expect( + handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/repo/app/deleted-folder', + cwdFallback: 'worktree', + sessionId: 'session-1', + worktreeId: 'repo-1::/repo/app' + }) + ).rejects.toThrow('Working directory "/repo/app/deleted-folder" does not exist.') + + expect(spawnMock).not.toHaveBeenCalled() + }) + it('rejects missing WSL worktree cwd instead of validating only the fallback Windows cwd', async () => { const originalPlatform = process.platform const originalUserProfile = process.env.USERPROFILE @@ -6589,7 +6907,7 @@ describe('registerPtyHandlers', () => { mockProc.emitData('background output') expect(mainWindow.webContents.send).not.toHaveBeenCalled() - vi.advanceTimersByTime(7) + vi.advanceTimersByTime(1) expect(mainWindow.webContents.send).not.toHaveBeenCalled() vi.advanceTimersByTime(1) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { @@ -6618,7 +6936,7 @@ describe('registerPtyHandlers', () => { setRendererPtyVisible(null, { id: spawnResult.id, visible: true }) mockProc.emitData('visible output') - vi.advanceTimersByTime(8) + vi.advanceTimersByTime(2) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, data: 'visible output' @@ -6628,7 +6946,7 @@ describe('registerPtyHandlers', () => { setRendererPtyVisible(null, { id: spawnResult.id, visible: false }) mockProc.emitData('\x1b[2Khidden-width redraw') setRendererPtyVisible(null, { id: spawnResult.id, visible: true }) - vi.advanceTimersByTime(8) + vi.advanceTimersByTime(2) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, @@ -6654,12 +6972,15 @@ describe('registerPtyHandlers', () => { })) as { id: string } const setRendererPtyVisible = getPtySetRendererPtyVisibleListener() const handleRendererLoading = getMainWindowWebContentsListener('did-start-loading') + const handleRendererDispatcherReady = getPtyRendererDispatcherReadyListener() mainWindow.webContents.send.mockClear() setRendererPtyVisible(null, { id: spawnResult.id, visible: true }) handleRendererLoading() + // Reloaded page's dispatcher re-registers, releasing held sends (§1b). + handleRendererDispatcherReady() mockProc.emitData('reload-gap output') - vi.advanceTimersByTime(8) + vi.advanceTimersByTime(2) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, @@ -6670,7 +6991,7 @@ describe('registerPtyHandlers', () => { mainWindow.webContents.send.mockClear() setRendererPtyVisible(null, { id: spawnResult.id, visible: true }) mockProc.emitData('visible output') - vi.advanceTimersByTime(8) + vi.advanceTimersByTime(2) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, @@ -6681,7 +7002,7 @@ describe('registerPtyHandlers', () => { } }) - it('preserves background-origin metadata for repaint output caused by a hidden resize', async () => { + it('resets leaked delivery accounting on renderer lifecycle reset so a saturated PTY resumes', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -6693,37 +7014,80 @@ describe('registerPtyHandlers', () => { rows: 24, cwd: '/tmp' })) as { id: string } - const setRendererPtyVisible = getPtySetRendererPtyVisibleListener() - const resizePty = getPtyResizeListener() + const handleRendererLoading = getMainWindowWebContentsListener('did-start-loading') + const handleRendererDispatcherReady = getPtyRendererDispatcherReadyListener() + // Drain the initial dispatcher-ready flush (beforeEach fires the handshake + // to model a live page) so the flood timing below starts from a clean slate. + vi.advanceTimersByTime(1) mainWindow.webContents.send.mockClear() - setRendererPtyVisible(null, { id: spawnResult.id, visible: false }) - resizePty(null, { id: spawnResult.id, cols: 72, rows: 24 }) - setRendererPtyVisible(null, { id: spawnResult.id, visible: true }) - mockProc.emitData('\x1b[2Khidden-resize redraw') + // Saturate the PTY past the 512 KB per-PTY high-water with no ACKs. + mockProc.emitData('x'.repeat(600 * 1024)) vi.advanceTimersByTime(8) - - expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { - id: spawnResult.id, - data: '\x1b[2Khidden-resize redraw', - background: true + for (let index = 0; index < 31; index++) { + vi.advanceTimersByTime(1) + } + + // Gate closed: sends stop at the cap and the remainder accrues as pending. + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(32) + vi.advanceTimersByTime(1) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(32) + expect(vi.getTimerCount()).toBe(0) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 512 * 1024, + pendingChars: 88 * 1024, + pendingPtyCount: 1, + rendererLifecycleResetCount: 0, + lastLifecycleResetClearedChars: 0 }) + // Renderer reload: the dead page never ACKs, so its in-flight/pending + // accounting must clear or the surviving PTY stays delivery-gated forever. + handleRendererLoading() + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 0, + rendererInFlightPtyCount: 0, + pendingChars: 0, + pendingPtyCount: 0, + rendererLifecycleResetCount: 1, + lastLifecycleResetClearedChars: 512 * 1024 + }) + + // Boot window (§1b): the reloaded page's dispatcher has not re-registered + // yet, so main must hold sends — bytes sent into the listener-less page are + // dropped but still counted in-flight, which would re-pin the gate. The + // output must accrue in pending, unsent and NOT counted in-flight. mainWindow.webContents.send.mockClear() - resizePty(null, { id: spawnResult.id, cols: 80, rows: 24 }) - mockProc.emitData('visible repaint') + mockProc.emitData('post-reload output') vi.advanceTimersByTime(8) + expect(mainWindow.webContents.send).not.toHaveBeenCalled() + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 0, + pendingChars: 'post-reload output'.length, + pendingPtyCount: 1 + }) + // The reloaded page's dispatcher-ready handshake releases the held backlog. + // Counters-zero alone is insufficient — prove delivery actually resumes and + // the pending backlog drains (bytes now correctly counted in-flight, the + // mirror image of the NOT-counted boot-window hold above). + handleRendererDispatcherReady() + vi.advanceTimersByTime(8) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: 'visible repaint' + data: 'post-reload output' + }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 'post-reload output'.length, + pendingChars: 0, + pendingPtyCount: 0 }) } finally { vi.useRealTimers() } }) - it('does not keep hidden resize metadata after visible user input', async () => { + it('ignores a subframe did-start-loading (isLoadingMainFrame false) so an in-page iframe load cannot freeze delivery', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -6735,28 +7099,49 @@ describe('registerPtyHandlers', () => { rows: 24, cwd: '/tmp' })) as { id: string } - const setRendererPtyVisible = getPtySetRendererPtyVisibleListener() - const resizePty = getPtyResizeListener() - const writePty = getPtyWriteListener() + const handleRendererLoading = getMainWindowWebContentsListener('did-start-loading') + const ackData = getPtyAckDataListener() + // Drain the initial dispatcher-ready flush (beforeEach fires the handshake). + vi.advanceTimersByTime(1) mainWindow.webContents.send.mockClear() - setRendererPtyVisible(null, { id: spawnResult.id, visible: false }) - resizePty(null, { id: spawnResult.id, cols: 72, rows: 24 }) - setRendererPtyVisible(null, { id: spawnResult.id, visible: true }) - writePty(mainWindowIpcEvent, { id: spawnResult.id, data: 'x' }) - mockProc.emitData('x') + // Saturate the PTY past the 512 KB per-PTY high-water with no ACKs. + mockProc.emitData('x'.repeat(600 * 1024)) vi.advanceTimersByTime(8) + for (let index = 0; index < 31; index++) { + vi.advanceTimersByTime(1) + } + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(32) - expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { - id: spawnResult.id, - data: 'x' + // A sandboxed srcDoc iframe (notebook HTML output) loading fires + // did-start-loading with isLoadingMainFrame() === false. This is NOT a + // renderer lifecycle reset: the still-alive page keeps its dispatcher, so + // clearing accounting or dropping the ready flag here would freeze every + // pane for the whole watchdog window. Nothing must change. + mainWindow.webContents.isLoadingMainFrame.mockReturnValueOnce(false) + handleRendererLoading() + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 512 * 1024, + pendingChars: 88 * 1024, + pendingPtyCount: 1, + rendererLifecycleResetCount: 0, + lastLifecycleResetClearedChars: 0, + rendererPtyDispatcherReady: true }) + + // The gate is still open: ACKing the in-flight cap drains the held backlog + // (a spurious reset would have cleared pending and dropped ready, so this + // send would never fire). + mainWindow.webContents.send.mockClear() + ackData(null, { id: spawnResult.id, charCount: 512 * 1024 }) + vi.advanceTimersByTime(8) + expect(mainWindow.webContents.send).toHaveBeenCalled() } finally { vi.useRealTimers() } }) - it('answers agent startup OSC color queries before renderer batching', async () => { + it('reconciles stale delivery accounting when a fresh dispatcher-ready handshake arrives while the gate is still open (missed lifecycle reset)', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -6766,31 +7151,65 @@ describe('registerPtyHandlers', () => { const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, - cwd: '/tmp', - launchAgent: 'codex', - terminalColorQueryReplies: { - foreground: '#eeeeee', - background: '#111111' - } + cwd: '/tmp' })) as { id: string } - mockProc.proc.write.mockClear() + const handleRendererDispatcherReady = getPtyRendererDispatcherReadyListener() + const ackData = getPtyAckDataListener() + // Drain the initial dispatcher-ready flush (beforeEach fires the handshake). + vi.advanceTimersByTime(1) mainWindow.webContents.send.mockClear() - mockProc.emitData('\x1b]10;?\x1b\\\x1b]11;?\x1b\\ready') + // Saturate the PTY past the 512 KB per-PTY high-water with no ACKs. + mockProc.emitData('x'.repeat(600 * 1024)) + vi.advanceTimersByTime(8) + for (let index = 0; index < 31; index++) { + vi.advanceTimersByTime(1) + } + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 512 * 1024, + pendingChars: 88 * 1024, + rendererLifecycleResetCount: 0, + rendererPtyDispatcherReady: true + }) - expect(mockProc.proc.write).toHaveBeenCalledWith('\x1b]10;rgb:eeee/eeee/eeee\x1b\\') - expect(mockProc.proc.write).toHaveBeenCalledWith('\x1b]11;rgb:1111/1111/1111\x1b\\') + // A main-frame reload overlapped by an in-page subframe load emits no + // did-start-loading, so the lifecycle reset never ran: the gate stayed open + // holding the dead page's in-flight accounting. The reloaded page's fresh + // dispatcher now sends its one-shot handshake. Receiving it while the gate is + // already open is proof a reset was missed, so it must reconcile — clear the + // stale accounting and count the reset — before re-opening. Without that + // reconcile the survivors stay pinned at the cap forever (this turns red). + mainWindow.webContents.send.mockClear() + handleRendererDispatcherReady() + const reconciled = getPtyRendererDeliveryDebugSnapshot() + expect(reconciled).toMatchObject({ + rendererInFlightChars: 0, + pendingChars: 0, + pendingPtyCount: 0, + rendererLifecycleResetCount: 1, + rendererPtyDispatcherReady: true + }) + expect(reconciled.lastLifecycleResetClearedChars).toBeGreaterThan(0) + + // Delivery has resumed: fresh output flows immediately instead of piling up + // behind the stale cap. + mockProc.emitData('post-reconcile output') vi.advanceTimersByTime(8) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: 'ready' + data: 'post-reconcile output' }) + + // A straggler ACK from the dead page is clamped and cannot underflow the + // reconciled counters below zero. + ackData(null, { id: spawnResult.id, charCount: 512 * 1024 }) + expect(getPtyRendererDeliveryDebugSnapshot().rendererInFlightChars).toBe(0) } finally { vi.useRealTimers() } }) - it('answers combined agent startup OSC foreground and background color queries', async () => { + it('holds interactive input echo during the boot window until the dispatcher-ready handshake', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -6800,31 +7219,46 @@ describe('registerPtyHandlers', () => { const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, - cwd: '/tmp', - launchAgent: 'codex', - terminalColorQueryReplies: { - foreground: '#eeeeee', - background: '#111111' - } + cwd: '/tmp' })) as { id: string } - mockProc.proc.write.mockClear() + const handleRendererLoading = getMainWindowWebContentsListener('did-start-loading') + const handleRendererDispatcherReady = getPtyRendererDispatcherReadyListener() + const writeListener = getPtyWriteListener() + // Drain the initial ready-flush the beforeEach handshake schedules. + vi.advanceTimersByTime(1) + + // Reload closes the gate; the reloaded page's dispatcher has not re-registered. + handleRendererLoading() mainWindow.webContents.send.mockClear() - mockProc.emitData('\x1b]10;?;?\x1b\\ready') + // Prime the interactive window with a keystroke, then emit a small redraw: + // shouldSendInteractiveOutputNow() is true here, so ONLY the + // `&& rendererPtyDispatcherReady` guard on the interactive fast path keeps this + // echo from being sent into the still-listener-less page (removing that flag + // check turns this red). It must accrue in pending, unsent and NOT in-flight. + const redraw = '\x1b[20;2Hredraw' + writeListener(mainWindowIpcEvent, { id: spawnResult.id, data: 'a' }) + mockProc.emitData(redraw) + expect(mainWindow.webContents.send).not.toHaveBeenCalled() + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 0, + pendingChars: redraw.length, + pendingPtyCount: 1 + }) - expect(mockProc.proc.write).toHaveBeenCalledWith('\x1b]10;rgb:eeee/eeee/eeee\x1b\\') - expect(mockProc.proc.write).toHaveBeenCalledWith('\x1b]11;rgb:1111/1111/1111\x1b\\') + // The handshake releases the held echo (drained via the batch flush). + handleRendererDispatcherReady() vi.advanceTimersByTime(8) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: 'ready' + data: redraw }) } finally { vi.useRealTimers() } }) - it('does not answer ordinary terminal OSC color queries in main', async () => { + it('force-opens the delivery gate if no dispatcher-ready handshake arrives after a reload', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -6834,29 +7268,42 @@ describe('registerPtyHandlers', () => { const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, - cwd: '/tmp', - terminalColorQueryReplies: { - foreground: '#eeeeee', - background: '#111111' - } + cwd: '/tmp' })) as { id: string } - mainWindow.webContents.send.mockClear() + const handleRendererLoading = getMainWindowWebContentsListener('did-start-loading') + vi.advanceTimersByTime(1) - const query = '\x1b]10;?\x1b\\\x1b]11;?\x1b\\' - mockProc.emitData(`${query}ready`) + // Reload closes the gate and arms the ~10s watchdog; the reloaded page never + // sends the handshake (dropped IPC), so output stays held in pending. + handleRendererLoading() + mainWindow.webContents.send.mockClear() + mockProc.emitData('post-reload output') + vi.advanceTimersByTime(8) + expect(mainWindow.webContents.send).not.toHaveBeenCalled() + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererPtyDispatcherReady: false, + rendererDispatcherReadyForcedCount: 0 + }) - expect(mockProc.proc.write).not.toHaveBeenCalled() + // Past the watchdog window (10s) the gate self-heals: ready is forced, the + // counter increments, and the held backlog drains — degrading to pre-handshake + // behavior instead of a permanent freeze. + vi.advanceTimersByTime(10_000) vi.advanceTimersByTime(8) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: `${query}ready` + data: 'post-reload output' + }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererPtyDispatcherReady: true, + rendererDispatcherReadyForcedCount: 1 }) } finally { vi.useRealTimers() } }) - it('does not answer agent OSC color commands that only start like startup queries', async () => { + it('ignores a dispatcher-ready handshake from a sender other than the main window', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -6866,170 +7313,114 @@ describe('registerPtyHandlers', () => { const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, - cwd: '/tmp', - launchAgent: 'codex', - terminalColorQueryReplies: { - foreground: '#eeeeee', - background: '#111111' - } + cwd: '/tmp' })) as { id: string } - mockProc.proc.write.mockClear() - mainWindow.webContents.send.mockClear() + const handleRendererLoading = getMainWindowWebContentsListener('did-start-loading') + const readyCall = onMock.mock.calls.find( + (call: unknown[]) => call[0] === 'pty:rendererDispatcherReady' + )! + const rawReadyListener = readyCall[1] as (event: unknown) => void + vi.advanceTimersByTime(1) - const command = '\x1b]10;?not-a-query\x1b\\' - mockProc.emitData(`${command}ready`) + // Why: a straggler handshake from a dying window's webContents must not + // reopen the gate (or trigger the destructive reconcile) for the new page. + handleRendererLoading() + mainWindow.webContents.send.mockClear() + rawReadyListener({ sender: { isDestroyed: () => false } }) + mockProc.emitData('post-reload output') + vi.advanceTimersByTime(8) + expect(mainWindow.webContents.send).not.toHaveBeenCalled() + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererPtyDispatcherReady: false + }) - expect(mockProc.proc.write).not.toHaveBeenCalled() + // The genuine main-window handshake still opens the gate and drains. + rawReadyListener({ sender: mainWindow.webContents }) vi.advanceTimersByTime(8) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: `${command}ready` + data: 'post-reload output' + }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererPtyDispatcherReady: true }) } finally { vi.useRealTimers() } }) - it('answers daemon agent startup OSC color queries before spawn resolves', async () => { + it('cancels the dispatcher-ready watchdog when the handshake arrives in time', async () => { vi.useFakeTimers() - let dataHandler: ((payload: { id: string; data: string }) => void) | null = null - const write = vi.fn() - const spawn = vi.fn(async (options: { sessionId?: string }) => { - const id = options.sessionId ?? 'daemon-pty' - dataHandler?.({ id, data: '\x1b]10;?\x1b\\\x1b]11;?\x1b\\daemon-ready' }) - return { id } - }) - setLocalPtyProvider({ - spawn, - write, - resize: vi.fn(), - kill: vi.fn(), - shutdown: vi.fn(), - sendSignal: vi.fn(), - getCwd: vi.fn(), - getInitialCwd: vi.fn(), - clearBuffer: vi.fn(), - acknowledgeDataEvent: vi.fn(), - hasChildProcesses: vi.fn(), - getForegroundProcess: vi.fn(), - serialize: vi.fn(), - revive: vi.fn(), - onData: vi.fn((handler: (payload: { id: string; data: string }) => void) => { - dataHandler = handler - return () => {} - }), - onReplay: vi.fn(() => () => {}), - onExit: vi.fn(() => () => {}), - listProcesses: vi.fn(async () => []), - attach: vi.fn(), - getDefaultShell: vi.fn(), - getProfiles: vi.fn() - } as never) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) try { registerPtyHandlers(mainWindow as never) - const spawnResult = (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp', - launchAgent: 'codex', - terminalColorQueryReplies: { - foreground: '#eeeeee', - background: '#111111' - } - })) as { id: string } + await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, cwd: '/tmp' }) + const handleRendererLoading = getMainWindowWebContentsListener('did-start-loading') + const handleRendererDispatcherReady = getPtyRendererDispatcherReadyListener() + vi.advanceTimersByTime(1) - expect(write).toHaveBeenCalledWith(spawnResult.id, '\x1b]10;rgb:eeee/eeee/eeee\x1b\\') - expect(write).toHaveBeenCalledWith(spawnResult.id, '\x1b]11;rgb:1111/1111/1111\x1b\\') - vi.advanceTimersByTime(8) - expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { - id: spawnResult.id, - data: 'daemon-ready' + // Reload arms the watchdog; a timely handshake must cancel it so no orphaned + // ~10s timer lingers. Draining the handshake's empty flush must leave zero + // pending timers — a surviving watchdog would show up here (the forced-count + // guard alone can't catch it, since the watchdog no-ops once ready is true). + handleRendererLoading() + handleRendererDispatcherReady() + vi.advanceTimersByTime(0) + expect(vi.getTimerCount()).toBe(0) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererPtyDispatcherReady: true, + rendererDispatcherReadyForcedCount: 0 + }) + + // Advancing well past the watchdog window leaves the forced counter at zero. + vi.advanceTimersByTime(20_000) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererPtyDispatcherReady: true, + rendererDispatcherReadyForcedCount: 0 }) } finally { vi.useRealTimers() } }) - it('drops renderer sequence metadata when an answered OSC query is batched', async () => { + it("cancels a prior registration's armed dispatcher-ready watchdog when handlers re-register (no orphaned timer across window re-creation)", async () => { vi.useFakeTimers() - const providerEvents: { - dataHandler?: (payload: { id: string; data: string }) => void - } = {} - const write = vi.fn() - const spawn = vi.fn(async (options: { sessionId?: string }) => ({ - id: options.sessionId ?? 'daemon-pty' - })) - setLocalPtyProvider({ - spawn, - write, - resize: vi.fn(), - kill: vi.fn(), - shutdown: vi.fn(), - sendSignal: vi.fn(), - getCwd: vi.fn(), - getInitialCwd: vi.fn(), - clearBuffer: vi.fn(), - acknowledgeDataEvent: vi.fn(), - hasChildProcesses: vi.fn(), - getForegroundProcess: vi.fn(), - serialize: vi.fn(), - revive: vi.fn(), - onData: vi.fn((handler: (payload: { id: string; data: string }) => void) => { - providerEvents.dataHandler = handler - return () => {} - }), - onReplay: vi.fn(() => () => {}), - onExit: vi.fn(() => () => {}), - listProcesses: vi.fn(async () => []), - attach: vi.fn(), - getDefaultShell: vi.fn(), - getProfiles: vi.fn() - } as never) - let seq = 0 - const runtime = { - setPtyController: vi.fn(), - createPreAllocatedTerminalHandle: vi.fn(() => null), - onPtyData: vi.fn((_id: string, data: string) => { - seq += data.length - return seq - }), - registerPty: vi.fn() - } + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) try { - registerPtyHandlers(mainWindow as never, runtime as never) - const spawnResult = (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp', - launchAgent: 'codex', - terminalColorQueryReplies: { - foreground: '#eeeeee', - background: '#111111' - } - })) as { id: string } - mainWindow.webContents.send.mockClear() + registerPtyHandlers(mainWindow as never) + await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, cwd: '/tmp' }) + const handleRendererLoading = getMainWindowWebContentsListener('did-start-loading') + // Drain the initial dispatcher-ready flush; the baseline is timer-free. + vi.advanceTimersByTime(1) + expect(vi.getTimerCount()).toBe(0) - providerEvents.dataHandler?.({ id: spawnResult.id, data: 'prefix' }) - providerEvents.dataHandler?.({ - id: spawnResult.id, - data: '\x1b]10;?\x1b\\\x1b]11;?\x1b\\ready' - }) - vi.advanceTimersByTime(8) + // A reload closes the gate and arms the ~10s self-heal watchdog on THIS + // registration's closure. + handleRendererLoading() + expect(vi.getTimerCount()).toBe(1) - expect(write).toHaveBeenCalledWith(spawnResult.id, '\x1b]10;rgb:eeee/eeee/eeee\x1b\\') - expect(write).toHaveBeenCalledWith(spawnResult.id, '\x1b]11;rgb:1111/1111/1111\x1b\\') - expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { - id: spawnResult.id, - data: 'prefixready' - }) + // Re-registering handlers (macOS re-activate / new window owns delivery) must + // cancel that armed watchdog via the cross-registration bridge at the top of + // registerPtyHandlers — otherwise the prior closure's timer survives and later + // force-opens a dead window's gate. The re-registration's own dispatcher-ready + // handshake schedules and drains one 0ms flush; nothing else may remain. + registerPtyHandlers(mainWindow as never) + expect(vi.getTimerCount()).toBe(0) + + // And no orphaned ~10s watchdog fires later (removing the bridge cancel turns + // this red: the prior closure's timer would still be pending here). + vi.advanceTimersByTime(20_000) + expect(vi.getTimerCount()).toBe(0) } finally { vi.useRealTimers() } }) - it('sends small PTY redraws immediately after terminal input', async () => { + it('preserves background-origin metadata for repaint output caused by a hidden resize', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -7041,54 +7432,70 @@ describe('registerPtyHandlers', () => { rows: 24, cwd: '/tmp' })) as { id: string } - const writeListener = getPtyWriteListener() + const setRendererPtyVisible = getPtySetRendererPtyVisibleListener() + const resizePty = getPtyResizeListener() + mainWindow.webContents.send.mockClear() - writeListener(mainWindowIpcEvent, { + setRendererPtyVisible(null, { id: spawnResult.id, visible: false }) + resizePty(null, { id: spawnResult.id, cols: 72, rows: 24 }) + setRendererPtyVisible(null, { id: spawnResult.id, visible: true }) + mockProc.emitData('\x1b[2Khidden-resize redraw') + vi.advanceTimersByTime(2) + + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: 'a' + data: '\x1b[2Khidden-resize redraw', + background: true }) - mainWindow.webContents.send.mockClear() - mockProc.emitData('\x1b[20;2Hredraw') + mainWindow.webContents.send.mockClear() + resizePty(null, { id: spawnResult.id, cols: 80, rows: 24 }) + mockProc.emitData('visible repaint') + vi.advanceTimersByTime(2) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: '\x1b[20;2Hredraw' + data: 'visible repaint' }) - vi.advanceTimersByTime(8) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) } finally { vi.useRealTimers() } }) - it('ignores PTY input for unknown sessions', async () => { + it('does not keep hidden resize metadata after visible user input', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) try { registerPtyHandlers(mainWindow as never) - await handlers.get('pty:spawn')!(null, { + const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, cwd: '/tmp' - }) - const writeListener = getPtyWriteListener() + })) as { id: string } + const setRendererPtyVisible = getPtySetRendererPtyVisibleListener() + const resizePty = getPtyResizeListener() + const writePty = getPtyWriteListener() + mainWindow.webContents.send.mockClear() - writeListener(mainWindowIpcEvent, { - id: 'missing-pty', - data: 'a' - }) + setRendererPtyVisible(null, { id: spawnResult.id, visible: false }) + resizePty(null, { id: spawnResult.id, cols: 72, rows: 24 }) + setRendererPtyVisible(null, { id: spawnResult.id, visible: true }) + writePty(mainWindowIpcEvent, { id: spawnResult.id, data: 'x' }) + mockProc.emitData('x') + vi.advanceTimersByTime(2) - expect(mockProc.proc.write).not.toHaveBeenCalled() + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawnResult.id, + data: 'x' + }) } finally { vi.useRealTimers() } }) - it('batches large PTY output even after recent terminal input', async () => { + it('answers agent startup OSC color queries before renderer batching', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -7098,31 +7505,31 @@ describe('registerPtyHandlers', () => { const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, - cwd: '/tmp' + cwd: '/tmp', + launchAgent: 'codex', + terminalColorQueryReplies: { + foreground: '#eeeeee', + background: '#111111' + } })) as { id: string } - const writeListener = getPtyWriteListener() - - writeListener(mainWindowIpcEvent, { - id: spawnResult.id, - data: 'a' - }) + mockProc.proc.write.mockClear() mainWindow.webContents.send.mockClear() - const largeOutput = 'x'.repeat(1025) - mockProc.emitData(largeOutput) + mockProc.emitData('\x1b]10;?\x1b\\\x1b]11;?\x1b\\ready') - expect(mainWindow.webContents.send).not.toHaveBeenCalled() - vi.advanceTimersByTime(8) + expect(mockProc.proc.write).toHaveBeenCalledWith('\x1b]10;rgb:eeee/eeee/eeee\x1b\\') + expect(mockProc.proc.write).toHaveBeenCalledWith('\x1b]11;rgb:1111/1111/1111\x1b\\') + vi.advanceTimersByTime(2) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: largeOutput + data: 'ready' }) } finally { vi.useRealTimers() } }) - it('batches repeated small PTY chunks after the interactive output budget is exhausted', async () => { + it('answers combined agent startup OSC foreground and background color queries', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -7132,34 +7539,31 @@ describe('registerPtyHandlers', () => { const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, - cwd: '/tmp' + cwd: '/tmp', + launchAgent: 'codex', + terminalColorQueryReplies: { + foreground: '#eeeeee', + background: '#111111' + } })) as { id: string } - const writeListener = getPtyWriteListener() - - writeListener(mainWindowIpcEvent, { - id: spawnResult.id, - data: 'a' - }) + mockProc.proc.write.mockClear() mainWindow.webContents.send.mockClear() - const smallChunk = 'x'.repeat(512) - for (let index = 0; index < 65; index++) { - mockProc.emitData(smallChunk) - } + mockProc.emitData('\x1b]10;?;?\x1b\\ready') - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(64) - vi.advanceTimersByTime(8) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(65) - expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(65, 'pty:data', { + expect(mockProc.proc.write).toHaveBeenCalledWith('\x1b]10;rgb:eeee/eeee/eeee\x1b\\') + expect(mockProc.proc.write).toHaveBeenCalledWith('\x1b]11;rgb:1111/1111/1111\x1b\\') + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: smallChunk + data: 'ready' }) } finally { vi.useRealTimers() } }) - it('sends larger ANSI redraws immediately after terminal input', async () => { + it('does not answer ordinary terminal OSC color queries in main', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -7169,31 +7573,29 @@ describe('registerPtyHandlers', () => { const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, - cwd: '/tmp' + cwd: '/tmp', + terminalColorQueryReplies: { + foreground: '#eeeeee', + background: '#111111' + } })) as { id: string } - const writeListener = getPtyWriteListener() - - writeListener(mainWindowIpcEvent, { - id: spawnResult.id, - data: 'a' - }) mainWindow.webContents.send.mockClear() - const redraw = `\x1b[2J\x1b[H${'codex composer redraw '.repeat(80)}` - mockProc.emitData(redraw) + const query = '\x1b]10;?\x1b\\\x1b]11;?\x1b\\' + mockProc.emitData(`${query}ready`) + expect(mockProc.proc.write).not.toHaveBeenCalled() + vi.advanceTimersByTime(2) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: redraw + data: `${query}ready` }) - vi.advanceTimersByTime(8) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) } finally { vi.useRealTimers() } }) - it('batches combined pending output that exceeds the interactive size limit', async () => { + it('does not answer agent OSC color commands that only start like startup queries', async () => { vi.useFakeTimers() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -7203,435 +7605,2352 @@ describe('registerPtyHandlers', () => { const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, - cwd: '/tmp' + cwd: '/tmp', + launchAgent: 'codex', + terminalColorQueryReplies: { + foreground: '#eeeeee', + background: '#111111' + } })) as { id: string } - const writeListener = getPtyWriteListener() - - const pendingOutput = 'x'.repeat(1020) - mockProc.emitData(pendingOutput) - expect(mainWindow.webContents.send).not.toHaveBeenCalled() + mockProc.proc.write.mockClear() + mainWindow.webContents.send.mockClear() - writeListener(mainWindowIpcEvent, { - id: spawnResult.id, - data: 'a' - }) - mockProc.emitData('redraw') + const command = '\x1b]10;?not-a-query\x1b\\' + mockProc.emitData(`${command}ready`) - expect(mainWindow.webContents.send).not.toHaveBeenCalled() - vi.advanceTimersByTime(8) + expect(mockProc.proc.write).not.toHaveBeenCalled() + vi.advanceTimersByTime(2) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, - data: `${pendingOutput}redraw` + data: `${command}ready` }) } finally { vi.useRealTimers() } }) - it('drains large batched PTY output in bounded slices', async () => { + it('answers daemon agent startup OSC color queries before spawn resolves', async () => { vi.useFakeTimers() - const firstProc = createMockProc() - const secondProc = createMockProc() - spawnMock.mockReturnValueOnce(firstProc.proc).mockReturnValueOnce(secondProc.proc) + let dataHandler: ((payload: { id: string; data: string }) => void) | null = null + const write = vi.fn() + const spawn = vi.fn(async (options: { sessionId?: string }) => { + const id = options.sessionId ?? 'daemon-pty' + dataHandler?.({ id, data: '\x1b]10;?\x1b\\\x1b]11;?\x1b\\daemon-ready' }) + return { id } + }) + setLocalPtyProvider({ + spawn, + write, + resize: vi.fn(), + kill: vi.fn(), + shutdown: vi.fn(), + sendSignal: vi.fn(), + getCwd: vi.fn(), + getInitialCwd: vi.fn(), + clearBuffer: vi.fn(), + acknowledgeDataEvent: vi.fn(), + hasChildProcesses: vi.fn(), + getForegroundProcess: vi.fn(), + serialize: vi.fn(), + revive: vi.fn(), + onData: vi.fn((handler: (payload: { id: string; data: string }) => void) => { + dataHandler = handler + return () => {} + }), + onReplay: vi.fn(() => () => {}), + onExit: vi.fn(() => () => {}), + listProcesses: vi.fn(async () => []), + attach: vi.fn(), + getDefaultShell: vi.fn(), + getProfiles: vi.fn() + } as never) try { registerPtyHandlers(mainWindow as never) - const firstSpawn = (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - })) as { id: string } - const secondSpawn = (await handlers.get('pty:spawn')!(null, { + const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, - cwd: '/tmp' + cwd: '/tmp', + launchAgent: 'codex', + terminalColorQueryReplies: { + foreground: '#eeeeee', + background: '#111111' + } })) as { id: string } - mainWindow.webContents.send.mockClear() - const firstChunk = 'x'.repeat(16 * 1024) - const firstRemainder = 'tail' - secondProc.emitData('second-terminal-output') - firstProc.emitData(`${firstChunk}${firstRemainder}`) + expect(write).toHaveBeenCalledWith(spawnResult.id, '\x1b]10;rgb:eeee/eeee/eeee\x1b\\') + expect(write).toHaveBeenCalledWith(spawnResult.id, '\x1b]11;rgb:1111/1111/1111\x1b\\') + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawnResult.id, + data: 'daemon-ready' + }) + } finally { + vi.useRealTimers() + } + }) - vi.advanceTimersByTime(8) + it('drops renderer sequence metadata when an answered OSC query is batched', async () => { + vi.useFakeTimers() + const providerEvents: { + dataHandler?: (payload: { id: string; data: string }) => void + } = {} + const write = vi.fn() + const spawn = vi.fn(async (options: { sessionId?: string }) => ({ + id: options.sessionId ?? 'daemon-pty' + })) + setLocalPtyProvider({ + spawn, + write, + resize: vi.fn(), + kill: vi.fn(), + shutdown: vi.fn(), + sendSignal: vi.fn(), + getCwd: vi.fn(), + getInitialCwd: vi.fn(), + clearBuffer: vi.fn(), + acknowledgeDataEvent: vi.fn(), + hasChildProcesses: vi.fn(), + getForegroundProcess: vi.fn(), + serialize: vi.fn(), + revive: vi.fn(), + onData: vi.fn((handler: (payload: { id: string; data: string }) => void) => { + providerEvents.dataHandler = handler + return () => {} + }), + onReplay: vi.fn(() => () => {}), + onExit: vi.fn(() => () => {}), + listProcesses: vi.fn(async () => []), + attach: vi.fn(), + getDefaultShell: vi.fn(), + getProfiles: vi.fn() + } as never) + let seq = 0 + const runtime = { + setPtyController: vi.fn(), + createPreAllocatedTerminalHandle: vi.fn(() => null), + onPtyData: vi.fn((_id: string, data: string) => { + seq += data.length + return seq + }), + registerPty: vi.fn() + } - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(2) - expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(1, 'pty:data', { - id: secondSpawn.id, - data: 'second-terminal-output' - }) - expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(2, 'pty:data', { - id: firstSpawn.id, - data: firstChunk - }) + try { + registerPtyHandlers(mainWindow as never, runtime as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp', + launchAgent: 'codex', + terminalColorQueryReplies: { + foreground: '#eeeeee', + background: '#111111' + } + })) as { id: string } + mainWindow.webContents.send.mockClear() - vi.advanceTimersByTime(1) + providerEvents.dataHandler?.({ id: spawnResult.id, data: 'prefix' }) + providerEvents.dataHandler?.({ + id: spawnResult.id, + data: '\x1b]10;?\x1b\\\x1b]11;?\x1b\\ready' + }) + vi.advanceTimersByTime(2) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(3) - expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(3, 'pty:data', { - id: firstSpawn.id, - data: firstRemainder + expect(write).toHaveBeenCalledWith(spawnResult.id, '\x1b]10;rgb:eeee/eeee/eeee\x1b\\') + expect(write).toHaveBeenCalledWith(spawnResult.id, '\x1b]11;rgb:1111/1111/1111\x1b\\') + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawnResult.id, + data: 'prefixready' }) } finally { vi.useRealTimers() } }) - it('waits for renderer ACKs before sending more output for a saturated PTY', async () => { + it('sends small PTY redraws immediately after terminal input', async () => { vi.useFakeTimers() - const firstProc = createMockProc() - const secondProc = createMockProc() - spawnMock.mockReturnValueOnce(firstProc.proc).mockReturnValueOnce(secondProc.proc) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) try { registerPtyHandlers(mainWindow as never) - const firstSpawn = (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - })) as { id: string } - const secondSpawn = (await handlers.get('pty:spawn')!(null, { + const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, cwd: '/tmp' })) as { id: string } - const ackData = getPtyAckDataListener() - mainWindow.webContents.send.mockClear() - - firstProc.emitData('x'.repeat(600 * 1024)) - vi.advanceTimersByTime(8) - for (let index = 0; index < 31; index++) { - vi.advanceTimersByTime(1) - } - - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(32) - vi.advanceTimersByTime(1) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(32) - expect(vi.getTimerCount()).toBe(0) - expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ - pendingPtyCount: 1, - pendingChars: 88 * 1024, - maxPendingCharsByPty: 88 * 1024, - rendererInFlightPtyCount: 1, - rendererInFlightChars: 512 * 1024, - maxRendererInFlightCharsByPty: 512 * 1024, - flushScheduled: false, - peakPendingChars: 600 * 1024, - peakMaxPendingCharsByPty: 600 * 1024, - peakRendererInFlightChars: 512 * 1024, - peakMaxRendererInFlightCharsByPty: 512 * 1024, - ackGatedFlushSkipCount: 1 - }) - - secondProc.emitData('second-terminal-output') - vi.advanceTimersByTime(8) - - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(33) - expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(33, 'pty:data', { - id: secondSpawn.id, - data: 'second-terminal-output' - }) - - ackData(null, { id: firstSpawn.id, charCount: 16 * 1024 }) - vi.advanceTimersByTime(1) + const writeListener = getPtyWriteListener() - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(34) - expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(34, 'pty:data', { - id: firstSpawn.id, - data: 'x'.repeat(16 * 1024) - }) - expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ - pendingPtyCount: 1, - pendingChars: 72 * 1024, - rendererInFlightChars: 512 * 1024 + 'second-terminal-output'.length, - peakPendingChars: 600 * 1024, - peakRendererInFlightChars: 512 * 1024 + 'second-terminal-output'.length + writeListener(mainWindowIpcEvent, { + id: spawnResult.id, + data: 'a' }) + mainWindow.webContents.send.mockClear() - resetPtyRendererDeliveryDebug() + mockProc.emitData('\x1b[20;2Hredraw') - expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ - pendingPtyCount: 1, - pendingChars: 72 * 1024, - rendererInFlightChars: 512 * 1024 + 'second-terminal-output'.length, - peakPendingChars: 72 * 1024, - peakRendererInFlightChars: 512 * 1024 + 'second-terminal-output'.length, - ackGatedFlushSkipCount: 0 + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawnResult.id, + data: '\x1b[20;2Hredraw' }) + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) } finally { vi.useRealTimers() } }) - it('forwards only actually in-flight bytes to provider ACK backpressure', async () => { + it('ignores PTY input for unknown sessions', async () => { vi.useFakeTimers() - const acknowledgeDataEvent = vi.fn() const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) try { - setLocalPtyProvider({ - spawn: vi.fn(async () => ({ id: 'remote-like-pty' })), - write: vi.fn(), - resize: vi.fn(), - shutdown: vi.fn(), - sendSignal: vi.fn(), - getCwd: vi.fn(), - getInitialCwd: vi.fn(), - clearBuffer: vi.fn(), - acknowledgeDataEvent, - hasChildProcesses: vi.fn(), - getForegroundProcess: vi.fn(), - serialize: vi.fn(), - revive: vi.fn(), - onData: vi.fn((callback) => { - mockProc.proc.onData((data: string) => callback({ id: 'remote-like-pty', data })) - return () => {} - }), - onReplay: vi.fn(() => () => {}), - onExit: vi.fn(() => () => {}), - listProcesses: vi.fn(async () => []), - attach: vi.fn(), - getDefaultShell: vi.fn(), - getProfiles: vi.fn() - } as never) registerPtyHandlers(mainWindow as never) - const ackData = getPtyAckDataListener() - mainWindow.webContents.send.mockClear() - - mockProc.emitData('remote-output') - vi.advanceTimersByTime(8) - - expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { - id: 'remote-like-pty', - data: 'remote-output' + await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' }) + const writeListener = getPtyWriteListener() - // Why: stale or duplicated renderer ACKs must not over-credit SSH/relay - // flow control beyond the bytes main actually sent to the renderer. - ackData(null, { id: 'remote-like-pty', charCount: 1024 }) - ackData(null, { id: 'remote-like-pty', charCount: 1024 }) + writeListener(mainWindowIpcEvent, { + id: 'missing-pty', + data: 'a' + }) - expect(acknowledgeDataEvent).toHaveBeenNthCalledWith( - 1, - 'remote-like-pty', - 'remote-output'.length - ) - expect(acknowledgeDataEvent).toHaveBeenNthCalledWith(2, 'remote-like-pty', 0) + expect(mockProc.proc.write).not.toHaveBeenCalled() } finally { vi.useRealTimers() } }) - it('reserves a bounded renderer lane for interactive output when bulk output is saturated', async () => { + it('batches large PTY output even after recent terminal input', async () => { vi.useFakeTimers() - const bulkProcs = Array.from({ length: 16 }, () => createMockProc()) - const interactiveProc = createMockProc() - for (const proc of [...bulkProcs, interactiveProc]) { - spawnMock.mockReturnValueOnce(proc.proc) - } + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) try { registerPtyHandlers(mainWindow as never) - for (const _proc of bulkProcs) { - await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - }) - } - const interactiveSpawn = (await handlers.get('pty:spawn')!(null, { + const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, cwd: '/tmp' })) as { id: string } const writeListener = getPtyWriteListener() - mainWindow.webContents.send.mockClear() - - for (const proc of bulkProcs) { - proc.emitData('x'.repeat(600 * 1024)) - } - vi.advanceTimersByTime(8) - for (let index = 0; index < 400; index++) { - vi.advanceTimersByTime(1) - } - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(512) - expect(vi.getTimerCount()).toBe(0) writeListener(mainWindowIpcEvent, { - id: interactiveSpawn.id, + id: spawnResult.id, data: 'a' }) - interactiveProc.emitData('\x1b[20;2Hredraw') + mainWindow.webContents.send.mockClear() - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(513) - expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(513, 'pty:data', { - id: interactiveSpawn.id, - data: '\x1b[20;2Hredraw' + const largeOutput = 'x'.repeat(1025) + mockProc.emitData(largeOutput) + + expect(mainWindow.webContents.send).not.toHaveBeenCalled() + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawnResult.id, + data: largeOutput }) + } finally { + vi.useRealTimers() + } + }) - const reservePrefix = '\x1b[20;2H' - const reserveChunk = `${reservePrefix}${'r'.repeat(16 * 1024 - reservePrefix.length)}` - for (let index = 0; index < 16; index++) { - writeListener(mainWindowIpcEvent, { - id: interactiveSpawn.id, - data: 'a' - }) - interactiveProc.emitData(reserveChunk) + it('batches repeated small PTY chunks after the interactive output budget is exhausted', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const writeListener = getPtyWriteListener() + + writeListener(mainWindowIpcEvent, { + id: spawnResult.id, + data: 'a' + }) + mainWindow.webContents.send.mockClear() + + const smallChunk = 'x'.repeat(512) + for (let index = 0; index < 65; index++) { + mockProc.emitData(smallChunk) } - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(529) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(64) + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(65) + expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(65, 'pty:data', { + id: spawnResult.id, + data: smallChunk + }) + } finally { + vi.useRealTimers() + } + }) + + it('sends larger ANSI redraws immediately after terminal input', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const writeListener = getPtyWriteListener() writeListener(mainWindowIpcEvent, { - id: interactiveSpawn.id, + id: spawnResult.id, data: 'a' }) - interactiveProc.emitData(reserveChunk) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(529) + mainWindow.webContents.send.mockClear() + + const redraw = `\x1b[2J\x1b[H${'codex composer redraw '.repeat(80)}` + mockProc.emitData(redraw) + + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawnResult.id, + data: redraw + }) + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) } finally { vi.useRealTimers() } }) - it('caps total renderer in-flight output across many PTYs', async () => { + it('batches combined pending output that exceeds the interactive size limit', async () => { vi.useFakeTimers() - const procs = Array.from({ length: 17 }, () => createMockProc()) - for (const proc of procs) { - spawnMock.mockReturnValueOnce(proc.proc) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const writeListener = getPtyWriteListener() + + const pendingOutput = 'x'.repeat(1020) + mockProc.emitData(pendingOutput) + expect(mainWindow.webContents.send).not.toHaveBeenCalled() + + writeListener(mainWindowIpcEvent, { + id: spawnResult.id, + data: 'a' + }) + mockProc.emitData('redraw') + + expect(mainWindow.webContents.send).not.toHaveBeenCalled() + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawnResult.id, + data: `${pendingOutput}redraw` + }) + } finally { + vi.useRealTimers() } + }) + + it('drains large batched PTY output in bounded slices', async () => { + vi.useFakeTimers() + const firstProc = createMockProc() + const secondProc = createMockProc() + spawnMock.mockReturnValueOnce(firstProc.proc).mockReturnValueOnce(secondProc.proc) try { registerPtyHandlers(mainWindow as never) - const spawns: { id: string }[] = [] - for (const _proc of procs) { - spawns.push( - (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - })) as { id: string } + const firstSpawn = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const secondSpawn = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + mainWindow.webContents.send.mockClear() + + const firstChunk = 'x'.repeat(16 * 1024) + const firstRemainder = 'tail' + secondProc.emitData('second-terminal-output') + firstProc.emitData(`${firstChunk}${firstRemainder}`) + + vi.advanceTimersByTime(2) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(2) + expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(1, 'pty:data', { + id: secondSpawn.id, + data: 'second-terminal-output' + }) + expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(2, 'pty:data', { + id: firstSpawn.id, + data: firstChunk + }) + + vi.advanceTimersByTime(1) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(3) + expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(3, 'pty:data', { + id: firstSpawn.id, + data: firstRemainder + }) + } finally { + vi.useRealTimers() + } + }) + + it('waits for renderer ACKs before sending more output for a saturated PTY', async () => { + vi.useFakeTimers() + const firstProc = createMockProc() + const secondProc = createMockProc() + spawnMock.mockReturnValueOnce(firstProc.proc).mockReturnValueOnce(secondProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const firstSpawn = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const secondSpawn = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const ackData = getPtyAckDataListener() + mainWindow.webContents.send.mockClear() + + firstProc.emitData('x'.repeat(600 * 1024)) + vi.advanceTimersByTime(2) + for (let index = 0; index < 31; index++) { + vi.advanceTimersByTime(1) + } + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(32) + vi.advanceTimersByTime(1) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(32) + expect(vi.getTimerCount()).toBe(0) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingPtyCount: 1, + pendingChars: 88 * 1024, + maxPendingCharsByPty: 88 * 1024, + rendererInFlightPtyCount: 1, + rendererInFlightChars: 512 * 1024, + maxRendererInFlightCharsByPty: 512 * 1024, + flushScheduled: false, + peakPendingChars: 600 * 1024, + peakMaxPendingCharsByPty: 600 * 1024, + peakRendererInFlightChars: 512 * 1024, + peakMaxRendererInFlightCharsByPty: 512 * 1024, + ackGatedFlushSkipCount: 1 + }) + + secondProc.emitData('second-terminal-output') + vi.advanceTimersByTime(2) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(33) + expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(33, 'pty:data', { + id: secondSpawn.id, + data: 'second-terminal-output' + }) + + ackData(null, { id: firstSpawn.id, charCount: 16 * 1024 }) + vi.advanceTimersByTime(1) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(34) + expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(34, 'pty:data', { + id: firstSpawn.id, + data: 'x'.repeat(16 * 1024) + }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingPtyCount: 1, + pendingChars: 72 * 1024, + rendererInFlightChars: 512 * 1024 + 'second-terminal-output'.length, + peakPendingChars: 600 * 1024, + peakRendererInFlightChars: 512 * 1024 + 'second-terminal-output'.length + }) + + resetPtyRendererDeliveryDebug() + + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingPtyCount: 1, + pendingChars: 72 * 1024, + rendererInFlightChars: 512 * 1024 + 'second-terminal-output'.length, + peakPendingChars: 72 * 1024, + peakRendererInFlightChars: 512 * 1024 + 'second-terminal-output'.length, + ackGatedFlushSkipCount: 0 + }) + } finally { + vi.useRealTimers() + } + }) + + it('caps per-PTY pending output while the renderer is starved and heals via a droppedOutput sentinel', async () => { + vi.useFakeTimers() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawn = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const ackData = getPtyAckDataListener() + mainWindow.webContents.send.mockClear() + + // Saturate the renderer in-flight window (512 KB) with no ACKs — the + // frozen/starved-renderer shape from the field reports. + mockProc.emitData('x'.repeat(600 * 1024)) + vi.advanceTimersByTime(2) + for (let index = 0; index < 32; index++) { + vi.advanceTimersByTime(1) + } + + // Keep flooding well past the 2 MB per-PTY pending cap. Main must not + // buffer this unboundedly (previously: unbounded string concat). + mockProc.emitData('y'.repeat(3 * 1024 * 1024)) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingPtyCount: 1, + pendingChars: 0 + }) + + // Later output while dropped must stay O(1), not start re-accumulating. + mockProc.emitData('z'.repeat(64 * 1024)) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingPtyCount: 1, + pendingChars: 0 + }) + + // Renderer recovers and ACKs: the flush must deliver the droppedOutput + // sentinel so the pane repaints from the main-owned snapshot. + mainWindow.webContents.send.mockClear() + ackData(null, { id: spawn.id, charCount: 512 * 1024 }) + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawn.id, + data: '', + droppedOutput: true + }) + + // Fresh output after the sentinel flows normally again. + mainWindow.webContents.send.mockClear() + mockProc.emitData('back to normal') + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawn.id, + data: 'back to normal' + }) + } finally { + errorSpy.mockRestore() + vi.useRealTimers() + } + }) + + it('carves reply-eliciting queries out of a pending-cap bulk drop so probes survive', async () => { + vi.useFakeTimers() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawn = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const ackData = getPtyAckDataListener() + mainWindow.webContents.send.mockClear() + + // Saturate the in-flight window so everything after buffers in pendingData. + mockProc.emitData('x'.repeat(600 * 1024)) + vi.advanceTimersByTime(2) + for (let index = 0; index < 32; index++) { + vi.advanceTimersByTime(1) + } + + // Flood past the pending cap WITH an embedded DSR probe — the program + // that wrote it blocks on the reply (the bench DSR timeout). + mockProc.emitData(`${'y'.repeat(2 * 1024 * 1024)}\x1b[6n${'y'.repeat(1024 * 1024)}`) + // While latched, a later probe must also be carved out (bounded). + mockProc.emitData(`${'z'.repeat(32 * 1024)}\x1b[0c${'z'.repeat(32 * 1024)}`) + + mainWindow.webContents.send.mockClear() + ackData(null, { id: spawn.id, charCount: 512 * 1024 }) + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawn.id, + data: '\x1b[6n\x1b[0c', + droppedOutput: true + }) + } finally { + errorSpy.mockRestore() + vi.useRealTimers() + } + }) + + it('scales the pending-output cap with the scrollback setting', async () => { + vi.useFakeTimers() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + // 50k-row scrollback ⇒ 6 MB pending cap instead of the 2 MB floor. + registerPtyHandlers(mainWindow as never, undefined, undefined, (() => ({ + terminalScrollbackRows: 50_000 + })) as never) + await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, cwd: '/tmp' }) + mainWindow.webContents.send.mockClear() + + // Saturate the in-flight window with no ACKs, then buffer 3 MB — over + // the floor, under the scaled cap: it must be retained, not dropped. + mockProc.emitData('x'.repeat(600 * 1024)) + vi.advanceTimersByTime(2) + for (let index = 0; index < 32; index++) { + vi.advanceTimersByTime(1) + } + mockProc.emitData('y'.repeat(3 * 1024 * 1024)) + expect(getPtyRendererDeliveryDebugSnapshot().pendingChars).toBeGreaterThan(3 * 1024 * 1024) + + // The scaled cap still bounds a runaway flood. + mockProc.emitData('z'.repeat(4 * 1024 * 1024)) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingPtyCount: 1, + pendingChars: 0 + }) + } finally { + errorSpy.mockRestore() + vi.useRealTimers() + } + }) + + it('pauses the producer at the pending high watermark and resumes after drain', async () => { + vi.useFakeTimers() + try { + const provider = installObservableDaemonTestProvider() + registerPtyHandlers(mainWindow as never) + mainWindow.webContents.send.mockClear() + + // Flood in 64KB chunks like a `yes`-style producer that honors pause — + // node-pty pause() stops the fd read, so a real producer stops emitting. + const chunk = 'x'.repeat(64 * 1024) + let chunks = 0 + while (provider.pauseProducer.mock.calls.length === 0 && chunks < 100) { + provider.emitData('flood-pty', chunk) + chunks++ + } + + // Pause fires exactly once, on the first chunk past the 256KB high + // watermark (the 5th 64KB chunk), not once per chunk. + expect(provider.pauseProducer).toHaveBeenCalledTimes(1) + expect(provider.pauseProducer).toHaveBeenCalledWith('flood-pty') + expect(chunks).toBe(5) + // Bounded: main buffered at most HIGH + one chunk while paused. + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingPtyCount: 1, + pendingChars: 320 * 1024, + peakPendingChars: 320 * 1024 + }) + + // Drain to the renderer. Resume must fire exactly once — when pending + // drops below the 32KB low watermark — with no pause/resume flapping + // while pending crosses the 32-256KB hysteresis band. + vi.runAllTimers() + expect(provider.resumeProducer).toHaveBeenCalledTimes(1) + expect(provider.resumeProducer).toHaveBeenCalledWith('flood-pty') + expect(provider.pauseProducer).toHaveBeenCalledTimes(1) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ pendingChars: 0 }) + } finally { + vi.useRealTimers() + } + }) + + it('resumes a paused producer when the PTY exits before draining', async () => { + vi.useFakeTimers() + try { + const provider = installObservableDaemonTestProvider() + registerPtyHandlers(mainWindow as never) + mainWindow.webContents.send.mockClear() + + provider.emitData('flood-pty', 'x'.repeat(320 * 1024)) + expect(provider.pauseProducer).toHaveBeenCalledTimes(1) + + // Exit while pending is still above the low watermark: the exit path + // must release the pause instead of leaving a stale mark behind. + provider.emitExit('flood-pty', 0) + expect(provider.resumeProducer).toHaveBeenCalledTimes(1) + expect(provider.resumeProducer).toHaveBeenCalledWith('flood-pty') + } finally { + vi.useRealTimers() + } + }) + + const DELIVERY_RESYNC_UNANSWERED_WARNING = + '[pty] delivery resync probe unanswered — renderer IPC unresponsive' + + function countResyncUnansweredWarnings(warnSpy: { mock: { calls: unknown[][] } }): number { + return warnSpy.mock.calls.filter((call) => call[0] === DELIVERY_RESYNC_UNANSWERED_WARNING) + .length + } + + function getPtyDataSendCalls(): unknown[][] { + return mainWindow.webContents.send.mock.calls.filter( + (call: unknown[]) => call[0] === 'pty:data' + ) + } + + function getDeliveryResyncProbeCalls(): unknown[][] { + return mainWindow.webContents.send.mock.calls.filter( + (call: unknown[]) => call[0] === 'pty:requestDeliveryResync' + ) + } + + function getDeliveryResyncResponseListener(): ( + event: unknown, + args: { requestId: number; processedCharsByPty: Record } + ) => void { + const responseCall = onMock.mock.calls.find( + (call: unknown[]) => call[0] === 'pty:deliveryResyncResponse' + ) + if (!responseCall) { + throw new Error('missing pty:deliveryResyncResponse listener') + } + return responseCall[1] as ( + event: unknown, + args: { requestId: number; processedCharsByPty: Record } + ) => void + } + + /** Saturates one PTY to its 512 KiB in-flight cap so delivery is fully + * gated for that PTY. Leaves 88 KiB pending and no timers scheduled. */ + async function spawnAndSaturateRendererDeliveryGate( + mockProc: ReturnType + ): Promise<{ id: string }> { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + mainWindow.webContents.send.mockClear() + mockProc.emitData('x'.repeat(600 * 1024)) + vi.advanceTimersByTime(8) + for (let index = 0; index < 32; index++) { + vi.advanceTimersByTime(1) + } + return spawnResult + } + + it('self-heals lost ACKs when a later cumulative ACK arrives', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + const spawnResult = await spawnAndSaturateRendererDeliveryGate(mockProc) + expect(getPtyDataSendCalls()).toHaveLength(32) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 512 * 1024, + rendererInFlightPtyCount: 1 + }) + + // Every per-chunk ACK was lost, but the next ACK carries the renderer's + // full cumulative total — the debt clears without any timer or reset. + const ackData = getPtyAckDataListener() + ackData(null, { id: spawnResult.id, processedChars: 512 * 1024 }) + + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 0, + rendererInFlightPtyCount: 0 + }) + + vi.runOnlyPendingTimers() + expect(getPtyDataSendCalls()).toHaveLength(33) + } finally { + vi.useRealTimers() + } + }) + + it('applies cumulative ACKs idempotently and ignores stale reordered totals', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + const spawnResult = await spawnAndSaturateRendererDeliveryGate(mockProc) + const ackData = getPtyAckDataListener() + + ackData(null, { id: spawnResult.id, processedChars: 256 * 1024 }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 256 * 1024, + maxRendererInFlightCharsByPty: 256 * 1024 + }) + + // Replayed duplicate credits nothing further. + ackData(null, { id: spawnResult.id, processedChars: 256 * 1024 }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 256 * 1024 + }) + + // A stale reordered total can never move accounting backwards. + ackData(null, { id: spawnResult.id, processedChars: 128 * 1024 }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 256 * 1024 + }) + } finally { + vi.useRealTimers() + } + }) + + it('tolerates mixed legacy delta and cumulative ACK payloads', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + const spawnResult = await spawnAndSaturateRendererDeliveryGate(mockProc) + const ackData = getPtyAckDataListener() + + // Legacy delta shape (no processedChars) still credits per chunk. + ackData(null, { id: spawnResult.id, charCount: 16 * 1024 }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 496 * 1024 + }) + + // A cumulative total then supersedes without double-crediting the delta. + ackData(null, { id: spawnResult.id, processedChars: 512 * 1024 }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 0, + rendererInFlightPtyCount: 0 + }) + } finally { + vi.useRealTimers() + } + }) + + it('forwards only newly acknowledged cumulative bytes to provider ACK backpressure', async () => { + vi.useFakeTimers() + const acknowledgeDataEvent = vi.fn() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + setLocalPtyProvider({ + spawn: vi.fn(async () => ({ id: 'cumulative-pty' })), + write: vi.fn(), + resize: vi.fn(), + shutdown: vi.fn(), + sendSignal: vi.fn(), + getCwd: vi.fn(), + getInitialCwd: vi.fn(), + clearBuffer: vi.fn(), + acknowledgeDataEvent, + hasChildProcesses: vi.fn(), + getForegroundProcess: vi.fn(), + serialize: vi.fn(), + revive: vi.fn(), + onData: vi.fn((callback) => { + mockProc.proc.onData((data: string) => callback({ id: 'cumulative-pty', data })) + return () => {} + }), + onReplay: vi.fn(() => () => {}), + onExit: vi.fn(() => () => {}), + listProcesses: vi.fn(async () => []), + attach: vi.fn(), + getDefaultShell: vi.fn(), + getProfiles: vi.fn() + } as never) + registerPtyHandlers(mainWindow as never) + const ackData = getPtyAckDataListener() + mainWindow.webContents.send.mockClear() + + mockProc.emitData('remote-output') + vi.advanceTimersByTime(8) + + // Why: cumulative totals are clamped to what main actually sent, and a + // replayed total must credit SSH/relay flow control with zero, not + // duplicate bytes. + ackData(null, { id: 'cumulative-pty', processedChars: 1024 }) + ackData(null, { id: 'cumulative-pty', processedChars: 1024 }) + + expect(acknowledgeDataEvent).toHaveBeenNthCalledWith( + 1, + 'cumulative-pty', + 'remote-output'.length + ) + expect(acknowledgeDataEvent).toHaveBeenNthCalledWith(2, 'cumulative-pty', 0) + } finally { + vi.useRealTimers() + } + }) + + it('probes for a delivery resync when data arrives for a fully gated PTY and reconciles on reply', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + const spawnResult = await spawnAndSaturateRendererDeliveryGate(mockProc) + + mockProc.emitData('stuck-output') + expect(getDeliveryResyncProbeCalls()).toHaveLength(1) + const probePayload = getDeliveryResyncProbeCalls()[0]![1] as { requestId: number } + + // Only one probe may be outstanding at a time. + mockProc.emitData('still-stuck') + expect(getDeliveryResyncProbeCalls()).toHaveLength(1) + + const respondDeliveryResync = getDeliveryResyncResponseListener() + respondDeliveryResync(null, { + requestId: probePayload.requestId, + processedCharsByPty: { [spawnResult.id]: 512 * 1024 } + }) + + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 0, + rendererInFlightPtyCount: 0 + }) + + // The reconciled gate lets the held pendingData flush again (one 2ms + // batch window = one 16KB slice). + vi.advanceTimersByTime(2) + expect(getPtyDataSendCalls()).toHaveLength(33) + } finally { + vi.useRealTimers() + } + }) + + it('ignores resync replies with stale request ids', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + const spawnResult = await spawnAndSaturateRendererDeliveryGate(mockProc) + mockProc.emitData('stuck-output') + const probePayload = getDeliveryResyncProbeCalls()[0]![1] as { requestId: number } + + const respondDeliveryResync = getDeliveryResyncResponseListener() + respondDeliveryResync(null, { + requestId: probePayload.requestId + 41, + processedCharsByPty: { [spawnResult.id]: 512 * 1024 } + }) + + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 512 * 1024 + }) + } finally { + vi.useRealTimers() + } + }) + + it('clears an unanswered resync probe, warns once per silent streak, and never mutates counters', async () => { + vi.useFakeTimers() + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + await spawnAndSaturateRendererDeliveryGate(mockProc) + + mockProc.emitData('stuck-output') + expect(getDeliveryResyncProbeCalls()).toHaveLength(1) + + vi.advanceTimersByTime(4_999) + expect(countResyncUnansweredWarnings(warnSpy)).toBe(0) + + vi.advanceTimersByTime(1) + expect(countResyncUnansweredWarnings(warnSpy)).toBe(1) + expect(warnSpy).toHaveBeenCalledWith( + DELIVERY_RESYNC_UNANSWERED_WARNING, + expect.objectContaining({ + rendererInFlightChars: 512 * 1024, + pendingPtyCount: 1 + }) + ) + // No blind reset: counters and pending output are untouched. + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 512 * 1024, + pendingChars: 88 * 1024 + 'stuck-output'.length + }) + expect(getPtyDataSendCalls()).toHaveLength(32) + + // The cleared flag lets the next gated arrival probe again, but a + // still-silent renderer does not spam a second warn. + mockProc.emitData('still-stuck') + expect(getDeliveryResyncProbeCalls()).toHaveLength(2) + vi.advanceTimersByTime(5_000) + expect(countResyncUnansweredWarnings(warnSpy)).toBe(1) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 512 * 1024 + }) + } finally { + warnSpy.mockRestore() + vi.useRealTimers() + } + }) + + it('clears resync probe state when the window is destroyed', async () => { + vi.useFakeTimers() + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + let destroyed = false + const destroyableWindow = { + isDestroyed: () => destroyed, + isFocused: () => true, + isVisible: () => true, + isMinimized: () => false, + webContents: { on: vi.fn(), send: vi.fn(), removeListener: vi.fn() } + } + + try { + registerPtyHandlers(destroyableWindow as never) + await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, cwd: '/tmp' }) + destroyableWindow.webContents.send.mockClear() + mockProc.emitData('x'.repeat(600 * 1024)) + vi.advanceTimersByTime(8) + for (let index = 0; index < 32; index++) { + vi.advanceTimersByTime(1) + } + mockProc.emitData('stuck-output') + // The outstanding probe's hygiene timeout is the only remaining timer; + // the dispatcher-ready handshake already drained the pending flush. + expect(vi.getTimerCount()).toBe(1) + + destroyed = true + mockProc.emitData('post-destroy output') + + expect(vi.getTimerCount()).toBe(0) + vi.advanceTimersByTime(60_000) + expect(countResyncUnansweredWarnings(warnSpy)).toBe(0) + } finally { + warnSpy.mockRestore() + vi.useRealTimers() + } + }) + + // ── Renderer-initiated delivery health/heal (pty:reportRendererDeliveryState) ── + // Field wedge repro (v1.4.121-rc.0 snapshot): push delivery dead, invoke + // alive. The solicited-resync probe above rides push and can never be + // answered in that state; this invoke lane is the recovery that can. + + function reportRendererDeliveryState(args: { + receivedCharsByPty: Record + processedCharsByPty: Record + heal?: boolean + rendererPtyDataListenerCount?: number | null + }): { + inFlightTotalChars: number + inFlightPtyCount: number + msSinceLastAck: number | null + writtenOff?: { id: string; markerSeq?: number; writtenOffChars: number }[] + } { + const handler = handlers.get('pty:reportRendererDeliveryState') + if (!handler) { + throw new Error('missing pty:reportRendererDeliveryState handler') + } + return handler(null, args) as ReturnType + } + + it('reports delivery health over invoke without mutating any delivery state', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + await spawnAndSaturateRendererDeliveryGate(mockProc) + + // The field wedge in miniature: renderer received nothing, no ACK ever. + const health = reportRendererDeliveryState({ + receivedCharsByPty: {}, + processedCharsByPty: {} + }) + + expect(health).toMatchObject({ + inFlightTotalChars: 512 * 1024, + inFlightPtyCount: 1, + msSinceLastAck: null + }) + expect(health.writtenOff).toBeUndefined() + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 512 * 1024, + pendingChars: 88 * 1024 + }) + } finally { + vi.useRealTimers() + } + }) + + it('merges cumulative processed totals from a health report as a repair lane', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + const spawnResult = await spawnAndSaturateRendererDeliveryGate(mockProc) + + // Lost-ACK variant: renderer processed everything; only the ACK + // messages vanished. A plain report (no heal) must drain the debt. + const health = reportRendererDeliveryState({ + receivedCharsByPty: { [spawnResult.id]: 512 * 1024 }, + processedCharsByPty: { [spawnResult.id]: 512 * 1024 } + }) + + expect(health).toMatchObject({ inFlightTotalChars: 0, inFlightPtyCount: 0 }) + expect(health.writtenOff).toBeUndefined() + // Fully reopened gate drains one 16K slice per batcher tick (0/1/2 ms). + vi.advanceTimersByTime(2) + expect(getPtyDataSendCalls()).toHaveLength(35) + } finally { + vi.useRealTimers() + } + }) + + it('heals a dead push channel: writes off unreceived bytes and returns restore markers', async () => { + vi.useFakeTimers() + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + const spawnResult = await spawnAndSaturateRendererDeliveryGate(mockProc) + + const healed = reportRendererDeliveryState({ + receivedCharsByPty: {}, + processedCharsByPty: {}, + heal: true, + rendererPtyDataListenerCount: 1 + }) + + // The 512 KiB the renderer provably never received is written off; the + // 88 KiB still pending is dropped because the snapshot restore covers + // everything at or before the marker (hidden-drop parity). + expect(healed.writtenOff).toEqual([{ id: spawnResult.id, writtenOffChars: 512 * 1024 }]) + expect(healed).toMatchObject({ inFlightTotalChars: 0, inFlightPtyCount: 0 }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 0, + pendingChars: 0, + pendingDroppedChars: 88 * 1024 + }) + expect(warnSpy).toHaveBeenCalledWith( + '[pty] delivery heal: wrote off renderer-bound bytes lost in push channel', + expect.objectContaining({ rendererPtyDataListenerCount: 1 }) + ) + + // Delivery is unwedged: fresh output flows to the renderer again. + mockProc.emitData('after-heal') + vi.advanceTimersByTime(2) + expect(getPtyDataSendCalls()).toHaveLength(33) + } finally { + warnSpy.mockRestore() + vi.useRealTimers() + } + }) + + it('never writes off bytes the renderer received but has not parsed yet', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + const spawnResult = await spawnAndSaturateRendererDeliveryGate(mockProc) + + // Parse backpressure, not a wedge: every byte arrived, ACK credit is + // deferred to the scheduler consume point and will still repay this. + const health = reportRendererDeliveryState({ + receivedCharsByPty: { [spawnResult.id]: 512 * 1024 }, + processedCharsByPty: {}, + heal: true, + rendererPtyDataListenerCount: 1 + }) + + expect(health.writtenOff).toBeUndefined() + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 512 * 1024, + pendingChars: 88 * 1024 + }) + } finally { + vi.useRealTimers() + } + }) + + it('refuses a heal while main has seen a recent ACK', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + const spawnResult = await spawnAndSaturateRendererDeliveryGate(mockProc) + const ackData = getPtyAckDataListener() + ackData(null, { id: spawnResult.id, processedChars: 16 * 1024 }) + + // Some pty still round-trips ACKs — whatever the renderer thinks, the + // channel is not dead, so a heal request must not destroy accounting. + const blocked = reportRendererDeliveryState({ + receivedCharsByPty: {}, + processedCharsByPty: {}, + heal: true + }) + expect(blocked.writtenOff).toBeUndefined() + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightChars: 496 * 1024 + }) + + // Once main-side ACK silence crosses the floor, the same heal proceeds. + // (The ACK freed a 16K window slot, so one more pending slice shipped + // during the advance — the write-off covers 512K un-received again.) + vi.advanceTimersByTime(10_000) + const healed = reportRendererDeliveryState({ + receivedCharsByPty: {}, + processedCharsByPty: {}, + heal: true + }) + expect(healed.writtenOff).toEqual([{ id: spawnResult.id, writtenOffChars: 512 * 1024 }]) + } finally { + vi.useRealTimers() + } + }) + + it('zeroes renderer in-flight delivery counters when the renderer lifecycle resets', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + await spawnAndSaturateRendererDeliveryGate(mockProc) + const handleRendererLoading = getMainWindowWebContentsListener('did-start-loading') + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightPtyCount: 1, + rendererInFlightChars: 512 * 1024 + }) + + handleRendererLoading() + + // Why: reload kills the renderer dispatcher that would have ACKed, so + // keeping the counters would gate PTYs in the fresh renderer forever. + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + rendererInFlightPtyCount: 0, + rendererInFlightChars: 0 + }) + // Main now holds sends until the replacement page confirms its dispatcher + // is installed; the lifecycle reset arms a bounded handshake watchdog. + expect(vi.getTimerCount()).toBe(1) + + mockProc.emitData('after-reload') + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(32) + + getPtyRendererDispatcherReadyListener()() + // One 2ms batch window releases the fresh page's held output. + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(33) + } finally { + vi.useRealTimers() + } + }) + + it('forwards only actually in-flight bytes to provider ACK backpressure', async () => { + vi.useFakeTimers() + const acknowledgeDataEvent = vi.fn() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + setLocalPtyProvider({ + spawn: vi.fn(async () => ({ id: 'remote-like-pty' })), + write: vi.fn(), + resize: vi.fn(), + shutdown: vi.fn(), + sendSignal: vi.fn(), + getCwd: vi.fn(), + getInitialCwd: vi.fn(), + clearBuffer: vi.fn(), + acknowledgeDataEvent, + hasChildProcesses: vi.fn(), + getForegroundProcess: vi.fn(), + serialize: vi.fn(), + revive: vi.fn(), + onData: vi.fn((callback) => { + mockProc.proc.onData((data: string) => callback({ id: 'remote-like-pty', data })) + return () => {} + }), + onReplay: vi.fn(() => () => {}), + onExit: vi.fn(() => () => {}), + listProcesses: vi.fn(async () => []), + attach: vi.fn(), + getDefaultShell: vi.fn(), + getProfiles: vi.fn() + } as never) + registerPtyHandlers(mainWindow as never) + const ackData = getPtyAckDataListener() + mainWindow.webContents.send.mockClear() + + mockProc.emitData('remote-output') + vi.advanceTimersByTime(2) + + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: 'remote-like-pty', + data: 'remote-output' + }) + + // Why: stale or duplicated renderer ACKs must not over-credit SSH/relay + // flow control beyond the bytes main actually sent to the renderer. + ackData(null, { id: 'remote-like-pty', charCount: 1024 }) + ackData(null, { id: 'remote-like-pty', charCount: 1024 }) + + expect(acknowledgeDataEvent).toHaveBeenNthCalledWith( + 1, + 'remote-like-pty', + 'remote-output'.length + ) + expect(acknowledgeDataEvent).toHaveBeenNthCalledWith(2, 'remote-like-pty', 0) + } finally { + vi.useRealTimers() + } + }) + + it('reserves a bounded renderer lane for interactive output when bulk output is saturated', async () => { + vi.useFakeTimers() + const bulkProcs = Array.from({ length: 16 }, () => createMockProc()) + const interactiveProc = createMockProc() + for (const proc of [...bulkProcs, interactiveProc]) { + spawnMock.mockReturnValueOnce(proc.proc) + } + + try { + registerPtyHandlers(mainWindow as never) + for (const _proc of bulkProcs) { + await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + }) + } + const interactiveSpawn = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const writeListener = getPtyWriteListener() + mainWindow.webContents.send.mockClear() + + for (const proc of bulkProcs) { + proc.emitData('x'.repeat(600 * 1024)) + } + vi.advanceTimersByTime(2) + for (let index = 0; index < 400; index++) { + vi.advanceTimersByTime(1) + } + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(512) + expect(vi.getTimerCount()).toBe(0) + + writeListener(mainWindowIpcEvent, { + id: interactiveSpawn.id, + data: 'a' + }) + interactiveProc.emitData('\x1b[20;2Hredraw') + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(513) + expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(513, 'pty:data', { + id: interactiveSpawn.id, + data: '\x1b[20;2Hredraw' + }) + + const reservePrefix = '\x1b[20;2H' + const reserveChunk = `${reservePrefix}${'r'.repeat(16 * 1024 - reservePrefix.length)}` + for (let index = 0; index < 16; index++) { + writeListener(mainWindowIpcEvent, { + id: interactiveSpawn.id, + data: 'a' + }) + interactiveProc.emitData(reserveChunk) + } + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(529) + + writeListener(mainWindowIpcEvent, { + id: interactiveSpawn.id, + data: 'a' + }) + interactiveProc.emitData(reserveChunk) + // Why: the reserve-exhausted send stays gated, and the fully gated + // arrival now also emits one delivery resync probe (not pty:data). + expect(getPtyDataSendCalls()).toHaveLength(529) + expect(getDeliveryResyncProbeCalls()).toHaveLength(1) + } finally { + vi.useRealTimers() + } + }) + + it('caps total renderer in-flight output across many PTYs', async () => { + vi.useFakeTimers() + const procs = Array.from({ length: 17 }, () => createMockProc()) + for (const proc of procs) { + spawnMock.mockReturnValueOnce(proc.proc) + } + + try { + registerPtyHandlers(mainWindow as never) + const spawns: { id: string }[] = [] + for (const _proc of procs) { + spawns.push( + (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + ) + } + const ackData = getPtyAckDataListener() + mainWindow.webContents.send.mockClear() + + for (const proc of procs) { + proc.emitData('x'.repeat(600 * 1024)) + } + vi.advanceTimersByTime(2) + for (let index = 0; index < 400; index++) { + vi.advanceTimersByTime(1) + } + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(512) + ackData(null, { id: spawns[0].id, charCount: 16 * 1024 }) + vi.advanceTimersByTime(1) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(513) + } finally { + vi.useRealTimers() + } + }) + + it('prioritizes active PTY pending output during renderer backpressure', async () => { + vi.useFakeTimers() + const procs = Array.from({ length: 18 }, () => createMockProc()) + for (const proc of procs) { + spawnMock.mockReturnValueOnce(proc.proc) + } + + try { + registerPtyHandlers(mainWindow as never) + const spawns: { id: string }[] = [] + for (const _proc of procs) { + spawns.push( + (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + ) + } + const ackData = getPtyAckDataListener() + const setActiveRendererPty = getPtySetActiveRendererPtyListener() + mainWindow.webContents.send.mockClear() + + for (let index = 0; index < procs.length - 1; index++) { + procs[index]!.emitData('x'.repeat(600 * 1024)) + } + vi.advanceTimersByTime(2) + for (let index = 0; index < 400; index++) { + vi.advanceTimersByTime(1) + } + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(512) + + const activeIndex = procs.length - 1 + procs[activeIndex]!.emitData('active-output') + setActiveRendererPty(null, { id: spawns[activeIndex]!.id, active: true }) + vi.advanceTimersByTime(2) + + // Why: the fully gated arrival also emits one delivery resync probe, so + // count pty:data sends rather than raw webContents.send calls. + expect(getPtyDataSendCalls()).toHaveLength(513) + expect(getPtyDataSendCalls()[512]).toEqual([ + 'pty:data', + { + id: spawns[activeIndex]!.id, + data: 'active-output' + } + ]) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + activeRendererPtyCount: 1, + pendingPtyCount: procs.length - 1, + rendererInFlightChars: 8 * 1024 * 1024 + 'active-output'.length + }) + ackData(null, { id: spawns[0]!.id, charCount: 16 * 1024 }) + } finally { + vi.useRealTimers() + } + }) + + it('lets active PTY output exceed its old background in-flight cap', async () => { + vi.useFakeTimers() + const activeProc = createMockProc() + spawnMock.mockReturnValue(activeProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const activeSpawn = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const setActiveRendererPty = getPtySetActiveRendererPtyListener() + mainWindow.webContents.send.mockClear() + + activeProc.emitData('x'.repeat(768 * 1024)) + vi.advanceTimersByTime(2) + for (let index = 0; index < 31; index++) { + vi.advanceTimersByTime(1) + } + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(32) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingPtyCount: 1, + pendingChars: 256 * 1024, + rendererInFlightChars: 512 * 1024, + maxRendererInFlightCharsByPty: 512 * 1024 + }) + + setActiveRendererPty(null, { id: activeSpawn.id, active: true }) + vi.advanceTimersByTime(1) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(33) + expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(33, 'pty:data', { + id: activeSpawn.id, + data: 'x'.repeat(16 * 1024) + }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingChars: 240 * 1024, + rendererInFlightChars: 528 * 1024, + maxRendererInFlightCharsByPty: 528 * 1024 + }) + } finally { + vi.useRealTimers() + } + }) + + describe('hidden renderer delivery gate', () => { + it('drops hidden PTY data after model ingestion and emits one out-of-band restore marker', async () => { + vi.useFakeTimers() + const runtime = { + setPtyController: vi.fn(), + registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn(() => 42), + getPtyOutputSequence: vi.fn(() => 42), + hasRemoteTerminalViewSubscriber: vi.fn(() => false), + createPreAllocatedTerminalHandle: vi.fn(() => 'terminal-handle-1'), + registerPreAllocatedHandleForPty: vi.fn() + } + const daemon = installObservableDaemonTestProvider() + try { + registerPtyHandlers(mainWindow as never, runtime as never) + const result = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + sessionId: 'daemon-session' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + mainWindow.webContents.send.mockClear() + + setHidden(null, { id: result.id, hidden: true }) + daemon.emitData(result.id, 'hidden output') + vi.advanceTimersByTime(50) + + // Model ingestion still ran — only renderer delivery was dropped. + expect(runtime.onPtyData).toHaveBeenCalledWith( + result.id, + 'hidden output', + expect.any(Number), + 'hidden output'.length + ) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + // Why out-of-band: an in-band empty pty:data chunk is ambiguous with + // chunks fully consumed by renderer OSC-9999 stripping. + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:modelRestoreNeeded', { + id: result.id, + reason: 'hidden-drop', + markerSeq: 42 + }) + + // Subsequent gated chunks drop silently — the marker is one-shot. + daemon.emitData(result.id, 'more hidden output') + vi.advanceTimersByTime(50) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + hiddenDeliveryGatedPtyCount: 1, + hiddenDeliveryGatedVisiblePtyCount: 0, + hiddenDeliveryGatedActivePtyCount: 0, + hiddenDeliveryDroppedChars: 'hidden output'.length + 'more hidden output'.length, + hiddenDeliveryDroppedChunks: 2, + pendingPtyCount: 0, + rendererInFlightChars: 0 + }) + } finally { + vi.useRealTimers() + } + }) + + it('surfaces the hidden-yet-visible contradiction in the snapshot and warns on drop', async () => { + // Why: v1.4.124-rc.2.perf field snapshot — blank terminal with 2 ptys + // hidden-gated and 78MB dropped. The aggregate counts could not say + // whether the pane the user was staring at was one of them; this + // overlap counter + warn makes the next occurrence decisive. + vi.useFakeTimers() + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const daemon = installObservableDaemonTestProvider() + try { + registerPtyHandlers(mainWindow as never) + const result = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + sessionId: 'daemon-session' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + const setVisible = getPtySetRendererPtyVisibleListener() + + // The two renderer visibility signals contradict: the pane reports + // itself visible while the hidden-delivery gate still holds it. + setVisible(null, { id: result.id, visible: true }) + setHidden(null, { id: result.id, hidden: true }) + daemon.emitData(result.id, 'starved visible output') + vi.advanceTimersByTime(50) + + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + hiddenDeliveryGatedPtyCount: 1, + hiddenDeliveryGatedVisiblePtyCount: 1, + hiddenDeliveryDroppedChars: 'starved visible output'.length + }) + expect(warnSpy).toHaveBeenCalledWith( + '[pty] hidden-delivery gate is dropping bytes for a visible/active pty', + expect.objectContaining({ id: result.id, visible: true }) + ) + + // Unhiding resolves the contradiction. + setHidden(null, { id: result.id, hidden: false }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + hiddenDeliveryGatedPtyCount: 0, + hiddenDeliveryGatedVisiblePtyCount: 0 + }) + } finally { + warnSpy.mockRestore() + vi.useRealTimers() + } + }) + + it('embeds one-paste freeze diagnostics: per-pty table and breadcrumb history', async () => { + vi.useFakeTimers() + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const daemon = installObservableDaemonTestProvider() + try { + registerPtyHandlers(mainWindow as never) + const result = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + sessionId: 'daemon-session' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + const setVisible = getPtySetRendererPtyVisibleListener() + setVisible(null, { id: result.id, visible: true }) + setHidden(null, { id: result.id, hidden: true }) + daemon.emitData(result.id, 'starved visible output') + vi.advanceTimersByTime(50) + + const { diagnostics } = getPtyRendererDeliveryDebugSnapshot() + expect(diagnostics.appVersion).toBe('0.0.0-test') + expect(diagnostics.windowFocused).toBe(true) + expect(diagnostics.windowVisible).toBe(true) + const entry = diagnostics.perPty.find( + (candidate) => candidate.id === redactPtyIdForDiagnostics(result.id) + ) + expect(entry).toMatchObject({ + hidden: true, + visible: true, + inFlightChars: 0, + pendingChars: 0 + }) + // Why redaction is pinned here: daemon session ids embed worktree + // paths; the report must never carry the raw id. + expect(diagnostics.perPty.some((candidate) => candidate.id === result.id)).toBe(false) + const breadcrumbKinds = diagnostics.breadcrumbs.map((crumb) => crumb.kind) + expect(breadcrumbKinds).toContain('gate-mark') + expect(breadcrumbKinds).toContain('hidden-drop-visible') + } finally { + warnSpy.mockRestore() + vi.useRealTimers() + } + }) + + it('keeps the interactive bypass gated for hidden PTYs', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const writeListener = getPtyWriteListener() + const setHidden = getPtySetHiddenRendererPtyListener() + + writeListener(mainWindowIpcEvent, { id: spawnResult.id, data: 'a' }) + setHidden(null, { id: spawnResult.id, hidden: true }) + mainWindow.webContents.send.mockClear() + + // A keystroke-sized redraw would take the immediate path when visible. + mockProc.emitData('\x1b[20;2Hredraw') + vi.advanceTimersByTime(2) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:modelRestoreNeeded', { + id: spawnResult.id, + reason: 'hidden-drop' + }) + } finally { + vi.useRealTimers() + } + }) + + it('suppresses the gate while renderer delivery interest is registered', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + const setInterest = getPtySetDeliveryInterestListener() + mainWindow.webContents.send.mockClear() + + setHidden(null, { id: spawnResult.id, hidden: true }) + setInterest(null, { id: spawnResult.id, interested: true }) + mockProc.emitData('sidecar bytes') + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawnResult.id, + data: 'sidecar bytes' + }) + + setInterest(null, { id: spawnResult.id, interested: false }) + mainWindow.webContents.send.mockClear() + mockProc.emitData('gated bytes') + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:modelRestoreNeeded', { + id: spawnResult.id, + reason: 'hidden-drop' + }) + } finally { + vi.useRealTimers() + } + }) + + it.each([ + ['terminalHiddenDeliveryGate', { terminalHiddenDeliveryGate: false }], + ['terminalMainSideEffectAuthority', { terminalMainSideEffectAuthority: false }] + ])('keeps delivery when the %s kill switch is off', async (_name, settings) => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never, undefined, undefined, (() => settings) as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + mainWindow.webContents.send.mockClear() + + setHidden(null, { id: spawnResult.id, hidden: true }) + mockProc.emitData('still delivered') + vi.advanceTimersByTime(2) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawnResult.id, + data: 'still delivered' + }) + } finally { + vi.useRealTimers() + } + }) + + it('drops queued pending data when a PTY is marked hidden', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + mainWindow.webContents.send.mockClear() + + mockProc.emitData('queued before hidden') + expect(mainWindow.webContents.send).not.toHaveBeenCalled() + setHidden(null, { id: spawnResult.id, hidden: true }) + + // The queued bytes are model-owned; only the restore marker goes out. + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:modelRestoreNeeded', { + id: spawnResult.id, + reason: 'hidden-drop' + }) + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ pendingPtyCount: 0 }) + } finally { + vi.useRealTimers() + } + }) + + it('re-emits the restore marker on unhide and resumes delivery', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + mainWindow.webContents.send.mockClear() + + setHidden(null, { id: spawnResult.id, hidden: true }) + mockProc.emitData('dropped while hidden') + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + + // Why: a renderer reload can replace the view that latched + // restore-needed; unhide repeats the marker so the live view heals. + setHidden(null, { id: spawnResult.id, hidden: false }) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(2) + expect(mainWindow.webContents.send).toHaveBeenLastCalledWith('pty:modelRestoreNeeded', { + id: spawnResult.id, + reason: 'unhide' + }) + + mockProc.emitData('visible again') + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenLastCalledWith('pty:data', { + id: spawnResult.id, + data: 'visible again' + }) + } finally { + vi.useRealTimers() + } + }) + + it('does not emit an unhide marker when nothing was dropped', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + mainWindow.webContents.send.mockClear() + + setHidden(null, { id: spawnResult.id, hidden: true }) + setHidden(null, { id: spawnResult.id, hidden: false }) + + expect(mainWindow.webContents.send).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('clears gate state on PTY exit', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + + setHidden(null, { id: spawnResult.id, hidden: true }) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + hiddenDeliveryGatedPtyCount: 1 + }) + + mockProc.emitExit(0) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + hiddenDeliveryGatedPtyCount: 0, + deliveryInterestPtyCount: 0 + }) + } finally { + vi.useRealTimers() + } + }) + + it('keeps drop memory across a hidden remount so reveal still restores', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + mainWindow.webContents.send.mockClear() + + setHidden(null, { id: spawnResult.id, hidden: true }) + mockProc.emitData('dropped while hidden') + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + + // Why: a hidden remount (tab move, parking handoff) re-marks the PTY + // without an unhide in between. The fresh view never saw the first + // marker, so re-marking must NOT erase the drop memory. + setHidden(null, { id: spawnResult.id, hidden: true }) + setHidden(null, { id: spawnResult.id, hidden: false }) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(2) + expect(mainWindow.webContents.send).toHaveBeenLastCalledWith('pty:modelRestoreNeeded', { + id: spawnResult.id, + reason: 'unhide' + }) + } finally { + vi.useRealTimers() + } + }) + + it('keeps drop memory across a renderer reload while clearing hidden/interest state', async () => { + vi.useFakeTimers() + const runtime = { + setPtyController: vi.fn(), + registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn(() => 42), + getPtyOutputSequence: vi.fn(() => 42), + hasRemoteTerminalViewSubscriber: vi.fn(() => false), + createPreAllocatedTerminalHandle: vi.fn(() => 'terminal-handle-1'), + registerPreAllocatedHandleForPty: vi.fn() + } + const daemon = installObservableDaemonTestProvider() + try { + registerPtyHandlers(mainWindow as never, runtime as never) + // Why daemon provider: it survives renderer reloads (the scenario + // under test) and keeps the LocalPtyProvider orphan-kill handler off + // this webContents, so 'did-finish-load' maps to the gate reset only. + const reloadHandlers = mainWindow.webContents.on.mock.calls + .filter((call: unknown[]) => call[0] === 'did-finish-load') + .map((call: unknown[]) => call[1] as () => void) + expect(reloadHandlers).toHaveLength(1) + const result = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + sessionId: 'daemon-session' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + mainWindow.webContents.send.mockClear() + + setHidden(null, { id: result.id, hidden: true }) + daemon.emitData(result.id, 'dropped while hidden') + vi.advanceTimersByTime(50) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + + // Renderer reload: hidden marks die with the old renderer, but the + // dropped bytes were never restored — memory must survive. + reloadHandlers[0]() + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + hiddenDeliveryGatedPtyCount: 0 + }) + + // The reloaded pane's first sync re-marks hidden, then reveals. + setHidden(null, { id: result.id, hidden: true }) + setHidden(null, { id: result.id, hidden: false }) + expect(mainWindow.webContents.send).toHaveBeenLastCalledWith('pty:modelRestoreNeeded', { + id: result.id, + reason: 'unhide', + markerSeq: 42 + }) + } finally { + vi.useRealTimers() + } + }) + + it('clears leaked delivery interest on renderer reload so the gate re-engages', async () => { + vi.useFakeTimers() + const runtime = { + setPtyController: vi.fn(), + registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn(() => 42), + getPtyOutputSequence: vi.fn(() => 42), + hasRemoteTerminalViewSubscriber: vi.fn(() => false), + createPreAllocatedTerminalHandle: vi.fn(() => 'terminal-handle-1'), + registerPreAllocatedHandleForPty: vi.fn() + } + const daemon = installObservableDaemonTestProvider() + try { + registerPtyHandlers(mainWindow as never, runtime as never) + const reloadHandlers = mainWindow.webContents.on.mock.calls + .filter((call: unknown[]) => call[0] === 'did-finish-load') + .map((call: unknown[]) => call[1] as () => void) + expect(reloadHandlers).toHaveLength(1) + const result = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + sessionId: 'daemon-session' + })) as { id: string } + const setHidden = getPtySetHiddenRendererPtyListener() + const setInterest = getPtySetDeliveryInterestListener() + mainWindow.webContents.send.mockClear() + + // A sidecar holds interest, so hidden bytes still flow. + setInterest(null, { id: result.id, interested: true }) + setHidden(null, { id: result.id, hidden: true }) + daemon.emitData(result.id, 'sidecar bytes') + vi.advanceTimersByTime(50) + expect(mainWindow.webContents.send).toHaveBeenLastCalledWith( + 'pty:data', + expect.objectContaining({ id: result.id, data: 'sidecar bytes' }) + ) + + // Why: the renderer reload killed the sidecar's ref count without a + // release IPC — the leaked hold must not force-feed the PTY forever. + reloadHandlers[0]() + mainWindow.webContents.send.mockClear() + setHidden(null, { id: result.id, hidden: true }) + daemon.emitData(result.id, 'gated after reload') + vi.advanceTimersByTime(50) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:modelRestoreNeeded', { + id: result.id, + reason: 'hidden-drop', + markerSeq: 42 + }) + } finally { + vi.useRealTimers() + } + }) + }) + + describe('hidden-at-spawn mark (initiallyHidden)', () => { + // terminal-query-authority.md §races: the renderer declares hidden-at- + // spawn so main marks the PTY before its first byte — the spawn-time + // query window where neither side replied (the non-codex DA1 loss) is + // closed by the gate + responder owning queries from byte one. + function createRuntimeMock() { + return { + setPtyController: vi.fn(), + registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn(() => 42), + getPtyOutputSequence: vi.fn(() => 42), + hasRemoteTerminalViewSubscriber: vi.fn(() => false), + createPreAllocatedTerminalHandle: vi.fn(() => 'terminal-handle-1'), + registerPreAllocatedHandleForPty: vi.fn() + } + } + + it('marks a daemon PTY hidden before spawn resolves so byte zero is gated', async () => { + vi.useFakeTimers() + const runtime = createRuntimeMock() + const daemon = installObservableDaemonTestProvider() + const spawnGate = makeDeferred() + daemon.spawn.mockImplementation(async (options: { sessionId?: string }) => { + await spawnGate.promise + return { id: options.sessionId ?? 'daemon-pty' } + }) + try { + registerPtyHandlers(mainWindow as never, runtime as never) + const spawnPromise = handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + sessionId: 'daemon-session', + initiallyHidden: true + }) as Promise<{ id: string }> + // Let the handler run up to the awaited provider.spawn. + await Promise.resolve() + mainWindow.webContents.send.mockClear() + + // Daemon PTYs can emit prompt bytes before spawn() resolves — the + // pre-spawn mark must already gate them. + expect(isHiddenRendererPty('daemon-session')).toBe(true) + daemon.emitData('daemon-session', 'pre-spawn prompt\x1b[c') + vi.advanceTimersByTime(50) + expect(runtime.onPtyData).toHaveBeenCalledWith( + 'daemon-session', + 'pre-spawn prompt\x1b[c', + expect.any(Number), + 'pre-spawn prompt\x1b[c'.length ) - } - const ackData = getPtyAckDataListener() - mainWindow.webContents.send.mockClear() + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:modelRestoreNeeded', { + id: 'daemon-session', + reason: 'hidden-drop', + markerSeq: 42 + }) - for (const proc of procs) { - proc.emitData('x'.repeat(600 * 1024)) - } - vi.advanceTimersByTime(8) - for (let index = 0; index < 400; index++) { - vi.advanceTimersByTime(1) + spawnGate.resolve() + const result = await spawnPromise + expect(isHiddenRendererPty(result.id)).toBe(true) + } finally { + vi.useRealTimers() } + }) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(512) - ackData(null, { id: spawns[0].id, charCount: 16 * 1024 }) - vi.advanceTimersByTime(1) + it('clears the pre-spawn hidden mark when the spawn fails', async () => { + const daemon = installObservableDaemonTestProvider() + daemon.spawn.mockRejectedValue(new Error('spawn exploded')) + registerPtyHandlers(mainWindow as never) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(513) - } finally { - vi.useRealTimers() - } - }) + await expect( + handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + sessionId: 'daemon-session', + initiallyHidden: true + }) + ).rejects.toThrow('spawn exploded') - it('prioritizes active PTY pending output during renderer backpressure', async () => { - vi.useFakeTimers() - const procs = Array.from({ length: 18 }, () => createMockProc()) - for (const proc of procs) { - spawnMock.mockReturnValueOnce(proc.proc) - } + // A later visible attach reusing this session id must not start gated. + expect(isHiddenRendererPty('daemon-session')).toBe(false) + }) - try { - registerPtyHandlers(mainWindow as never) - const spawns: { id: string }[] = [] - for (const _proc of procs) { - spawns.push( - (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - })) as { id: string } - ) + it('marks local PTYs hidden after spawn, before their first data task', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp', + initiallyHidden: true + })) as { id: string } + mainWindow.webContents.send.mockClear() + + expect(isHiddenRendererPty(spawnResult.id)).toBe(true) + mockProc.emitData('first chunk') + vi.advanceTimersByTime(2) + + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:modelRestoreNeeded', { + id: spawnResult.id, + reason: 'hidden-drop' + }) + } finally { + vi.useRealTimers() } - const ackData = getPtyAckDataListener() - const setActiveRendererPty = getPtySetActiveRendererPtyListener() - mainWindow.webContents.send.mockClear() + }) - for (let index = 0; index < procs.length - 1; index++) { - procs[index]!.emitData('x'.repeat(600 * 1024)) - } - vi.advanceTimersByTime(8) - for (let index = 0; index < 400; index++) { - vi.advanceTimersByTime(1) + it('keeps spawns without the flag delivering to the renderer (visible unchanged)', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + try { + registerPtyHandlers(mainWindow as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + mainWindow.webContents.send.mockClear() + + expect(isHiddenRendererPty(spawnResult.id)).toBe(false) + mockProc.emitData('visible output') + vi.advanceTimersByTime(2) + + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawnResult.id, + data: 'visible output' + }) + } finally { + vi.useRealTimers() } - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(512) + }) - const activeIndex = procs.length - 1 - procs[activeIndex]!.emitData('active-output') - setActiveRendererPty(null, { id: spawns[activeIndex]!.id, active: true }) - vi.advanceTimersByTime(8) + it('answers DA1 from the model on the first chunk of a hidden-at-spawn PTY', async () => { + // End-to-end through a REAL runtime: spawn-marked → first chunk dropped + // → runtime emulator parses the query → reply written to the provider + // input path (the renderer never saw the bytes; main is the answerer). + const daemon = installObservableDaemonTestProvider() + const runtime = new OrcaRuntimeService({ + getRepo: () => undefined, + getRepos: () => [], + addRepo: () => {}, + updateRepo: () => undefined as never, + getAllWorktreeMeta: () => ({}), + getWorktreeMeta: () => undefined, + setWorktreeMeta: () => undefined as never, + removeWorktreeMeta: () => {}, + getGitHubCache: () => ({ pr: {}, issue: {} }) as never, + getSettings: () => ({ + workspaceDir: '/tmp/workspaces', + nestWorkspaces: false, + refreshLocalBaseRefOnWorktreeCreate: false, + branchPrefix: 'none', + branchPrefixCustom: '', + terminalMainSideEffectAuthority: true, + terminalHiddenDeliveryGate: true, + terminalModelQueryAuthority: true + }) + } as never) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(513) - expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(513, 'pty:data', { - id: spawns[activeIndex]!.id, - data: 'active-output' - }) - expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ - activeRendererPtyCount: 1, - pendingPtyCount: procs.length - 1, - rendererInFlightChars: 8 * 1024 * 1024 + 'active-output'.length - }) - ackData(null, { id: spawns[0]!.id, charCount: 16 * 1024 }) - } finally { - vi.useRealTimers() - } + registerPtyHandlers(mainWindow as never, runtime as never) + const result = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + sessionId: 'daemon-session', + initiallyHidden: true + })) as { id: string } + + daemon.emitData(result.id, '\x1b[c') + // Settle the per-PTY emulator writeChain (and the reply it forwards). + await runtime.serializeMainTerminalBuffer(result.id) + + expect(daemon.write).toHaveBeenCalledWith(result.id, '\x1b[?1;2c') + }) }) - it('lets active PTY output exceed its old background in-flight cap', async () => { + it('caps pending renderer delivery per PTY with oldest-drop and one restore marker', async () => { vi.useFakeTimers() - const activeProc = createMockProc() - spawnMock.mockReturnValue(activeProc.proc) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) try { registerPtyHandlers(mainWindow as never) - const activeSpawn = (await handlers.get('pty:spawn')!(null, { + const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, cwd: '/tmp' })) as { id: string } - const setActiveRendererPty = getPtySetActiveRendererPtyListener() mainWindow.webContents.send.mockClear() - activeProc.emitData('x'.repeat(768 * 1024)) - vi.advanceTimersByTime(8) - for (let index = 0; index < 31; index++) { - vi.advanceTimersByTime(1) - } + // 3 MB in one starved pending entry: the scrollback-scaled cap (2 MB at + // default settings) drops the buffered bytes to O(1) memory. One + // out-of-band restore marker fires; the droppedOutput sentinel then + // routes the pane through the main-owned snapshot repaint. + mockProc.emitData('x'.repeat(1024 * 1024) + 'y'.repeat(2 * 1024 * 1024)) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(32) - expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ - pendingPtyCount: 1, - pendingChars: 256 * 1024, - rendererInFlightChars: 512 * 1024, - maxRendererInFlightCharsByPty: 512 * 1024 + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:modelRestoreNeeded', { + id: spawnResult.id, + reason: 'pending-cap' }) - setActiveRendererPty(null, { id: activeSpawn.id, active: true }) - vi.advanceTimersByTime(1) + // A second overflow before the entry drains must not re-mark. + mockProc.emitData('z'.repeat(64 * 1024)) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1) - expect(mainWindow.webContents.send).toHaveBeenCalledTimes(33) - expect(mainWindow.webContents.send).toHaveBeenNthCalledWith(33, 'pty:data', { - id: activeSpawn.id, - data: 'x'.repeat(16 * 1024) - }) - expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ - pendingChars: 240 * 1024, - rendererInFlightChars: 528 * 1024, - maxRendererInFlightCharsByPty: 528 * 1024 + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenCalledTimes(2) + expect(mainWindow.webContents.send).toHaveBeenLastCalledWith('pty:data', { + id: spawnResult.id, + data: '', + droppedOutput: true }) } finally { vi.useRealTimers() } }) + it.each([ + ['terminalHiddenDeliveryGate', { terminalHiddenDeliveryGate: false }], + ['terminalMainSideEffectAuthority', { terminalMainSideEffectAuthority: false }] + ])( + 'keeps the pending cap active without a restore marker when the %s kill switch is off', + async (_name, settings) => { + // Why: the scrollback-scaled pending cap ships independently of the gate + // (#7150) — the droppedOutput sentinel repaints the pane from the + // main-owned snapshot even with the model/view kill switches off. Only the + // gate's out-of-band pty:modelRestoreNeeded marker is switch-scoped. + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never, undefined, undefined, (() => settings) as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + mainWindow.webContents.send.mockClear() + + mockProc.emitData('x'.repeat(3 * 1024 * 1024)) + + expect(mainWindow.webContents.send).not.toHaveBeenCalledWith( + 'pty:modelRestoreNeeded', + expect.anything() + ) + + vi.advanceTimersByTime(2) + expect(mainWindow.webContents.send).toHaveBeenLastCalledWith('pty:data', { + id: spawnResult.id, + data: '', + droppedOutput: true + }) + } finally { + vi.useRealTimers() + } + } + ) + it('batches stale PTY output after the interactive window expires', async () => { vi.useFakeTimers() const mockProc = createMockProc() @@ -7656,7 +9975,7 @@ describe('registerPtyHandlers', () => { mockProc.emitData('stale redraw') expect(mainWindow.webContents.send).not.toHaveBeenCalled() - vi.advanceTimersByTime(8) + vi.advanceTimersByTime(2) expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { id: spawnResult.id, data: 'stale redraw' @@ -7803,6 +10122,34 @@ describe('registerPtyHandlers', () => { expect(mockProc.proc.write).not.toHaveBeenCalled() }) + it('silently drops writes to a live PTY after ownership loss until pty:listSessions rebuilds it (frozen-terminal repro)', async () => { + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + registerPtyHandlers(mainWindow as never) + const result = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24 + })) as { id: string } + const write = getPtyWriteListener() + + write(mainWindowIpcEvent, { id: result.id, data: 'alive' }) + expect(mockProc.proc.write).toHaveBeenCalledWith('alive') + + // Field failure shape (Discord #performance / #2836): a pane can keep + // rendering with a ptyId whose ownership entry is gone while the provider + // still holds the live PTY — every keystroke then vanishes with no error, + // no log, and no signal back to the renderer. + deletePtyOwnership(result.id) + write(mainWindowIpcEvent, { id: result.id, data: 'dropped' }) + expect(mockProc.proc.write).not.toHaveBeenCalledWith('dropped') + + // pty:listSessions rebuilds ownership from provider sessions — the + // revival lever the frozen-pane e2e probes depend on. + await handlers.get('pty:listSessions')!(null, undefined) + write(mainWindowIpcEvent, { id: result.id, data: 'revived' }) + expect(mockProc.proc.write).toHaveBeenCalledWith('revived') + }) + it('chunks large acknowledged pty writes before provider writes', async () => { const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) @@ -7886,6 +10233,7 @@ describe('registerPtyHandlers', () => { } as never) const runtime = { setPtyController: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), seedHeadlessTerminal: vi.fn(), onPtySpawned: vi.fn(), onPtyData: vi.fn(), @@ -8151,6 +10499,7 @@ describe('registerPtyHandlers', () => { } const runtime = { setPtyController: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyData: vi.fn(), onPtyExit: vi.fn(), @@ -8191,6 +10540,7 @@ describe('registerPtyHandlers', () => { } const runtime = { setPtyController: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), onPtySpawned: vi.fn(), onPtyData: vi.fn(), onPtyExit: vi.fn(), @@ -8199,16 +10549,23 @@ describe('registerPtyHandlers', () => { spawnMock.mockReturnValue(proc) registerPtyHandlers(mainWindow as never, runtime as never) - const didFinishLoad = mainWindow.webContents.on.mock.calls.find( - ([eventName]) => eventName === 'did-finish-load' - )?.[1] as (() => void) | undefined - expect(didFinishLoad).toBeTypeOf('function') + // Why both: a reload fires the hidden-delivery gate reset AND the orphan + // cleanup; invoke every registered listener like a real did-finish-load. + const didFinishLoadHandlers = mainWindow.webContents.on.mock.calls + .filter(([eventName]) => eventName === 'did-finish-load') + .map(([, handler]) => handler as () => void) + expect(didFinishLoadHandlers.length).toBeGreaterThan(0) + const didFinishLoad = (): void => { + for (const handler of didFinishLoadHandlers) { + handler() + } + } await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 }) // The first load after spawn only advances generation. The second one sees // this PTY as belonging to a prior page load and kills it as orphaned. - didFinishLoad?.() - didFinishLoad?.() + didFinishLoad() + didFinishLoad() expect(onDataDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan( killSpy.mock.invocationCallOrder[0] @@ -8221,6 +10578,9 @@ describe('registerPtyHandlers', () => { it('removes the previous orphan-cleanup listener from its original webContents', () => { const firstWindow = { isDestroyed: () => false, + isFocused: () => true, + isVisible: () => true, + isMinimized: () => false, webContents: { on: vi.fn(), send: vi.fn(), @@ -8229,6 +10589,9 @@ describe('registerPtyHandlers', () => { } const secondWindow = { isDestroyed: () => false, + isFocused: () => true, + isVisible: () => true, + isMinimized: () => false, webContents: { on: vi.fn(), send: vi.fn(), @@ -8237,10 +10600,12 @@ describe('registerPtyHandlers', () => { } registerPtyHandlers(firstWindow as never) - const didFinishLoad = firstWindow.webContents.on.mock.calls.find( + // Two listeners on the first (LocalPtyProvider) window: the renderer-gate + // reset and the orphan cleanup. + const firstWindowLoadHandlers = firstWindow.webContents.on.mock.calls.filter( ([eventName]) => eventName === 'did-finish-load' - )?.[1] as (() => void) | undefined - expect(didFinishLoad).toBeTypeOf('function') + ) + expect(firstWindowLoadHandlers).toHaveLength(2) setLocalPtyProvider({ spawn: vi.fn(), @@ -8255,13 +10620,20 @@ describe('registerPtyHandlers', () => { } as never) registerPtyHandlers(secondWindow as never) - expect(firstWindow.webContents.removeListener).toHaveBeenCalledWith( - 'did-finish-load', - didFinishLoad - ) + // Every first-window load listener was detached from its webContents. + for (const [, handler] of firstWindowLoadHandlers) { + expect(firstWindow.webContents.removeListener).toHaveBeenCalledWith( + 'did-finish-load', + handler + ) + } + // The non-Local provider keeps orphan cleanup off the second window — + // only the renderer-gate reset listener remains. expect( - secondWindow.webContents.on.mock.calls.some(([eventName]) => eventName === 'did-finish-load') - ).toBe(false) + secondWindow.webContents.on.mock.calls.filter( + ([eventName]) => eventName === 'did-finish-load' + ) + ).toHaveLength(1) }) // Why (#5787): a crash/freeze-recovery reload re-fires did-finish-load on the @@ -8298,10 +10670,14 @@ describe('registerPtyHandlers', () => { undefined, { isRecoveryReloadInFlight } ) - const didFinishLoad = mainWindow.webContents.on.mock.calls.find( - ([eventName]) => eventName === 'did-finish-load' - )?.[1] as (() => void) | undefined - expect(didFinishLoad).toBeTypeOf('function') + // This branch registers two did-finish-load listeners (renderer delivery-gate + // reset first, orphan sweep second); a real reload fires both, so must we — + // otherwise the suppression assertion passes vacuously without reaching the sweep. + const didFinishLoadHandlers = mainWindow.webContents.on.mock.calls + .filter(([eventName]) => eventName === 'did-finish-load') + .map(([, handler]) => handler as () => void) + expect(didFinishLoadHandlers.length).toBeGreaterThan(0) + const didFinishLoad = (): void => didFinishLoadHandlers.forEach((handler) => handler()) const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 })) as { id: string @@ -8309,8 +10685,8 @@ describe('registerPtyHandlers', () => { // Without the guard the second load would sweep this PTY as a prior-generation // orphan. Under recovery-in-flight neither load may touch it. - didFinishLoad?.() - didFinishLoad?.() + didFinishLoad() + didFinishLoad() expect(killSpy).not.toHaveBeenCalled() expect(runtime.onPtyExit).not.toHaveBeenCalled() @@ -8353,9 +10729,12 @@ describe('registerPtyHandlers', () => { undefined, { isRecoveryReloadInFlight } ) - const didFinishLoad = mainWindow.webContents.on.mock.calls.find( - ([eventName]) => eventName === 'did-finish-load' - )?.[1] as (() => void) | undefined + // This branch registers two did-finish-load listeners (renderer delivery-gate + // reset first, orphan sweep second); a real reload fires both, so must we. + const didFinishLoadHandlers = mainWindow.webContents.on.mock.calls + .filter(([eventName]) => eventName === 'did-finish-load') + .map(([, handler]) => handler as () => void) + const didFinishLoad = (): void => didFinishLoadHandlers.forEach((handler) => handler()) const spawnResult = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 })) as { id: string @@ -8363,8 +10742,8 @@ describe('registerPtyHandlers', () => { // First load only advances the generation; the second sees this PTY as a // prior-load orphan. With the flag false the guard must NOT suppress the sweep. - didFinishLoad?.() - didFinishLoad?.() + didFinishLoad() + didFinishLoad() expect(killSpy).toHaveBeenCalled() expect(runtime.onPtyExit).toHaveBeenCalledWith(spawnResult.id, -1) @@ -8395,9 +10774,12 @@ describe('registerPtyHandlers', () => { undefined, { isRecoveryReloadInFlight } ) - const didFinishLoad = mainWindow.webContents.on.mock.calls.find( - ([eventName]) => eventName === 'did-finish-load' - )?.[1] as (() => void) | undefined + // Fire ALL did-finish-load listeners (gate reset + orphan sweep), as a + // real reload does — the sweep listener is the one under test. + const didFinishLoadHandlers = mainWindow.webContents.on.mock.calls + .filter(([eventName]) => eventName === 'did-finish-load') + .map(([, handler]) => handler as () => void) + const didFinishLoad = (): void => didFinishLoadHandlers.forEach((handler) => handler()) spawnMock.mockReturnValue({ onData: vi.fn(() => makeDisposable()), @@ -8412,7 +10794,7 @@ describe('registerPtyHandlers', () => { // Advance the generation without sweeping (recovery-in-flight), then spawn a // second PTY so the two live in different load generations. - didFinishLoad?.() + didFinishLoad() spawnMock.mockReturnValue({ onData: vi.fn(() => makeDisposable()), @@ -8425,7 +10807,7 @@ describe('registerPtyHandlers', () => { }) const ptyB = (await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 })) as { id: string } - didFinishLoad?.() + didFinishLoad() expect(killSpyA).not.toHaveBeenCalled() expect(killSpyB).not.toHaveBeenCalled() @@ -8687,6 +11069,7 @@ describe('registerPtyHandlers', () => { it('returns a hidden-output recovery snapshot with clamped scrollback', async () => { const runtime = { setPtyController: vi.fn(), + getPtyOutputSequence: vi.fn(() => 42), serializeHiddenOutputRecoveryBuffer: vi.fn().mockResolvedValue({ data: 'snapshot\r\n', cols: 120, @@ -8707,14 +11090,146 @@ describe('registerPtyHandlers', () => { expect(runtime.serializeHiddenOutputRecoveryBuffer).toHaveBeenCalledWith('pty-1', { scrollbackRows: 50_000 }) + // Why pendingDeliveryStartSeq === seq: the pending renderer-delivery + // queue is empty, so the renderer's post-restore duplicate window is + // empty too — low-seq live chunks (fresh seq domain) must not be + // dropped against the snapshot baseline. expect(result).toEqual({ data: 'snapshot\r\n', cols: 120, rows: 40, cwd: '/projects/restored', seq: 42, + pendingDeliveryStartSeq: 42, + source: 'headless' + }) + }) + + it('uses the complete provider model after daemon stream thinning', async () => { + const provider = installObservableDaemonTestProvider() + provider.getBufferSnapshot.mockResolvedValue({ + data: 'complete daemon scrollback\r\n', + cols: 100, + rows: 30, + seq: 900, source: 'headless' }) + const runtime = { + setPtyController: vi.fn(), + getPtyOutputSequence: vi.fn(() => 640), + notePtyDataGap: vi.fn(), + onPtyExit: vi.fn(), + serializeHiddenOutputRecoveryBuffer: vi.fn().mockResolvedValue({ + data: 'kept tail only\r\n', + cols: 100, + rows: 30, + seq: 640, + source: 'headless' + }) + } + handlers.clear() + registerPtyHandlers(mainWindow as never, runtime as never) + provider.emitDataGap('daemon-pty', 512) + + const result = await handlers.get('pty:getMainBufferSnapshot')!(null, { + id: 'daemon-pty', + opts: { scrollbackRows: 5000 } + }) + + expect(runtime.notePtyDataGap).toHaveBeenCalledWith('daemon-pty', 512) + expect(provider.getBufferSnapshot).toHaveBeenCalledWith('daemon-pty', { + scrollbackRows: 5000 + }) + expect(runtime.serializeHiddenOutputRecoveryBuffer).not.toHaveBeenCalled() + expect(result).toEqual({ + data: 'complete daemon scrollback\r\n', + cols: 100, + rows: 30, + seq: 900, + source: 'headless', + // Bytes between main's current absolute seq and the daemon snapshot + // may still be queued on the stream socket and must dedupe on arrival. + pendingDeliveryStartSeq: 640 + }) + provider.emitExit('daemon-pty') + }) + + it("never paints main's incomplete tail when a required provider snapshot is unavailable", async () => { + const provider = installObservableDaemonTestProvider() + provider.getBufferSnapshot.mockResolvedValue(null) + const runtime = { + setPtyController: vi.fn(), + getPtyOutputSequence: vi.fn(() => 640), + notePtyDataGap: vi.fn(), + onPtyExit: vi.fn(), + serializeHiddenOutputRecoveryBuffer: vi.fn().mockResolvedValue({ + data: 'kept tail only\r\n', + cols: 100, + rows: 30, + seq: 640, + source: 'headless' + }) + } + handlers.clear() + registerPtyHandlers(mainWindow as never, runtime as never) + provider.emitDataGap('daemon-pty', 512) + + const result = await handlers.get('pty:getMainBufferSnapshot')!(null, { + id: 'daemon-pty', + opts: { scrollbackRows: 5000 } + }) + + expect(provider.getBufferSnapshot).toHaveBeenCalledWith('daemon-pty', { + scrollbackRows: 5000 + }) + expect(runtime.serializeHiddenOutputRecoveryBuffer).not.toHaveBeenCalled() + expect(result).toBeNull() + provider.emitExit('daemon-pty') + }) + + it('reports where the undelivered pending backlog starts alongside the snapshot', async () => { + vi.useFakeTimers() + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + const runtime = { + setPtyController: vi.fn(), + registerPty: vi.fn(), + noteTerminalSpawnCommand: vi.fn(), + onPtySpawned: vi.fn(), + onPtyExit: vi.fn(), + onPtyData: vi.fn(), + preAllocateHandleForPty: vi.fn(() => null), + getPtyOutputSequence: vi.fn(() => 2_472), + hasRemoteTerminalViewSubscriber: vi.fn(() => false), + serializeHiddenOutputRecoveryBuffer: vi.fn().mockResolvedValue({ + data: 'snapshot\r\n', + cols: 100, + rows: 30, + seq: 2_472, + source: 'headless' + }) + } + try { + handlers.clear() + registerPtyHandlers(mainWindow as never, runtime as never) + const spawnResult = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + + // Starved pending entry: bytes ingested up to seq 2_472 but not yet + // flushed to the renderer — they can still arrive after the snapshot. + mockProc.emitData('frame-bytes') + + const result = (await handlers.get('pty:getMainBufferSnapshot')!(null, { + id: spawnResult.id + })) as { pendingDeliveryStartSeq?: number } + + expect(result.pendingDeliveryStartSeq).toBe(2_472 - 'frame-bytes'.length) + } finally { + vi.useRealTimers() + } }) }) }) diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index e12c2b7f2629..893a65e4c659 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -5,18 +5,36 @@ boundary. Splitting it by line count would scatter tightly coupled terminal process behavior across files without a cleaner ownership seam. */ import { join, delimiter } from 'node:path' import { randomUUID } from 'node:crypto' +import { statSync } from 'node:fs' import { type BrowserWindow, type IpcMainEvent, type IpcMainInvokeEvent, type WebContents, ipcMain, - app + app, + powerMonitor } from 'electron' export { getBashShellReadyRcfileContent } from '../providers/local-pty-shell-ready' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { Store } from '../persistence' import type { GlobalSettings, TuiAgent } from '../../shared/types' +import { terminalOutputBacklogCapChars } from '../../shared/terminal-scrollback-policy' +import type { + PtyDeliveryWriteOff, + PtyRendererDeliveryHealthReply, + PtyRendererDeliveryStateReport +} from '../../shared/pty-renderer-delivery-health' +import { extractHiddenStartupRendererQueryData } from '../../shared/terminal-reply-query-extraction' +import { + type PtyMainDeliveryDiagnostics, + type PtyPerPtyDeliveryDiagnostics, + EMPTY_PTY_MAIN_DELIVERY_DIAGNOSTICS, + createPtyDeliveryBreadcrumbRing, + redactPtyIdForDiagnostics +} from '../../shared/pty-delivery-diagnostics' +import { recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' +import { isTuiAgent } from '../../shared/tui-agent-config' import type { SleepingAgentLaunchConfig } from '../../shared/agent-session-resume' import type { ProjectExecutionRuntimeResolution } from '../../shared/project-execution-runtime' import { @@ -30,6 +48,7 @@ import { getFirstCommandToken } from '../../shared/command-token-scanner' import { agentHookServer } from '../agent-hooks/server' +import { wslHookRelayManager } from '../agent-hooks/wsl-hook-relay-manager' import { isAgentStatusHooksEnabled } from '../agent-hooks/managed-agent-hook-controls' import { piTitlebarExtensionService } from '../pi/titlebar-extension-service' import { detectPiAgentKindFromCommand, type PiAgentKind } from '../../shared/pi-agent-kind' @@ -46,6 +65,7 @@ import { parseAppSshPtyId, toAppSshPtyId, toRelaySshPtyId } from '../providers/s import { createPtySpawnTiming } from './pty-spawn-timing' import { mintPtySessionId, isSafePtySessionId } from '../daemon/pty-session-id' import { addNodePtyRecoveryHint } from '../daemon/node-pty-error-hints' +import { recordDaemonStreamBacklogEvent } from '../daemon/daemon-stream-backlog-probe' import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth-service' import type { ClaudeAccountSelectionTarget } from '../claude-accounts/runtime-selection' import { CLAUDE_AUTH_ENV_VARS, hasClaudeAuthEnvConflict } from '../claude-accounts/environment' @@ -82,8 +102,11 @@ import { parsePaneKey } from '../../shared/stable-pane-id' import { isValidTerminalTabId } from '../../shared/terminal-tab-id' -import { resolveTerminalStartupCwdForWorkspace } from '../../shared/terminal-startup-cwd' -import { localTerminalCwdCanonicalizer } from '../pty/terminal-cwd-realpath' +import { + resolveTerminalStartupCwdForWorkspace, + type TerminalStartupCwdMissingDirFallback +} from '../../shared/terminal-startup-cwd' +import { isWslUncPath } from '../../shared/wsl-paths' import { clearMigrationUnsupportedPty, clearMigrationUnsupportedPtysForPaneKey @@ -91,6 +114,29 @@ import { import { parseWslPath } from '../wsl' import { mergePersistedWindowsPath } from '../pty/windows-environment-path' import { addOrcaWslInteropEnv } from '../pty/wsl-orca-env' +import { PtyProducerFlowController } from './pty-producer-flow-control' +import { + clearHiddenRendererPtyDeliveryState, + getHiddenRendererPtyDeliveryDebug, + getHiddenRendererPtyIds, + isHiddenPtyDeliveryGateEnabled, + isHiddenRendererPty, + markHiddenRendererPty, + recordHiddenRendererPtyDataDrop, + resetHiddenRendererPtyDeliveryDebugCounters, + resetRendererScopedHiddenPtyDeliveryState, + setRendererPtyDeliveryInterest, + shouldDropHiddenRendererPtyData, + unmarkHiddenRendererPty +} from './pty-hidden-delivery-gate' +import { + clearNativeWindowsConptyPty, + isNativeWindowsLocalPtySpawn, + markNativeWindowsConptyPty +} from '../runtime/terminal-model-query-authority' +import { setTerminalViewAttributes } from '../runtime/terminal-view-attribute-store' +import { validateTerminalViewAttributes } from '../../shared/terminal-view-attributes' +import type { PtyModelRestoreReason } from '../../shared/pty-model-restore-marker' import type { CodexAccountSelectionTarget } from '../codex-accounts/runtime-selection' import { isHostCodexHomeForWsl, isWslCodexHomeForHost } from '../pty/codex-home-wsl-env' import { buildConfiguredProxyEnv, type NetworkProxySettings } from '../../shared/network-proxy' @@ -120,6 +166,10 @@ type FreshLocalFallbackProvider = IPtyProvider & { } const sshProviders = new Map() const SYNTHETIC_KILL_EXIT_DUPLICATE_WINDOW_MS = 30_000 +// Why: producer flow control changes terminal physics — a flooding shell now +// blocks on write instead of buffering in main. Kill switch: flip this one +// line to disable pause/resume entirely without untangling the wiring. +const PRODUCER_FLOW_CONTROL_ENABLED = true // Why: PTY IDs are assigned at spawn time with a connectionId, but subsequent // write/resize/kill calls only carry the PTY ID. This map lets us route // post-spawn operations to the correct provider without the renderer needing @@ -504,6 +554,9 @@ export type BuildPtyHostEnvOptions = { launchCommand?: string shellPath?: string isWsl?: boolean + /** Distro for WSL spawns (null = Windows default distro). Drives the WSL + * hook relay ensure + guest endpoint repoint; only read when isWsl. */ + wslDistro?: string | null agentStatusHooksEnabled: boolean networkProxySettings?: NetworkProxySettings } @@ -861,6 +914,19 @@ export function buildPtyHostEnv( } if (opts.agentStatusHooksEnabled) { Object.assign(baseEnv, agentHookServer.buildPtyEnv()) + if (opts.isWsl === true) { + // Why: hook POSTs to 127.0.0.1 die inside WSL's NAT namespace. Ensure + // the guest-resident relay for this distro (covers fresh spawns and + // post-restart reattach re-spawns), and once the relay has reported the + // guest home, point restart re-coordination at the relay-written + // guest-side endpoint file instead of the /p-translated Windows one. + const distro = opts.wslDistro ?? null + wslHookRelayManager.ensureForDistro(distro) + const guestEndpoint = wslHookRelayManager.getGuestEndpointFilePath(distro) + if (guestEndpoint) { + baseEnv.ORCA_AGENT_HOOK_ENDPOINT = guestEndpoint + } + } } // Why: PI_CODING_AGENT_DIR owns Pi's / OMP's full config/session root. Keep @@ -910,15 +976,14 @@ export function buildPtyHostEnv( baseEnv.ORCA_CODEX_HOME = opts.selectedCodexHomePath } - // Why: in dev mode the `orca` CLI defaults to the production userData - // path, which routes status updates to the packaged Orca instead of this - // dev instance. Injecting ORCA_USER_DATA_PATH ensures CLI calls from - // agents running inside dev terminals reach the correct runtime. We also - // prepend the dev CLI launcher directory to PATH so `orca` resolves to - // the dev build (which supports ORCA_USER_DATA_PATH) instead of the - // production binary at /usr/local/bin/orca. - if (!opts.isPackaged) { + // Why: WSL shells need the managed userData root for shell-ready wrappers; dev-mode terminals need the same export so `orca` targets the live dev instance. + if (opts.isWsl) { + baseEnv.ORCA_USER_DATA_PATH = opts.userDataPath + } else if (!opts.isPackaged) { baseEnv.ORCA_USER_DATA_PATH ??= opts.userDataPath + } + // Why: dev mode needs the launcher PATH override so `orca` resolves to the dev build instead of the production binary at /usr/local/bin/orca. + if (!opts.isPackaged) { const devCliBin = join(opts.userDataPath, 'cli', 'bin') const inheritedPath = readInheritedPath(baseEnv) // Why: avoid a trailing delimiter when PATH is empty — some shells @@ -1049,6 +1114,14 @@ export function clearProviderPtyState(id: string): void { pendingHiddenRendererResizeOutputPtys.delete(id) deliveredHiddenRendererResizeOutputPtys.delete(id) clearStartupTerminalColorQueryReplies(id) + // Why: every PTY teardown path funnels through here (local exit, daemon + // shutdown, SSH exit/connection teardown) — hidden/interest gate bits must + // not outlive the PTY or a reused map entry could silently gate a new one. + clearHiddenRendererPtyDeliveryState(id) + clearBackgroundedDeliverySyncForPty(id) + providerSnapshotRequiredPtys.delete(id) + // Why: the Phase-5 ConPTY DA1 spawn record must not leak onto a reused id. + clearNativeWindowsConptyPty(id) const paneKey = ptyPaneKey.get(id) const stillOwnsPaneKey = paneKey ? paneKeyPtyId.get(paneKey) === id : false // Why: drop the memory-collector registration so a dead PTY does not keep @@ -1124,10 +1197,30 @@ export function setPtyOwnership(id: string, connectionId: string | null): void { // duplicate listeners that forward every event twice. let localDataUnsub: (() => void) | null = null let localExitUnsub: (() => void) | null = null +let localBackgroundStreamUnsub: (() => void) | null = null let didFinishLoadHandler: (() => void) | null = null let didFinishLoadWebContents: WebContents | null = null let rendererLifecycleResetWebContents: WebContents | null = null let rendererLifecycleResetHandler: (() => void) | null = null +// Why: the hidden-delivery gate's interest/hidden registries mirror renderer +// state (ref-counted holds, per-pane hidden marks). A reload or renderer +// crash destroys the owners without unregistering, so the registries are +// reset whenever the renderer process is replaced +// (resetRendererScopedHiddenPtyDeliveryState preserves drop memory). +let rendererGateResetLoadHandler: (() => void) | null = null +let rendererGateResetGoneHandler: (() => void) | null = null +let rendererGateResetWebContents: WebContents | null = null +// Why: the backgrounded-delivery dedupe map lives in the registerPtyHandlers +// closure but teardown funnels through module-scope clearProviderPtyState. +let clearBackgroundedDeliverySyncForPty: (id: string) => void = () => {} +// Why: after daemon keep-tail thinning, main's mirror contains only the kept +// tail. Recovery must keep consulting the daemon's complete model until exit. +const providerSnapshotRequiredPtys = new Set() +// Why: did-start-loading also fires for in-page subframe loads (e.g. the +// sandboxed srcDoc iframes notebook HTML output renders), which are not renderer +// lifecycle resets. A dedicated handler filters those via isLoadingMainFrame so a +// subframe load cannot reset delivery accounting on the still-alive page. +let rendererDidStartLoadingHandler: (() => void) | null = null // Why: the "Restart daemon" path needs to re-bind provider→renderer listeners // against the freshly-created adapter after replaceDaemonProvider swaps the @@ -1155,6 +1248,52 @@ export type PtyRendererDeliveryDebugSnapshot = { peakRendererInFlightChars: number peakMaxRendererInFlightCharsByPty: number ackGatedFlushSkipCount: number + hiddenDeliveryGatedPtyCount: number + /** Hidden-gated ptys the renderer ALSO reports visible/active — a + * contradiction that should be zero; nonzero means the user may be staring + * at a pane main is deliberately starving (v1.4.124-rc.2.perf field lead). */ + hiddenDeliveryGatedVisiblePtyCount: number + hiddenDeliveryGatedActivePtyCount: number + deliveryInterestPtyCount: number + hiddenDeliveryDroppedChars: number + hiddenDeliveryDroppedChunks: number + pendingDroppedChars: number + /** One-paste freeze diagnostics: per-pty delivery table + event history. */ + diagnostics: PtyMainDeliveryDiagnostics + // Why: a nonzero lastLifecycleResetClearedChars is the exact signature of the + // leaked-delivery-accounting freeze this reset fixes; the count tracks how + // many renderer lifecycle resets have run since launch. + rendererLifecycleResetCount: number + lastLifecycleResetClearedChars: number + // Why: the boot-window hold early-returns before ackGatedFlushSkipCount++, so + // without these a held gate is invisible in the snapshot; forcedCount > 0 flags + // that the watchdog self-healed a lost handshake. + rendererPtyDispatcherReady: boolean + rendererDispatcherReadyForcedCount: number +} + +// Why module scope: breadcrumb writers live both inside registerPtyHandlers +// (gate marks, heals) and outside it (renderer lifecycle resets). +const mainDeliveryBreadcrumbs = createPtyDeliveryBreadcrumbRing() +let lastPowerSuspendAtMs: number | null = null +let lastPowerResumeAtMs: number | null = null +let powerSignalBreadcrumbsInstalled = false + +// Why: both field freeze variants correlate with display sleep; suspend/resume +// timestamps in the report let us line breadcrumbs up against the wake. +function installPowerSignalBreadcrumbs(): void { + if (powerSignalBreadcrumbsInstalled) { + return + } + powerSignalBreadcrumbsInstalled = true + powerMonitor.on('suspend', () => { + lastPowerSuspendAtMs = Date.now() + mainDeliveryBreadcrumbs.record('power-suspend') + }) + powerMonitor.on('resume', () => { + lastPowerResumeAtMs = Date.now() + mainDeliveryBreadcrumbs.record('power-resume') + }) } const EMPTY_PTY_RENDERER_DELIVERY_DEBUG_SNAPSHOT: PtyRendererDeliveryDebugSnapshot = { @@ -1170,13 +1309,32 @@ const EMPTY_PTY_RENDERER_DELIVERY_DEBUG_SNAPSHOT: PtyRendererDeliveryDebugSnapsh peakMaxPendingCharsByPty: 0, peakRendererInFlightChars: 0, peakMaxRendererInFlightCharsByPty: 0, - ackGatedFlushSkipCount: 0 + ackGatedFlushSkipCount: 0, + hiddenDeliveryGatedPtyCount: 0, + hiddenDeliveryGatedVisiblePtyCount: 0, + hiddenDeliveryGatedActivePtyCount: 0, + deliveryInterestPtyCount: 0, + hiddenDeliveryDroppedChars: 0, + hiddenDeliveryDroppedChunks: 0, + pendingDroppedChars: 0, + diagnostics: EMPTY_PTY_MAIN_DELIVERY_DIAGNOSTICS, + rendererLifecycleResetCount: 0, + lastLifecycleResetClearedChars: 0, + rendererPtyDispatcherReady: false, + rendererDispatcherReadyForcedCount: 0 } let readPtyRendererDeliveryDebugSnapshot = (): PtyRendererDeliveryDebugSnapshot => ({ ...EMPTY_PTY_RENDERER_DELIVERY_DEBUG_SNAPSHOT }) let resetPtyRendererDeliveryDebugSnapshot = (): void => {} +// Bridged into the registerPtyHandlers closure (like readPtyRendererDeliveryDebugSnapshot) +// so the module-scope lifecycle-reset handler can zero the closure-owned delivery +// accounting on a renderer reload/crash. +let resetRendererDeliveryAccountingForLifecycleReset = (): void => {} +// Bridged so a re-registration (new window) can cancel the prior closure's +// dispatcher-ready watchdog before wiring up its own. +let clearRendererDispatcherReadyWatchdog = (): void => {} export function getPtyRendererDeliveryDebugSnapshot(): PtyRendererDeliveryDebugSnapshot { return readPtyRendererDeliveryDebugSnapshot() @@ -1195,21 +1353,29 @@ function clearDidFinishLoadHandler(): void { } function markRendererPtysHiddenForRendererLifecycleReset(): void { + // A reload/crash in the history is load-bearing context for any freeze + // report ("did the user already reload before capturing?"). + mainDeliveryBreadcrumbs.record('renderer-lifecycle-reset') // Why: renderer-owned hints die with the page; keep known-visibility state so // surviving daemon/SSH PTYs fail closed until the new renderer reports again. activeRendererPtys.clear() visibleRendererPtys.clear() + // Why: the dead page never ACKs its in-flight bytes, so leaked in-flight/pending + // accounting would delivery-gate surviving PTYs forever after a reload/crash. + resetRendererDeliveryAccountingForLifecycleReset() } function clearRendererLifecycleResetHandlers(): void { if (!rendererLifecycleResetWebContents) { return } - if (rendererLifecycleResetHandler) { + if (rendererDidStartLoadingHandler) { rendererLifecycleResetWebContents.removeListener( 'did-start-loading', - rendererLifecycleResetHandler + rendererDidStartLoadingHandler ) + } + if (rendererLifecycleResetHandler) { rendererLifecycleResetWebContents.removeListener( 'render-process-gone', rendererLifecycleResetHandler @@ -1218,6 +1384,7 @@ function clearRendererLifecycleResetHandlers(): void { } rendererLifecycleResetWebContents = null rendererLifecycleResetHandler = null + rendererDidStartLoadingHandler = null } function registerRendererLifecycleResetHandlers(webContents: WebContents): void { @@ -1225,11 +1392,39 @@ function registerRendererLifecycleResetHandlers(webContents: WebContents): void markRendererPtysHiddenForRendererLifecycleReset() rendererLifecycleResetWebContents = webContents rendererLifecycleResetHandler = markRendererPtysHiddenForRendererLifecycleReset - webContents.on('did-start-loading', rendererLifecycleResetHandler) + // Why: did-start-loading also fires for in-page subframe loads (sandboxed + // srcDoc iframes in notebook HTML output), where isLoadingMainFrame() is false. + // Only a main-frame load is a real renderer lifecycle reset; filtering here + // stops a subframe load from clearing pendingData and holding the send gate + // (a spurious multi-second freeze) on the otherwise-alive page. + rendererDidStartLoadingHandler = () => { + if (!webContents.isLoadingMainFrame()) { + return + } + markRendererPtysHiddenForRendererLifecycleReset() + } + webContents.on('did-start-loading', rendererDidStartLoadingHandler) webContents.on('render-process-gone', rendererLifecycleResetHandler) webContents.on('destroyed', rendererLifecycleResetHandler) } +function clearRendererGateResetHandlers(): void { + if (rendererGateResetWebContents) { + if (rendererGateResetLoadHandler) { + rendererGateResetWebContents.removeListener('did-finish-load', rendererGateResetLoadHandler) + } + if (rendererGateResetGoneHandler) { + rendererGateResetWebContents.removeListener( + 'render-process-gone', + rendererGateResetGoneHandler + ) + } + } + rendererGateResetLoadHandler = null + rendererGateResetGoneHandler = null + rendererGateResetWebContents = null +} + // Why: the "Restart daemon" flow needs to detach listeners from the current // adapter *after* synthetic pty:exit events fan out (so the renderer receives // them) but *before* replaceDaemonProvider swaps in the new adapter (so the @@ -1238,8 +1433,10 @@ function registerRendererLifecycleResetHandlers(webContents: WebContents): void export function unbindLocalProviderListeners(): void { localDataUnsub?.() localExitUnsub?.() + localBackgroundStreamUnsub?.() localDataUnsub = null localExitUnsub = null + localBackgroundStreamUnsub = null } // ─── IPC Registration ─────────────────────────────────────────────── @@ -1258,6 +1455,12 @@ export function registerPtyHandlers( isRecoveryReloadInFlight?: (webContentsId: number) => boolean } ): void { + // Why: a re-registration means a new window owns delivery. Cancel any watchdog the + // prior closure armed, and neutralize its bridged reset so the registration-time + // mark-hidden below can't arm a timer against the now-dead closure — the fresh + // closure re-installs both bridges once its state is set up. + clearRendererDispatcherReadyWatchdog() + resetRendererDeliveryAccountingForLifecycleReset = () => {} registerRendererLifecycleResetHandlers(mainWindow.webContents) const getLocalPtyStartupPromise = (connectionId?: string | null): Promise | undefined => { @@ -1278,18 +1481,22 @@ export function registerPtyHandlers( ipcMain.removeHandler('pty:hasPty') ipcMain.removeHandler('pty:hasChildProcesses') ipcMain.removeHandler('pty:getForegroundProcess') + ipcMain.removeHandler('pty:confirmForegroundProcess') ipcMain.removeHandler('pty:getCwd') ipcMain.removeHandler('pty:getSize') ipcMain.removeHandler('pty:declarePendingPaneSerializer') ipcMain.removeHandler('pty:settlePaneSerializer') ipcMain.removeHandler('pty:clearPendingPaneSerializer') ipcMain.removeHandler('pty:getMainBufferSnapshot') + ipcMain.removeHandler('pty:sideEffectSnapshot') ipcMain.removeHandler('pty:getRendererDeliveryDebugSnapshot') ipcMain.removeHandler('pty:resetRendererDeliveryDebug') + ipcMain.removeHandler('pty:reportRendererDeliveryState') ipcMain.removeHandler('pty:writeAccepted') ipcMain.removeAllListeners('pty:write') ipcMain.removeAllListeners('pty:ackColdRestore') ipcMain.removeAllListeners('pty:ackData') + ipcMain.removeAllListeners('pty:deliveryResyncResponse') ipcMain.removeAllListeners('pty:serializeBuffer:response') // Configure the local provider with app-specific hooks. @@ -1324,6 +1531,7 @@ export function registerPtyHandlers( launchCommand: ctx?.command, shellPath: ctx?.shellPath, isWsl: ctx?.isWsl, + wslDistro: ctx?.wslDistro ?? null, agentStatusHooksEnabled: isAgentStatusHooksEnabled(getSettings?.()), networkProxySettings: getSettings?.() }) @@ -1364,10 +1572,12 @@ export function registerPtyHandlers( data: string startSeq?: number containsBackgroundOutput?: boolean - /** Set once this pty's unsent backlog was trimmed past the cap; rides the - * next payload so the renderer rebuilds the dropped span from the main - * headless snapshot (see appendPendingPtyData / dataCallback). */ - droppedBacklog?: boolean + // Why droppedOutput (not main's droppedBacklog trim): this branch bounds + // the unsent backlog with the O(1) drop-to-sentinel + query-salvage + + // snapshot-restore mechanism below, which strictly supersedes main's + // #7630 keep-2MB-tail trim — carrying both would race two cap policies + // over the same buffer. + droppedOutput?: true } type PtyDataPayload = { @@ -1376,33 +1586,70 @@ export function registerPtyHandlers( seq?: number rawLength?: number background?: boolean - droppedBacklog?: boolean + droppedOutput?: boolean } const pendingData = new Map() - const rendererInFlightCharsByPty = new Map() + // Why: one restore marker per overflow episode — cleared when the entry + // fully drains so a later overflow re-marks the renderer exactly once. + const pendingOverflowMarkedPtys = new Set() + // Why: TCP-style cumulative delivery accounting. Relative in-flight counters + // make every lost ACK a permanent debt; monotonic sent/acked totals self-heal + // as soon as any later ACK (or resync reply) reports the renderer's full + // processed count. + type RendererPtyDeliveryAccounting = { + sentChars: number + ackedChars: number + lastSendAtMs: number + lastAckAtMs: number | null + } + const rendererDeliveryAccountingByPty = new Map() const trustedTerminalHandleEnv = new Set() let flushTimer: ReturnType | null = null let rendererInFlightTotalChars = 0 - const PTY_BATCH_INTERVAL_MS = 8 + let pendingDroppedChars = 0 + let deliveryResyncRequestSerial = 0 + let deliveryResyncOutstandingRequestId: number | null = null + let deliveryResyncTimer: ReturnType | null = null + let deliveryResyncUnansweredWarnLogged = false + let lastAckReceivedAtMs: number | null = null + // Why 2ms: pairs with the daemon stream batcher (see + // daemon-stream-data-batcher.ts) — both hops charged an expected + // half-window per chunk; 2ms keeps flood coalescing at negligible IPC + // overhead while cutting the pipeline's fixed latency tax. + const PTY_BATCH_INTERVAL_MS = 2 const PTY_BATCH_DRAIN_CONTINUE_MS = 1 const PTY_BATCH_FLUSH_CHUNK_CHARS = 16 * 1024 const PTY_BATCH_FLUSH_MAX_WRITES = 2 const PTY_RENDERER_IN_FLIGHT_HIGH_WATER_CHARS = 512 * 1024 const PTY_RENDERER_TOTAL_IN_FLIGHT_HIGH_WATER_CHARS = 8 * 1024 * 1024 - // Why: the in-flight caps above bound only SENT-but-unacked bytes; the unsent - // `pendingData` backlog is drained only when the renderer ACKs. A background- - // throttled/frozen renderer (Win/Linux — macOS disables throttling) stops - // ACKing while a busy pane keeps producing, so without this the per-pty queue - // grows at raw PTY throughput (MB->GB). Cap it (matching the daemon 2 MB - // pendingOutput and renderer 2 MB scheduler caps); the trimmed span is - // recovered from the main headless buffer via the renderer's hidden-output - // snapshot restore, flagged by droppedBacklog — so no output is lost. - const PENDING_DATA_MAX_CHARS = 2 * 1024 * 1024 + // Why: while the renderer cannot receive (frozen, starved, mid-reload), a + // chatty PTY used to grow its pendingData string without bound — main-process + // heap ballooning that a renderer reload cannot clear (main's #7630 fixed the + // same Win/Linux background-throttled-renderer leak with a 2MB tail trim; + // this branch's sentinel mechanism supersedes it). Beyond this cap the + // buffered bytes are dropped and the pane heals from the main-owned buffer + // snapshot via the droppedOutput sentinel (renderer hidden-output restore). + // Why read settings live: the cap scales with the user's scrollback setting + // so power users don't lose lines their scrollback would have retained. + const pendingDataCapChars = (): number => + terminalOutputBacklogCapChars(getSettings?.().terminalScrollbackRows) + // Why: self-heal bound for the dispatcher-ready gate — if a reloaded page never + // sends pty:rendererDispatcherReady (lost IPC), force sends back on after this + // window so a dropped handshake can't itself become a permanent hold. + const PTY_DISPATCHER_READY_WATCHDOG_MS = 10_000 const PTY_RENDERER_INTERACTIVE_RESERVE_CHARS = 256 * 1024 // Why: active panes need a bounded lane through old hidden bulk output so a // keystroke redraw can reach the renderer before every background ACK lands. const PTY_RENDERER_ACTIVE_PTY_IN_FLIGHT_RESERVE_CHARS = 512 * 1024 + // Why: request/response hygiene only — this timeout never mutates delivery + // state. It clears the outstanding-probe flag so a later gated arrival can + // probe again, and logs once per silent streak for field diagnosis. + const PTY_DELIVERY_RESYNC_TIMEOUT_MS = 5_000 + // Why: a heal write-off destroys delivery accounting; require main to have + // seen zero ACKs for this long too, independent of the renderer's own + // two-silent-ticks evidence, before believing the channel is dead. + const PTY_DELIVERY_HEAL_MIN_ACK_SILENCE_MS = 10_000 // Why: keep the immediate path bounded to keystroke-sized TUI redraws; // large output and non-interactive output must still use the batcher. const INTERACTIVE_OUTPUT_WINDOW_MS = 100 @@ -1414,13 +1661,89 @@ export function registerPtyHandlers( let peakRendererInFlightChars = 0 let peakMaxRendererInFlightCharsByPty = 0 let ackGatedFlushSkipCount = 0 + let rendererLifecycleResetCount = 0 + let lastLifecycleResetClearedChars = 0 + // Why: how many times the watchdog force-opened the gate because no handshake + // arrived; nonzero flags a dropped-handshake self-heal (degrades to pre-§1b + // behavior, observable + recoverable at the next reset, never a freeze). + let rendererDispatcherReadyForcedCount = 0 + // Why: gate sends until the current page's pty:data listener is registered. + // A reloaded/first-load page has no listener yet, so webContents.send drops + // the bytes but still counts them in-flight, permanently pinning the gate. + // Flipped true by the pty:rendererDispatcherReady handshake, reset false on + // every lifecycle reset (below); starts false so nothing sends pre-handshake. + let rendererPtyDispatcherReady = false + let dispatcherReadyWatchdogTimer: ReturnType | null = null + + // Why: watermark-driven producer pause/resume (terminal-performance + // initiative §5). Signal source is per-PTY pendingData only — renderer + // in-flight is already bounded by the ACK window above, while pendingData + // is what grows without bound when the renderer cannot keep up. Providers + // without support (SSH, legacy daemon protocol) surface no pauseProducer + // and the call chain no-ops; the pending cap still bounds memory then. + const producerFlowControl = new PtyProducerFlowController({ + pauseProducer: (id) => tryGetProviderForPty(id)?.pauseProducer?.(id), + resumeProducer: (id) => tryGetProviderForPty(id)?.resumeProducer?.(id) + }) - function getMaxMapValue(values: Iterable): number { - let max = 0 - for (const value of values) { - max = Math.max(max, value) + function updateProducerFlowControl(id: string): void { + if (!PRODUCER_FLOW_CONTROL_ENABLED) { + return + } + producerFlowControl.update(id, pendingData.get(id)?.data.length ?? 0) + } + + // Why this exists: hidden ptys are exempt from pendingData flow control + // (their bytes are dropped after model ingestion, so pendingData never + // grows), which let background agents run 100MB+ ahead of main in the + // daemon's stream-socket buffer and bury the visible pane's echo. The + // provider transport keep-tail thins backgrounded ptys' monitoring stream + // under backlog; this sync tells it which ptys qualify. + // Why keyed on the visibility registry (NOT gate marks or gate-effective + // shouldDrop): delivery claims and raw-byte sidecars describe transport + // ownership, while thinning asks the semantic question "does any visible + // view show this PTY?" Remote view subscribers (mobile/web live terminals) + // consume raw bytes from main's fan-out, so their presence vetoes thinning + // outright. Dedupe keeps visibility-sync churn off the wire; `?? false` + // also swallows the initial + // not-background state. + const backgroundedDeliverySyncByPty = new Map() + function syncPtyBackgroundedDelivery(id: string, caller: string): void { + const background = + rendererPtyIsKnownHidden(id) && !(runtime?.hasRemoteTerminalViewSubscriber(id) ?? false) + if ((backgroundedDeliverySyncByPty.get(id) ?? false) === background) { + return + } + const provider = tryGetProviderForPty(id) + if (!provider?.setPtyBackgrounded) { + return + } + recordDaemonStreamBacklogEvent('mainBackgroundSync', { + sessionIdSuffix: id.slice(-10), + background, + caller, + known: rendererVisibilityKnownPtys.has(id), + visible: visibleRendererPtys.has(id) + }) + backgroundedDeliverySyncByPty.set(id, background) + provider.setPtyBackgrounded(id, background) + } + clearBackgroundedDeliverySyncForPty = (id: string) => { + backgroundedDeliverySyncByPty.delete(id) + } + if (runtime) { + runtime.onRemoteTerminalViewPresenceChanged = (id) => + syncPtyBackgroundedDelivery(id, 'remote-view') + } + function resyncBackgroundedDeliveriesAfterGateReset(): void { + for (const id of backgroundedDeliverySyncByPty.keys()) { + syncPtyBackgroundedDelivery(id, 'gate-reset') } - return max + } + + function getRendererInFlightCharsForPty(id: string): number { + const accounting = rendererDeliveryAccountingByPty.get(id) + return accounting ? accounting.sentChars - accounting.ackedChars : 0 } function readCurrentPtyRendererDeliveryDebugSnapshot(): PtyRendererDeliveryDebugSnapshot { @@ -1431,23 +1754,132 @@ export function registerPtyHandlers( pendingChars += chars maxPendingCharsByPty = Math.max(maxPendingCharsByPty, chars) } + const hiddenDeliveryDebug = getHiddenRendererPtyDeliveryDebug() + let rendererInFlightPtyCount = 0 + let maxRendererInFlightCharsByPty = 0 + for (const accounting of rendererDeliveryAccountingByPty.values()) { + const inFlight = accounting.sentChars - accounting.ackedChars + if (inFlight > 0) { + rendererInFlightPtyCount++ + } + maxRendererInFlightCharsByPty = Math.max(maxRendererInFlightCharsByPty, inFlight) + } + // Why: the two renderer visibility signals must agree; a pty both + // hidden-gated and reported visible means main is starving a pane the + // user can see (v1.4.124-rc.2.perf blank-terminal field lead). + let hiddenDeliveryGatedVisiblePtyCount = 0 + for (const id of visibleRendererPtys) { + if (isHiddenRendererPty(id)) { + hiddenDeliveryGatedVisiblePtyCount++ + } + } + let hiddenDeliveryGatedActivePtyCount = 0 + for (const id of activeRendererPtys) { + if (isHiddenRendererPty(id)) { + hiddenDeliveryGatedActivePtyCount++ + } + } return { pendingPtyCount: pendingData.size, pendingChars, maxPendingCharsByPty, - rendererInFlightPtyCount: rendererInFlightCharsByPty.size, + rendererInFlightPtyCount, rendererInFlightChars: rendererInFlightTotalChars, - maxRendererInFlightCharsByPty: getMaxMapValue(rendererInFlightCharsByPty.values()), + maxRendererInFlightCharsByPty, activeRendererPtyCount: activeRendererPtys.size, flushScheduled: flushTimer !== null, peakPendingChars, peakMaxPendingCharsByPty, peakRendererInFlightChars, peakMaxRendererInFlightCharsByPty, - ackGatedFlushSkipCount + ackGatedFlushSkipCount, + ...hiddenDeliveryDebug, + hiddenDeliveryGatedVisiblePtyCount, + hiddenDeliveryGatedActivePtyCount, + pendingDroppedChars, + diagnostics: buildMainDeliveryDiagnostics(), + rendererLifecycleResetCount, + lastLifecycleResetClearedChars, + rendererPtyDispatcherReady, + rendererDispatcherReadyForcedCount } } + const DELIVERY_DIAGNOSTICS_MAX_PTYS = 30 + + // Built only when the debug snapshot is actually read — never on the data + // path. Aggregate counters can't say WHICH pty is wedged or WHEN the state + // arose; this per-pty table + both-process breadcrumb history can. + function buildMainDeliveryDiagnostics(): PtyMainDeliveryDiagnostics { + const now = Date.now() + // Hidden/visible/active set members are included even with no accounting + // entry: a pty gated before its first byte is exactly the wedge case the + // table must surface. + const ids = new Set([ + ...rendererDeliveryAccountingByPty.keys(), + ...pendingData.keys(), + ...getHiddenRendererPtyIds(), + ...visibleRendererPtys, + ...activeRendererPtys + ]) + const perPty: PtyPerPtyDeliveryDiagnostics[] = [] + for (const id of ids) { + const accounting = rendererDeliveryAccountingByPty.get(id) + perPty.push({ + id: redactPtyIdForDiagnostics(id), + sentChars: accounting?.sentChars ?? 0, + ackedChars: accounting?.ackedChars ?? 0, + inFlightChars: accounting ? accounting.sentChars - accounting.ackedChars : 0, + pendingChars: pendingData.get(id)?.data.length ?? 0, + hidden: isHiddenRendererPty(id), + visible: visibleRendererPtys.has(id), + active: activeRendererPtys.has(id), + msSinceLastSend: accounting ? now - accounting.lastSendAtMs : null, + msSinceLastAck: accounting?.lastAckAtMs == null ? null : now - accounting.lastAckAtMs + }) + } + perPty.sort((a, b) => b.inFlightChars + b.pendingChars - (a.inFlightChars + a.pendingChars)) + const windowAlive = !mainWindow.isDestroyed() + return { + appVersion: app.getVersion(), + mainUptimeMs: Math.round(process.uptime() * 1000), + windowFocused: windowAlive ? mainWindow.isFocused() : null, + windowVisible: windowAlive ? mainWindow.isVisible() : null, + windowMinimized: windowAlive ? mainWindow.isMinimized() : null, + msSinceLastPowerSuspend: lastPowerSuspendAtMs === null ? null : now - lastPowerSuspendAtMs, + msSinceLastPowerResume: lastPowerResumeAtMs === null ? null : now - lastPowerResumeAtMs, + perPty: perPty.slice(0, DELIVERY_DIAGNOSTICS_MAX_PTYS), + breadcrumbs: mainDeliveryBreadcrumbs.snapshot() + } + } + + // Why rate-limited: the contradiction persists chunk after chunk while + // latched; one line per minute keeps field logs readable but present. + let lastHiddenDropContradictionWarnAtMs = 0 + function warnIfDroppingHiddenBytesForVisiblePty(id: string, droppedChars: number): void { + if (!visibleRendererPtys.has(id) && !activeRendererPtys.has(id)) { + return + } + // Recorded before the warn rate limit: the ring coalesces repeats itself, + // and the contradiction must appear in the freeze report either way. + mainDeliveryBreadcrumbs.record('hidden-drop-visible', { + id: redactPtyIdForDiagnostics(id), + droppedChars + }) + const now = Date.now() + if (now - lastHiddenDropContradictionWarnAtMs < 60_000) { + return + } + lastHiddenDropContradictionWarnAtMs = now + console.warn('[pty] hidden-delivery gate is dropping bytes for a visible/active pty', { + id, + droppedChars, + visible: visibleRendererPtys.has(id), + active: activeRendererPtys.has(id), + ...readCurrentPtyRendererDeliveryDebugSnapshot() + }) + } + function recordPtyRendererDeliveryPressure(): void { // Why: this fires on every PTY delivery event (per send, per flush, per // onData append). Update the four diagnostic peaks directly instead of @@ -1464,9 +1896,18 @@ export function registerPtyHandlers( peakPendingChars = Math.max(peakPendingChars, pendingChars) peakMaxPendingCharsByPty = Math.max(peakMaxPendingCharsByPty, maxPendingCharsByPty) peakRendererInFlightChars = Math.max(peakRendererInFlightChars, rendererInFlightTotalChars) + // Why derived per entry: this branch tracks cumulative sent/acked totals + // (TCP-style), not a per-pty in-flight map — in-flight is the difference. + let maxRendererInFlightCharsByPty = 0 + for (const accounting of rendererDeliveryAccountingByPty.values()) { + maxRendererInFlightCharsByPty = Math.max( + maxRendererInFlightCharsByPty, + accounting.sentChars - accounting.ackedChars + ) + } peakMaxRendererInFlightCharsByPty = Math.max( peakMaxRendererInFlightCharsByPty, - getMaxMapValue(rendererInFlightCharsByPty.values()) + maxRendererInFlightCharsByPty ) } @@ -1477,8 +1918,38 @@ export function registerPtyHandlers( peakRendererInFlightChars = 0 peakMaxRendererInFlightCharsByPty = 0 ackGatedFlushSkipCount = 0 + pendingDroppedChars = 0 + resetHiddenRendererPtyDeliveryDebugCounters() recordPtyRendererDeliveryPressure() } + resetRendererDeliveryAccountingForLifecycleReset = () => { + // Why: clearing pendingData is lossless — its bytes were only ever bound for + // the dead page, and the replacement page repaints each pane from main's + // authoritative sources (daemon snapshot / headless buffer / cold-restore), + // which are fed before the pendingData append so they always superset it. + lastLifecycleResetClearedChars = rendererInFlightTotalChars + rendererLifecycleResetCount += 1 + // Why: pending bytes and outstanding credits belonged to the dead page. + // Release producer pauses before clearing them so no shell stays wedged. + producerFlowControl.releaseAll() + clearDeliveryResyncProbe() + deliveryResyncUnansweredWarnLogged = false + rendererDeliveryAccountingByPty.clear() + rendererInFlightTotalChars = 0 + pendingData.clear() + pendingOverflowMarkedPtys.clear() + // Why: the reloading page's pty:data listener is gone until it re-registers + // and re-sends the handshake; hold sends until then so the boot window can't + // re-pin the gate with bytes dropped into a listener-less page. + rendererPtyDispatcherReady = false + // Why: arm the self-heal watchdog so a never-arriving handshake can't leave the + // gate held forever; the real handshake cancels it. + armDispatcherReadyWatchdog() + recordPtyRendererDeliveryPressure() + } + // Why: let a later re-registration cancel this closure's watchdog (armed via a + // hoisted fn, so this bridge assignment can precede its definition). + clearRendererDispatcherReadyWatchdog = clearDispatcherReadyWatchdog function isLikelyInteractiveRedraw(data: string): boolean { if (data.length <= INTERACTIVE_OUTPUT_MAX_CHARS) { @@ -1517,8 +1988,7 @@ export function registerPtyHandlers( id: string, data: string, startSeq: number | undefined, - containsBackgroundOutput: boolean | undefined, - droppedBacklog?: boolean + containsBackgroundOutput: boolean | undefined ): PtyDataPayload { const payload: PtyDataPayload = { id, data } if (typeof startSeq === 'number') { @@ -1528,9 +1998,6 @@ export function registerPtyHandlers( if (containsBackgroundOutput === true) { payload.background = true } - if (droppedBacklog === true) { - payload.droppedBacklog = true - } return payload } @@ -1547,15 +2014,147 @@ export function registerPtyHandlers( const ptyLimit = PTY_RENDERER_IN_FLIGHT_HIGH_WATER_CHARS + (options.interactive === true ? PTY_RENDERER_ACTIVE_PTY_IN_FLIGHT_RESERVE_CHARS : 0) - return ( - (rendererInFlightCharsByPty.get(id) ?? 0) < ptyLimit && - rendererInFlightTotalChars < totalLimit + return getRendererInFlightCharsForPty(id) < ptyLimit && rendererInFlightTotalChars < totalLimit + } + + // Why: max-merge on cumulative totals is idempotent and reorder-tolerant — + // a replayed or out-of-order ACK can never double-credit, and a lost ACK + // self-heals when any later ACK reports the full processed count. Returns + // the newly acknowledged delta so provider (SSH/daemon) backpressure is only + // credited for bytes main actually tracked in flight, never negative. + function applyCumulativeAck(id: string, processedChars: number): number { + const accounting = rendererDeliveryAccountingByPty.get(id) + if (!accounting) { + return 0 + } + // Clamped to sentChars so a corrupt payload cannot drive in-flight negative. + const nextAckedChars = Math.min( + accounting.sentChars, + Math.max(accounting.ackedChars, processedChars) ) + const acknowledged = nextAckedChars - accounting.ackedChars + accounting.ackedChars = nextAckedChars + if (acknowledged > 0) { + accounting.lastAckAtMs = Date.now() + } + rendererInFlightTotalChars = Math.max(0, rendererInFlightTotalChars - acknowledged) + return acknowledged + } + + function clearDeliveryResyncProbe(): void { + deliveryResyncOutstandingRequestId = null + if (deliveryResyncTimer) { + clearTimeout(deliveryResyncTimer) + deliveryResyncTimer = null + } + } + + // Why: event-triggered verified-state recovery. Data arriving for a fully + // gated PTY is the deterministic signal that delivery may be stuck on lost + // ACKs (e.g. dropped across a system suspend); ask the renderer for its + // authoritative processed totals instead of resetting on a wall-clock guess. + function requestDeliveryResyncForGatedPty(): void { + if (deliveryResyncOutstandingRequestId !== null || mainWindow.isDestroyed()) { + return + } + deliveryResyncRequestSerial += 1 + const requestId = deliveryResyncRequestSerial + deliveryResyncOutstandingRequestId = requestId + deliveryResyncTimer = setTimeout(() => { + if (deliveryResyncOutstandingRequestId !== requestId) { + return + } + clearDeliveryResyncProbe() + // Why: no state mutation on timeout — a renderer that cannot answer has + // dead IPC, and only a reload cures that. Log once per silent streak so + // field diagnosis is captured without spamming every probe cycle. + if (deliveryResyncUnansweredWarnLogged) { + return + } + deliveryResyncUnansweredWarnLogged = true + console.warn('[pty] delivery resync probe unanswered — renderer IPC unresponsive', { + msSinceLastAck: lastAckReceivedAtMs === null ? null : Date.now() - lastAckReceivedAtMs, + ...readCurrentPtyRendererDeliveryDebugSnapshot() + }) + }, PTY_DELIVERY_RESYNC_TIMEOUT_MS) + deliveryResyncTimer.unref?.() + mainWindow.webContents.send('pty:requestDeliveryResync', { requestId }) + } + + // Why: bytes sent but never counted received by the renderer after a + // confirmed wedge are gone — no ACK message can ever repay them (unlike a + // lost ACK, which any later cumulative total heals). Write the debt off and + // hand back restore markers so panes repaint from the main-owned snapshot; + // the caller routes them locally because push markers cannot arrive. + function writeOffLostRendererDelivery( + report: PtyRendererDeliveryStateReport + ): PtyDeliveryWriteOff[] { + const writtenOff: PtyDeliveryWriteOff[] = [] + for (const [id, accounting] of rendererDeliveryAccountingByPty) { + if (accounting.sentChars - accounting.ackedChars <= 0) { + continue + } + const received = report.receivedCharsByPty?.[id] + const receivedChars = + typeof received === 'number' && Number.isFinite(received) ? Math.max(0, received) : 0 + // Why skip a parse-pending window: received-but-unparsed bytes sit alive + // in the renderer write queue; their deferred ACK still repays this debt. + if (receivedChars > accounting.ackedChars) { + continue + } + const acknowledged = applyCumulativeAck(id, accounting.sentChars) + if (acknowledged <= 0) { + continue + } + tryGetProviderForPty(id)?.acknowledgeDataEvent(id, acknowledged) + // Why drop pending: everything at or before markerSeq comes from the + // snapshot (hidden-drop parity); flushing pre-marker bytes afterward + // would double-paint what the restore already covers. + const pending = pendingData.get(id) + if (pending) { + pendingDroppedChars += pending.data.length + pendingData.delete(id) + pendingOverflowMarkedPtys.delete(id) + updateProducerFlowControl(id) + } + const markerSeq = runtime?.getPtyOutputSequence(id) + writtenOff.push({ + id, + ...(typeof markerSeq === 'number' ? { markerSeq } : {}), + writtenOffChars: acknowledged + }) + } + if (writtenOff.length > 0) { + clearDeliveryResyncProbe() + deliveryResyncUnansweredWarnLogged = false + mainDeliveryBreadcrumbs.record('delivery-heal-writeoff', { + writtenOffPtyCount: writtenOff.length, + writtenOffChars: writtenOff.reduce((sum, { writtenOffChars }) => sum + writtenOffChars, 0) + }) + console.warn('[pty] delivery heal: wrote off renderer-bound bytes lost in push channel', { + rendererPtyDataListenerCount: report.rendererPtyDataListenerCount ?? null, + msSinceLastAck: lastAckReceivedAtMs === null ? null : Date.now() - lastAckReceivedAtMs, + writtenOffByPty: writtenOff.map(({ id, writtenOffChars }) => ({ id, writtenOffChars })), + ...readCurrentPtyRendererDeliveryDebugSnapshot() + }) + } + return writtenOff } function sendPtyDataToRenderer(id: string, payload: PtyDataPayload): void { const charCount = getPtyPayloadCharCount(payload) - rendererInFlightCharsByPty.set(id, (rendererInFlightCharsByPty.get(id) ?? 0) + charCount) + const accounting = rendererDeliveryAccountingByPty.get(id) + if (accounting) { + accounting.sentChars += charCount + accounting.lastSendAtMs = Date.now() + } else { + rendererDeliveryAccountingByPty.set(id, { + sentChars: charCount, + ackedChars: 0, + lastSendAtMs: Date.now(), + lastAckAtMs: null + }) + } rendererInFlightTotalChars += charCount recordPtyRendererDeliveryPressure() mainWindow.webContents.send('pty:data', payload) @@ -1588,6 +2187,26 @@ export function registerPtyHandlers( deliveredHiddenRendererResizeOutputPtys.delete(id) } + // Why: when main drops renderer delivery (hidden gate / pending cap), an + // explicit out-of-band pty:modelRestoreNeeded signal tells the renderer to + // latch model-restore-needed. It must NOT ride pty:data: an in-band empty + // chunk is indistinguishable from a chunk fully consumed by renderer-side + // OSC-9999 stripping, which spuriously restored visible panes. + function sendModelRestoreNeededMarker( + id: string, + reason: PtyModelRestoreReason, + markerSeq: number | undefined + ): void { + if (mainWindow.isDestroyed()) { + return + } + mainWindow.webContents.send('pty:modelRestoreNeeded', { + id, + reason, + ...(typeof markerSeq === 'number' ? { markerSeq } : {}) + }) + } + function getPendingPtyFlushEntries(): [string, PendingPtyData][] { const entries = Array.from(pendingData.entries()) const active: [string, PendingPtyData][] = [] @@ -1602,60 +2221,106 @@ export function registerPtyHandlers( return [...active, ...background] } - // Why: bound the unsent backlog to the most-recent PENDING_DATA_MAX_CHARS, - // advancing startSeq by the dropped-char count (same arithmetic flushPendingData - // uses when it slices) so the remaining tail's seq stays correct. Flags - // droppedBacklog so the next payload tells the renderer to rebuild the dropped - // span from the main headless snapshot. A no-op when under the cap (the common - // case: the renderer is ACKing and pendingData stays tiny). - function capPendingPtyData(pending: PendingPtyData): PendingPtyData { - if (pending.data.length <= PENDING_DATA_MAX_CHARS) { + const pendingDataDropWarnedPtys = new Set() + + // Why capped: the drop path guarantees O(1) memory per PTY; salvaged query + // bytes are tiny (a DSR probe is 4 chars) and anything past the cap means a + // pathological stream, where degrading to the plain sentinel is fine. + const DROPPED_QUERY_SALVAGE_MAX_CHARS = 4096 + + // Why: a bulk drop must not swallow reply-eliciting queries embedded in the + // flood (DSR 6n / CPR, DA1/DA2, DECRQM, OSC 10/11 probes). The program that + // wrote them blocks on the reply (the bench DSR timeout). Carve just the + // query bytes out and let them ride the droppedOutput sentinel — content is + // healed by the snapshot restore, so replies cannot double-fire. + function extractDroppedPtyQueryBytes(data: string): string { + if (!data.includes('\x1b')) { + return '' + } + const extracted = extractHiddenStartupRendererQueryData(data, '') + return extracted.statelessQueryData + extracted.statefulQueryData + extracted.oscColorQueryData + } + + function dropOversizedPendingPtyData(id: string, pending: PendingPtyData): PendingPtyData { + const capChars = pendingDataCapChars() + if (pending.droppedOutput === true || pending.data.length <= capChars) { return pending } - const trimmed = pending.data.slice(pending.data.length - PENDING_DATA_MAX_CHARS) - const droppedChars = pending.data.length - trimmed.length - const next: PendingPtyData = { data: trimmed, droppedBacklog: true } - if (typeof pending.startSeq === 'number') { - next.startSeq = pending.startSeq + droppedChars + if (!pendingDataDropWarnedPtys.has(id)) { + pendingDataDropWarnedPtys.add(id) + console.error( + `[pty] dropped ${pending.data.length} buffered chars for ${id}: renderer not receiving and per-PTY pending cap exceeded; pane will restore from the main-owned snapshot` + ) + // Why: field visibility for cap tuning — drop frequency and size decide + // whether the cap is too small (issue #2836 / #7017). No pty id: session + // ids can embed workspace paths. + recordCrashBreadcrumb('terminal_pending_output_dropped', { + droppedChars: pending.data.length, + capChars + }) + } + // Why: with the hidden-delivery gate rolled out, the model snapshot can + // recover the dropped middle — emit the out-of-band restore marker once + // per overflow episode alongside the droppedOutput sentinel so a fresh + // or reloaded view latches restore too. + if (isHiddenPtyDeliveryGateEnabled(getSettings?.()) && !pendingOverflowMarkedPtys.has(id)) { + pendingOverflowMarkedPtys.add(id) + sendModelRestoreNeededMarker(id, 'pending-cap', runtime?.getPtyOutputSequence(id)) } - if (pending.containsBackgroundOutput === true) { - next.containsBackgroundOutput = true + pendingDroppedChars += pending.data.length + // Why no trimmed content tail: a mid-stream gap would silently corrupt + // the pane. The droppedOutput sentinel routes the pane through + // hidden-output restore, which repaints from the authoritative main-owned + // buffer and realigns with the live stream by sequence. Only carved-out + // query bytes ride along so their replies survive the drop. + return { + data: extractDroppedPtyQueryBytes(pending.data).slice(0, DROPPED_QUERY_SALVAGE_MAX_CHARS), + droppedOutput: true } - return next } function appendPendingPtyData( + id: string, existing: PendingPtyData | undefined, data: string, startSeq: number | undefined, preservesSeq: boolean, containsBackgroundOutput: boolean ): PendingPtyData { + // Why: once over the cap, stay dropped at O(1) memory until the renderer + // can receive again — the restore sentinel supersedes any interim bytes. + // Queries arriving while latched still get carved out (bounded) so their + // replies survive the whole drop episode, not just the first burst. + if (existing?.droppedOutput === true) { + if (existing.data.length >= DROPPED_QUERY_SALVAGE_MAX_CHARS) { + return existing + } + const salvaged = extractDroppedPtyQueryBytes(data) + return salvaged ? { ...existing, data: existing.data + salvaged } : existing + } const nextContainsBackgroundOutput = existing?.containsBackgroundOutput === true || containsBackgroundOutput - // Carry a prior drop flag forward until it actually rides an outgoing payload. - const inheritedDropped = existing?.droppedBacklog === true - const base: PendingPtyData = { data: '' } if (!preservesSeq) { - base.data = (existing?.data ?? '') + data - } else if (!existing) { - base.data = data - if (typeof startSeq === 'number') { - base.startSeq = startSeq - } - } else { - base.data = existing.data + data - if (typeof existing.startSeq === 'number') { - base.startSeq = existing.startSeq - } + return dropOversizedPendingPtyData(id, { + data: (existing?.data ?? '') + data, + ...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {}) + }) + } + if (!existing) { + return dropOversizedPendingPtyData(id, { + data, + ...(typeof startSeq === 'number' ? { startSeq } : {}), + ...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {}) + }) } - if (nextContainsBackgroundOutput) { - base.containsBackgroundOutput = true + const next: PendingPtyData = { + data: existing.data + data, + ...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {}) } - if (inheritedDropped) { - base.droppedBacklog = true + if (typeof existing.startSeq === 'number') { + next.startSeq = existing.startSeq } - return capPendingPtyData(base) + return dropOversizedPendingPtyData(id, next) } function schedulePendingDataFlush(delayMs: number): void { @@ -1665,24 +2330,88 @@ export function registerPtyHandlers( flushTimer = setTimeout(flushPendingData, delayMs) } + function clearDispatcherReadyWatchdog(): void { + if (dispatcherReadyWatchdogTimer) { + clearTimeout(dispatcherReadyWatchdogTimer) + dispatcherReadyWatchdogTimer = null + } + } + + function armDispatcherReadyWatchdog(): void { + clearDispatcherReadyWatchdog() + if (mainWindow.isDestroyed()) { + return + } + // Why: one-shot self-heal — if the reloaded page never signals ready, force the + // gate open so a dropped handshake degrades to pre-handshake behavior (bounded + // duplicate/overwrite at worst) instead of a permanent hold. Unref'd so it can + // never keep the process alive. + dispatcherReadyWatchdogTimer = setTimeout(() => { + dispatcherReadyWatchdogTimer = null + if (rendererPtyDispatcherReady || mainWindow.isDestroyed()) { + return + } + rendererPtyDispatcherReady = true + rendererDispatcherReadyForcedCount += 1 + schedulePendingDataFlush(0) + }, PTY_DISPATCHER_READY_WATCHDOG_MS) + dispatcherReadyWatchdogTimer.unref?.() + } + function flushPendingData(): void { flushTimer = null if (mainWindow.isDestroyed()) { + // Why: the bookkeeping is being wiped, so no future drain can ever + // resume these producers — release them now or local shells wedge. + producerFlowControl.releaseAll() + clearDeliveryResyncProbe() pendingData.clear() - rendererInFlightCharsByPty.clear() + pendingOverflowMarkedPtys.clear() + rendererDeliveryAccountingByPty.clear() rendererInFlightTotalChars = 0 + clearDispatcherReadyWatchdog() recordPtyRendererDeliveryPressure() return } + // Why: hold sends until the page's pty:data listener is registered. Bytes + // keep accruing in pendingData (2 MB cap + droppedBacklog rebuild it + // losslessly); the ready handshake reschedules this flush. + if (!rendererPtyDispatcherReady) { + return + } + const settings = getSettings?.() let writes = 0 for (const [id, pending] of getPendingPtyFlushEntries()) { if (writes >= PTY_BATCH_FLUSH_MAX_WRITES) { break } + // Why: hidden-gated bytes are dropped, never re-queued — the model + // already ingested them; reveal restores from the snapshot+seq machinery. + if (shouldDropHiddenRendererPtyData(id, settings)) { + pendingData.delete(id) + pendingOverflowMarkedPtys.delete(id) + updateProducerFlowControl(id) + const drop = recordHiddenRendererPtyDataDrop(id, pending.data.length) + warnIfDroppingHiddenBytesForVisiblePty(id, pending.data.length) + if (drop.shouldEmitRestoreMarker) { + sendModelRestoreNeededMarker(id, 'hidden-drop', runtime?.getPtyOutputSequence(id)) + } + continue + } if (!canSendPtyDataToRenderer(id, { interactive: activeRendererPtys.has(id) })) { continue } pendingData.delete(id) + if (pending.droppedOutput === true) { + updateProducerFlowControl(id) + // Why: the buffered bytes were dropped at the pending cap; tell the + // renderer so the pane repaints from the main-owned buffer snapshot + // instead of continuing a stream with a silent gap. data carries only + // the carved-out query bytes (see extractDroppedPtyQueryBytes). + sendPtyDataToRenderer(id, { id, data: pending.data, droppedOutput: true }) + writes++ + continue + } const { data } = pending const chunk = data.slice(0, PTY_BATCH_FLUSH_CHUNK_CHARS) const remaining = data.slice(PTY_BATCH_FLUSH_CHUNK_CHARS) @@ -1695,19 +2424,13 @@ export function registerPtyHandlers( nextPending.containsBackgroundOutput = true } pendingData.set(id, nextPending) + } else { + pendingOverflowMarkedPtys.delete(id) } - // Why: the drop flag rides the first emitted chunk (renderer restore is - // idempotent) and is intentionally not copied onto `remaining` above, so a - // single backlog trim signals the renderer exactly once. + updateProducerFlowControl(id) sendPtyDataToRenderer( id, - makePtyDataPayload( - id, - chunk, - pending.startSeq, - pending.containsBackgroundOutput, - pending.droppedBacklog - ) + makePtyDataPayload(id, chunk, pending.startSeq, pending.containsBackgroundOutput) ) writes++ } @@ -1765,25 +2488,40 @@ export function registerPtyHandlers( // tears down the terminal on pty:exit before the batch timer fires. const remaining = pendingData.get(payload.id) if (remaining) { - sendPtyDataToRenderer( - payload.id, - makePtyDataPayload( + if (remaining.droppedOutput === true) { + // Sentinel entry: only salvaged query bytes remain; keep the flag so + // the renderer knows the span was dropped (same as the flush loop). + sendPtyDataToRenderer(payload.id, { + id: payload.id, + data: remaining.data, + droppedOutput: true + }) + } else { + sendPtyDataToRenderer( payload.id, - remaining.data, - remaining.startSeq, - remaining.containsBackgroundOutput, - remaining.droppedBacklog + makePtyDataPayload( + payload.id, + remaining.data, + remaining.startSeq, + remaining.containsBackgroundOutput + ) ) - ) + } pendingData.delete(payload.id) } + // Why: exit drops this PTY's bookkeeping; resume (no-op on a dead PTY) + // rather than leave a stale paused mark behind for a reused id. + producerFlowControl.release(payload.id) + pendingOverflowMarkedPtys.delete(payload.id) lastInputAtByPty.delete(payload.id) interactiveOutputCharsByPty.delete(payload.id) rendererInFlightTotalChars = Math.max( 0, - rendererInFlightTotalChars - (rendererInFlightCharsByPty.get(payload.id) ?? 0) + rendererInFlightTotalChars - getRendererInFlightCharsForPty(payload.id) ) - rendererInFlightCharsByPty.delete(payload.id) + // Why: the renderer also drops its cumulative total on pty:exit, so a + // reused id restarts aligned at zero on both sides. + rendererDeliveryAccountingByPty.delete(payload.id) recordPtyRendererDeliveryPressure() mainWindow.webContents.send('pty:exit', payload) } @@ -1814,6 +2552,35 @@ export function registerPtyHandlers( const bindProviderListeners = (): void => { localDataUnsub?.() localExitUnsub?.() + localBackgroundStreamUnsub?.() + + // Keep-tail thinning facts from the daemon, in byte order with onData. + // The marker flips scan authority for the four transient-fact scanners; + // a gap resets main's cross-chunk parse state and forces the renderer to + // restore from the model snapshot (same seq-guard path as hidden drops) + // in case any view — eager buffer included — was receiving bytes. + localBackgroundStreamUnsub = + localProvider.onBackgroundStreamEvent?.((payload) => { + if (payload.kind === 'backgroundMarker') { + runtime?.setPtyTransientFactDelegation( + payload.id, + payload.background, + payload.scanSeedAnsi + ) + return + } + if (payload.kind === 'dataGap') { + providerSnapshotRequiredPtys.add(payload.id) + runtime?.notePtyDataGap(payload.id, payload.sequenceChars ?? payload.droppedChars) + sendModelRestoreNeededMarker( + payload.id, + 'hidden-drop', + runtime?.getPtyOutputSequence(payload.id) + ) + return + } + runtime?.emitDaemonPtyTransientFact(payload.id, payload.fact) + }) ?? null // Why: LocalPtyProvider routes data to the runtime via configure().onData, // but daemon-backed providers don't have configure(). Without this, daemon @@ -1826,9 +2593,16 @@ export function registerPtyHandlers( localDataUnsub = localProvider.onData((payload) => { const outputSeq = isLocalProvider ? runtime?.getPtyOutputSequence(payload.id) - : runtime?.onPtyData(payload.id, payload.data, Date.now()) + : runtime?.onPtyData( + payload.id, + payload.data, + Date.now(), + payload.sequenceChars ?? payload.data.length + ) const rendererData = answerStartupTerminalColorQueriesForPty(payload.id, payload.data) - const preservesSeq = rendererData === payload.data + const preservesSeq = + rendererData === payload.data && + (payload.sequenceChars === undefined || payload.sequenceChars === payload.data.length) const startSeq = preservesSeq ? getChunkStartSeq(outputSeq, payload.data) : undefined if (mainWindow.isDestroyed()) { // Why: clear the pending flush timer so it doesn't fire after the window @@ -1838,12 +2612,30 @@ export function registerPtyHandlers( clearTimeout(flushTimer) flushTimer = null } + producerFlowControl.releaseAll() + clearDeliveryResyncProbe() pendingData.clear() - rendererInFlightCharsByPty.clear() + pendingOverflowMarkedPtys.clear() + rendererDeliveryAccountingByPty.clear() rendererInFlightTotalChars = 0 + clearDispatcherReadyWatchdog() recordPtyRendererDeliveryPressure() return } + const settings = getSettings?.() + // Why: hidden-delivery gate — runtime ingestion above already consumed + // the chunk; gated renderer delivery is DROPPED (never queued) and the + // reveal path restores from the model snapshot via the seq guard. The + // drop sits before the interactive bypass so gated PTYs take neither + // the immediate nor the batched renderer path. + if (shouldDropHiddenRendererPtyData(payload.id, settings)) { + const drop = recordHiddenRendererPtyDataDrop(payload.id, payload.data.length) + warnIfDroppingHiddenBytesForVisiblePty(payload.id, payload.data.length) + if (drop.shouldEmitRestoreMarker) { + sendModelRestoreNeededMarker(payload.id, 'hidden-drop', outputSeq) + } + return + } if (rendererData.length === 0) { return } @@ -1854,6 +2646,7 @@ export function registerPtyHandlers( } const existing = pendingData.get(payload.id) const pending = appendPendingPtyData( + payload.id, existing, rendererData, startSeq, @@ -1866,16 +2659,23 @@ export function registerPtyHandlers( nextData, performance.now() ) - if (isInteractiveOutput) { + // Why: gate the interactive fast path on the dispatcher handshake too, so + // boot-window keystroke echo accrues in pendingData instead of being sent + // into a listener-less page and pinning the gate. + if (isInteractiveOutput && rendererPtyDispatcherReady) { // Why: user-input echo should not be pinned behind unrelated bulk // terminal output already handed to the renderer. The reserve is // bounded, and the per-PTY cap still prevents an active TUI runaway. if (!canSendPtyDataToRenderer(payload.id, { interactive: true })) { + requestDeliveryResyncForGatedPty() pendingData.set(payload.id, pending) + updateProducerFlowControl(payload.id) recordPtyRendererDeliveryPressure() return } pendingData.delete(payload.id) + updateProducerFlowControl(payload.id) + pendingOverflowMarkedPtys.delete(payload.id) clearFlushTimerIfIdle() // Why: agent TUIs redraw small prompt regions after every keystroke. // Waiting for the throughput batch timer adds visible input latency. @@ -1886,12 +2686,20 @@ export function registerPtyHandlers( ? { seq: pending.startSeq + nextData.length, rawLength: nextData.length } : {}), ...(pending.containsBackgroundOutput === true ? { background: true } : {}), - ...(pending.droppedBacklog === true ? { droppedBacklog: true } : {}) + ...(pending.droppedOutput === true ? { droppedOutput: true } : {}) }) return } pendingData.set(payload.id, pending) + updateProducerFlowControl(payload.id) recordPtyRendererDeliveryPressure() + // Why: probe on data arrival, not on flush skips — new output for a + // fully gated PTY is the moment stuck delivery becomes observable. + if ( + !canSendPtyDataToRenderer(payload.id, { interactive: activeRendererPtys.has(payload.id) }) + ) { + requestDeliveryResyncForGatedPty() + } if (!flushTimer) { schedulePendingDataFlush(PTY_BATCH_INTERVAL_MS) } @@ -1999,6 +2807,28 @@ export function registerPtyHandlers( }) } + // Why: a reload (did-finish-load) or renderer crash replaces the process + // that owned every delivery-interest hold and hidden mark; surviving + // daemon/SSH PTYs would otherwise stay force-fed (leaked interest defeats + // the gate) or stay gated against a renderer that never marked them. Drop + // memory is preserved — each pane's first sync re-marks/unmarks and the + // unmark path re-emits the restore marker for unrestored drops. + clearRendererGateResetHandlers() + rendererGateResetLoadHandler = () => { + resetRendererScopedHiddenPtyDeliveryState() + // Why: the daemon pacer must not keep throttling ptys whose hidden marks + // died with the renderer; the fresh renderer's first visibility sync + // re-marks the ones that are still hidden. + resyncBackgroundedDeliveriesAfterGateReset() + } + rendererGateResetGoneHandler = () => { + resetRendererScopedHiddenPtyDeliveryState() + resyncBackgroundedDeliveriesAfterGateReset() + } + rendererGateResetWebContents = mainWindow.webContents + mainWindow.webContents.on('did-finish-load', rendererGateResetLoadHandler) + mainWindow.webContents.on('render-process-gone', rendererGateResetGoneHandler) + // Kill orphaned PTY processes from previous page loads when the renderer reloads. // Why: only applies to LocalPtyProvider where PTYs live in the Electron main // process and can become orphaned on page reload. Daemon-backed sessions @@ -2043,21 +2873,33 @@ export function registerPtyHandlers( assertFolderWorkspacePathUsable(status) } - const resolveGuardedPtySpawnCwd = ( + const resolvePtySpawnStartupCwd = ( worktreeId: string | undefined, cwd: string | undefined, - connectionId?: string | null + missingDirFallback?: TerminalStartupCwdMissingDirFallback ): string | undefined => resolveTerminalStartupCwdForWorkspace({ workspaceId: worktreeId, requestedCwd: cwd, + missingDirFallback, resolveFolderWorkspacePath: (folderWorkspaceId) => - store?.getFolderWorkspace(folderWorkspaceId)?.folderPath, - // Why: realpath only makes sense on the local filesystem; SSH worktree - // paths live on the remote host. - canonicalizePath: localTerminalCwdCanonicalizer(connectionId) + store?.getFolderWorkspace(folderWorkspaceId)?.folderPath }) + const localStartupCwdDirectoryExists = (path: string): boolean => { + // Why: Win32 statSync on \\wsl.localhost 9P shares can falsely report + // ENOENT for directories that exist on the Linux side; never fall back on + // that signal — the provider's WSL-aware validation decides instead. + if (isWslUncPath(path)) { + return true + } + try { + return statSync(path).isDirectory() + } catch { + return false + } + } + // Why: the runtime controller must route through getProviderForPty() so that // CLI commands (terminal.send, terminal.stop) work for both local and remote PTYs. // Hardcoding localProvider.getPtyProcess() would silently fail for remote PTYs. @@ -2068,7 +2910,7 @@ export function registerPtyHandlers( await startupPromise } await assertFolderWorkspacePtyPathUsable(args.worktreeId) - const cwd = resolveGuardedPtySpawnCwd(args.worktreeId, args.cwd, args.connectionId) + const cwd = resolvePtySpawnStartupCwd(args.worktreeId, args.cwd) const provider = getProvider(args.connectionId) const isClaudeLaunch = !args.connectionId && isClaudeLaunchCommand(args.command) if (isClaudeLaunch && isClaudeAuthSwitchInProgress()) { @@ -2172,6 +3014,7 @@ export function registerPtyHandlers( launchCommand: args.command, shellPath: daemonShellOverride ?? process.env.COMSPEC, isWsl: shouldSkipCodexHomeEnvForWindowsShell(daemonShellOverride, cwd), + wslDistro: codexSelectionTarget.runtime === 'wsl' ? codexSelectionTarget.wslDistro : null, agentStatusHooksEnabled: isAgentStatusHooksEnabled(getSettings?.()), networkProxySettings: getSettings?.() }) @@ -2300,6 +3143,18 @@ export function registerPtyHandlers( } } ptyOwnership.set(result.id, args.connectionId ?? null) + // Why: Phase-5 ConPTY DA1 — record the native-Windows-local-PTY + // determination from the spawn record before any byte reaches the + // runtime emulator, so its DA1 override exists from byte zero. + if ( + isNativeWindowsLocalPtySpawn({ + connectionId: args.connectionId, + cwd: args.cwd, + shellOverride: daemonShellOverride + }) + ) { + markNativeWindowsConptyPty(result.id) + } const relayResultId = getRelayPtyId(args.connectionId, result.id) const persistSshLease = (): void => { if (!store || !args.connectionId) { @@ -2354,8 +3209,25 @@ export function registerPtyHandlers( runtime?.registerPreAllocatedHandleForPty(result.id, args.preAllocatedHandle) } if (args.worktreeId) { - runtime?.registerPty(result.id, args.worktreeId, args.connectionId ?? null) + runtime?.registerPty( + result.id, + args.worktreeId, + args.connectionId ?? null, + // Why: thread the validated pane identity so main can back a pending + // mobile create from this live spawn even if graph-sync stalls (#7587). + // Bound tabId like the sibling metadataPaneKey/spawnOptions.tabId here. + typeof args.tabId === 'string' && + isValidTerminalTabId(args.tabId) && + args.tabId.length <= 512 && + metadataLeafId !== null + ? { tabId: args.tabId, leafId: metadataLeafId } + : undefined + ) } + // Why: arms main's per-PTY Command Code output detector from the launch + // command (renderer startupCommand parity); banner detection covers + // PTYs spawned without one. + runtime?.noteTerminalSpawnCommand?.(result.id, args.command ?? null) if (isClaudeLaunch) { markClaudePtySpawned(result.id) } @@ -2604,21 +3476,72 @@ export function registerPtyHandlers( cwd?: string | null lastTitle?: string seq?: number + pendingDeliveryStartSeq?: number source?: 'headless' | 'renderer' alternateScreen?: boolean + scrollbackAnsi?: string + pendingEscapeTailAnsi?: string } | null> => { if (!runtime || typeof args?.id !== 'string' || args.id.length === 0) { return null } const scrollbackRows = normalizeSnapshotScrollbackRows(args.opts?.scrollbackRows) try { - return await runtime.serializeHiddenOutputRecoveryBuffer(args.id, { scrollbackRows }) + const runtimeSeqBeforeSnapshot = runtime.getPtyOutputSequence(args.id) + const providerSnapshotRequired = providerSnapshotRequiredPtys.has(args.id) + const providerSnapshot = providerSnapshotRequired + ? await tryGetProviderForPty(args.id)?.getBufferSnapshot?.(args.id, { + scrollbackRows + }) + : null + // Why: after a data gap, main's model contains only the retained tail. + // Returning it as a full snapshot would silently erase older scrollback. + if (providerSnapshotRequired && !providerSnapshot) { + return null + } + const snapshot = + providerSnapshot ?? + (await runtime.serializeHiddenOutputRecoveryBuffer(args.id, { + scrollbackRows + })) + if (!snapshot || typeof snapshot.seq !== 'number') { + return snapshot + } + // Why: sampled after serialize — every byte at or below snapshot.seq + // that can still reach the renderer sits in this pending queue. The + // renderer's post-restore dedupe bounds its duplicate window with it; + // without the bound a stale baseline silently swallows genuinely-new + // chunks whose seq domain sits below the snapshot counter. + const pending = pendingData.get(args.id) + if (pending && typeof pending.startSeq !== 'number') { + // Why: a seq-less backlog cannot be bounded — stay conservative. + return snapshot + } + return { + ...snapshot, + pendingDeliveryStartSeq: Math.min( + pending?.startSeq ?? (providerSnapshot ? runtimeSeqBeforeSnapshot : snapshot.seq), + snapshot.seq + ) + } } catch { return null } } ) + // Why: with main holding side-effect authority the renderer no longer + // derives titles from replayed bytes on (re)attach. This title-only replay + // snapshot restores title state — never historical bells/completions (the + // no-attention-replay rule, terminal-side-effect-authority.md). + ipcMain.handle('pty:sideEffectSnapshot', (_event, args: { id: string }) => { + if (!runtime || typeof args?.id !== 'string' || args.id.length === 0) { + return null + } + return runtime.getTerminalSideEffectSnapshot(args.id) + }) + + installPowerSignalBreadcrumbs() ipcMain.handle('pty:getRendererDeliveryDebugSnapshot', (): PtyRendererDeliveryDebugSnapshot => { return getPtyRendererDeliveryDebugSnapshot() }) @@ -2634,6 +3557,10 @@ export function registerPtyHandlers( cols: number rows: number cwd?: string + // Why: fresh local renderer spawns opt into recovering a saved cwd + // whose directory was deleted (#7239); reattach/remote callers must + // keep exact cwd semantics, so the flag alone is not sufficient. + cwdFallback?: 'worktree' env?: Record envToDelete?: string[] command?: string @@ -2650,6 +3577,11 @@ export function registerPtyHandlers( foreground?: unknown background?: unknown } + // Why: hidden-at-spawn declaration (terminal-query-authority.md + // §races) — the renderer knows at spawn time that no visible view + // will consume this PTY's bytes, so main marks it hidden BEFORE the + // first byte and the gate + model responder own spawn-time queries. + initiallyHidden?: boolean // Why: closes the SIGKILL race documented in INVESTIGATION.md by // letting main patch + sync-flush the (worktreeId, tabId, leafId → // ptyId) binding before pty:spawn returns. Only the renderer's @@ -2677,7 +3609,26 @@ export function registerPtyHandlers( await startupPromise } await assertFolderWorkspacePtyPathUsable(args.worktreeId) - const cwd = resolveGuardedPtySpawnCwd(args.worktreeId, args.cwd, args.connectionId) + // Why: honor the fallback only for fresh local spawns even if a caller + // sends the flag — reattach must keep the session's exact cwd and + // remote/SSH paths cannot probe the local filesystem meaningfully. + const allowMissingCwdFallback = + !args.connectionId && !args.sessionId && args.cwdFallback === 'worktree' + let didFallbackToWorkspaceRootCwd = false + const cwd = resolvePtySpawnStartupCwd( + args.worktreeId, + args.cwd, + allowMissingCwdFallback + ? { + directoryExists: localStartupCwdDirectoryExists, + onFallbackToWorkspaceRoot: () => { + didFallbackToWorkspaceRootCwd = true + } + } + : undefined + ) + const startupCwdFallback = + didFallbackToWorkspaceRootCwd && cwd ? ({ kind: 'worktree', cwd } as const) : undefined spawnTiming.mark('preflight') const provider = getProvider(args.connectionId) const isClaudeLaunch = !args.connectionId && isClaudeLaunchCommand(args.command) @@ -2908,6 +3859,8 @@ export function registerPtyHandlers( launchCommand: args.command, shellPath: effectiveShellOverride ?? process.env.COMSPEC, isWsl: shouldSkipCodexHomeEnvForWindowsShell(effectiveShellOverride, cwd), + wslDistro: + codexSelectionTarget.runtime === 'wsl' ? codexSelectionTarget.wslDistro : null, agentStatusHooksEnabled: isAgentStatusHooksEnabled(getSettings?.()), networkProxySettings: getSettings?.() }) @@ -2965,6 +3918,9 @@ export function registerPtyHandlers( if (args.startupCommandDelivery !== undefined) { spawnOptions.startupCommandDelivery = args.startupCommandDelivery } + if (isTuiAgent(args.launchAgent)) { + spawnOptions.launchAgent = args.launchAgent + } if (args.worktreeId !== undefined) { spawnOptions.worktreeId = args.worktreeId } @@ -3018,6 +3974,20 @@ export function registerPtyHandlers( return await existingPaneSpawn.promise } const paneSpawnReservation = reservationPaneKey ? reservePaneSpawn(reservationPaneKey) : null + const initiallyHidden = args.initiallyHidden === true + // Why pre-spawn for daemon-host sessions (id minted up front): daemon + // PTYs can emit prompt bytes before spawn() resolves, and the hidden + // mark must beat the first byte so the gate + model responder own + // spawn-time queries (terminal-query-authority.md §races). Other + // providers cannot emit until spawn resolves; the post-spawn mark + // below is byte-zero-safe for them. + const preSpawnHiddenMarkId = + initiallyHidden && isDaemonHostSpawn && effectiveSessionAppId !== undefined + ? effectiveSessionAppId + : null + if (preSpawnHiddenMarkId !== null) { + markHiddenRendererPty(preSpawnHiddenMarkId) + } let result: PtySpawnResult try { try { @@ -3036,6 +4006,11 @@ export function registerPtyHandlers( result = await provider.spawn(spawnOptions) spawnTiming.mark('provider_spawn') } catch (err) { + // Why: a failed spawn must not leave a stale hidden mark on a session + // id a later visible attach may reuse. + if (preSpawnHiddenMarkId !== null) { + unmarkHiddenRendererPty(preSpawnHiddenMarkId) + } const rawMessage = err instanceof Error ? err.message : String(err) const spawnError = normalizeNodePtySpawnError(err) const isIdentityMismatch = @@ -3108,6 +4083,34 @@ export function registerPtyHandlers( reattach: result.isReattach ?? false }) ptyOwnership.set(result.id, args.connectionId ?? null) + if (initiallyHidden) { + // Why marked synchronously before any await below: local/SSH provider + // data events dispatch on later tasks, so this is still ahead of the + // first byte's delivery decision. Idempotent for daemon hosts already + // marked pre-spawn; the renderer's first visibility sync re-marks or + // unmarks (emitting the restore marker) through the Phase-4 path. + markHiddenRendererPty(result.id) + if (preSpawnHiddenMarkId !== null && preSpawnHiddenMarkId !== result.id) { + // Defense: never strand a mark on an id the provider renamed. + unmarkHiddenRendererPty(preSpawnHiddenMarkId) + } + // Why after ptyOwnership.set: the provider lookup routes by + // ownership, and a hidden-spawned agent should be paceable from its + // first flood, not from its first visibility transition. + syncPtyBackgroundedDelivery(result.id, 'spawn') + } + // Why: Phase-5 ConPTY DA1 — record the native-Windows-local-PTY + // determination from the spawn record before the headless seed below, + // so the runtime emulator's DA1 override exists from byte zero. + if ( + isNativeWindowsLocalPtySpawn({ + connectionId: args.connectionId, + cwd: args.cwd, + shellOverride: effectiveShellOverride + }) + ) { + markNativeWindowsConptyPty(result.id) + } if (startupTerminalColorQueryReplyColors) { if (result.isReattach) { if (preSpawnStartupTerminalColorReplyPtyId) { @@ -3216,7 +4219,18 @@ export function registerPtyHandlers( ? { cols: result.snapshotCols, rows: result.snapshotRows } : undefined if (typeof result.snapshot === 'string' && result.snapshot.length > 0) { - runtime.seedHeadlessTerminal(result.id, result.snapshot, seedSize) + // Why kitty flags ride seed metadata: the snapshot string omits + // them by design (renderer kitty reset stays authoritative), but + // the re-seeded emulator must answer hidden `CSI ? u` with the + // flags the still-running app pushed (terminal-query-authority.md). + runtime.seedHeadlessTerminal( + result.id, + result.snapshot, + seedSize, + typeof result.snapshotKittyKeyboardFlags === 'number' + ? { kittyKeyboardFlags: result.snapshotKittyKeyboardFlags } + : {} + ) } else if ( result.coldRestore && typeof result.coldRestore.scrollback === 'string' && @@ -3233,8 +4247,29 @@ export function registerPtyHandlers( args.worktreeId.length > 0 && args.worktreeId.length <= 512 ) { - runtime?.registerPty(result.id, args.worktreeId, args.connectionId ?? null) + runtime?.registerPty( + result.id, + args.worktreeId, + args.connectionId ?? null, + // Why: pass the validated pane identity so a mobile create waiting on + // this renderer tab can publish its surface main-side when graph-sync + // is throttled, instead of destroying the live PTY (#7587). Bound the + // untrusted tabId like the sibling metadataPaneKey/spawnOptions.tabId. + typeof args.tabId === 'string' && + isValidTerminalTabId(args.tabId) && + args.tabId.length <= 512 && + metadataLeafId !== null + ? { tabId: args.tabId, leafId: metadataLeafId } + : undefined + ) } + // Why: arms main's per-PTY Command Code output detector from the launch + // command (renderer startupCommand parity); banner detection covers + // PTYs spawned without one. + runtime?.noteTerminalSpawnCommand?.( + result.id, + typeof args.command === 'string' ? args.command : null + ) if (isClaudeLaunch) { markClaudePtySpawned(result.id) } @@ -3325,7 +4360,10 @@ export function registerPtyHandlers( ...result, ...(!result.isReattach && effectiveLaunchConfig ? { launchConfig: effectiveLaunchConfig } - : {}) + : {}), + // Why: a daemon-retry race can surface isReattach even for a minted + // session id, and a reattach must never claim its cwd was remapped. + ...(startupCwdFallback && !result.isReattach ? { startupCwdFallback } : {}) } return resolvePaneSpawnReservation(reservationPaneKey, paneSpawnReservation, response) } catch (err) { @@ -3567,22 +4605,136 @@ export function registerPtyHandlers( // Why: renderer ACKs bound main→renderer terminal delivery without stopping // PTY ingestion. Agent/status consumers still see every chunk through the // provider/runtime path while background renderer writes wait their turn. - ipcMain.on('pty:ackData', (_event, args: { id: string; charCount: number }) => { - const charCount = Number.isFinite(args.charCount) ? Math.max(0, args.charCount) : 0 - const current = rendererInFlightCharsByPty.get(args.id) ?? 0 - const acknowledged = Math.min(current, charCount) - const next = Math.max(0, current - charCount) - rendererInFlightTotalChars = Math.max(0, rendererInFlightTotalChars - acknowledged) - if (next === 0) { - rendererInFlightCharsByPty.delete(args.id) - } else { - rendererInFlightCharsByPty.set(args.id, next) + ipcMain.on( + 'pty:ackData', + (_event, args: { id: string; charCount?: number; processedChars?: number }) => { + lastAckReceivedAtMs = Date.now() + // Why: a live ACK channel means a future unanswered probe is a fresh + // diagnostic event, not a continuation of the last silent streak. + deliveryResyncUnansweredWarnLogged = false + let acknowledged = 0 + if (typeof args.processedChars === 'number' && Number.isFinite(args.processedChars)) { + acknowledged = applyCumulativeAck(args.id, Math.max(0, args.processedChars)) + } else { + // Why: tolerate legacy per-chunk delta payloads — dev hot-reload can + // pair an old renderer with a new main. Keyed by field presence. + const accounting = rendererDeliveryAccountingByPty.get(args.id) + const delta = Number.isFinite(args.charCount) ? Math.max(0, args.charCount ?? 0) : 0 + acknowledged = accounting ? applyCumulativeAck(args.id, accounting.ackedChars + delta) : 0 + } + tryGetProviderForPty(args.id)?.acknowledgeDataEvent(args.id, acknowledged) + recordPtyRendererDeliveryPressure() + if (pendingData.size > 0 && !flushTimer) { + schedulePendingDataFlush(0) + } } - tryGetProviderForPty(args.id)?.acknowledgeDataEvent(args.id, acknowledged) - recordPtyRendererDeliveryPressure() - if (pendingData.size > 0 && !flushTimer) { - schedulePendingDataFlush(0) + ) + + ipcMain.on( + 'pty:deliveryResyncResponse', + (_event, args: { requestId: number; processedCharsByPty: Record }) => { + if ( + deliveryResyncOutstandingRequestId === null || + args?.requestId !== deliveryResyncOutstandingRequestId + ) { + return + } + clearDeliveryResyncProbe() + deliveryResyncUnansweredWarnLogged = false + // Why: max-merge — the renderer's cumulative totals are authoritative + // for what it processed; reconciling them drains exactly the in-flight + // debt left by lost ACKs, nothing more. + for (const [id, processedChars] of Object.entries(args.processedCharsByPty ?? {})) { + if (typeof processedChars !== 'number' || !Number.isFinite(processedChars)) { + continue + } + const acknowledged = applyCumulativeAck(id, Math.max(0, processedChars)) + if (acknowledged > 0) { + tryGetProviderForPty(id)?.acknowledgeDataEvent(id, acknowledged) + } + } + recordPtyRendererDeliveryPressure() + if (pendingData.size > 0 && !flushTimer) { + schedulePendingDataFlush(0) + } } + ) + + // Why invoke + renderer-initiated: the field wedge (v1.4.121-rc.0 snapshot, + // 2026-07-06) kills every main→renderer push channel while invoke stays + // alive, so the solicited-resync probe above can never be answered there. + // This is the same reconcile, ridden over the direction proven to work, plus + // a write-off lane for bytes the renderer provably never received. + ipcMain.handle( + 'pty:reportRendererDeliveryState', + (_event, args: PtyRendererDeliveryStateReport): PtyRendererDeliveryHealthReply => { + // Extra repair lane for the lost-ACK variant: identical max-merge to the + // resync response, so a heal is only reached when merging cannot drain. + for (const [id, processedChars] of Object.entries(args?.processedCharsByPty ?? {})) { + if (typeof processedChars !== 'number' || !Number.isFinite(processedChars)) { + continue + } + const acknowledged = applyCumulativeAck(id, Math.max(0, processedChars)) + if (acknowledged > 0) { + tryGetProviderForPty(id)?.acknowledgeDataEvent(id, acknowledged) + } + } + let writtenOff: PtyDeliveryWriteOff[] = [] + // Why the main-side ACK-silence check: the renderer's two silent ticks + // already argue for a wedge; requiring main to have seen no ACK either + // keeps a buggy/foreign caller from writing off live delivery. + if ( + args?.heal === true && + rendererInFlightTotalChars > 0 && + (lastAckReceivedAtMs === null || + Date.now() - lastAckReceivedAtMs >= PTY_DELIVERY_HEAL_MIN_ACK_SILENCE_MS) + ) { + writtenOff = writeOffLostRendererDelivery(args) + } + recordPtyRendererDeliveryPressure() + if (pendingData.size > 0 && !flushTimer) { + schedulePendingDataFlush(0) + } + let inFlightPtyCount = 0 + for (const accounting of rendererDeliveryAccountingByPty.values()) { + if (accounting.sentChars - accounting.ackedChars > 0) { + inFlightPtyCount++ + } + } + return { + inFlightTotalChars: rendererInFlightTotalChars, + inFlightPtyCount, + msSinceLastAck: lastAckReceivedAtMs === null ? null : Date.now() - lastAckReceivedAtMs, + ...(writtenOff.length > 0 ? { writtenOff } : {}) + } + } + ) + + // Why: the renderer sends this once its pty:data listener is live (per page + // load / reload). Until it arrives, sends are held so boot-window bytes can't + // drop into a listener-less page and pin the delivery gate; on arrival, flush + // the backlog that accrued during the boot window. + ipcMain.removeAllListeners('pty:rendererDispatcherReady') + ipcMain.on('pty:rendererDispatcherReady', (event) => { + // Why: the reconcile below destructively clears delivery accounting, so a + // straggler handshake from a dying window must not reset the new window. + if (!isPtyWriteEventFromMainWindow(event, mainWindow.webContents)) { + return + } + // Why: the handshake is one-shot per page load, so receiving it while the gate + // is already open means a fresh page loaded but its lifecycle reset was missed — + // a main-frame reload overlapped by an in-page subframe load emits no + // did-start-loading, and the watchdog may have force-opened the gate — leaving + // main holding the dead page's in-flight accounting, which permanently gates the + // survivors. Reconcile by clearing that stale accounting before re-opening. + if (rendererPtyDispatcherReady) { + resetRendererDeliveryAccountingForLifecycleReset() + } + // Why: real handshake landed — cancel the self-heal watchdog so it can't later + // force-open the gate and inflate rendererDispatcherReadyForcedCount. + clearDispatcherReadyWatchdog() + rendererPtyDispatcherReady = true + schedulePendingDataFlush(0) }) ipcMain.removeAllListeners('pty:setActiveRendererPty') @@ -3616,6 +4768,75 @@ export function registerPtyHandlers( } else { visibleRendererPtys.delete(args.id) } + syncPtyBackgroundedDelivery(args.id, 'visibility-report') + }) + + ipcMain.removeAllListeners('pty:setHiddenRendererPty') + ipcMain.on('pty:setHiddenRendererPty', (_event, args: { id: string; hidden: boolean }) => { + if (typeof args.id !== 'string' || !args.id) { + return + } + mainDeliveryBreadcrumbs.record(args.hidden === true ? 'gate-mark' : 'gate-unmark', { + id: redactPtyIdForDiagnostics(args.id) + }) + if (args.hidden === true) { + markHiddenRendererPty(args.id) + // Why: bytes already queued for a newly hidden PTY are model-owned + // state; drop them now instead of holding them under ACK starvation. + // Reveal restores from the snapshot. + const pending = pendingData.get(args.id) + if (pending && shouldDropHiddenRendererPtyData(args.id, getSettings?.())) { + pendingData.delete(args.id) + updateProducerFlowControl(args.id) + pendingOverflowMarkedPtys.delete(args.id) + const drop = recordHiddenRendererPtyDataDrop(args.id, pending.data.length) + if (drop.shouldEmitRestoreMarker) { + sendModelRestoreNeededMarker( + args.id, + 'hidden-drop', + runtime?.getPtyOutputSequence(args.id) + ) + } + recordPtyRendererDeliveryPressure() + } + syncPtyBackgroundedDelivery(args.id, 'gate-mark') + return + } + const { droppedWhileHidden } = unmarkHiddenRendererPty(args.id) + syncPtyBackgroundedDelivery(args.id, 'gate-unmark') + // Why: a renderer reload or remount can replace the view that latched + // restore-needed from the first-drop marker. Re-emit on unhide so the + // (possibly fresh) visible view still pulls the model snapshot covering + // the dropped bytes. If the original view is still alive this can trigger + // a redundant second restore — accepted: a snapshot replay is cheap and + // idempotent, while a missed restore leaves a corrupt pane. + if (droppedWhileHidden) { + sendModelRestoreNeededMarker(args.id, 'unhide', runtime?.getPtyOutputSequence(args.id)) + } + }) + + ipcMain.removeAllListeners('pty:terminalViewAttributes') + ipcMain.on('pty:terminalViewAttributes', (_event, args: unknown) => { + // Why validate-or-drop: the responder must never store a malformed + // palette — a wrong color reply breaks TUI theme detection worse than + // the documented silent-until-first-push behavior. + const attributes = validateTerminalViewAttributes(args) + if (attributes) { + setTerminalViewAttributes(attributes) + } + }) + + ipcMain.removeAllListeners('pty:setPtyDeliveryInterest') + ipcMain.on('pty:setPtyDeliveryInterest', (_event, args: { id: string; interested: boolean }) => { + if (typeof args.id !== 'string' || !args.id) { + return + } + // Why: explicit delivery-interest signal from renderer byte sidecars — + // any interest suppresses the hidden-delivery gate so + // raw-byte consumers keep receiving while the view is hidden or parked. + // Deliberately NOT synced to the daemon backlog pacer: interest consumers + // tolerate paced data, and interest churn must not un-pace a flood. + setRendererPtyDeliveryInterest(args.id, args.interested === true) }) ipcMain.removeAllListeners('pty:signal') @@ -3741,6 +4962,19 @@ export function registerPtyHandlers( } ) + ipcMain.handle( + 'pty:confirmForegroundProcess', + async (_event, args: { id: string }): Promise => { + if (!hasPtyProviderForInspection(args.id)) { + return null + } + const provider = getProviderForPty(args.id) + // Why: falling back to the cached foreground API would turn stale + // process identity into shell/agent authority at a command boundary. + return provider.confirmForegroundProcess?.(args.id) ?? null + } + ) + // Why: renderer needs the live shell cwd when the user presses Cmd+D so // the new split pane inherits the source pane's cwd instead of the // worktree root. Routed through getProviderForPty so local and SSH PTYs @@ -3859,7 +5093,7 @@ export function registerHeadlessPtyRuntime( } /** - * Kill all PTY processes. Call on app quit. + * Kill in-process local PTYs. Daemon-backed PTYs are preserved by daemon disconnect. */ export function killAllPty(): void { if (localProvider instanceof LocalPtyProvider) { diff --git a/src/main/ipc/rate-limits.test.ts b/src/main/ipc/rate-limits.test.ts index 3a299c5bda6b..b53d87d5d832 100644 --- a/src/main/ipc/rate-limits.test.ts +++ b/src/main/ipc/rate-limits.test.ts @@ -16,11 +16,17 @@ import { registerRateLimitHandlers } from './rate-limits' import type { RateLimitService } from '../rate-limits/service' import type { RateLimitState } from '../../shared/rate-limit-types' -function makeService(): { service: RateLimitService; refresh: ReturnType } { +function makeService(): { + service: RateLimitService + refresh: ReturnType + refreshGrok: ReturnType +} { const refresh = vi.fn(() => Promise.resolve({} as RateLimitState)) + const refreshGrok = vi.fn(() => Promise.resolve({} as RateLimitState)) const service = { getState: vi.fn(() => ({}) as RateLimitState), refresh, + refreshGrok, refreshCodexForTarget: vi.fn(() => Promise.resolve({} as RateLimitState)), refreshClaudeForTarget: vi.fn(() => Promise.resolve({} as RateLimitState)), consumeCodexRateLimitResetCredit: vi.fn(() => @@ -30,7 +36,7 @@ function makeService(): { service: RateLimitService; refresh: ReturnType Promise.resolve()), fetchInactiveCodexAccountsOnOpen: vi.fn(() => Promise.resolve()) } - return { service: service as unknown as RateLimitService, refresh } + return { service: service as unknown as RateLimitService, refresh, refreshGrok } } describe('registerRateLimitHandlers', () => { @@ -53,5 +59,15 @@ describe('registerRateLimitHandlers', () => { expect(ipcState.handleHandlers.has('rateLimits:get')).toBe(true) expect(ipcState.handleHandlers.has('rateLimits:refresh')).toBe(true) expect(ipcState.handleHandlers.has('rateLimits:refreshMiniMax')).toBe(true) + expect(ipcState.handleHandlers.has('rateLimits:refreshGrok')).toBe(true) + }) + + it('registers a refreshGrok channel that delegates to refreshGrok()', async () => { + const { service, refreshGrok } = makeService() + registerRateLimitHandlers(service) + const handler = ipcState.handleHandlers.get('rateLimits:refreshGrok') + expect(handler).toBeDefined() + await handler!({}) + expect(refreshGrok).toHaveBeenCalledTimes(1) }) }) diff --git a/src/main/ipc/rate-limits.ts b/src/main/ipc/rate-limits.ts index a28b7810263e..b906ddce51f1 100644 --- a/src/main/ipc/rate-limits.ts +++ b/src/main/ipc/rate-limits.ts @@ -24,4 +24,5 @@ export function registerRateLimitHandlers(rateLimits: RateLimitService): void { rateLimits.fetchInactiveCodexAccountsOnOpen() ) ipcMain.handle('rateLimits:refreshMiniMax', () => rateLimits.refresh()) + ipcMain.handle('rateLimits:refreshGrok', () => rateLimits.refreshGrok()) } diff --git a/src/main/ipc/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers.test.ts index 0b7c4e07146f..08af6977efab 100644 --- a/src/main/ipc/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers.test.ts @@ -1,6 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const { + getPathMock, + listEnvironmentsMock, + callRuntimeEnvironmentMock, registerCliHandlersMock, registerPreflightHandlersMock, registerClaudeUsageHandlersMock, @@ -28,11 +31,13 @@ const { registerRuntimeEnvironmentHandlersMock, registerEphemeralVmHandlersMock, registerAiVaultHandlersMock, + registerOrcaProfileHandlersMock, registerCodexAccountHandlersMock, registerAgentHookHandlersMock, registerAgentTrustHandlersMock, registerClaudeAccountHandlersMock, registerMiniMaxCredentialsHandlersMock, + registerGrokAccountHandlersMock, registerClipboardHandlersMock, setTrustedClipboardRendererWebContentsIdMock, registerUpdaterHandlersMock, @@ -57,6 +62,9 @@ const { registerEmulatorFrameStreamHandlersMock, registerEmulatorVideoStreamHandlersMock } = vi.hoisted(() => ({ + getPathMock: vi.fn(() => '/test/user-data'), + listEnvironmentsMock: vi.fn(() => []), + callRuntimeEnvironmentMock: vi.fn(), registerCliHandlersMock: vi.fn(), registerPreflightHandlersMock: vi.fn(), registerClaudeUsageHandlersMock: vi.fn(), @@ -84,11 +92,13 @@ const { registerRuntimeEnvironmentHandlersMock: vi.fn(), registerEphemeralVmHandlersMock: vi.fn(), registerAiVaultHandlersMock: vi.fn(), + registerOrcaProfileHandlersMock: vi.fn(), registerCodexAccountHandlersMock: vi.fn(), registerAgentHookHandlersMock: vi.fn(), registerAgentTrustHandlersMock: vi.fn(), registerClaudeAccountHandlersMock: vi.fn(), registerMiniMaxCredentialsHandlersMock: vi.fn(), + registerGrokAccountHandlersMock: vi.fn(), registerClipboardHandlersMock: vi.fn(), setTrustedClipboardRendererWebContentsIdMock: vi.fn(), registerUpdaterHandlersMock: vi.fn(), @@ -114,6 +124,20 @@ const { registerEmulatorVideoStreamHandlersMock: vi.fn() })) +vi.mock('electron', () => ({ + app: { + getPath: getPathMock + } +})) + +vi.mock('../../shared/runtime-environment-store', () => ({ + listEnvironments: listEnvironmentsMock +})) + +vi.mock('./runtime-environment-transport-routing', () => ({ + callRuntimeEnvironment: callRuntimeEnvironmentMock +})) + vi.mock('./onboarding', () => ({ registerOnboardingHandlers: registerOnboardingHandlersMock })) @@ -263,6 +287,10 @@ vi.mock('./ai-vault', () => ({ registerAiVaultHandlers: registerAiVaultHandlersMock })) +vi.mock('./orca-profiles', () => ({ + registerOrcaProfileHandlers: registerOrcaProfileHandlersMock +})) + vi.mock('./codex-accounts', () => ({ registerCodexAccountHandlers: registerCodexAccountHandlersMock })) @@ -283,6 +311,10 @@ vi.mock('./minimax-credentials', () => ({ registerMiniMaxCredentialsHandlers: registerMiniMaxCredentialsHandlersMock })) +vi.mock('./grok-accounts', () => ({ + registerGrokAccountHandlers: registerGrokAccountHandlersMock +})) + vi.mock('../window/attach-main-window-services', () => ({ registerUpdaterHandlers: registerUpdaterHandlersMock })) @@ -326,6 +358,11 @@ import { registerCoreHandlers } from './register-core-handlers' describe('registerCoreHandlers', () => { beforeEach(() => { + getPathMock.mockReset() + getPathMock.mockReturnValue('/test/user-data') + listEnvironmentsMock.mockReset() + listEnvironmentsMock.mockReturnValue([]) + callRuntimeEnvironmentMock.mockReset() registerCliHandlersMock.mockReset() registerPreflightHandlersMock.mockReset() registerClaudeUsageHandlersMock.mockReset() @@ -353,6 +390,7 @@ describe('registerCoreHandlers', () => { registerRuntimeEnvironmentHandlersMock.mockReset() registerEphemeralVmHandlersMock.mockReset() registerAiVaultHandlersMock.mockReset() + registerOrcaProfileHandlersMock.mockReset() registerCodexAccountHandlersMock.mockReset() registerAgentHookHandlersMock.mockReset() registerAgentTrustHandlersMock.mockReset() @@ -382,7 +420,7 @@ describe('registerCoreHandlers', () => { registerEmulatorVideoStreamHandlersMock.mockReset() }) - it('passes the store through to handler registrars that need it', () => { + it('passes the store through to handler registrars that need it', async () => { const store = { marker: 'store' } const runtime = { marker: 'runtime', getAgentBrowserBridge: () => null } const stats = { marker: 'stats' } @@ -415,6 +453,14 @@ describe('registerCoreHandlers', () => { { getAdditionalAiVaultCodexHomePaths, onBeforeRelaunch } ) + const aiVaultOptions = registerAiVaultHandlersMock.mock.calls[0]?.[0] + expect(aiVaultOptions).toBeDefined() + + callRuntimeEnvironmentMock.mockResolvedValueOnce({ + ok: true, + result: { sessions: 'bad-shape' } + }) + expect(registerClaudeUsageHandlersMock).toHaveBeenCalledWith(claudeUsage) expect(registerCodexUsageHandlersMock).toHaveBeenCalledWith(codexUsage) expect(registerOpenCodeUsageHandlersMock).toHaveBeenCalledWith(openCodeUsage) @@ -424,6 +470,7 @@ describe('registerCoreHandlers', () => { expect(registerPetHandlersMock).toHaveBeenCalled() expect(registerClaudeAccountHandlersMock).toHaveBeenCalledWith(claudeAccounts) expect(registerMiniMaxCredentialsHandlersMock).toHaveBeenCalledWith(rateLimits) + expect(registerGrokAccountHandlersMock).toHaveBeenCalled() expect(registerRateLimitHandlersMock).toHaveBeenCalledWith(rateLimits) expect(registerGitHubHandlersMock).toHaveBeenCalledWith(store, stats) expect(registerLinearHandlersMock).toHaveBeenCalled() @@ -443,6 +490,7 @@ describe('registerCoreHandlers', () => { expect(registerWorkspacePortHandlersMock).toHaveBeenCalledWith(store) expect(registerLocalhostWorktreeLabelHandlersMock).toHaveBeenCalledWith(store) expect(registerTelemetryHandlersMock).toHaveBeenCalledWith(store) + expect(registerOrcaProfileHandlersMock).toHaveBeenCalledWith(store, { onBeforeRelaunch }) expect(registerSessionHandlersMock).toHaveBeenCalledWith(store) expect(registerUIHandlersMock).toHaveBeenCalledWith(store) expect(registerEmulatorFrameStreamHandlersMock).toHaveBeenCalled() @@ -451,9 +499,14 @@ describe('registerCoreHandlers', () => { expect(registerRuntimeHandlersMock).toHaveBeenCalledWith(runtime) expect(registerRuntimeEnvironmentHandlersMock).toHaveBeenCalledWith(store) expect(registerEphemeralVmHandlersMock).toHaveBeenCalledWith(store) - expect(registerAiVaultHandlersMock).toHaveBeenCalledWith({ - getAdditionalCodexHomePaths: getAdditionalAiVaultCodexHomePaths - }) + expect(registerAiVaultHandlersMock).toHaveBeenCalledWith( + expect.objectContaining({ + getAdditionalCodexHomePaths: getAdditionalAiVaultCodexHomePaths, + getActiveRuntimeAiVaultHostInfos: expect.any(Function), + scanRuntimeAiVaultSessions: expect.any(Function) + }) + ) + expect(aiVaultOptions.getActiveRuntimeAiVaultHostInfos()).toEqual([]) expect(registerNativeChatHandlersMock).toHaveBeenCalled() expect(registerCliHandlersMock).toHaveBeenCalled() expect(registerPreflightHandlersMock).toHaveBeenCalled() @@ -466,6 +519,40 @@ describe('registerCoreHandlers', () => { expect(registerBrowserHandlersMock).toHaveBeenCalled() expect(registerFilesystemWatcherHandlersMock).toHaveBeenCalled() expect(registerSpeechHandlersMock).toHaveBeenCalledWith(store) + + await expect( + aiVaultOptions.scanRuntimeAiVaultSessions( + 'env-123', + { + limit: 10, + scopePaths: ['/workspace'] + }, + { timeoutMs: 3000 } + ) + ).resolves.toEqual({ + sessions: [], + issues: [ + expect.objectContaining({ + executionHostId: 'runtime:env-123', + agent: 'codex', + path: 'env-123', + message: expect.stringContaining('Invalid aiVault.listSessions response') + }) + ], + scannedAt: expect.any(String) + }) + expect(callRuntimeEnvironmentMock).toHaveBeenCalledWith( + '/test/user-data', + 'env-123', + 'aiVault.listSessions', + { + limit: 10, + force: undefined, + scopePaths: ['/workspace'], + executionHostId: 'runtime:env-123' + }, + 3000 + ) }) it('only registers IPC handlers once but always updates web contents id', () => { diff --git a/src/main/ipc/register-core-handlers.ts b/src/main/ipc/register-core-handlers.ts index 50dbd0a8ff45..dc2c219025ad 100644 --- a/src/main/ipc/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers.ts @@ -1,3 +1,4 @@ +import { app } from 'electron' import { registerAppHandlers } from './app' import { registerCliHandlers } from './cli' import { registerPreflightHandlers } from './preflight' @@ -49,11 +50,13 @@ import { registerUIHandlers, setTrustedUIRendererWebContentsId } from './ui' import { registerEmulatorFrameStreamHandlers } from './emulator-frame-stream' import { registerEmulatorVideoStreamHandlers } from './emulator-video-stream' import { registerSpeechHandlers } from './speech' +import { registerOrcaProfileHandlers } from './orca-profiles' import { registerCodexAccountHandlers } from './codex-accounts' import { registerAgentHookHandlers } from './agent-hooks' import { registerAgentTrustHandlers } from './agent-trust' import { registerClaudeAccountHandlers } from './claude-accounts' import { registerMiniMaxCredentialsHandlers } from './minimax-credentials' +import { registerGrokAccountHandlers } from './grok-accounts' import { registerUpdaterHandlers } from '../window/attach-main-window-services' import { registerClipboardHandlers, @@ -69,6 +72,10 @@ import type { AutomationService } from '../automations/service' import type { AgentAwakeService } from '../agent-awake-service' import type { CrashReportStore } from '../crash-reporting/crash-report-store' import type { KeybindingService } from '../keybindings/keybinding-service' +import { + getSavedRuntimeAiVaultHostInfos, + scanRuntimeAiVaultSessions +} from '../ai-vault/runtime-session-scanner' let registered = false @@ -119,6 +126,7 @@ export function registerCoreHandlers( registerAgentTrustHandlers() registerClaudeAccountHandlers(claudeAccounts) registerMiniMaxCredentialsHandlers(rateLimits) + registerGrokAccountHandlers() registerRateLimitHandlers(rateLimits) registerGitHubHandlers(store, stats) registerGitLabHandlers(store) @@ -151,6 +159,9 @@ export function registerCoreHandlers( registerKeybindingHandlers(keybindings) } registerTelemetryHandlers(store) + registerOrcaProfileHandlers(store, { + onBeforeRelaunch: lifecycleOptions.onBeforeRelaunch + }) registerBrowserHandlers() registerShellHandlers() registerPetHandlers() @@ -171,7 +182,11 @@ export function registerCoreHandlers( registerRuntimeEnvironmentHandlers(store) registerEphemeralVmHandlers(store) registerAiVaultHandlers({ - getAdditionalCodexHomePaths: lifecycleOptions.getAdditionalAiVaultCodexHomePaths + getAdditionalCodexHomePaths: lifecycleOptions.getAdditionalAiVaultCodexHomePaths, + getActiveRuntimeAiVaultHostInfos: () => + getSavedRuntimeAiVaultHostInfos(app.getPath('userData')), + scanRuntimeAiVaultSessions: async (environmentId, args, options) => + scanRuntimeAiVaultSessions(app.getPath('userData'), environmentId, args, options) }) registerNativeChatHandlers() registerClipboardHandlers(store) diff --git a/src/main/ipc/repos-remote.test.ts b/src/main/ipc/repos-remote.test.ts index bd2541c7ebd6..7a23522ac926 100644 --- a/src/main/ipc/repos-remote.test.ts +++ b/src/main/ipc/repos-remote.test.ts @@ -12,6 +12,7 @@ import { join } from 'node:path' import type * as RepoModule from '../git/repo' import { DEFAULT_REPO_BADGE_COLOR } from '../../shared/constants' import { getGitRepoRoot, isGitRepo } from '../git/repo' +import { clearGitCapabilityStateForTests } from '../git/git-capability-state' const { handleMock, @@ -147,6 +148,10 @@ vi.mock('./ssh', () => ({ import { registerRepoHandlers } from './repos' +beforeEach(() => { + clearGitCapabilityStateForTests() +}) + describe('projectGroups IPC validation', () => { const handlers = new Map unknown>() const mockWindow = { @@ -2698,15 +2703,22 @@ describe('repos:searchBaseRefs SSH relay', () => { query: '', limit: 1 }) + const repeatedResult = await handlers.get('repos:searchBaseRefs')!(null, { + repoId: 'r1', + query: '', + limit: 1 + }) expect(result).toEqual(['origin/main']) + expect(repeatedResult).toEqual(['origin/main']) const forEachRefCalls = mockGitProvider.exec.mock.calls.filter( (call) => (call[0] as string[])[0] === 'for-each-ref' ) - expect(forEachRefCalls).toHaveLength(2) + expect(forEachRefCalls).toHaveLength(3) expect(forEachRefCalls[0][0]).toContain('--exclude=refs/remotes/**/HEAD') expect(forEachRefCalls[1][0]).not.toContain('--exclude=refs/remotes/**/HEAD') expect(forEachRefCalls[1][0]).toContain('--count=104') + expect(forEachRefCalls[2][0]).not.toContain('--exclude=refs/remotes/**/HEAD') }) it('sends the widened `**` argv so all remotes and slash-named branches are discoverable', async () => { diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index e34c43821f8d..57225c63c283 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -74,6 +74,7 @@ import { searchBaseRefDetails } from '../git/repo' import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { getSshGitCapabilityCache } from '../git/git-capability-state' import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' import { getSshGitUsername, resolveLocalGitUsername } from '../git/git-username' import { enrichRepoGitUsernames } from '../repo-git-username-enrichment' @@ -1118,6 +1119,7 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v ipcMain.removeHandler('repos:list') ipcMain.removeHandler('repos:add') ipcMain.removeHandler('repos:remove') + ipcMain.removeHandler('repos:removeForHost') ipcMain.removeHandler('repos:reorder') ipcMain.removeHandler('repos:update') ipcMain.removeHandler('projects:list') @@ -1926,6 +1928,22 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v notifyReposChanged(mainWindow) }) + // Why: forget a project on a single execution host without disturbing the + // same repo id on other hosts (local or a re-added SSH target). Used by the + // SSH-workspace forget flow when a host is removed/disconnected. + ipcMain.handle( + 'repos:removeForHost', + async (_event, args: { repoId: string; hostId: string }) => { + const hostId = normalizeExecutionHostId(args.hostId) + if (!hostId) { + throw new Error(`Invalid host ID: ${args.hostId}`) + } + store.removeProjectForHost(args.repoId, hostId) + invalidateAuthorizedRootsCache() + notifyReposChanged(mainWindow) + } + ) + ipcMain.handle( 'repos:update', ( @@ -2531,32 +2549,33 @@ async function searchBaseRefDetailsForRepo( .split('\n') .map((line) => line.trim()) .filter(Boolean) + const capabilities = getSshGitCapabilityCache(provider) const runSearch = async (patternGroup?: 'segmented' | 'branchRoot'): Promise => { - try { - return ( - await provider.exec( - buildSearchBaseRefsArgv(normalizedQuery, limit, { - remoteNames: remotes, - patternGroup - }), - repo.path - ) - ).stdout - } catch (err) { - if (!isForEachRefExcludeUnsupportedError(err)) { - throw err - } - return ( - await provider.exec( - buildSearchBaseRefsArgv(normalizedQuery, limit, { - excludeRemoteHead: false, - remoteNames: remotes, - patternGroup - }), - repo.path - ) - ).stdout - } + return capabilities.runWithFallback( + 'for-each-ref-exclude', + async () => + ( + await provider.exec( + buildSearchBaseRefsArgv(normalizedQuery, limit, { + remoteNames: remotes, + patternGroup + }), + repo.path + ) + ).stdout, + async () => + ( + await provider.exec( + buildSearchBaseRefsArgv(normalizedQuery, limit, { + excludeRemoteHead: false, + remoteNames: remotes, + patternGroup + }), + repo.path + ) + ).stdout, + isForEachRefExcludeUnsupportedError + ) } // Why: delegate the NUL-parse + HEAD filter + dedup + limit pipeline // to the shared helper so the SSH and local paths cannot diverge. diff --git a/src/main/ipc/settings.test.ts b/src/main/ipc/settings.test.ts index 540079a510e4..7af303c72a36 100644 --- a/src/main/ipc/settings.test.ts +++ b/src/main/ipc/settings.test.ts @@ -5,6 +5,7 @@ const { applyElectronProxySettingsMock, browserWindowGetAllWindowsMock, handleMock, + onMock, previewGhosttyImportMock, previewWarpThemeImportMock, prepareLocalWorktreeRootsForReposMock, @@ -14,6 +15,7 @@ const { applyElectronProxySettingsMock: vi.fn(), browserWindowGetAllWindowsMock: vi.fn(), handleMock: vi.fn(), + onMock: vi.fn(), previewGhosttyImportMock: vi.fn(), previewWarpThemeImportMock: vi.fn(), prepareLocalWorktreeRootsForReposMock: vi.fn(), @@ -22,7 +24,7 @@ const { vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: browserWindowGetAllWindowsMock }, - ipcMain: { handle: handleMock }, + ipcMain: { handle: handleMock, on: onMock }, nativeTheme: { themeSource: 'system' } })) @@ -70,6 +72,7 @@ const store = { describe('registerSettingsHandlers', () => { beforeEach(() => { handleMock.mockClear() + onMock.mockClear() applyAppIconMock.mockClear() applyElectronProxySettingsMock.mockClear() applyElectronProxySettingsMock.mockResolvedValue({ source: 'settings' }) @@ -89,6 +92,22 @@ describe('registerSettingsHandlers', () => { expect(channels).toContain('settings:previewGhosttyImport') }) + it('answers the synchronous settings read with the persisted settings', () => { + // Why: panes can bind PTYs before async hydration; the side-effect + // authority kill switch needs the persisted value synchronously. + store.getSettings.mockReturnValue({ terminalMainSideEffectAuthority: false }) + registerSettingsHandlers(store as never) + + const listener = onMock.mock.calls.find( + (call) => call[0] === 'settings:get-sync' + )?.[1] as (event: { returnValue: unknown }) => void + expect(listener).toBeTypeOf('function') + + const event = { returnValue: undefined as unknown } + listener(event) + expect(event.returnValue).toEqual({ terminalMainSideEffectAuthority: false }) + }) + it('registers settings:previewWarpThemeImport handler', () => { registerSettingsHandlers(store as never) const channels = handleMock.mock.calls.map((call) => call[0]) @@ -306,6 +325,24 @@ describe('registerSettingsHandlers', () => { ) }) + it('normalizes terminal line height updates before persistence', async () => { + store.getSettings.mockReturnValue({ terminalLineHeight: 1 }) + store.updateSettings.mockReturnValue({ terminalLineHeight: 1 }) + registerSettingsHandlers(store as never) + + const handler = handleMock.mock.calls.find((call) => call[0] === 'settings:set')?.[1] as ( + _event: unknown, + args: unknown + ) => Promise + + await handler(settingsInvokeEvent, { terminalLineHeight: 0.85 }) + + expect(store.updateSettings).toHaveBeenCalledWith( + { terminalLineHeight: 1 }, + { notifyListeners: true, originWebContentsId: 1 } + ) + }) + it('normalizes custom terminal themes from renderer settings IPC', async () => { store.getSettings.mockReturnValue({ terminalCustomThemes: [] }) store.updateSettings.mockReturnValue({ terminalCustomThemes: [] }) diff --git a/src/main/ipc/settings.ts b/src/main/ipc/settings.ts index 712f49f6d43b..b59bf6add2ec 100644 --- a/src/main/ipc/settings.ts +++ b/src/main/ipc/settings.ts @@ -18,6 +18,7 @@ import { normalizeUiLanguage } from '../../shared/ui-language' import { applyAppIcon } from '../app-icon' import { normalizeTerminalCustomThemes } from '../../shared/terminal-custom-themes' import { normalizeDesktopTerminalScrollbackRows } from '../../shared/terminal-scrollback-policy' +import { normalizeTerminalLineHeight } from '../../shared/terminal-line-height-settings' import { prepareLocalWorktreeRootsForRepos } from '../worktree-root-preparation' import { scheduleCurrentWorktreeBaseDirectoryWatcherSync } from './worktree-base-directory-watcher' @@ -66,6 +67,15 @@ export function registerSettingsHandlers( return store.getSettings() }) + // Why: terminal panes can bind PTYs before async settings hydration + // completes. The side-effect authority kill switch is consulted once at + // transport creation, so the renderer needs the persisted value + // synchronously or pre-hydration bindings would always pick main authority + // (terminal-side-effect-authority.md, migration switch). + ipcMain.on('settings:get-sync', (event) => { + event.returnValue = store.getSettings() + }) + ipcMain.handle('settings:set', async (event, args: Partial) => { const sanitizedArgs = sanitizeRendererSettingsUpdate(args) // Why: Floating Workspace grants are trusted only when written by the @@ -95,6 +105,9 @@ export function registerSettingsHandlers( args.terminalScrollbackRows ) } + if ('terminalLineHeight' in args) { + sanitizedArgs.terminalLineHeight = normalizeTerminalLineHeight(args.terminalLineHeight) + } if ('uiLanguage' in args) { sanitizedArgs.uiLanguage = normalizeUiLanguage(args.uiLanguage) } diff --git a/src/main/ipc/shell.test.ts b/src/main/ipc/shell.test.ts index 2e1b842904d4..b3afc70b4a5f 100644 --- a/src/main/ipc/shell.test.ts +++ b/src/main/ipc/shell.test.ts @@ -321,6 +321,23 @@ describe('registerShellHandlers', () => { ]) }) + it.runIf(process.platform === 'win32')( + 'forwards WSL remote arguments with spaces through the Windows launcher shim', + async () => { + const workspacePath = '\\\\wsl.localhost\\Ubuntu Preview\\home\\Ada Lovelace\\project' + const codeShim = 'C:\\Tools\\CODE.CMD' + resolveCliCommandMock.mockReturnValueOnce(codeShim) + const handler = getHandler('shell:openInExternalEditor') + + await expect(handler({}, workspacePath, 'code')).resolves.toEqual({ ok: true }) + expect(getSpawnArgsForWindowsMock).toHaveBeenCalledWith(codeShim, [ + '--remote', + 'wsl+Ubuntu Preview', + '/home/Ada Lovelace/project' + ]) + } + ) + it('shows the Windows console for NeoVim executable launchers on Windows', async () => { const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform') Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) diff --git a/src/main/ipc/ssh.test.ts b/src/main/ipc/ssh.test.ts index a1db12efa51d..0c5a51d9ae2a 100644 --- a/src/main/ipc/ssh.test.ts +++ b/src/main/ipc/ssh.test.ts @@ -50,7 +50,8 @@ const { onRequest: vi.fn().mockReturnValue(() => {}), onDispose: vi.fn().mockReturnValue(() => {}), request: vi.fn().mockResolvedValue({}), - notify: vi.fn() + notify: vi.fn(), + probeLiveness: vi.fn().mockResolvedValue(false) }, mockPtyProvider: { onData: vi.fn(), @@ -316,6 +317,7 @@ describe('SSH IPC handlers', () => { mockMux.isDisposed.mockReset().mockReturnValue(false) mockMux.onNotification.mockReset() mockMux.onDispose.mockReset().mockReturnValue(() => {}) + mockMux.probeLiveness.mockReset().mockResolvedValue(false) mockPtyProvider.onData.mockReset() mockPtyProvider.onExit.mockReset() mockPtyProvider.onReplay.mockReset() @@ -778,6 +780,39 @@ describe('SSH IPC handlers', () => { expect(runtime.onPtyExit).toHaveBeenCalledWith('remote-pty', 7) }) + it('mirrors SSH state broadcasts onto the runtime client-event stream', async () => { + const runtime = { + onPtyData: vi.fn(), + onPtyExit: vi.fn(), + notifySshStateChanged: vi.fn() + } + registerSshHandlers(mockStore as never, () => mockWindow as never, runtime as never) + const target: SshTarget = { + id: 'ssh-1', + label: 'Server', + host: 'example.com', + port: 22, + username: 'deploy' + } + mockSshStore.getTarget.mockReturnValue(target) + mockConnectionManager.connect.mockResolvedValue({}) + mockConnectionManager.getState.mockReturnValue({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + + await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) + + // Why: paired remote clients only learn SSH state through this hook — + // without it their reconnect overlays never clear (STA-1468). + expect(runtime.notifySshStateChanged).toHaveBeenCalledWith( + 'ssh-1', + expect.objectContaining({ targetId: 'ssh-1', status: 'connected' }) + ) + }) + it('preserves active port forwards and live connections across handler re-registration', async () => { const target: SshTarget = { id: 'ssh-1', @@ -1368,7 +1403,7 @@ describe('SSH IPC handlers', () => { expect(mockConnectionManager.disconnect).toHaveBeenCalledWith('ssh-1') }) - it('forces active SSH sessions to reconnect when the system resumes from sleep', async () => { + it('reconnects on system resume when the relay liveness probe fails', async () => { const target: SshTarget = { id: 'ssh-1', label: 'Server', @@ -1386,6 +1421,7 @@ describe('SSH IPC handlers', () => { error: null, reconnectAttempt: 0 }) + mockMux.probeLiveness.mockResolvedValue(false) await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) @@ -1394,7 +1430,77 @@ describe('SSH IPC handlers', () => { resumeListener() - expect(mockConnectionManager.reconnect).toHaveBeenCalledWith('ssh-1') + await vi.waitFor(() => expect(mockConnectionManager.reconnect).toHaveBeenCalledWith('ssh-1')) + // Why: a failed first probe gets one retry before teardown (slow post-wake network). + expect(mockMux.probeLiveness).toHaveBeenCalledTimes(2) + }) + + it('skips reconnect on system resume when the relay link is still alive', async () => { + const target: SshTarget = { + id: 'ssh-1', + label: 'Server', + host: 'example.com', + port: 22, + username: 'deploy' + } + const conn = {} + mockSshStore.getTarget.mockReturnValue(target) + mockConnectionManager.connect.mockResolvedValue(conn) + mockConnectionManager.getConnection.mockReturnValue(conn) + mockConnectionManager.getState.mockReturnValue({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + mockMux.probeLiveness.mockResolvedValue(true) + + await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) + + const resumeListener = powerMonitorOnMock.mock.calls.find(([event]) => event === 'resume')?.[1] + expect(resumeListener).toBeTypeOf('function') + + resumeListener() + + await vi.waitFor(() => expect(mockMux.probeLiveness).toHaveBeenCalledTimes(1)) + // Let the async resume handler settle before asserting no teardown happened. + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(mockConnectionManager.reconnect).not.toHaveBeenCalled() + }) + + it('does not reconnect after resume when the target was disconnected during the probe', async () => { + const target: SshTarget = { + id: 'ssh-1', + label: 'Server', + host: 'example.com', + port: 22, + username: 'deploy' + } + const conn = {} + mockSshStore.getTarget.mockReturnValue(target) + mockConnectionManager.connect.mockResolvedValue(conn) + mockConnectionManager.getConnection.mockReturnValue(conn) + mockConnectionManager.getState.mockReturnValue({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + mockMux.probeLiveness.mockResolvedValue(false) + + await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) + + const resumeListener = powerMonitorOnMock.mock.calls.find(([event]) => event === 'resume')?.[1] + expect(resumeListener).toBeTypeOf('function') + + resumeListener() + // Why: the probe window is seconds long; a user disconnect during it must + // win — reconnecting afterwards would resurrect the torn-down target. + mockConnectionManager.getConnection.mockReturnValue(undefined) + + await vi.waitFor(() => expect(mockMux.probeLiveness).toHaveBeenCalledTimes(2)) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(mockConnectionManager.reconnect).not.toHaveBeenCalled() }) it('extends active relay grace while the system is suspending', async () => { diff --git a/src/main/ipc/ssh.ts b/src/main/ipc/ssh.ts index 0ac0c5e0db07..8b5756bff386 100644 --- a/src/main/ipc/ssh.ts +++ b/src/main/ipc/ssh.ts @@ -51,6 +51,7 @@ let currentRuntime: OrcaRuntimeService | undefined const SSH_IPC_CHANNELS = [ 'ssh:listTargets', + 'ssh:listRemovedTargetLabels', 'ssh:addTarget', 'ssh:updateTarget', 'ssh:removeTarget', @@ -89,6 +90,16 @@ export function getRegisteredSshState(targetId: string): SshConnectionState | un return registeredGetSshState?.(targetId) } +/** Public targets for runtime RPC clients — same list the desktop renderer gets. */ +export function listRegisteredSshTargets(): SshTarget[] { + return sshStore?.listTargets() ?? [] +} + +/** Removed-target id → last known label, for ghost-host display on paired clients. */ +export function listRegisteredRemovedSshTargetLabels(): Record { + return sshStore?.listRemovedTargetLabels() ?? {} +} + export async function disconnectRegisteredSshTarget(targetId: string): Promise { if (!connectionManager) { return @@ -234,13 +245,14 @@ function broadcastSshState( if (isRuntimeOwnedSshTargetId(targetId)) { return } + const enrichedState = withSshRemotePlatform(targetId, state) const win = getMainWindow() if (win && !win.isDestroyed()) { - win.webContents.send('ssh:state-changed', { - targetId, - state: withSshRemotePlatform(targetId, state) - }) + win.webContents.send('ssh:state-changed', { targetId, state: enrichedState }) } + // Why: paired remote clients have no ssh:state-changed IPC; without this + // their terminals keep a stale reconnect overlay after the host connects. + currentRuntime?.notifySshStateChanged?.(targetId, enrichedState) } function withSshRemotePlatform(targetId: string, state: SshConnectionState): SshConnectionState { @@ -430,6 +442,24 @@ function registerAdvertisedUrlRefresh(getMainWindow: () => BrowserWindow | null) }) } +// Why: macOS can resume the process before the network stack is back up, so +// a failed first probe gets one retry before the link is declared dead (#7773). +const RESUME_PROBE_TIMEOUT_MS = 5_000 +const RESUME_PROBE_ATTEMPTS = 2 + +async function isRelayLinkAliveAfterResume(session: SshRelaySession): Promise { + const mux = session.getMux() + if (!mux || mux.isDisposed()) { + return false + } + for (let attempt = 0; attempt < RESUME_PROBE_ATTEMPTS; attempt++) { + if (await mux.probeLiveness(RESUME_PROBE_TIMEOUT_MS)) { + return true + } + } + return false +} + function registerPowerMonitorReconnect(): void { powerMonitorUnsubscribe?.() const onSuspend = (): void => { @@ -438,19 +468,35 @@ function registerPowerMonitorReconnect(): void { } } const onResume = (): void => { - for (const targetId of activeSessions.keys()) { - const conn = connectionManager?.getConnection(targetId) + for (const [targetId, session] of activeSessions) { + const manager = connectionManager + const conn = manager?.getConnection(targetId) if (!conn) { continue } - const reconnect = connectionManager?.reconnect(targetId) - void reconnect?.catch((err) => { - console.warn( - `[ssh] Failed to reconnect ${targetId} after system resume: ${ - err instanceof Error ? err.message : String(err) - }` - ) - }) + void (async () => { + // Why: unconditional reconnect on every wake tore down live sessions + // and flashed the reconnect overlay (#7773). Only reconnect targets + // whose relay link actually died during sleep. + if (await isRelayLinkAliveAfterResume(session)) { + return + } + // Why: the probe can take ~10s. If the user disconnected or the + // session/connection was replaced meanwhile, reconnecting would + // resurrect a connection that was intentionally torn down. + if (activeSessions.get(targetId) !== session || manager?.getConnection(targetId) !== conn) { + return + } + try { + await manager?.reconnect(targetId) + } catch (err) { + console.warn( + `[ssh] Failed to reconnect ${targetId} after system resume: ${ + err instanceof Error ? err.message : String(err) + }` + ) + } + })() } } powerMonitor.on('suspend', onSuspend) @@ -695,12 +741,35 @@ export function registerSshHandlers( // ── Target CRUD ──────────────────────────────────────────────────── + // Why: SSH target add/import can re-adopt workspaces orphaned on a removed + // target id (see ssh-target-readoption). When that re-points repos, the + // renderer must refresh its repo list to surface the reattached workspaces. + function notifyReposChangedIfReadopted(): void { + if (!sshStore || sshStore.lastReadoptedRepoCount <= 0) { + return + } + sshStore.lastReadoptedRepoCount = 0 + const win = getCurrentMainWindow() + if (win && !win.isDestroyed()) { + win.webContents.send('repos:changed') + } + } + ipcMain.handle('ssh:listTargets', () => { return sshStore!.listTargets() }) + ipcMain.handle('ssh:listRemovedTargetLabels', () => { + return sshStore!.listRemovedTargetLabels() + }) + ipcMain.handle('ssh:addTarget', (_event, args: { target: Omit }) => { - return sshStore!.addTarget(args.target) + const target = sshStore!.addTarget(args.target) + // Why: re-adding a removed host can re-adopt orphaned workspaces (re-point + // repos/worktrees off the dead id). Refresh the renderer's repo list so the + // reattached workspaces move from grey ghosts back onto the live host. + notifyReposChangedIfReadopted() + return target }) ipcMain.handle( @@ -715,7 +784,9 @@ export function registerSshHandlers( }) ipcMain.handle('ssh:importConfig', (_event, args?: { reAdopt?: boolean }) => { - return sshStore!.importFromSshConfig(args) + const result = sshStore!.importFromSshConfig(args) + notifyReposChangedIfReadopted() + return result }) // ── Connection lifecycle ─────────────────────────────────────────── diff --git a/src/main/ipc/tui-agent-detection-commands.test.ts b/src/main/ipc/tui-agent-detection-commands.test.ts new file mode 100644 index 000000000000..b6d536f732bb --- /dev/null +++ b/src/main/ipc/tui-agent-detection-commands.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest' +import { + getTuiAgentDetectionProbeCommands, + KNOWN_TUI_AGENT_DETECTION_COMMANDS, + resolveDetectedTuiAgentIds +} from './tui-agent-detection-commands' + +describe('tui agent detection commands', () => { + it('requires Claude before reporting Claude Agent Teams', () => { + const commands = KNOWN_TUI_AGENT_DETECTION_COMMANDS.filter( + (command) => command.id === 'claude-agent-teams' + ) + + expect(commands).toEqual([ + { + id: 'claude-agent-teams', + cmd: 'orca', + requiredCommands: ['claude'], + unsupportedRuntimes: ['win32', 'wsl'] + }, + { + id: 'claude-agent-teams', + cmd: 'orca-dev', + requiredCommands: ['claude'], + unsupportedRuntimes: ['win32', 'wsl'] + }, + { + id: 'claude-agent-teams', + cmd: 'orca-ide', + requiredCommands: ['claude'], + unsupportedRuntimes: ['win32', 'wsl'] + } + ]) + expect(getTuiAgentDetectionProbeCommands(commands, 'linux')).toEqual([ + 'orca', + 'claude', + 'orca-dev', + 'orca-ide' + ]) + expect(resolveDetectedTuiAgentIds(commands, new Set(['orca']), 'linux')).toEqual([]) + expect(resolveDetectedTuiAgentIds(commands, new Set(['orca', 'claude']), 'linux')).toEqual([ + 'claude-agent-teams' + ]) + expect(getTuiAgentDetectionProbeCommands(commands, 'win32')).toEqual([]) + expect(resolveDetectedTuiAgentIds(commands, new Set(['orca', 'claude']), 'win32')).toEqual([]) + expect(getTuiAgentDetectionProbeCommands(commands, 'wsl')).toEqual([]) + expect(resolveDetectedTuiAgentIds(commands, new Set(['orca-ide', 'claude']), 'wsl')).toEqual([]) + }) +}) diff --git a/src/main/ipc/tui-agent-detection-commands.ts b/src/main/ipc/tui-agent-detection-commands.ts new file mode 100644 index 000000000000..dc5d59095438 --- /dev/null +++ b/src/main/ipc/tui-agent-detection-commands.ts @@ -0,0 +1,77 @@ +import type { TuiAgent } from '../../shared/types' +import { + getTuiAgentDetectCommands, + TUI_AGENT_CONFIG, + type TuiAgentConfig, + type TuiAgentDetectionRuntime +} from '../../shared/tui-agent-config' + +export type TuiAgentDetectionCommand = { + id: TuiAgent + cmd: string + requiredCommands?: readonly string[] + unsupportedRuntimes?: readonly TuiAgentDetectionRuntime[] +} + +export const KNOWN_TUI_AGENT_DETECTION_COMMANDS = buildTuiAgentDetectionCommands() + +function buildTuiAgentDetectionCommands(): TuiAgentDetectionCommand[] { + return Object.entries(TUI_AGENT_CONFIG).flatMap(([id, config]) => + getTuiAgentDetectCommands(config).map((cmd) => + buildTuiAgentDetectionCommand(id as TuiAgent, cmd, config) + ) + ) +} + +function buildTuiAgentDetectionCommand( + id: TuiAgent, + cmd: string, + config: TuiAgentConfig +): TuiAgentDetectionCommand { + return { + id, + cmd, + ...(config.detectRequiredCommands?.length + ? { requiredCommands: config.detectRequiredCommands } + : {}), + ...(config.detectUnsupportedRuntimes?.length + ? { unsupportedRuntimes: config.detectUnsupportedRuntimes } + : {}) + } +} + +export function getTuiAgentDetectionProbeCommands( + commands: readonly TuiAgentDetectionCommand[], + runtime: TuiAgentDetectionRuntime +): string[] { + return [ + ...new Set( + commands + .filter((command) => !isDetectionUnsupportedInRuntime(command, runtime)) + .flatMap((command) => [command.cmd, ...(command.requiredCommands ?? [])]) + ) + ] +} + +export function resolveDetectedTuiAgentIds( + commands: readonly TuiAgentDetectionCommand[], + foundCommands: ReadonlySet, + runtime: TuiAgentDetectionRuntime +): TuiAgent[] { + const detected = commands + .filter( + (command) => + !isDetectionUnsupportedInRuntime(command, runtime) && + foundCommands.has(command.cmd) && + (command.requiredCommands ?? []).every((required) => foundCommands.has(required)) + ) + .map(({ id }) => id) + return [...new Set(detected)] +} + +export function isDetectionUnsupportedInRuntime( + command: TuiAgentDetectionCommand, + runtime: TuiAgentDetectionRuntime +): boolean { + return command.unsupportedRuntimes?.includes(runtime) === true +} diff --git a/src/main/ipc/workspace-cleanup-activity.test.ts b/src/main/ipc/workspace-cleanup-activity.test.ts new file mode 100644 index 000000000000..72f20291f4a3 --- /dev/null +++ b/src/main/ipc/workspace-cleanup-activity.test.ts @@ -0,0 +1,163 @@ +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import type { Repo, Worktree } from '../../shared/types' +import { resolveWorkspaceCleanupActivityWorktree } from './workspace-cleanup-activity' + +const REPO: Repo = { + id: 'repo-1', + path: '/repo', + displayName: 'Repo', + badgeColor: '#000', + addedAt: 1 +} + +function makeWorktree(overrides: Partial = {}): Worktree { + return { + id: 'repo-1::/repo-feature', + repoId: 'repo-1', + path: '/repo-feature', + head: 'abc123', + branch: 'refs/heads/feature', + isBare: false, + isMainWorktree: false, + displayName: 'feature', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + linkedLinearIssueWorkspaceId: null, + linkedLinearIssueOrganizationUrlKey: null, + linkedGitLabMR: null, + linkedGitLabIssue: null, + linkedBitbucketPR: null, + linkedAzureDevOpsPR: null, + linkedGiteaPR: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + workspaceStatus: 'in-progress', + ...overrides + } +} + +describe('resolveWorkspaceCleanupActivityWorktree', () => { + it('uses local worktree filesystem metadata when persisted activity is missing', async () => { + const statPath = vi.fn(async (targetPath: string) => ({ + mtimeMs: targetPath.endsWith('.git') ? 20_000 : 10_000 + })) + + const worktree = await resolveWorkspaceCleanupActivityWorktree(REPO, makeWorktree(), statPath) + + expect(statPath).toHaveBeenCalledWith('/repo-feature') + expect(statPath).toHaveBeenCalledWith(path.join('/repo-feature', '.git')) + expect(worktree.lastActivityAt).toBe(20_000) + }) + + it('uses linked worktree gitdir metadata when the .git pointer is stale', async () => { + const gitDirPath = path.join('/repo', '.git', 'worktrees', 'repo-feature') + const gitDirHeadPath = path.join(gitDirPath, 'HEAD') + const gitDirLogsHeadPath = path.join(gitDirPath, 'logs', 'HEAD') + const statPath = vi.fn(async (targetPath: string) => { + const mtimes: Record = { + '/repo-feature': 10_000, + [path.join('/repo-feature', '.git')]: 20_000, + [gitDirPath]: 50_000, + [gitDirHeadPath]: 60_000, + [gitDirLogsHeadPath]: 70_000 + } + return { mtimeMs: mtimes[targetPath] ?? 0 } + }) + const readTextFile = vi.fn(async () => `gitdir: ${gitDirPath}\n`) + + const worktree = await resolveWorkspaceCleanupActivityWorktree( + REPO, + makeWorktree(), + statPath, + readTextFile + ) + + expect(readTextFile).toHaveBeenCalledWith(path.join('/repo-feature', '.git')) + expect(statPath).toHaveBeenCalledWith(gitDirPath) + expect(statPath).toHaveBeenCalledWith(gitDirHeadPath) + expect(statPath).toHaveBeenCalledWith(gitDirLogsHeadPath) + expect(worktree.lastActivityAt).toBe(70_000) + }) + + it('resolves relative linked worktree gitdir pointers from the worktree path', async () => { + const gitDirPath = path.resolve('/repo-feature', '.repo/gitdir') + const gitDirLogsHeadPath = path.join(gitDirPath, 'logs', 'HEAD') + const statPath = vi.fn(async (targetPath: string) => ({ + mtimeMs: targetPath === gitDirLogsHeadPath ? 40_000 : 10_000 + })) + const readTextFile = vi.fn(async () => 'gitdir: .repo/gitdir\n') + + const worktree = await resolveWorkspaceCleanupActivityWorktree( + REPO, + makeWorktree(), + statPath, + readTextFile + ) + + expect(statPath).toHaveBeenCalledWith(gitDirLogsHeadPath) + expect(worktree.lastActivityAt).toBe(40_000) + }) + + it('converts WSL linked worktree gitdir pointers before reading metadata', async () => { + const worktreePath = String.raw`\\wsl.localhost\Ubuntu\home\me\repo-feature` + const gitDirPath = String.raw`\\wsl.localhost\Ubuntu\home\me\repo\.git\worktrees\repo-feature` + const gitDirHeadPath = path.join(gitDirPath, 'HEAD') + const gitDirLogsHeadPath = path.join(gitDirPath, 'logs', 'HEAD') + const statPath = vi.fn(async (targetPath: string) => { + const mtimes: Record = { + [worktreePath]: 10_000, + [path.join(worktreePath, '.git')]: 20_000, + [gitDirPath]: 50_000, + [gitDirHeadPath]: 60_000, + [gitDirLogsHeadPath]: 70_000 + } + return { mtimeMs: mtimes[targetPath] ?? 0 } + }) + const readTextFile = vi.fn(async () => 'gitdir: /home/me/repo/.git/worktrees/repo-feature\n') + + const worktree = await resolveWorkspaceCleanupActivityWorktree( + REPO, + makeWorktree({ path: worktreePath }), + statPath, + readTextFile + ) + + expect(readTextFile).toHaveBeenCalledWith(path.join(worktreePath, '.git')) + expect(statPath).toHaveBeenCalledWith(gitDirPath) + expect(statPath).toHaveBeenCalledWith(gitDirHeadPath) + expect(statPath).toHaveBeenCalledWith(gitDirLogsHeadPath) + expect(statPath).not.toHaveBeenCalledWith('/home/me/repo/.git/worktrees/repo-feature') + expect(worktree.lastActivityAt).toBe(70_000) + }) + + it('keeps persisted activity when it is newer than local metadata', async () => { + const statPath = vi.fn(async () => ({ mtimeMs: 10_000 })) + + const worktree = await resolveWorkspaceCleanupActivityWorktree( + REPO, + makeWorktree({ lastActivityAt: 30_000 }), + statPath + ) + + expect(worktree.lastActivityAt).toBe(30_000) + }) + + it('does not stat remote worktree paths', async () => { + const statPath = vi.fn(async () => ({ mtimeMs: 20_000 })) + + const worktree = await resolveWorkspaceCleanupActivityWorktree( + { ...REPO, connectionId: 'ssh-1' }, + makeWorktree({ createdAt: 10_000 }), + statPath + ) + + expect(statPath).not.toHaveBeenCalled() + expect(worktree.lastActivityAt).toBe(10_000) + }) +}) diff --git a/src/main/ipc/workspace-cleanup-activity.ts b/src/main/ipc/workspace-cleanup-activity.ts new file mode 100644 index 000000000000..9026b4464d97 --- /dev/null +++ b/src/main/ipc/workspace-cleanup-activity.ts @@ -0,0 +1,126 @@ +import { lstat, readFile } from 'node:fs/promises' +import path from 'node:path' +import type { Repo, Worktree } from '../../shared/types' +import { parseWslUncPath } from '../../shared/wsl-paths' +import { toWindowsWslPath } from '../wsl' + +type StatPath = (targetPath: string) => Promise<{ mtimeMs: number }> +type ReadTextFile = (targetPath: string) => Promise + +export function getPersistedWorkspaceCleanupActivityAt( + worktree: Pick +): number { + const persistedActivityAt = Number.isFinite(worktree.lastActivityAt) ? worktree.lastActivityAt : 0 + const createdAt = Number.isFinite(worktree.createdAt) ? (worktree.createdAt ?? 0) : 0 + return Math.max(persistedActivityAt, createdAt) +} + +export function resolvePersistedWorkspaceCleanupActivityWorktree(worktree: Worktree): Worktree { + const persistedActivityAt = getPersistedWorkspaceCleanupActivityAt(worktree) + if (persistedActivityAt <= worktree.lastActivityAt) { + return worktree + } + return { ...worktree, lastActivityAt: persistedActivityAt } +} + +export async function resolveWorkspaceCleanupActivityWorktree( + repo: Repo, + worktree: Worktree, + statPath: StatPath = statLocalPath, + readTextFile: ReadTextFile = readLocalTextFile +): Promise { + const activityAt = await resolveWorkspaceCleanupActivityAt(repo, worktree, statPath, readTextFile) + if (activityAt <= worktree.lastActivityAt) { + return worktree + } + return { ...worktree, lastActivityAt: activityAt } +} + +async function statLocalPath(targetPath: string): Promise<{ mtimeMs: number }> { + const stats = await lstat(targetPath) + return { mtimeMs: Number(stats.mtimeMs) } +} + +async function readLocalTextFile(targetPath: string): Promise { + return readFile(targetPath, 'utf8') +} + +async function resolveWorkspaceCleanupActivityAt( + repo: Repo, + worktree: Worktree, + statPath: StatPath, + readTextFile: ReadTextFile +): Promise { + const persistedActivityAt = getPersistedWorkspaceCleanupActivityAt(worktree) + if (repo.connectionId) { + return persistedActivityAt + } + + const filesystemActivityAt = await getNewestLocalWorktreeStatMtime( + worktree.path, + statPath, + readTextFile + ) + return Math.max(persistedActivityAt, filesystemActivityAt) +} + +// Why: best-effort only. Win32 stat over \\wsl.localhost (9P) can falsely +// report ENOENT (see wslUncDirectoryExists), so a failed stat degrades to the +// persisted activity timestamp instead of blocking or mislabeling the row. +async function getNewestLocalWorktreeStatMtime( + worktreePath: string, + statPath: StatPath, + readTextFile: ReadTextFile +): Promise { + const gitPath = path.join(worktreePath, '.git') + const gitDirPath = await readLocalWorktreeGitDir(worktreePath, gitPath, readTextFile) + const gitDirMtimePromises = gitDirPath + ? [ + readMtime(gitDirPath, statPath), + readMtime(path.join(gitDirPath, 'HEAD'), statPath), + readMtime(path.join(gitDirPath, 'logs', 'HEAD'), statPath) + ] + : [] + const mtimes = await Promise.all([ + readMtime(worktreePath, statPath), + readMtime(gitPath, statPath), + ...gitDirMtimePromises + ]) + return Math.max(0, ...mtimes) +} + +async function readLocalWorktreeGitDir( + worktreePath: string, + gitPath: string, + readTextFile: ReadTextFile +): Promise { + try { + const contents = await readTextFile(gitPath) + const match = /^gitdir:\s*(.+)\s*$/im.exec(contents) + if (!match) { + return null + } + const gitDir = match[1]?.trim() + if (!gitDir) { + return null + } + // Why: linked worktrees keep mutable git state outside the worktree; the + // pointer file mtime alone can miss recent external commits. + const wslWorktree = parseWslUncPath(worktreePath) + if (wslWorktree && gitDir.startsWith('/')) { + return toWindowsWslPath(gitDir, wslWorktree.distro) + } + return path.isAbsolute(gitDir) ? gitDir : path.resolve(worktreePath, gitDir) + } catch { + return null + } +} + +async function readMtime(targetPath: string, statPath: StatPath): Promise { + try { + const stats = await statPath(targetPath) + return Number.isFinite(stats.mtimeMs) ? stats.mtimeMs : 0 + } catch { + return 0 + } +} diff --git a/src/main/ipc/workspace-cleanup-scan.ts b/src/main/ipc/workspace-cleanup-scan.ts index 33866e6cd73f..a9b6ff704ca5 100644 --- a/src/main/ipc/workspace-cleanup-scan.ts +++ b/src/main/ipc/workspace-cleanup-scan.ts @@ -3,7 +3,7 @@ import { listRepoWorktrees, createFolderWorktree } from '../repo-worktrees' import { getSshGitProvider } from '../providers/ssh-git-dispatch' import type { IGitProvider } from '../providers/types' import { isFolderRepo } from '../../shared/repo-kind' -import type { GitWorktreeInfo, Repo } from '../../shared/types' +import type { GitWorktreeInfo, Repo, Worktree } from '../../shared/types' import { mergeWorktree } from './worktree-logic' import { splitWorktreeId } from '../../shared/worktree-id' import type { @@ -13,6 +13,11 @@ import type { WorkspaceCleanupScanProgress, WorkspaceCleanupScanResult } from '../../shared/workspace-cleanup' +import { + getPersistedWorkspaceCleanupActivityAt, + resolvePersistedWorkspaceCleanupActivityWorktree, + resolveWorkspaceCleanupActivityWorktree +} from './workspace-cleanup-activity' import { buildWorkspaceCleanupCandidate, buildWorkspaceCleanupCandidateFromError, @@ -124,48 +129,92 @@ async function scanRepoWorkspaces( return { scannedAt, candidates, errors: [] } } - const worktrees = gitWorktrees - .map((gitWorktree) => { - const worktreeId = `${repo.id}::${gitWorktree.path}` - const meta = store.getWorktreeMeta(worktreeId) - return mergeWorktree(repo.id, gitWorktree, meta, repo.displayName) - }) - .filter((worktree) => { - if (targetWorktreeId) { - return worktree.id === targetWorktreeId - } - return ( - !repoIsFolder && - !worktree.isMainWorktree && - isWorkspaceInactiveForCleanup(worktree, scannedAt) + const mergedWorktrees = gitWorktrees.map((gitWorktree) => { + const worktreeId = `${repo.id}::${gitWorktree.path}` + const meta = store.getWorktreeMeta(worktreeId) + return mergeWorktree(repo.id, gitWorktree, meta, repo.displayName) + }) + const candidateWorktrees = targetWorktreeId + ? mergedWorktrees.filter((worktree) => worktree.id === targetWorktreeId) + : mergedWorktrees.filter((worktree) => + shouldResolveBroadWorkspaceCleanupActivity(repoIsFolder, worktree, scannedAt) ) - }) - - onWorktreesDiscovered?.(worktrees.length) - - const candidates = await mapWorkspaceCleanupWithConcurrency( - worktrees, + // Why: fs stat has no cancellation, so on a hung network/WSL mount every + // timed-out row would abandon more threadpool work. After the first timeout, + // stop statting this repo and use persisted activity only. + let activityStatsUnavailable = false + const candidatesWithSkipped = await mapWorkspaceCleanupWithConcurrency( + candidateWorktrees, WORKTREE_SCAN_CONCURRENCY, async (worktree) => { + // Why: externally-created worktrees can miss Orca activity stamps; local + // filesystem metadata is a conservative guard before suggesting deletion. + const worktreeWithActivity = activityStatsUnavailable + ? resolvePersistedWorkspaceCleanupActivityWorktree(worktree) + : await resolveCleanupActivityWithTimeout(repo, worktree, () => { + activityStatsUnavailable = true + }) + if (!targetWorktreeId && !isWorkspaceInactiveForCleanup(worktreeWithActivity, scannedAt)) { + return null + } + onWorktreesDiscovered?.(1) const candidate = await buildWorkspaceCleanupCandidate({ repo, - worktree, + worktree: worktreeWithActivity, scannedAt, provider, - skipGit: skipGitWorktreeIds.has(worktree.id), + skipGit: skipGitWorktreeIds.has(worktreeWithActivity.id), forceGitCheck: Boolean(targetWorktreeId) }).catch((error) => { console.error('Workspace cleanup candidate scan failed', error) - return buildWorkspaceCleanupCandidateFromError(repo, worktree, scannedAt) + return buildWorkspaceCleanupCandidateFromError(repo, worktreeWithActivity, scannedAt) }) onCandidateScanned?.(candidate) return candidate } ) + const candidates = candidatesWithSkipped.filter( + (candidate): candidate is WorkspaceCleanupCandidate => candidate !== null + ) return { scannedAt, candidates, errors } } +async function resolveCleanupActivityWithTimeout( + repo: Repo, + worktree: Worktree, + onActivityStatsUnavailable: () => void +): Promise { + try { + return await withWorkspaceCleanupTimeout( + () => resolveWorkspaceCleanupActivityWorktree(repo, worktree), + WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS, + 'Timed out reading worktree activity.' + ) + } catch (error) { + onActivityStatsUnavailable() + console.warn('Workspace cleanup activity scan failed', error) + return resolvePersistedWorkspaceCleanupActivityWorktree(worktree) + } +} + +function shouldResolveBroadWorkspaceCleanupActivity( + repoIsFolder: boolean, + worktree: Worktree, + scannedAt: number +): boolean { + if (repoIsFolder || worktree.isMainWorktree) { + return false + } + return isWorkspaceInactiveForCleanup( + { + isArchived: worktree.isArchived, + lastActivityAt: getPersistedWorkspaceCleanupActivityAt(worktree) + }, + scannedAt + ) +} + async function listCleanupGitWorktrees( repo: Repo, repoIsFolder: boolean diff --git a/src/main/ipc/workspace-cleanup.test.ts b/src/main/ipc/workspace-cleanup.test.ts index af084713a0b7..1d02e59db291 100644 --- a/src/main/ipc/workspace-cleanup.test.ts +++ b/src/main/ipc/workspace-cleanup.test.ts @@ -1,3 +1,4 @@ +import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { ipcMain } from 'electron' import type { Store } from '../persistence' @@ -11,6 +12,8 @@ import type { import type { WorkspaceCleanupScanProgress } from '../../shared/workspace-cleanup' const { + lstatMock, + readFileMock, listRepoWorktreesMock, getStatusMock, gitExecFileAsyncMock, @@ -18,6 +21,8 @@ const { getSshPtyProviderMock, listRegisteredPtysMock } = vi.hoisted(() => ({ + lstatMock: vi.fn(), + readFileMock: vi.fn(), listRepoWorktreesMock: vi.fn(), getStatusMock: vi.fn(), gitExecFileAsyncMock: vi.fn(), @@ -26,6 +31,11 @@ const { listRegisteredPtysMock: vi.fn() })) +vi.mock('node:fs/promises', () => ({ + lstat: lstatMock, + readFile: readFileMock +})) + vi.mock('electron', () => ({ ipcMain: { handle: vi.fn(), @@ -92,6 +102,22 @@ function buildWorktreeIds(repoId: string, count: number): string[] { return worktreeIds } +function makeWorktreeMeta(overrides: Partial = {}): WorktreeMeta { + return { + displayName: 'Feature', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: NOW, + ...overrides + } +} + function makeStore( options: { baseRef?: string @@ -123,6 +149,8 @@ describe('workspace cleanup scan', () => { beforeEach(() => { vi.useFakeTimers() vi.setSystemTime(NOW) + lstatMock.mockReset() + readFileMock.mockReset() listRepoWorktreesMock.mockReset() getStatusMock.mockReset() gitExecFileAsyncMock.mockReset() @@ -130,6 +158,8 @@ describe('workspace cleanup scan', () => { getSshPtyProviderMock.mockReset() listRegisteredPtysMock.mockReset() listRegisteredPtysMock.mockReturnValue([]) + lstatMock.mockResolvedValue({ mtimeMs: 0 }) + readFileMock.mockRejectedValue(new Error('not a gitdir pointer')) vi.mocked(ipcMain.handle).mockReset() vi.mocked(ipcMain.removeHandler).mockReset() listRepoWorktreesMock.mockResolvedValue([ @@ -199,7 +229,7 @@ describe('workspace cleanup scan', () => { expect(progress[0]).toMatchObject({ scanId: 'scan-1', scannedWorktreeCount: 0, - totalWorktreeCount: 2, + totalWorktreeCount: 1, candidates: [] }) const candidateProgress = progress.filter( @@ -222,6 +252,55 @@ describe('workspace cleanup scan', () => { }) }) + it('emits ready rows while another activity metadata read is stalled', async () => { + listRepoWorktreesMock.mockResolvedValue([ + { + path: '/repo-feature-a', + head: 'abc123', + branch: 'refs/heads/feature-a', + isBare: false, + isMainWorktree: false + }, + { + path: '/repo-feature-b', + head: 'def456', + branch: 'refs/heads/feature-b', + isBare: false, + isMainWorktree: false + } + ]) + lstatMock.mockImplementation((targetPath: string) => { + if (targetPath.startsWith('/repo-feature-a')) { + return new Promise(() => undefined) + } + return Promise.resolve({ mtimeMs: 0 }) + }) + const progress: WorkspaceCleanupScanProgress[] = [] + + const scanPromise = scanWorkspaceCleanup( + makeStore(), + { scanId: 'scan-1' }, + { onProgress: (event) => progress.push(event) } + ) + + await vi.waitFor(() => { + expect( + progress.some((event) => event.candidates[0]?.worktreeId === 'repo-1::/repo-feature-b') + ).toBe(true) + }) + expect(progress.at(-1)).toMatchObject({ + scannedWorktreeCount: 1, + totalWorktreeCount: 1 + }) + + await vi.advanceTimersByTimeAsync(8_000) + const result = await scanPromise + + expect(result.candidates.map((candidate) => candidate.worktreeId)).toEqual( + expect.arrayContaining(['repo-1::/repo-feature-a', 'repo-1::/repo-feature-b']) + ) + }) + it('keeps raw scan errors out of renderer-facing results', async () => { listRepoWorktreesMock.mockRejectedValue(new Error('fatal: path /Users/alice/private failed')) @@ -273,18 +352,10 @@ describe('workspace cleanup scan', () => { it('uses direct metadata lookup for focused disconnected remote preflight', async () => { const targetWorktreeId = 'repo-1::/remote/repo-feature' - const targetMeta: WorktreeMeta = { + const targetMeta = makeWorktreeMeta({ displayName: 'Remote Feature', - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, lastActivityAt: NOW - 2 * 24 * 60 * 60 * 1000 - } + }) const getWorktreeMeta = vi.fn((worktreeId: string) => worktreeId === targetWorktreeId ? targetMeta : undefined ) @@ -313,6 +384,35 @@ describe('workspace cleanup scan', () => { }) }) + it('stats only the requested worktree during focused local preflight scans', async () => { + listRepoWorktreesMock.mockResolvedValue([ + { + path: '/repo-feature-a', + head: 'abc123', + branch: 'refs/heads/feature-a', + isBare: false, + isMainWorktree: false + }, + { + path: '/repo-feature-b', + head: 'def456', + branch: 'refs/heads/feature-b', + isBare: false, + isMainWorktree: false + } + ]) + + const result = await scanWorkspaceCleanup(makeStore(), { + worktreeId: 'repo-1::/repo-feature-b' + }) + + expect(result.candidates).toHaveLength(1) + expect(result.candidates[0]?.worktreeId).toBe('repo-1::/repo-feature-b') + expect(lstatMock).toHaveBeenCalledTimes(2) + expect(lstatMock).toHaveBeenCalledWith('/repo-feature-b') + expect(lstatMock).toHaveBeenCalledWith(path.join('/repo-feature-b', '.git')) + }) + it('scans connected remote workspaces through the SSH git provider', async () => { const provider = { listWorktrees: vi.fn().mockResolvedValue([ @@ -385,6 +485,116 @@ describe('workspace cleanup scan', () => { expect(result.candidates).toEqual([]) }) + it('stats only broad-scan rows that remain possible cleanup candidates', async () => { + listRepoWorktreesMock.mockResolvedValue([ + { + path: '/repo', + head: 'main123', + branch: 'refs/heads/main', + isBare: false, + isMainWorktree: true + }, + { + path: '/repo-old', + head: 'old123', + branch: 'refs/heads/old', + isBare: false, + isMainWorktree: false + }, + { + path: '/repo-recent', + head: 'recent123', + branch: 'refs/heads/recent', + isBare: false, + isMainWorktree: false + }, + { + path: '/repo-new-created', + head: 'created123', + branch: 'refs/heads/created', + isBare: false, + isMainWorktree: false + } + ]) + const metadataByWorktreeId: Record = { + 'repo-1::/repo-old': makeWorktreeMeta({ + lastActivityAt: NOW - 40 * 24 * 60 * 60 * 1000, + baseRef: 'origin/main' + }), + 'repo-1::/repo-recent': makeWorktreeMeta({ + lastActivityAt: NOW - 2 * 24 * 60 * 60 * 1000, + baseRef: 'origin/main' + }), + 'repo-1::/repo-new-created': makeWorktreeMeta({ + createdAt: NOW - 1_000, + lastActivityAt: NOW - 40 * 24 * 60 * 60 * 1000, + baseRef: 'origin/main' + }) + } + const store = { + ...makeStore(), + getWorktreeMeta: (worktreeId: string) => metadataByWorktreeId[worktreeId] + } as unknown as Store + + const result = await scanWorkspaceCleanup(store) + + expect(result.candidates.map((candidate) => candidate.worktreeId)).toEqual([ + 'repo-1::/repo-old' + ]) + expect(lstatMock).toHaveBeenCalledTimes(2) + expect(lstatMock).toHaveBeenCalledWith('/repo-old') + expect(lstatMock).toHaveBeenCalledWith(path.join('/repo-old', '.git')) + expect(getStatusMock).toHaveBeenCalledTimes(1) + }) + + it('falls back when broad-scan activity metadata stalls', async () => { + lstatMock.mockReturnValue(new Promise(() => undefined)) + const progress: unknown[] = [] + + const scanPromise = scanWorkspaceCleanup( + makeStore(), + { scanId: 'scan-1' }, + { onProgress: (event) => progress.push(event) } + ) + await vi.advanceTimersByTimeAsync(8_000) + + const result = await scanPromise + + expect(result.candidates).toHaveLength(1) + expect(result.candidates[0]?.worktreeId).toBe('repo-1::/repo-feature') + expect(progress[0]).toMatchObject({ + scanId: 'scan-1', + scannedWorktreeCount: 0, + totalWorktreeCount: 1 + }) + expect(progress.at(-1)).toMatchObject({ + scanId: 'scan-1', + scannedWorktreeCount: 1, + totalWorktreeCount: 1 + }) + }) + + it('stops statting a repo after the first activity metadata timeout', async () => { + listRepoWorktreesMock.mockResolvedValue( + ['/repo-a', '/repo-b', '/repo-c', '/repo-d'].map((worktreePath, index) => ({ + path: worktreePath, + head: `head-${index}`, + branch: `refs/heads/branch-${index}`, + isBare: false, + isMainWorktree: false + })) + ) + lstatMock.mockReturnValue(new Promise(() => undefined)) + + const scanPromise = scanWorkspaceCleanup(makeStore()) + await vi.advanceTimersByTimeAsync(8_000) + const result = await scanPromise + + expect(result.candidates).toHaveLength(4) + expect(lstatMock).not.toHaveBeenCalledWith('/repo-d') + expect(lstatMock).not.toHaveBeenCalledWith(path.join('/repo-d', '.git')) + }) + it('includes focused remove preflight rows even when they are recent', async () => { const result = await scanWorkspaceCleanup( makeStore({ diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index e0a2bbf5db12..43ef357eed6a 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -477,7 +477,11 @@ async function refreshRemoteTrackingBaseForWorktreeCreate( return getOrStartSshWorktreeCreateFetch( getSshWorktreeCreateBaseFetchKey(repo, base), getSshWorktreeCreateRemoteQueueKey(repo, base.remote), - () => provider.fetchRemoteTrackingRef(repo.path, base.remote, base.branch, base.ref) + () => + // Why: the exact-base refresh gates create; unrelated repo housekeeping must not extend it. + provider.fetchRemoteTrackingRef(repo.path, base.remote, base.branch, base.ref, { + skipAutoMaintenance: true + }) ) } diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index e9f9edfcdae2..8e128912517a 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -5,8 +5,10 @@ import { lstat, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import type { CreateWorktreeResult, GitWorktreeInfo, Worktree } from '../../shared/types' +import * as localWorktreeFilesystem from '../local-worktree-filesystem' const ORIGINAL_PLATFORM = process.platform +const removeWorktreeLinkedPathsMock = vi.hoisted(() => vi.fn()) function setPlatform(platform: NodeJS.Platform): void { Object.defineProperty(process, 'platform', { @@ -168,6 +170,11 @@ vi.mock('../providers/ssh-filesystem-dispatch', () => ({ getSshFilesystemProvider: getSshFilesystemProviderMock })) +vi.mock('./worktree-symlinks', () => ({ + createWorktreeLinkedPaths: vi.fn(), + removeWorktreeLinkedPaths: removeWorktreeLinkedPathsMock +})) + vi.mock('./ssh', () => ({ getActiveMultiplexer: getActiveMultiplexerMock })) @@ -336,7 +343,8 @@ describe('registerWorktreeHandlers', () => { clearProviderPtyStateMock, getLocalPtyProviderMock, deleteWorktreeHistoryDirMock, - advertisedUrlWatcherForgetWorktreeMock + advertisedUrlWatcherForgetWorktreeMock, + removeWorktreeLinkedPathsMock ]) { m.mockReset() } @@ -661,8 +669,8 @@ describe('registerWorktreeHandlers', () => { function mockKnownFeatureWorktree( path = '/workspace/feature-wt', repoPath = '/workspace/repo' - ): void { - listWorktreesMock.mockResolvedValue([ + ): GitWorktreeInfo[] { + const worktrees: GitWorktreeInfo[] = [ { path: repoPath, head: 'main', @@ -677,7 +685,9 @@ describe('registerWorktreeHandlers', () => { isBare: false, isMainWorktree: false } - ]) + ] + listWorktreesMock.mockResolvedValue(worktrees) + return worktrees } function makeWorktreeMeta(overrides: Record = {}): Record { @@ -3733,7 +3743,8 @@ describe('registerWorktreeHandlers', () => { '/remote/repo', 'origin', 'master', - 'refs/remotes/origin/master' + 'refs/remotes/origin/master', + { skipAutoMaintenance: true } ) }) @@ -3800,7 +3811,8 @@ describe('registerWorktreeHandlers', () => { '/remote/repo', 'origin', 'main', - 'refs/remotes/origin/main' + 'refs/remotes/origin/main', + { skipAutoMaintenance: true } ) expect(provider.addWorktree).toHaveBeenCalledWith( '/remote/repo', @@ -4032,7 +4044,8 @@ describe('registerWorktreeHandlers', () => { '/remote/repo', 'origin', 'main', - 'refs/remotes/origin/main' + 'refs/remotes/origin/main', + { skipAutoMaintenance: true } ) expect(provider.addWorktree).toHaveBeenCalledTimes(2) }) @@ -6258,7 +6271,11 @@ describe('registerWorktreeHandlers', () => { const worktreePath = join(parentDir, 'feature-wt') await mkdir(worktreePath, { recursive: true }) await writeFile(join(worktreePath, 'scratch.txt'), 'delete me') - mockKnownFeatureWorktree(worktreePath, repoPath) + const registeredWorktrees = mockKnownFeatureWorktree(worktreePath, repoPath) + listWorktreesMock + .mockResolvedValueOnce(registeredWorktrees) + .mockResolvedValueOnce(registeredWorktrees) + .mockResolvedValue([]) store.getWorktreeMeta.mockReturnValue(makeWorktreeMeta()) const longPathError = Object.assign(new Error('git worktree remove failed'), { stderr: 'error: failed to delete deep/file.txt: Filename too long' @@ -6292,7 +6309,11 @@ describe('registerWorktreeHandlers', () => { it('does not create a preserved-branch target when long-path recovery preserves branch by policy', async () => { setPlatform('win32') - mockKnownFeatureWorktree() + const registeredWorktrees = mockKnownFeatureWorktree() + listWorktreesMock + .mockResolvedValueOnce(registeredWorktrees) + .mockResolvedValueOnce(registeredWorktrees) + .mockResolvedValue([]) store.getWorktreeMeta.mockReturnValue(makeWorktreeMeta({ preserveBranchOnDelete: true })) removeWorktreeMock.mockRejectedValue( Object.assign(new Error('git worktree remove failed'), { @@ -6332,39 +6353,49 @@ describe('registerWorktreeHandlers', () => { expect(store.removeWorktreeMeta).not.toHaveBeenCalled() }) - it('keeps metadata when Windows long-path recovery deletes the directory but prune fails', async () => { + it('refuses Windows recovery while Git still reports the row and keeps metadata', async () => { setPlatform('win32') mockKnownFeatureWorktree() store.getWorktreeMeta.mockReturnValue(makeWorktreeMeta()) + const removePathSpy = vi + .spyOn(localWorktreeFilesystem, 'removeLocalWorktreePath') + .mockResolvedValue(undefined) removeWorktreeMock.mockRejectedValue( Object.assign(new Error('git worktree remove failed'), { stderr: 'error: failed to delete deep/file.txt: Filename too long' }) ) - gitExecFileAsyncMock.mockRejectedValue( - Object.assign(new Error('git prune failed'), { - stderr: 'fatal: unable to lock worktree admin dir' - }) - ) - await expect( - handlers['worktrees:remove'](null, { - worktreeId: 'repo-1::/workspace/feature-wt', - force: true - }) - ).rejects.toThrow('Git still has stale worktree registration') + try { + await expect( + handlers['worktrees:remove'](null, { + worktreeId: 'repo-1::/workspace/feature-wt', + force: true + }) + ).rejects.toThrow( + 'Failed to force delete worktree at /workspace/feature-wt. error: failed to delete deep/file.txt: Filename too long' + ) - expect(store.removeWorktreeMeta).not.toHaveBeenCalled() - expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('worktrees:changed', { - repoId: 'repo-1' - }) + expect(removePathSpy).not.toHaveBeenCalled() + expect(gitExecFileAsyncMock).not.toHaveBeenCalledWith( + ['worktree', 'prune'], + expect.anything() + ) + expect(store.removeWorktreeMeta).not.toHaveBeenCalled() + expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('worktrees:changed', { + repoId: 'repo-1' + }) + } finally { + removePathSpy.mockRestore() + } }) it('retries stale Git registration cleanup after prior local filesystem recovery', async () => { setPlatform('win32') const missingWorktreePath = 'C:\\workspace\\already-removed' const worktreeId = `repo-1::${missingWorktreePath}` - mockKnownFeatureWorktree(missingWorktreePath) + const registeredWorktrees = mockKnownFeatureWorktree(missingWorktreePath) + listWorktreesMock.mockResolvedValueOnce(registeredWorktrees).mockResolvedValue([]) store.getWorktreeMeta.mockReturnValue(makeWorktreeMeta()) const result = await handlers['worktrees:remove'](null, { @@ -6384,6 +6415,40 @@ describe('registerWorktreeHandlers', () => { expect(store.removeWorktreeMeta).toHaveBeenCalledWith(worktreeId) }) + it('preserves a locked missing registration even with force', async () => { + setPlatform('win32') + const missingWorktreePath = 'C:\\workspace\\locked-already-removed' + const worktreeId = `repo-1::${missingWorktreePath}` + const registeredWorktrees: GitWorktreeInfo[] = [ + { + path: '/workspace/repo', + head: 'main', + branch: 'main', + isBare: false, + isMainWorktree: true + }, + { + path: missingWorktreePath, + head: 'feature', + branch: 'feature', + isBare: false, + isMainWorktree: false, + locked: true, + lockReason: 'active agent session' + } + ] + listWorktreesMock.mockResolvedValue(registeredWorktrees) + store.getWorktreeMeta.mockReturnValue(makeWorktreeMeta()) + removeWorktreeMock.mockResolvedValue({}) + + await expect(handlers['worktrees:remove'](null, { worktreeId, force: true })).rejects.toThrow( + 'Worktree is locked by Git. Lock reason: active agent session' + ) + + expect(removeWorktreeMock).not.toHaveBeenCalled() + expect(store.removeWorktreeMeta).not.toHaveBeenCalled() + }) + it('refuses to delete the root workspace for folder-mode repos', async () => { store.getRepo.mockReturnValue({ id: 'repo-folder', @@ -6932,6 +6997,169 @@ describe('registerWorktreeHandlers', () => { expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/feature-wt', undefined) }) + it('uses the workspace host when duplicate repo ids exist across local and SSH', async () => { + const localRepo = { + id: 'repo-shared', + path: '/local/repo', + displayName: 'local', + badgeColor: '#000', + addedAt: 0, + worktreeBaseRef: null + } + const sshRepo = { + ...localRepo, + path: '/remote/repo', + displayName: 'ssh', + connectionId: 'conn-1' + } + const provider = { + listWorktrees: vi.fn().mockResolvedValue([ + { + path: sshRepo.path, + head: 'main', + branch: 'main', + isBare: false, + isMainWorktree: true + }, + { + path: '/remote/feature-wt', + head: 'feature', + branch: 'feature', + isBare: false, + isMainWorktree: false + } + ]), + removeWorktree: vi.fn().mockResolvedValue(undefined), + worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }) + } + store.getRepo.mockReturnValue(localRepo) + store.getRepos.mockReturnValue([localRepo, sshRepo]) + getSshGitProviderMock.mockReturnValue(provider) + + await handlers['worktrees:remove'](null, { + worktreeId: 'repo-shared::/remote/feature-wt', + hostId: 'ssh:conn-1' + }) + + expect(provider.removeWorktree).toHaveBeenCalledWith('/remote/feature-wt', undefined) + expect(removeWorktreeMock).not.toHaveBeenCalled() + }) + + it('fails closed when duplicate repo ids are deleted without a host', async () => { + const localRepo = { + id: 'repo-shared', + path: '/local/repo', + displayName: 'local', + badgeColor: '#000', + addedAt: 0 + } + const sshRepo = { ...localRepo, path: '/remote/repo', connectionId: 'conn-1' } + store.getRepos.mockReturnValue([localRepo, sshRepo]) + + await expect( + handlers['worktrees:remove'](null, { + worktreeId: 'repo-shared::/remote/feature-wt' + }) + ).rejects.toThrow('Repo not found: repo-shared') + + expect(removeWorktreeMock).not.toHaveBeenCalled() + expect(getSshGitProviderMock).not.toHaveBeenCalled() + }) + + it('inspects hooks on the requested host when repo ids collide', async () => { + const localRepo = { + id: 'repo-shared', + path: '/local/repo', + displayName: 'local', + badgeColor: '#000', + addedAt: 0 + } + const sshRepo = { ...localRepo, path: '/remote/repo', connectionId: 'conn-1' } + const fsProvider = { + readFile: vi.fn().mockResolvedValue({ + content: 'scripts:\n archive: remote-cleanup', + isBinary: false + }) + } + store.getRepos.mockReturnValue([localRepo, sshRepo]) + getSshFilesystemProviderMock.mockReturnValue(fsProvider) + parseOrcaYamlMock.mockReturnValue({ scripts: { archive: 'remote-cleanup' } }) + + await expect( + handlers['hooks:check'](null, { + repoId: 'repo-shared', + hostId: 'ssh:conn-1' + }) + ).resolves.toEqual({ + status: 'ok', + hasHooks: true, + hooks: { scripts: { archive: 'remote-cleanup' } }, + mayNeedUpdate: false + }) + expect(fsProvider.readFile).toHaveBeenCalledWith('/remote/repo/orca.yaml') + expect(hasHooksFileMock).not.toHaveBeenCalled() + }) + + it('fails hook inspection closed when duplicate repo ids omit the host', async () => { + const localRepo = { + id: 'repo-shared', + path: '/local/repo', + displayName: 'local', + badgeColor: '#000', + addedAt: 0 + } + const sshRepo = { ...localRepo, path: '/remote/repo', connectionId: 'conn-1' } + store.getRepos.mockReturnValue([localRepo, sshRepo]) + + await expect(handlers['hooks:check'](null, { repoId: 'repo-shared' })).resolves.toEqual({ + status: 'error', + hasHooks: false, + hooks: null, + mayNeedUpdate: false + }) + expect(getSshFilesystemProviderMock).not.toHaveBeenCalled() + expect(hasHooksFileMock).not.toHaveBeenCalled() + }) + + it('does not coalesce forget requests for the same id on different hosts', async () => { + const localRepo = { + id: 'repo-shared', + path: '/local/repo', + displayName: 'local', + badgeColor: '#000', + addedAt: 0 + } + const sshRepo = { ...localRepo, path: '/remote/repo', connectionId: 'conn-1' } + store.getRepos.mockReturnValue([localRepo, sshRepo]) + let finishFirst!: () => void + killAllProcessesForWorktreeMock + .mockImplementationOnce( + () => + new Promise((resolve) => { + finishFirst = () => + resolve({ runtimeStopped: 0, providerStopped: 0, registryStopped: 0 }) + }) + ) + .mockResolvedValueOnce({ runtimeStopped: 0, providerStopped: 0, registryStopped: 0 }) + + const first = handlers['worktrees:forgetLocal'](null, { + worktreeId: 'repo-shared::/same/path', + hostId: 'local' + }) as Promise + await vi.waitFor(() => expect(killAllProcessesForWorktreeMock).toHaveBeenCalledTimes(1)) + + await expect( + handlers['worktrees:forgetLocal'](null, { + worktreeId: 'repo-shared::/same/path', + hostId: 'ssh:conn-1' + }) + ).resolves.toEqual({}) + expect(killAllProcessesForWorktreeMock).toHaveBeenCalledTimes(2) + + finishFirst() + await expect(first).resolves.toEqual({}) + }) + it('preserves the branch on remove for worktrees created from an existing local branch', async () => { mockKnownFeatureWorktree() removeWorktreeMock.mockResolvedValue(undefined) @@ -7254,14 +7482,16 @@ describe('registerWorktreeHandlers', () => { await mkdir(adminWorktreePath, { recursive: true }) await writeFile(join(orphanPath, '.git'), `gitdir: ${adminWorktreePath}\n`) await writeFile(join(adminWorktreePath, 'gitdir'), `${join(orphanPath, '.git')}\n`) - store.getRepo.mockReturnValue({ + const repo = { id: 'repo-1', path: repoPath, displayName: 'repo', badgeColor: '#000', addedAt: 0, worktreeBaseRef: null - }) + } + store.getRepo.mockReturnValue(repo) + store.getRepos.mockReturnValue([repo]) mockKnownFeatureWorktree(join(parentDir, 'real-feature'), repoPath) store.getWorktreeMeta.mockReturnValue(makeWorktreeMeta({ createdAt: Date.now() })) @@ -7295,14 +7525,16 @@ describe('registerWorktreeHandlers', () => { await mkdir(adminWorktreePath, { recursive: true }) await writeFile(join(orphanPath, '.git'), `gitdir: ${adminWorktreePath}\n`) await writeFile(join(adminWorktreePath, 'gitdir'), `${join(orphanPath, '.git')}\n`) - store.getRepo.mockReturnValue({ + const repo = { id: 'repo-1', path: repoPath, displayName: 'repo', badgeColor: '#000', addedAt: 0, worktreeBaseRef: null - }) + } + store.getRepo.mockReturnValue(repo) + store.getRepos.mockReturnValue([repo]) mockKnownFeatureWorktree(join(parentDir, 'real-feature'), repoPath) store.getWorktreeMeta.mockReturnValue( makeWorktreeMeta({ orcaCreatedAt: Date.now(), orcaCreationSource: 'runtime' }) @@ -7524,6 +7756,7 @@ describe('registerWorktreeHandlers', () => { }) as Promise const second = handlers['worktrees:remove'](null, { worktreeId: 'repo-1::/workspace/feature-wt', + hostId: 'local', force: true }) as Promise @@ -7561,6 +7794,7 @@ describe('registerWorktreeHandlers', () => { await expect( handlers['worktrees:remove'](null, { worktreeId: 'repo-1::/workspace/feature-wt', + hostId: 'local', force: true }) ).rejects.toThrow('Worktree deletion already in progress') @@ -7733,6 +7967,86 @@ describe('registerWorktreeHandlers', () => { expect(removeWorktreeMock).not.toHaveBeenCalled() }) + it('fails locked dirty-force deletes before hooks, link cleanup, or PTY teardown', async () => { + listWorktreesMock.mockResolvedValue([ + { + path: '/workspace/repo', + head: 'main', + branch: 'main', + isBare: false, + isMainWorktree: true + }, + { + path: '/workspace/feature-wt', + head: 'feature', + branch: 'feature', + isBare: false, + isMainWorktree: false, + locked: true, + lockReason: 'active agent session' + } + ]) + store.getRepo.mockReturnValue({ + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + symlinkPaths: ['node_modules'] + }) + getEffectiveHooksMock.mockReturnValue({ scripts: { archive: 'echo archived' } }) + + await expect( + handlers['worktrees:remove'](null, { + worktreeId: 'repo-1::/workspace/feature-wt', + force: true + }) + ).rejects.toThrow( + 'Failed to force delete worktree at /workspace/feature-wt. Worktree is locked by Git.' + ) + + expect(assertWorktreeCleanForRemovalMock).not.toHaveBeenCalled() + expect(runHookMock).not.toHaveBeenCalled() + expect(removeWorktreeLinkedPathsMock).not.toHaveBeenCalled() + expect(killAllProcessesForWorktreeMock).not.toHaveBeenCalled() + expect(removeWorktreeMock).not.toHaveBeenCalled() + }) + + it('rechecks a local Git lock after the archive hook before teardown', async () => { + const unlockedWorktrees = mockKnownFeatureWorktree() + const lockedWorktrees = unlockedWorktrees.map((worktree) => + worktree.path === '/workspace/feature-wt' + ? { ...worktree, locked: true, lockReason: 'locked during archive' } + : worktree + ) + listWorktreesMock + .mockResolvedValueOnce(unlockedWorktrees) + .mockResolvedValueOnce(lockedWorktrees) + store.getRepo.mockReturnValue({ + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + symlinkPaths: ['node_modules'] + }) + getEffectiveHooksMock.mockReturnValue({ scripts: { archive: 'echo archived' } }) + runHookMock.mockResolvedValue({ success: true, output: '' }) + + await expect( + handlers['worktrees:remove'](null, { + worktreeId: 'repo-1::/workspace/feature-wt', + force: true + }) + ).rejects.toThrow('Worktree is locked by Git') + + expect(runHookMock).toHaveBeenCalled() + expect(removeWorktreeLinkedPathsMock).not.toHaveBeenCalled() + expect(assertWorktreeCleanForRemovalMock).not.toHaveBeenCalled() + expect(killAllProcessesForWorktreeMock).not.toHaveBeenCalled() + expect(removeWorktreeMock).not.toHaveBeenCalled() + }) + it('formats preflight subprocess failures and does not tear down PTYs', async () => { mockKnownFeatureWorktree() getEffectiveHooksMock.mockReturnValue(null) @@ -7946,4 +8260,80 @@ describe('registerWorktreeHandlers', () => { expect(store.setWorktreeMeta).not.toHaveBeenCalled() expect(createSetupRunnerScriptMock).not.toHaveBeenCalled() }) + + describe('worktrees:forgetLocal', () => { + it('forgets a workspace pinned to a removed SSH target without touching the provider', async () => { + const repo = { + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + connectionId: 'ssh-dead', + worktreeBaseRef: null + } + const ptyProvider = {} as never + const worktreeId = 'repo-1::/workspace/feature-wt' + store.getRepo.mockReturnValue(repo) + getLocalPtyProviderMock.mockReturnValue(ptyProvider) + // Why: a removed/disconnected SSH target has no live provider; forgetLocal + // must not reach for one. + getSshGitProviderMock.mockReturnValue(undefined) + + const result = await handlers['worktrees:forgetLocal'](null, { worktreeId }) + + expect(result).toEqual({}) + expect(killAllProcessesForWorktreeMock).toHaveBeenCalledWith(worktreeId, { + runtime: runtimeStub, + localProvider: ptyProvider, + onPtyStopped: clearProviderPtyStateMock + }) + expect(runtimeStub.clearOptimisticReconcileToken).toHaveBeenCalledWith(worktreeId) + expect(store.removeWorktreeMeta).toHaveBeenCalledWith(worktreeId) + expect(advertisedUrlWatcherForgetWorktreeMock).toHaveBeenCalledWith(worktreeId) + expect(deleteWorktreeHistoryDirMock).toHaveBeenCalledWith(worktreeId) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('worktrees:changed', { + repoId: 'repo-1' + }) + // The whole point: local-only cleanup never dispatches to the SSH provider. + expect(getSshGitProviderMock).not.toHaveBeenCalled() + expect(getSshFilesystemProviderMock).not.toHaveBeenCalled() + expect(listWorktreesMock).not.toHaveBeenCalled() + expect(removeWorktreeMock).not.toHaveBeenCalled() + }) + + it('throws when the repo is missing', async () => { + store.getRepo.mockReturnValue(undefined) + + await expect( + handlers['worktrees:forgetLocal'](null, { + worktreeId: 'repo-gone::/workspace/feature-wt' + }) + ).rejects.toThrow(/Repo not found/) + + expect(store.removeWorktreeMeta).not.toHaveBeenCalled() + expect(getSshGitProviderMock).not.toHaveBeenCalled() + }) + + it('rejects forgetting a folder project root', async () => { + const repo = { + id: 'repo-folder', + path: '/workspace/folder', + displayName: 'folder', + badgeColor: '#000', + addedAt: 0, + kind: 'folder' as const + } + store.getRepo.mockReturnValue(repo) + + await expect( + handlers['worktrees:forgetLocal'](null, { + worktreeId: `${repo.id}::${repo.path}` + }) + ).rejects.toThrow(/project root workspace/) + + expect(store.removeWorktreeMeta).not.toHaveBeenCalled() + expect(deleteWorktreeHistoryDirMock).not.toHaveBeenCalled() + }) + }) }) diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 8b966e2b5376..67468a78b067 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -29,6 +29,8 @@ import type { Worktree, WorktreeMeta } from '../../shared/types' +import { assertWorktreeUnlockedForRemoval } from '../../shared/worktree-removal' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../shared/execution-host' import { buildKnownOrcaWorkspaceLayouts, isLegacyRepoForExternalWorktreeVisibility, @@ -101,6 +103,35 @@ import { type CreateWorktreeArgsWithSystemProvenance = CreateWorktreeArgs & { automationProvenance?: AutomationWorkspaceProvenance } + +type RemoveWorktreeArgs = { + worktreeId: string + hostId?: ExecutionHostId + force?: boolean + skipArchive?: boolean +} + +function getRepoForWorktreeRemoval( + store: Store, + repoId: string, + hostId?: ExecutionHostId +): Repo | undefined { + const matches = store + .getRepos() + .filter((repo) => repo.id === repoId && (!hostId || getRepoExecutionHostId(repo) === hostId)) + // Why: deletion must never guess between host owners. Legacy unscoped calls + // remain compatible only while the repo id still has one unique owner. + if (matches.length === 1) { + return matches[0] + } + if (matches.length > 1) { + return undefined + } + const legacyMatch = store.getRepo(repoId) + return legacyMatch && (!hostId || getRepoExecutionHostId(legacyMatch) === hostId) + ? legacyMatch + : undefined +} import { classifyWorkspaceCreateError } from './workspace-create-error-classifier' import { advertisedUrlWatcher } from '../ports/advertised-url-watcher' import { localhostWorktreeLabelProxy } from '../localhost-worktree-label-proxy' @@ -130,8 +161,8 @@ import { toLocalWorktreeRuntimePath } from '../local-worktree-filesystem' import { - pruneStaleLocalWorktreeRegistrationAfterFilesystemRemoval, - recoverLocalWindowsLongPathWorktreeRemoval + removeStaleLocalWorktreeRegistrationAfterFilesystemRemoval, + recoverLocalWindowsWorktreeRemoval } from '../local-worktree-removal-recovery' const WORKTREE_ARCHIVE_HOOK_TIMEOUT_MS = 120_000 @@ -300,6 +331,10 @@ function getWorktreeRemovalOptionsKey(args: { force?: boolean; skipArchive?: boo return `${forceKey}:${archiveKey}` } +function getWorktreeRemovalInFlightKey(worktreeId: string, hostId?: ExecutionHostId): string { + return `${hostId ?? ''}\0${worktreeId}` +} + async function getArchiveHooksForRemoval(repo: Repo): Promise { if (!repo.connectionId) { return getEffectiveHooks(repo) @@ -931,6 +966,7 @@ export function registerWorktreeHandlers( ipcMain.removeHandler('worktrees:resolvePrBase') ipcMain.removeHandler('worktrees:resolveMrBase') ipcMain.removeHandler('worktrees:remove') + ipcMain.removeHandler('worktrees:forgetLocal') ipcMain.removeHandler('worktrees:forceDeletePreservedBranch') ipcMain.removeHandler('worktrees:updateMeta') ipcMain.removeHandler('worktrees:listLineage') @@ -1344,9 +1380,18 @@ export function registerWorktreeHandlers( ipcMain.handle( 'worktrees:remove', - async (_event, args: { worktreeId: string; force?: boolean; skipArchive?: boolean }) => { + async (_event, args: RemoveWorktreeArgs): Promise => { + const { repoId, worktreePath } = parseWorktreeId(args.worktreeId) + const repo = getRepoForWorktreeRemoval(store, repoId, args.hostId) + if (!repo) { + throw new Error(`Repo not found: ${repoId}`) + } + const inFlightKey = getWorktreeRemovalInFlightKey( + args.worktreeId, + getRepoExecutionHostId(repo) + ) const optionsKey = getWorktreeRemovalOptionsKey(args) - const inFlightRemoval = worktreeRemovalsInFlight.get(args.worktreeId) + const inFlightRemoval = worktreeRemovalsInFlight.get(inFlightKey) if (inFlightRemoval) { if (inFlightRemoval.optionsKey === optionsKey) { return inFlightRemoval.promise @@ -1358,11 +1403,6 @@ export function registerWorktreeHandlers( // target the same worktree concurrently. Share the destructive backend // operation so only one path touches Git and the filesystem. const removal = (async (): Promise => { - const { repoId, worktreePath } = parseWorktreeId(args.worktreeId) - const repo = store.getRepo(repoId) - if (!repo) { - throw new Error(`Repo not found: ${repoId}`) - } if (isFolderRepo(repo)) { if (args.worktreeId === getFolderWorkspaceRootId(repo)) { throw new Error( @@ -1544,8 +1584,18 @@ export function registerWorktreeHandlers( const canonicalWorktreePath = registeredWorktree.path const deleteBranch = removedMeta?.preserveBranchOnDelete !== true + // Why: a Git lock must block before archive hooks or linked-path cleanup + // mutate the workspace; dirty-file force is a separate permission. + try { + assertWorktreeUnlockedForRemoval(registeredWorktree) + } catch (error) { + throw new Error( + formatWorktreeRemovalError(error, canonicalWorktreePath, args.force ?? false) + ) + } + // Why: a prior forced Windows recovery can delete the directory but leave - // Git's stale registration; retry by pruning instead of removing a missing path. + // Git's stale registration; recover and verify it before clearing metadata. if ( !repo.connectionId && args.force === true && @@ -1555,7 +1605,7 @@ export function registerWorktreeHandlers( removedMeta && (await isAlreadyRemovedWorktreePath(repo, canonicalWorktreePath, localWorktreeGitOptions)) ) { - const removalResult = await pruneStaleLocalWorktreeRegistrationAfterFilesystemRemoval({ + const removalResult = await removeStaleLocalWorktreeRegistrationAfterFilesystemRemoval({ canonicalWorktreePath, repoPath: repo.path, localWorktreeGitOptions, @@ -1616,9 +1666,10 @@ export function registerWorktreeHandlers( } } - const rawRemovalResult = await (deleteBranch - ? provider!.removeWorktree(canonicalWorktreePath, args.force) - : provider!.removeWorktree(canonicalWorktreePath, args.force, { deleteBranch })) + const remoteRemoveOptions = !deleteBranch ? { deleteBranch } : {} + const rawRemovalResult = await (Object.keys(remoteRemoveOptions).length > 0 + ? provider!.removeWorktree(canonicalWorktreePath, args.force, remoteRemoveOptions) + : provider!.removeWorktree(canonicalWorktreePath, args.force)) const removalResult = preserveBranchHeadFallback( rawRemovalResult, registeredWorktree.head @@ -1642,6 +1693,29 @@ export function registerWorktreeHandlers( return removalResult ?? {} } + const refreshedWorktrees = hasLocalWorktreeGitOptions + ? await listGitWorktreesStrict(repo.path, localWorktreeGitOptions) + : await listGitWorktreesStrict(repo.path) + const refreshedRegisteredWorktree = findRegisteredDeletableWorktree( + repo.path, + canonicalWorktreePath, + refreshedWorktrees + ) + if (!refreshedRegisteredWorktree) { + throw new Error( + `Worktree registration changed during deletion: ${canonicalWorktreePath}. Retry deletion.` + ) + } + try { + // Why: an archive hook can race another Git client that locks the row; + // recheck before linked-path, watcher, or terminal teardown side effects. + assertWorktreeUnlockedForRemoval(refreshedRegisteredWorktree) + } catch (error) { + throw new Error( + formatWorktreeRemovalError(error, canonicalWorktreePath, args.force ?? false) + ) + } + // Why: `git worktree remove` (non-force) refuses to delete a worktree // that has untracked files. User-configured symlinks look untracked, // so unlink them before the clean check; regular APFS clone-copied @@ -1699,7 +1773,7 @@ export function registerWorktreeHandlers( // Why: this handler already paid for an authoritative worktree // list to validate the target; reuse it instead of rescanning // every sibling worktree during the hot delete path. - knownRemovedWorktree: registeredWorktree, + knownRemovedWorktree: refreshedRegisteredWorktree, ...(hasLocalWorktreeGitOptions ? localWorktreeGitOptions : {}) } removalResult = preserveBranchHeadFallback( @@ -1709,18 +1783,18 @@ export function registerWorktreeHandlers( args.force ?? false, removeOptions ), - registeredWorktree.head + refreshedRegisteredWorktree.head ) } catch (error) { - // Why: Git for Windows can fail long-path directory deletion after - // Orca has already validated the target and explicit force delete. - const recoveredRemovalResult = await recoverLocalWindowsLongPathWorktreeRemoval({ + // Why: Git for Windows can deregister a clean worktree before its + // recursive filesystem deletion fails transiently. + const recoveredRemovalResult = await recoverLocalWindowsWorktreeRemoval({ error, force: args.force ?? false, canonicalWorktreePath, repoPath: repo.path, localWorktreeGitOptions, - registeredWorktree, + registeredWorktree: refreshedRegisteredWorktree, deleteBranch, closeWatcher: closeLocalWatcherForRemoval }) @@ -1786,7 +1860,7 @@ export function registerWorktreeHandlers( rememberPreservedBranchCleanupTarget( args.worktreeId, removalResult, - registeredWorktree.head, + refreshedRegisteredWorktree.head, removedPushTarget ) runtime.clearOptimisticReconcileToken(args.worktreeId) @@ -1796,12 +1870,80 @@ export function registerWorktreeHandlers( notifyWorktreesChanged(mainWindow, repoId) return removalResult ?? {} })() - worktreeRemovalsInFlight.set(args.worktreeId, { optionsKey, promise: removal }) + worktreeRemovalsInFlight.set(inFlightKey, { optionsKey, promise: removal }) try { return await removal } finally { - if (worktreeRemovalsInFlight.get(args.worktreeId)?.promise === removal) { - worktreeRemovalsInFlight.delete(args.worktreeId) + if (worktreeRemovalsInFlight.get(inFlightKey)?.promise === removal) { + worktreeRemovalsInFlight.delete(inFlightKey) + } + } + } + ) + + // Why: forget-locally drops a workspace from Orca without any remote Git or + // filesystem work. It exists so a workspace pinned to a removed/disconnected + // SSH target — whose provider is gone and whose `worktrees:remove` therefore + // throws at requireSshGitProvider before any cleanup runs — can still be + // cleared from the app. It never touches the remote: no worktree registration, + // no branches, no files are deleted there. + ipcMain.handle( + 'worktrees:forgetLocal', + async ( + _event, + args: Pick + ): Promise => { + const { repoId } = parseWorktreeId(args.worktreeId) + const repo = getRepoForWorktreeRemoval(store, repoId, args.hostId) + if (!repo) { + throw new Error(`Repo not found: ${repoId}`) + } + // Why: share the removal in-flight map (not a separate one) so a concurrent + // worktrees:remove and worktrees:forgetLocal on the same id cannot both + // mutate metadata. A forget takes no force/skipArchive options. + const inFlightKey = getWorktreeRemovalInFlightKey( + args.worktreeId, + getRepoExecutionHostId(repo) + ) + const optionsKey = 'forget-local' + const inFlight = worktreeRemovalsInFlight.get(inFlightKey) + if (inFlight) { + if (inFlight.optionsKey === optionsKey) { + return inFlight.promise + } + throw new Error(`Worktree deletion already in progress: ${args.worktreeId}`) + } + + const forget = (async (): Promise => { + if (isFolderRepo(repo) && args.worktreeId === getFolderWorkspaceRootId(repo)) { + throw new Error( + 'Cannot delete the project root workspace. Remove the folder project instead.' + ) + } + + // Why: best-effort PTY sweep. killAllProcessesForWorktree resolves + // synchronously for a dead SSH relay (the provider tombstones the lease + // and returns without awaiting the remote), so this never hangs. + await killAllProcessesForWorktree(args.worktreeId, { + runtime, + localProvider: getLocalPtyProvider(), + onPtyStopped: clearProviderPtyState + }).catch((err) => { + console.warn(`[worktree-teardown] forget-local failed for ${args.worktreeId}:`, err) + }) + + runtime.clearOptimisticReconcileToken(args.worktreeId) + removeWorktreeMetadataAndTransientState(store, args.worktreeId) + preservedBranchCleanupByWorktreeId.delete(args.worktreeId) + notifyWorktreesChanged(mainWindow, repoId) + return {} + })() + worktreeRemovalsInFlight.set(inFlightKey, { optionsKey, promise: forget }) + try { + return await forget + } finally { + if (worktreeRemovalsInFlight.get(inFlightKey)?.promise === forget) { + worktreeRemovalsInFlight.delete(inFlightKey) } } } @@ -1934,49 +2076,63 @@ export function registerWorktreeHandlers( } }) - ipcMain.handle('hooks:check', async (_event, args: { repoId: string }) => { - const repo = store.getRepo(args.repoId) - if (!repo || isFolderRepo(repo)) { - return { status: 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false } - } - - if (repo.connectionId) { - const fsProvider = getSshFilesystemProvider(repo.connectionId) - if (!fsProvider) { - return { status: 'error', hasHooks: false, hooks: null, mayNeedUpdate: false } - } - try { - const result = await fsProvider.readFile(joinWorktreeRelativePath(repo.path, 'orca.yaml')) - return { - status: 'ok', - hasHooks: !result.isBinary, - hooks: result.isBinary ? null : parseOrcaYaml(result.content), - mayNeedUpdate: false - } - } catch (error) { + ipcMain.handle( + 'hooks:check', + async (_event, args: { repoId: string; hostId?: ExecutionHostId }) => { + const repo = getRepoForWorktreeRemoval(store, args.repoId, args.hostId) + if (!repo) { + const repoIdExists = store.getRepos().some((candidate) => candidate.id === args.repoId) + // Why: a requested or ambiguous host must not be reported as hook-free; + // callers treat inspection errors as "skip", which keeps hook execution fail closed. return { - status: isENOENT(error) ? 'ok' : 'error', + status: args.hostId || repoIdExists ? 'error' : 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false } } - } + if (isFolderRepo(repo)) { + return { status: 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false } + } - const has = hasHooksFile(repo.path) - const hooks = has ? loadHooks(repo.path) : null - // Why: when a newer Orca version adds a top-level key to `orca.yaml`, older - // versions that don't recognise it return null and show "could not be parsed". - // Detecting well-formed but unrecognised keys lets the UI suggest updating - // instead of implying the file is broken. - const mayNeedUpdate = has && !hooks && hasUnrecognizedOrcaYamlKeys(repo.path) - return { - status: 'ok', - hasHooks: has, - hooks, - mayNeedUpdate + if (repo.connectionId) { + const fsProvider = getSshFilesystemProvider(repo.connectionId) + if (!fsProvider) { + return { status: 'error', hasHooks: false, hooks: null, mayNeedUpdate: false } + } + try { + const result = await fsProvider.readFile(joinWorktreeRelativePath(repo.path, 'orca.yaml')) + return { + status: 'ok', + hasHooks: !result.isBinary, + hooks: result.isBinary ? null : parseOrcaYaml(result.content), + mayNeedUpdate: false + } + } catch (error) { + return { + status: isENOENT(error) ? 'ok' : 'error', + hasHooks: false, + hooks: null, + mayNeedUpdate: false + } + } + } + + const has = hasHooksFile(repo.path) + const hooks = has ? loadHooks(repo.path) : null + // Why: when a newer Orca version adds a top-level key to `orca.yaml`, older + // versions that don't recognise it return null and show "could not be parsed". + // Detecting well-formed but unrecognised keys lets the UI suggest updating + // instead of implying the file is broken. + const mayNeedUpdate = has && !hooks && hasUnrecognizedOrcaYamlKeys(repo.path) + return { + status: 'ok', + hasHooks: has, + hooks, + mayNeedUpdate + } } - }) + ) ipcMain.handle( 'hooks:createIssueCommandRunner', diff --git a/src/main/jira/issues.test.ts b/src/main/jira/issues.test.ts index 49a49a460762..1cf9ab312121 100644 --- a/src/main/jira/issues.test.ts +++ b/src/main/jira/issues.test.ts @@ -398,4 +398,100 @@ describe('Jira issue operations', () => { } ]) }) + + describe('getProjectStatusOrder', () => { + it('returns an empty order when no clients are available', async () => { + getClientsMock.mockReturnValue([]) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [] + }) + }) + + it('returns an empty order when an omitted site resolves to multiple clients', async () => { + getClientsMock.mockReturnValue([makeEntry('site-1'), makeEntry('site-2')]) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP')).resolves.toEqual({ statusIdsByColumn: [] }) + expect(jiraRequestMock).not.toHaveBeenCalled() + }) + + it('returns an empty order when the project has no accessible board', async () => { + jiraRequestMock.mockResolvedValueOnce({ values: [] }) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP & OPS', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [] + }) + expect(String(jiraRequestMock.mock.calls[0][1])).toContain( + '/rest/agile/1.0/board?projectKeyOrId=ALP+%26+OPS&maxResults=2' + ) + }) + + it('keeps alphabetical fallback when a project has multiple boards', async () => { + jiraRequestMock.mockResolvedValueOnce({ + total: 2, + values: [{ id: 42 }, { id: 43 }] + }) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [] + }) + expect(jiraRequestMock).toHaveBeenCalledTimes(1) + }) + + it('keeps alphabetical fallback when Jira reports another board page', async () => { + jiraRequestMock.mockResolvedValueOnce({ + isLast: false, + values: [{ id: 42 }] + }) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [] + }) + expect(jiraRequestMock).toHaveBeenCalledTimes(1) + }) + + it('returns status IDs grouped by Jira board column order', async () => { + jiraRequestMock + .mockResolvedValueOnce({ total: 1, values: [{ id: 42 }] }) + .mockResolvedValueOnce({ + columnConfig: { + columns: [ + { statuses: [{ id: '1' }, { id: '2' }] }, + { statuses: [{ id: '3' }, { id: '2' }] }, + { statuses: [] } + ] + } + }) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [['1', '2'], ['3']] + }) + expect(jiraRequestMock.mock.calls[1]?.[1]).toBe('/rest/agile/1.0/board/42/configuration') + }) + + it('clears the token and surfaces credential failures', async () => { + const authError = new Error('Unauthorized') + isAuthErrorMock.mockReturnValue(true) + jiraRequestMock.mockRejectedValueOnce(authError) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).rejects.toThrow('Unauthorized') + expect(clearTokenMock).toHaveBeenCalledWith('site-1') + }) + + it('falls back to an empty order on operational errors', async () => { + jiraRequestMock.mockRejectedValueOnce(new Error('Service Unavailable')) + const { getProjectStatusOrder } = await import('./issues') + + await expect(getProjectStatusOrder('ALP', 'site-1')).resolves.toEqual({ + statusIdsByColumn: [] + }) + }) + }) }) diff --git a/src/main/jira/issues.ts b/src/main/jira/issues.ts index 3bf8237349cd..5a19b9897b37 100644 --- a/src/main/jira/issues.ts +++ b/src/main/jira/issues.ts @@ -14,6 +14,7 @@ import type { JiraMutationResult, JiraPriority, JiraProject, + JiraProjectStatusOrder, JiraSite, JiraSiteSelection, JiraStatus, @@ -110,6 +111,13 @@ function asString(value: unknown, fallback = ''): string { return typeof value === 'string' ? value : fallback } +function asIdentifier(value: unknown): string { + if (typeof value === 'string') { + return value + } + return typeof value === 'number' && Number.isFinite(value) ? String(value) : '' +} + function asStringArray(value: unknown): string[] { return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') @@ -810,3 +818,77 @@ export async function listTransitions( release() } } + +export async function getProjectStatusOrder( + projectKey: string, + siteId?: string | null +): Promise { + // Why: an omitted site can resolve to the persisted "all" selection; board + // metadata is only truthful when exactly one Jira connection owns the project. + const entries = getClients(siteId) + const entry = entries.length === 1 ? entries[0] : undefined + if (!entry) { + return { statusIdsByColumn: [] } + } + await acquire() + try { + // Why: without an explicit board picker there is no truthful way to choose + // among multiple project boards, so ambiguous projects keep alphabetical order. + const params = new URLSearchParams({ projectKeyOrId: projectKey, maxResults: '2' }) + const boardsResponse = await jiraRequest>( + entry, + `/rest/agile/1.0/board?${params.toString()}` + ) + const boards = boardsResponse.values ?? [] + const boardCount = asFiniteNumber(boardsResponse.total) + const singleBoardIsProven = + boards.length === 1 && + boardsResponse.isLast !== false && + (boardCount === 1 || (boardCount === null && boardsResponse.isLast === true)) + const boardId = singleBoardIsProven ? asIdentifier(asRecord(boards[0]).id) : '' + if (!boardId) { + return { statusIdsByColumn: [] } + } + + const configResponse = await jiraRequest( + entry, + `/rest/agile/1.0/board/${encodeURIComponent(boardId)}/configuration` + ) + const columns = asRecord(asRecord(configResponse).columnConfig).columns + if (!Array.isArray(columns)) { + return { statusIdsByColumn: [] } + } + + // Why: issues already carry status names and IDs, so returning board IDs + // avoids a second metadata request and keeps duplicate names unambiguous. + const seenStatusIds = new Set() + const statusIdsByColumn: string[][] = [] + for (const column of columns) { + const statuses = asRecord(column).statuses + if (!Array.isArray(statuses)) { + continue + } + const columnStatusIds: string[] = [] + for (const status of statuses) { + const statusId = asIdentifier(asRecord(status).id) + if (statusId && !seenStatusIds.has(statusId)) { + seenStatusIds.add(statusId) + columnStatusIds.push(statusId) + } + } + if (columnStatusIds.length > 0) { + statusIdsByColumn.push(columnStatusIds) + } + } + return { statusIdsByColumn } + } catch (error) { + if (isAuthError(error)) { + clearToken(entry.site.id) + throw error + } + console.warn('[jira] getProjectStatusOrder failed:', error) + return { statusIdsByColumn: [] } + } finally { + release() + } +} diff --git a/src/main/linear/issue-list-filter.test.ts b/src/main/linear/issue-list-filter.test.ts new file mode 100644 index 000000000000..24fb3af3fd81 --- /dev/null +++ b/src/main/linear/issue-list-filter.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest' +import { buildLinearListIssueFilter } from './issue-list-filter' + +describe('buildLinearListIssueFilter', () => { + it('returns undefined for all preset without attributes or team', () => { + expect(buildLinearListIssueFilter({ filter: 'all' })).toBeUndefined() + }) + + it('merges status ids, priority, assignee, and labels for the all preset', () => { + expect( + buildLinearListIssueFilter({ + filter: 'all', + attributeFilter: { + stateIds: ['state-1', 'state-2'], + priorities: [0, 1], + assignee: { kind: 'user', id: 'user-1' }, + labelIds: ['label-1', 'label-2'] + } + }) + ).toEqual({ + state: { id: { in: ['state-1', 'state-2'] } }, + priority: { in: [0, 1] }, + assignee: { id: { eq: 'user-1' } }, + labels: { some: { id: { in: ['label-1', 'label-2'] } } } + }) + }) + + it('keeps preset state.type and attribute state.id together', () => { + expect( + buildLinearListIssueFilter({ + filter: 'assigned', + attributeFilter: { + stateIds: ['state-open'], + priorities: [], + assignee: null, + labelIds: [] + } + }) + ).toEqual({ + state: { + type: { nin: ['completed', 'canceled'] }, + id: { in: ['state-open'] } + } + }) + }) + + it('shapes unassigned and optional team filters', () => { + expect( + buildLinearListIssueFilter({ + filter: 'all', + teamId: 'team-1', + attributeFilter: { + stateIds: [], + priorities: [], + assignee: { kind: 'unassigned' }, + labelIds: [] + } + }) + ).toEqual({ + team: { id: { eq: 'team-1' } }, + assignee: { null: true } + }) + }) + + it('omits empty attribute filters so variables match the unfiltered path', () => { + expect( + buildLinearListIssueFilter({ + filter: 'completed', + attributeFilter: { + stateIds: [], + priorities: [], + assignee: null, + labelIds: [] + } + }) + ).toEqual({ + state: { type: { in: ['completed', 'canceled'] } } + }) + }) +}) diff --git a/src/main/linear/issue-list-filter.ts b/src/main/linear/issue-list-filter.ts new file mode 100644 index 000000000000..b85b7e3ba097 --- /dev/null +++ b/src/main/linear/issue-list-filter.ts @@ -0,0 +1,117 @@ +import { + isEmptyLinearIssueAttributeFilter, + type LinearIssueAttributeFilter +} from '../../shared/linear-issue-attribute-filter' +import type { LinearListFilter } from './issues' + +// Why: attribute facets must merge into Linear's IssueFilter before the first-N +// cursor walk so hasMore reflects the filtered set, not the unfiltered window. +// @linear/sdk does not export IssueFilter as a public type, so we keep a +// structural subset that matches the operators this list path actually sends. + +export type LinearGraphQLIssueFilter = { + state?: { + type?: { nin?: string[]; in?: string[] } + id?: { in?: string[] } + } + team?: { id?: { eq?: string } } + priority?: { in?: number[] } + assignee?: { null?: boolean; id?: { eq?: string } } + labels?: { some?: { id?: { in?: string[] } } } +} + +const ACTIVE_STATE_FILTER: LinearGraphQLIssueFilter = { + state: { type: { nin: ['completed', 'canceled'] } } +} +const COMPLETED_STATE_FILTER: LinearGraphQLIssueFilter = { + state: { type: { in: ['completed', 'canceled'] } } +} + +function listFilterForState(filter: LinearListFilter): LinearGraphQLIssueFilter | undefined { + if (filter === 'assigned' || filter === 'created' || filter === 'open') { + return ACTIVE_STATE_FILTER + } + if (filter === 'completed') { + return COMPLETED_STATE_FILTER + } + return undefined +} + +function attributeFacetFilter( + attributeFilter: LinearIssueAttributeFilter | null | undefined +): LinearGraphQLIssueFilter | undefined { + if (!attributeFilter || isEmptyLinearIssueAttributeFilter(attributeFilter)) { + return undefined + } + + const next: LinearGraphQLIssueFilter = {} + + if (attributeFilter.stateIds.length > 0) { + next.state = { id: { in: attributeFilter.stateIds } } + } + + if (attributeFilter.priorities.length > 0) { + next.priority = { in: attributeFilter.priorities } + } + + if (attributeFilter.assignee?.kind === 'unassigned') { + next.assignee = { null: true } + } else if (attributeFilter.assignee?.kind === 'user') { + next.assignee = { id: { eq: attributeFilter.assignee.id } } + } + + if (attributeFilter.labelIds.length > 0) { + // Why: collection `some` is any-of; a direct labels.id comparator would + // not express multi-label membership the same way. + next.labels = { some: { id: { in: attributeFilter.labelIds } } } + } + + return Object.keys(next).length > 0 ? next : undefined +} + +function mergeIssueFilters( + ...parts: (LinearGraphQLIssueFilter | undefined)[] +): LinearGraphQLIssueFilter | undefined { + const defined = parts.filter((part): part is LinearGraphQLIssueFilter => part !== undefined) + if (defined.length === 0) { + return undefined + } + if (defined.length === 1) { + return defined[0] + } + + const merged: LinearGraphQLIssueFilter = {} + for (const part of defined) { + if (part.state) { + // Why: preset state.type and attribute state.id must coexist; a top-level + // spread would overwrite one nested constraint. + merged.state = { ...merged.state, ...part.state } + } + if (part.team) { + merged.team = part.team + } + if (part.priority) { + merged.priority = part.priority + } + if (part.assignee) { + merged.assignee = part.assignee + } + if (part.labels) { + merged.labels = part.labels + } + } + return merged +} + +export function buildLinearListIssueFilter(options: { + filter: LinearListFilter + teamId?: string + attributeFilter?: LinearIssueAttributeFilter | null +}): LinearGraphQLIssueFilter | undefined { + const stateFilter = listFilterForState(options.filter) + const teamFilter: LinearGraphQLIssueFilter | undefined = options.teamId + ? { team: { id: { eq: options.teamId } } } + : undefined + const attributes = attributeFacetFilter(options.attributeFilter) + return mergeIssueFilters(stateFilter, teamFilter, attributes) +} diff --git a/src/main/linear/issues.test.ts b/src/main/linear/issues.test.ts index e341018f0abc..ef9ca38678ec 100644 --- a/src/main/linear/issues.test.ts +++ b/src/main/linear/issues.test.ts @@ -188,7 +188,9 @@ describe('Linear issue queries', () => { }) const { listIssues } = await import('./issues') - await expect(listIssues('open', 10, 'workspace-1', 'team-1')).resolves.toMatchObject({ + await expect( + listIssues('open', 10, 'workspace-1', { teamId: 'team-1' }) + ).resolves.toMatchObject({ items: [{ id: 'LIN-1' }], hasMore: false }) @@ -202,6 +204,48 @@ describe('Linear issue queries', () => { }) }) + it('passes attribute facets into Linear GraphQL variables before pagination', async () => { + rawRequest.mockResolvedValueOnce({ + data: { issues: { nodes: [rawIssue('LIN-1')], pageInfo: { hasNextPage: false } } } + }) + const { listIssues } = await import('./issues') + + await expect( + listIssues('all', 10, 'workspace-1', { + attributeFilter: { + stateIds: ['state-1'], + priorities: [0, 1], + assignee: { kind: 'unassigned' }, + labelIds: ['label-1'] + } + }) + ).resolves.toMatchObject({ items: [{ id: 'LIN-1' }] }) + + expect(rawRequest.mock.calls[0][1]).toMatchObject({ + filter: { + state: { id: { in: ['state-1'] } }, + priority: { in: [0, 1] }, + assignee: { null: true }, + labels: { some: { id: { in: ['label-1'] } } } + } + }) + }) + + it('rejects non-empty attribute filters when workspace scope is all', async () => { + const { listIssues } = await import('./issues') + await expect( + listIssues('all', 10, 'all', { + attributeFilter: { + stateIds: ['state-1'], + priorities: [], + assignee: null, + labelIds: [] + } + }) + ).rejects.toThrow(/concrete workspace/i) + expect(getClients).not.toHaveBeenCalled() + }) + it('keeps single-workspace search results in Linear relevance order', async () => { rawRequest.mockResolvedValueOnce({ data: { diff --git a/src/main/linear/issues.ts b/src/main/linear/issues.ts index b54c385d040e..f71ab7e35e15 100644 --- a/src/main/linear/issues.ts +++ b/src/main/linear/issues.ts @@ -14,6 +14,10 @@ import { LINEAR_ISSUE_API_PAGE_SIZE_MAX, clampLinearIssueListLimit } from '../../shared/linear-issue-read-limits' +import { + isEmptyLinearIssueAttributeFilter, + type LinearIssueAttributeFilter +} from '../../shared/linear-issue-attribute-filter' import { acquire, release, @@ -22,8 +26,14 @@ import { clearToken, type LinearClientForWorkspace } from './client' +import { buildLinearListIssueFilter } from './issue-list-filter' import { mapLinearIssue } from './mappers' +export type LinearIssueListOptions = { + teamId?: string + attributeFilter?: LinearIssueAttributeFilter | null +} + type LinearIssueNode = { id: string identifier: string @@ -457,11 +467,17 @@ function getOldestIssueTime(issues: LinearIssue[]): number { function getListIssueConnectionLoader( entry: LinearClientForWorkspace, filter: LinearListFilter, - teamId?: string + options?: LinearIssueListOptions ): LinearIssueConnectionLoader { const orderBy = 'updatedAt' const variables = { orderBy } - const filterInput = listIssueFilter(filter, teamId) + // Why: apply attribute + team filters in GraphQL variables before the first-N + // cursor walk so pagination hasMore matches the filtered set. + const filterInput = buildLinearListIssueFilter({ + filter, + teamId: options?.teamId, + attributeFilter: options?.attributeFilter + }) if (filter === 'assigned') { return async (page) => { @@ -833,31 +849,6 @@ export async function searchIssues( export type LinearListFilter = 'assigned' | 'created' | 'all' | 'completed' | 'open' -const ACTIVE_STATE_FILTER = { state: { type: { nin: ['completed', 'canceled'] } } } -const COMPLETED_STATE_FILTER = { state: { type: { in: ['completed', 'canceled'] } } } - -function listFilterForState(filter: LinearListFilter): Record | undefined { - if (filter === 'assigned' || filter === 'created' || filter === 'open') { - return ACTIVE_STATE_FILTER - } - if (filter === 'completed') { - return COMPLETED_STATE_FILTER - } - return undefined -} - -function listIssueFilter( - filter: LinearListFilter, - teamId?: string -): Record | undefined { - const stateFilter = listFilterForState(filter) - const teamFilter = teamId ? { team: { id: { eq: teamId } } } : undefined - if (stateFilter && teamFilter) { - return { ...stateFilter, ...teamFilter } - } - return stateFilter ?? teamFilter -} - type LinearIssuePageResult = { items: LinearIssue[] hasMore: boolean @@ -904,14 +895,14 @@ async function readListIssuesForWorkspace( filter: LinearListFilter, limit: number, workspaceId: LinearWorkspaceSelection | null | undefined, - teamId?: string + options?: LinearIssueListOptions ): Promise> { await acquire() try { return await readIssueConnectionPages( entry, limit, - getListIssueConnectionLoader(entry, filter, teamId) + getListIssueConnectionLoader(entry, filter, options) ) } catch (error) { if (isAuthError(error)) { @@ -1016,11 +1007,11 @@ async function readListIssuesAcrossWorkspaces( filter: LinearListFilter, limit: number, workspaceId: LinearWorkspaceSelection | null | undefined, - teamId?: string + options?: LinearIssueListOptions ): Promise> { const states: LinearIssueWorkspacePageState[] = entries.map((entry) => ({ entry, - loadConnection: getListIssueConnectionLoader(entry, filter, teamId), + loadConnection: getListIssueConnectionLoader(entry, filter, options), items: [], hasMore: false, canPage: false @@ -1063,19 +1054,32 @@ export async function listIssues( filter: LinearListFilter = 'assigned', limit = 20, workspaceId?: LinearWorkspaceSelection | null, - teamId?: string + options?: LinearIssueListOptions ): Promise> { const effectiveLimit = clampLinearIssueListLimit(limit) + const attributeFilter = options?.attributeFilter + // Why: workspace-specific state/member/label ids cannot fan out safely across + // "all" workspaces; reject before creating clients so non-UI callers cannot + // get a misleading partial subset. + if ( + attributeFilter && + !isEmptyLinearIssueAttributeFilter(attributeFilter) && + workspaceId === 'all' + ) { + throw new Error( + 'Linear attribute filters require a concrete workspace; "all" workspaces is not supported.' + ) + } const entries = getClients(workspaceId) if (entries.length === 0) { return { items: [] } } if (entries.length === 1) { - return readListIssuesForWorkspace(entries[0], filter, effectiveLimit, workspaceId, teamId) + return readListIssuesForWorkspace(entries[0], filter, effectiveLimit, workspaceId, options) } - return readListIssuesAcrossWorkspaces(entries, filter, effectiveLimit, workspaceId, teamId) + return readListIssuesAcrossWorkspaces(entries, filter, effectiveLimit, workspaceId, options) } export async function createIssue( diff --git a/src/main/local-worktree-removal-recovery-live.test.ts b/src/main/local-worktree-removal-recovery-live.test.ts new file mode 100644 index 000000000000..4d5a048b5f40 --- /dev/null +++ b/src/main/local-worktree-removal-recovery-live.test.ts @@ -0,0 +1,128 @@ +import { spawn, spawnSync, type ChildProcess } from 'node:child_process' +import { existsSync } from 'node:fs' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { setTimeout as delay } from 'node:timers/promises' +import { afterEach, describe, expect, it } from 'vitest' +import { recoverLocalWindowsWorktreeRemoval } from './local-worktree-removal-recovery' + +const tempRoots: string[] = [] + +function git(cwd: string, args: string[]): string { + const result = spawnSync('git', args, { cwd, encoding: 'utf8' }) + if (result.status !== 0) { + throw new Error(result.stderr || result.stdout || `git ${args.join(' ')} failed`) + } + return result.stdout.trim() +} + +async function waitForPath(targetPath: string): Promise { + const deadline = Date.now() + 5_000 + while (!existsSync(targetPath)) { + if (Date.now() >= deadline) { + throw new Error(`Timed out waiting for ${targetPath}`) + } + await delay(20) + } +} + +async function stopProcess(child: ChildProcess): Promise { + if (child.exitCode !== null || child.signalCode !== null) { + return + } + const exited = new Promise((resolve) => child.once('exit', () => resolve())) + child.kill() + await Promise.race([exited, delay(500)]) + if (child.exitCode === null && child.pid) { + spawnSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], { stdio: 'ignore' }) + await Promise.race([exited, delay(2_000)]) + } + if (child.exitCode === null && child.signalCode === null) { + throw new Error('Failed to stop the filesystem churn process') + } +} + +describe('local Windows worktree removal recovery (live Git)', () => { + afterEach(async () => { + await Promise.all( + tempRoots + .splice(0) + .map((root) => rm(root, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 })) + ) + }) + + it.runIf(process.platform === 'win32')( + 'finishes deletion when Git deregisters before a directory-not-empty failure', + async () => { + const root = await mkdtemp(path.join(tmpdir(), 'orca-worktree-enotempty-')) + tempRoots.push(root) + const repoPath = path.join(root, 'repo') + const worktreePath = path.join(root, 'worktree') + + git(root, ['init', '--quiet', repoPath]) + git(repoPath, ['config', 'user.email', 'test@example.com']) + git(repoPath, ['config', 'user.name', 'Test User']) + await writeFile(path.join(repoPath, '.gitignore'), 'churn/\n') + git(repoPath, ['add', '.gitignore']) + git(repoPath, ['commit', '--quiet', '-m', 'initial']) + git(repoPath, ['worktree', 'add', '--quiet', '-b', 'feature/churn', worktreePath]) + const head = git(worktreePath, ['rev-parse', 'HEAD']) + + // Why: a producer racing Git's recursive delete deterministically exposes + // the Windows ENOTEMPTY state reported by real workspace deletions. + const churn = spawn( + process.execPath, + [ + '-e', + [ + "const fs = require('node:fs')", + "const path = require('node:path')", + 'const root = process.argv[1]', + 'let i = 0', + 'while (fs.existsSync(root)) {', + ' try {', + " const dir = path.join(root, 'churn')", + ' fs.mkdirSync(dir, { recursive: true })', + " fs.writeFileSync(path.join(dir, 'f' + (i++ % 64) + '.txt'), 'x')", + ' } catch {}', + '}' + ].join('\n'), + worktreePath + ], + { stdio: 'ignore' } + ) + + try { + await waitForPath(path.join(worktreePath, 'churn')) + const removal = spawnSync('git', ['worktree', 'remove', worktreePath], { + cwd: repoPath, + encoding: 'utf8' + }) + expect(removal.status).not.toBe(0) + expect(git(repoPath, ['worktree', 'list', '--porcelain'])).not.toContain(worktreePath) + expect(existsSync(worktreePath)).toBe(true) + + await stopProcess(churn) + await expect( + recoverLocalWindowsWorktreeRemoval({ + error: Object.assign(new Error('git worktree remove failed'), { + stderr: removal.stderr + }), + force: false, + canonicalWorktreePath: worktreePath, + repoPath, + localWorktreeGitOptions: {}, + registeredWorktree: { branch: 'refs/heads/feature/churn', head }, + deleteBranch: false, + closeWatcher: async () => {} + }) + ).resolves.toEqual({}) + + expect(existsSync(worktreePath)).toBe(false) + } finally { + await stopProcess(churn) + } + } + ) +}) diff --git a/src/main/local-worktree-removal-recovery.test.ts b/src/main/local-worktree-removal-recovery.test.ts index 9f3d7550251b..cb6dbcbb51e4 100644 --- a/src/main/local-worktree-removal-recovery.test.ts +++ b/src/main/local-worktree-removal-recovery.test.ts @@ -1,9 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const { gitExecFileAsyncMock, removeLocalWorktreePathMock } = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn(), - removeLocalWorktreePathMock: vi.fn() -})) +const { gitExecFileAsyncMock, listWorktreesStrictMock, removeLocalWorktreePathMock } = vi.hoisted( + () => ({ + gitExecFileAsyncMock: vi.fn(), + listWorktreesStrictMock: vi.fn(), + removeLocalWorktreePathMock: vi.fn() + }) +) vi.mock('./git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock @@ -13,7 +16,14 @@ vi.mock('./local-worktree-filesystem', () => ({ removeLocalWorktreePath: removeLocalWorktreePathMock })) -import { recoverLocalWindowsLongPathWorktreeRemoval } from './local-worktree-removal-recovery' +vi.mock('./git/worktree', () => ({ + listWorktreesStrict: listWorktreesStrictMock +})) + +import { + recoverLocalWindowsWorktreeRemoval, + removeStaleLocalWorktreeRegistrationAfterFilesystemRemoval +} from './local-worktree-removal-recovery' async function withPlatform(platform: NodeJS.Platform, fn: () => Promise): Promise { const original = process.platform @@ -25,11 +35,13 @@ async function withPlatform(platform: NodeJS.Platform, fn: () => Promise): } } -describe('recoverLocalWindowsLongPathWorktreeRemoval', () => { +describe('recoverLocalWindowsWorktreeRemoval', () => { beforeEach(() => { gitExecFileAsyncMock.mockReset() + listWorktreesStrictMock.mockReset() removeLocalWorktreePathMock.mockReset() gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + listWorktreesStrictMock.mockResolvedValue([]) removeLocalWorktreePathMock.mockResolvedValue(undefined) }) @@ -43,7 +55,7 @@ describe('recoverLocalWindowsLongPathWorktreeRemoval', () => { stderr: "error: failed to delete 'C:/repo/worktree/delete-e2e-held-cwd': Permission denied" }) - const result = await recoverLocalWindowsLongPathWorktreeRemoval({ + const result = await recoverLocalWindowsWorktreeRemoval({ error, force: true, canonicalWorktreePath: 'C:/repo/worktree/delete-e2e-held-cwd', @@ -70,6 +82,90 @@ describe('recoverLocalWindowsLongPathWorktreeRemoval', () => { }) }) + it('finishes a clean non-force deletion after Git leaves a Windows directory behind', async () => { + await withPlatform('win32', async () => { + const error = Object.assign(new Error('git worktree remove failed'), { + stderr: + "error: failed to delete 'C:/repo/worktree/delete-e2e-held-cwd': Directory not empty" + }) + + const result = await recoverLocalWindowsWorktreeRemoval({ + error, + force: false, + canonicalWorktreePath: 'C:/repo/worktree/delete-e2e-held-cwd', + repoPath: 'C:/repo', + localWorktreeGitOptions: {}, + registeredWorktree: { branch: 'refs/heads/delete-e2e-held-cwd', head: 'abc123' }, + deleteBranch: true, + closeWatcher: vi.fn().mockResolvedValue(undefined) + }) + + expect(removeLocalWorktreePathMock).toHaveBeenCalledWith( + 'C:/repo/worktree/delete-e2e-held-cwd', + {} + ) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['worktree', 'prune'], { + cwd: 'C:/repo' + }) + expect(result).toEqual({ + preservedBranch: { + branchName: 'delete-e2e-held-cwd', + head: 'abc123' + } + }) + }) + }) + + it('recovers localized Windows failures after Git already removed the registration', async () => { + await withPlatform('win32', async () => { + const result = await recoverLocalWindowsWorktreeRemoval({ + error: Object.assign(new Error('git worktree remove failed'), { + stderr: "Fehler: 'C:/repo/worktree/feature' konnte nicht gelöscht werden" + }), + force: false, + canonicalWorktreePath: 'C:/repo/worktree/feature', + repoPath: 'C:/repo', + localWorktreeGitOptions: {}, + registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, + deleteBranch: false, + closeWatcher: vi.fn().mockResolvedValue(undefined) + }) + + expect(removeLocalWorktreePathMock).toHaveBeenCalledWith('C:/repo/worktree/feature', {}) + expect(result).toEqual({}) + }) + }) + + it('does not recover unrelated localized failures while Git still owns the row', async () => { + await withPlatform('win32', async () => { + listWorktreesStrictMock.mockResolvedValue([ + { + path: 'C:/repo/worktree/feature', + head: 'abc123', + branch: 'refs/heads/feature', + isBare: false, + isMainWorktree: false + } + ]) + + await expect( + recoverLocalWindowsWorktreeRemoval({ + error: Object.assign(new Error('git worktree remove failed'), { + stderr: 'Fehler: unerwarteter Git-Zustand' + }), + force: false, + canonicalWorktreePath: 'C:/repo/worktree/feature', + repoPath: 'C:/repo', + localWorktreeGitOptions: {}, + registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, + deleteBranch: false, + closeWatcher: vi.fn().mockResolvedValue(undefined) + }) + ).resolves.toBeUndefined() + expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() + }) + }) + it('does not recover partial filesystem deletion wording off Windows', async () => { await withPlatform('linux', async () => { const error = Object.assign(new Error('git worktree remove failed'), { @@ -77,7 +173,7 @@ describe('recoverLocalWindowsLongPathWorktreeRemoval', () => { }) await expect( - recoverLocalWindowsLongPathWorktreeRemoval({ + recoverLocalWindowsWorktreeRemoval({ error, force: true, canonicalWorktreePath: 'C:/repo/worktree/delete-e2e-held-cwd', @@ -91,4 +187,149 @@ describe('recoverLocalWindowsLongPathWorktreeRemoval', () => { expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() }) }) + + it('does not recover a locked registration after a filesystem removal failure', async () => { + await withPlatform('win32', async () => { + const registeredWorktree = { + branch: 'refs/heads/feature', + head: 'abc123', + locked: true, + lockReason: 'active agent' + } + const closeWatcher = vi.fn().mockResolvedValue(undefined) + + await expect( + recoverLocalWindowsWorktreeRemoval({ + error: Object.assign(new Error('git worktree remove failed'), { + stderr: 'error: failed to delete deep/file.txt: Filename too long' + }), + force: true, + canonicalWorktreePath: 'C:/workspaces/feature', + repoPath: 'C:/repo', + localWorktreeGitOptions: {}, + registeredWorktree, + deleteBranch: true, + closeWatcher + }) + ).rejects.toThrow('Worktree is locked by Git. Lock reason: active agent') + + expect(closeWatcher).not.toHaveBeenCalled() + expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() + expect(listWorktreesStrictMock).not.toHaveBeenCalled() + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) + }) + + it.each([ + "error: failed to delete 'C:/repo/worktree/feature': Directory not empty", + 'error: failed to delete deep/file.txt: Filename too long' + ])( + 'does not recover a recognized Windows failure while Git still owns the row: %s', + async (stderr) => { + await withPlatform('win32', async () => { + listWorktreesStrictMock.mockResolvedValue([ + { + path: 'C:/repo/worktree/feature', + head: 'abc123', + branch: 'refs/heads/feature', + isBare: false, + isMainWorktree: false + } + ]) + const closeWatcher = vi.fn().mockResolvedValue(undefined) + + await expect( + recoverLocalWindowsWorktreeRemoval({ + error: Object.assign(new Error('git worktree remove failed'), { stderr }), + force: true, + canonicalWorktreePath: 'C:/repo/worktree/feature', + repoPath: 'C:/repo', + localWorktreeGitOptions: { wslDistro: 'Ubuntu' }, + registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, + deleteBranch: true, + closeWatcher + }) + ).resolves.toBeUndefined() + + expect(listWorktreesStrictMock).toHaveBeenCalledWith('C:/repo', { wslDistro: 'Ubuntu' }) + expect(closeWatcher).not.toHaveBeenCalled() + expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() + }) + } + ) + + it('does not recover when structural registration verification fails', async () => { + await withPlatform('win32', async () => { + listWorktreesStrictMock.mockRejectedValue(new Error('git list failed')) + const closeWatcher = vi.fn().mockResolvedValue(undefined) + + await expect( + recoverLocalWindowsWorktreeRemoval({ + error: Object.assign(new Error('git worktree remove failed'), { + stderr: "error: failed to delete 'C:/repo/worktree/feature': Directory not empty" + }), + force: true, + canonicalWorktreePath: 'C:/repo/worktree/feature', + repoPath: 'C:/repo', + localWorktreeGitOptions: {}, + registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, + deleteBranch: true, + closeWatcher + }) + ).resolves.toBeUndefined() + + expect(closeWatcher).not.toHaveBeenCalled() + expect(removeLocalWorktreePathMock).not.toHaveBeenCalled() + }) + }) +}) + +describe('removeStaleLocalWorktreeRegistrationAfterFilesystemRemoval', () => { + beforeEach(() => { + gitExecFileAsyncMock.mockReset() + listWorktreesStrictMock.mockReset() + gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + listWorktreesStrictMock.mockResolvedValue([]) + }) + + it('does not override a locked missing registration', async () => { + await expect( + removeStaleLocalWorktreeRegistrationAfterFilesystemRemoval({ + canonicalWorktreePath: 'C:/workspaces/feature', + repoPath: 'C:/repo', + localWorktreeGitOptions: {}, + registeredWorktree: { + branch: 'refs/heads/feature', + head: 'abc123', + locked: true, + lockReason: 'active agent' + }, + deleteBranch: true + }) + ).rejects.toThrow('Worktree is locked by Git') + + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('does not report success when prune leaves the registration behind', async () => { + listWorktreesStrictMock.mockResolvedValue([ + { + path: 'C:/workspaces/feature', + head: 'abc123', + branch: 'refs/heads/feature', + isBare: false, + isMainWorktree: false + } + ]) + + await expect( + removeStaleLocalWorktreeRegistrationAfterFilesystemRemoval({ + canonicalWorktreePath: 'C:/workspaces/feature', + repoPath: 'C:/repo', + localWorktreeGitOptions: {}, + registeredWorktree: { branch: 'refs/heads/feature', head: 'abc123' }, + deleteBranch: true + }) + ).rejects.toThrow('Git still has stale worktree registration') + }) }) diff --git a/src/main/local-worktree-removal-recovery.ts b/src/main/local-worktree-removal-recovery.ts index 4e915bfa950d..25f93e2b2de2 100644 --- a/src/main/local-worktree-removal-recovery.ts +++ b/src/main/local-worktree-removal-recovery.ts @@ -1,25 +1,23 @@ import type { GitWorktreeInfo, RemoveWorktreeResult } from '../shared/types' -import { - formatWorktreeRemovalError, - isWindowsLongPathWorktreeRemovalError -} from './ipc/worktree-logic' +import { assertWorktreeUnlockedForRemoval } from '../shared/worktree-removal' +import { areWorktreePathsEqual, formatWorktreeRemovalError } from './ipc/worktree-logic' import { gitExecFileAsync } from './git/runner' -import type { GitWorktreeExecOptions } from './git/worktree' +import { listWorktreesStrict, type GitWorktreeExecOptions } from './git/worktree' import { removeLocalWorktreePath } from './local-worktree-filesystem' -type LocalWindowsLongPathRecoveryArgs = { +type LocalWindowsRemovalRecoveryArgs = { error: unknown force: boolean canonicalWorktreePath: string repoPath: string localWorktreeGitOptions: GitWorktreeExecOptions - registeredWorktree: Pick + registeredWorktree: Pick deleteBranch: boolean closeWatcher: (worktreePath: string) => Promise } type StaleLocalWorktreeRegistrationArgs = Omit< - LocalWindowsLongPathRecoveryArgs, + LocalWindowsRemovalRecoveryArgs, 'error' | 'force' | 'closeWatcher' > @@ -38,73 +36,120 @@ function preservedBranchResult( } } -async function pruneRequiredGitWorktreeRegistration( +function staleRegistrationRecoveryError( + error: unknown, + canonicalWorktreePath: string, + force: boolean +): Error { + return new Error( + `${formatWorktreeRemovalError( + error, + canonicalWorktreePath, + force + )} The worktree directory was removed, but Git still has stale worktree registration. Retry deletion after resolving the Git registration error.` + ) +} + +async function verifyGitWorktreeRegistrationRemoved( repoPath: string, localWorktreeGitOptions: GitWorktreeExecOptions, - canonicalWorktreePath: string + canonicalWorktreePath: string, + force: boolean ): Promise { + try { + const remainingWorktrees = await listWorktreesStrict(repoPath, localWorktreeGitOptions) + if ( + remainingWorktrees.some((worktree) => + areWorktreePathsEqual(worktree.path, canonicalWorktreePath) + ) + ) { + throw new Error('Git still reports the worktree registration after cleanup.') + } + } catch (error) { + throw staleRegistrationRecoveryError(error, canonicalWorktreePath, force) + } +} + +async function removeRequiredGitWorktreeRegistration( + args: StaleLocalWorktreeRegistrationArgs, + forceForError = true +): Promise { + assertWorktreeUnlockedForRemoval(args.registeredWorktree) + + let result: RemoveWorktreeResult | undefined + let removalError: unknown try { await gitExecFileAsync(['worktree', 'prune'], { - cwd: repoPath, - ...localWorktreeGitOptions + cwd: args.repoPath, + ...args.localWorktreeGitOptions }) + result = preservedBranchResult(args.registeredWorktree, args.deleteBranch) } catch (error) { - throw new Error( - `${formatWorktreeRemovalError( - error, - canonicalWorktreePath, - true - )} The worktree directory was removed, but Git still has stale worktree registration. Retry deletion after resolving the Git prune error.` + removalError = error + } + + // Why: Git prune exits successfully while retaining locked registrations; + // a failed remove can also have detached the row before filesystem cleanup. + try { + await verifyGitWorktreeRegistrationRemoved( + args.repoPath, + args.localWorktreeGitOptions, + args.canonicalWorktreePath, + forceForError ) + } catch (verificationError) { + throw removalError + ? staleRegistrationRecoveryError(removalError, args.canonicalWorktreePath, forceForError) + : verificationError } + // Why: if Git detached the row before reporting its filesystem error, keep + // the branch rather than guessing whether the normal branch cleanup ran. + return result ?? preservedBranchResult(args.registeredWorktree, args.deleteBranch) } -export async function recoverLocalWindowsLongPathWorktreeRemoval( - args: LocalWindowsLongPathRecoveryArgs +export async function recoverLocalWindowsWorktreeRemoval( + args: LocalWindowsRemovalRecoveryArgs ): Promise { - if (!args.force || !isRecoverableWindowsFilesystemRemovalError(args.error)) { + // Why: recovery can recursively delete the remaining directory, so a Git + // lock must reject the attempt before classification or any side effects. + assertWorktreeUnlockedForRemoval(args.registeredWorktree) + + if (!(await isRecoverableWindowsFilesystemRemovalFailure(args))) { return undefined } - // Why: watcher shutdown is best-effort, but Git registration must be pruned - // before callers clear Orca metadata or the branch remains locked. + // Why: this error means Git accepted removal and started deleting the path; + // finish that partial success with Windows retries, then verify Git metadata. await args.closeWatcher(args.canonicalWorktreePath).catch(() => {}) try { await removeLocalWorktreePath(args.canonicalWorktreePath, args.localWorktreeGitOptions) } catch (error) { - throw new Error(formatWorktreeRemovalError(error, args.canonicalWorktreePath, true)) + throw new Error(formatWorktreeRemovalError(error, args.canonicalWorktreePath, args.force)) } - await pruneRequiredGitWorktreeRegistration( - args.repoPath, - args.localWorktreeGitOptions, - args.canonicalWorktreePath - ) - return preservedBranchResult(args.registeredWorktree, args.deleteBranch) + return removeRequiredGitWorktreeRegistration(args, args.force) } -function isRecoverableWindowsFilesystemRemovalError(error: unknown): boolean { - if (isWindowsLongPathWorktreeRemovalError(error)) { - return true +async function isRecoverableWindowsFilesystemRemovalFailure( + args: LocalWindowsRemovalRecoveryArgs +): Promise { + if (process.platform !== 'win32' || typeof args.error !== 'object' || args.error === null) { + return false } - if (process.platform !== 'win32' || typeof error !== 'object' || error === null) { + + try { + const worktrees = await listWorktreesStrict(args.repoPath, args.localWorktreeGitOptions) + // Why: error prose can be localized or ambiguous. Only a missing Git row + // proves removal started and makes recursive Windows cleanup safe. + return !worktrees.some((worktree) => + areWorktreePathsEqual(worktree.path, args.canonicalWorktreePath) + ) + } catch { return false } - const errorWithDetails = error as { message?: unknown; stderr?: unknown; stdout?: unknown } - const details = [errorWithDetails.stderr, errorWithDetails.stdout, errorWithDetails.message] - .filter((value): value is string => typeof value === 'string' && value.trim().length > 0) - .join('\n') - return /failed to delete .*(?:directory not empty|permission denied|access is denied|being used by another process)|(?:directory not empty|permission denied|access is denied|being used by another process).*failed to delete/i.test( - details - ) } -export async function pruneStaleLocalWorktreeRegistrationAfterFilesystemRemoval( +export async function removeStaleLocalWorktreeRegistrationAfterFilesystemRemoval( args: StaleLocalWorktreeRegistrationArgs ): Promise { - await pruneRequiredGitWorktreeRegistration( - args.repoPath, - args.localWorktreeGitOptions, - args.canonicalWorktreePath - ) - return preservedBranchResult(args.registeredWorktree, args.deleteBranch) + return removeRequiredGitWorktreeRegistration(args) } diff --git a/src/main/memory/hydrate-local-pty-registry.test.ts b/src/main/memory/hydrate-local-pty-registry.test.ts index 0854fa2493b0..714f18b3cba2 100644 --- a/src/main/memory/hydrate-local-pty-registry.test.ts +++ b/src/main/memory/hydrate-local-pty-registry.test.ts @@ -32,9 +32,9 @@ vi.mock('../daemon/daemon-init', () => ({ getDaemonProvider: () => getDaemonProviderMock() })) -// Why: the hydrator builds its worktreeId → connectionId map by calling -// listRepoWorktrees(repo) for every repo in the store. The git I/O is -// out of scope for this unit; mock returns whatever the test wants. +// Why: the hydrator builds its worktreeId → connectionId map through +// listRepoWorktrees(repo). The git I/O is out of scope for this unit; the mock +// also lets count tests prove repos without live sessions launch no Git work. const listRepoWorktreesMock = vi.fn() vi.mock('../repo-worktrees', () => ({ listRepoWorktrees: (repo: unknown) => listRepoWorktreesMock(repo) @@ -79,6 +79,17 @@ function makeLocalSessions(repoId: string, worktreePath: string, count: number): return sessions } +function createDeferred(): { + promise: Promise + resolve: (value: T) => void +} { + let resolve!: (value: T) => void + const promise = new Promise((resolver) => { + resolve = resolver + }) + return { promise, resolve } +} + // Why: the module under test memoizes `hasHydrated` at module scope so it // only runs the git/RPC pass once per process. The pty-registry module // also stashes state in a module-level Map, so we have to load BOTH @@ -127,6 +138,7 @@ describe('hydrateLocalPtyRegistryAtBoot', () => { await hydrate(makeStore([{ id: 'repo-a' }])) expect(provider.listSessions).toHaveBeenCalledTimes(1) + expect(listRepoWorktreesMock).not.toHaveBeenCalled() }) it('catches provider.listSessions rejection and does not throw', async () => { @@ -145,6 +157,7 @@ describe('hydrateLocalPtyRegistryAtBoot', () => { warnSpy.mockRestore() expect(listRegisteredPtys()).toHaveLength(0) + expect(listRepoWorktreesMock).not.toHaveBeenCalled() }) it('does not clobber a pre-existing registry pid with a null pid from listSessions', async () => { @@ -180,6 +193,69 @@ describe('hydrateLocalPtyRegistryAtBoot', () => { expect(entry).toBeDefined() expect(entry!.pid).toBe(12345) expect(entry!.paneKey).toBe('tab-1:1') + expect(listRepoWorktreesMock).not.toHaveBeenCalled() + }) + + it('does not clobber a pty:spawn registration that arrives during worktree enumeration', async () => { + const { hydrate, listRegisteredPtys, registerPty } = await loadFresh() + const ptyId = 'repo-a::/local/Triton@@deadbeef' + const provider = makeProvider([ + { sessionId: ptyId, pid: null, cwd: '/local/Triton' } as unknown as SessionInfo + ]) + getDaemonProviderMock.mockReturnValue(provider) + const worktrees = + createDeferred< + { path: string; head: string; branch: string; isBare: boolean; isMainWorktree: boolean }[] + >() + listRepoWorktreesMock.mockReturnValue(worktrees.promise) + + const hydration = hydrate(makeStore([{ id: 'repo-a', connectionId: null }])) + await vi.waitFor(() => expect(listRepoWorktreesMock).toHaveBeenCalledTimes(1)) + registerPty({ + ptyId, + worktreeId: 'repo-a::/local/Triton', + sessionId: ptyId, + paneKey: 'tab-1:1', + pid: 12345 + }) + worktrees.resolve([ + { path: '/local/Triton', head: '', branch: '', isBare: false, isMainWorktree: true } + ]) + await hydration + + expect(listRegisteredPtys()).toEqual([ + expect.objectContaining({ ptyId, pid: 12345, paneKey: 'tab-1:1' }) + ]) + }) + + it('does not resurrect a daemon session that exits during worktree enumeration', async () => { + const { hydrate, listRegisteredPtys, unregisterPty } = await loadFresh() + const ptyId = 'repo-a::/local/Triton@@deadbeef' + const provider = { + listSessions: vi + .fn() + .mockResolvedValueOnce([ + { sessionId: ptyId, pid: 4242, cwd: '/local/Triton' } as unknown as SessionInfo + ]) + .mockResolvedValueOnce([]) + } + getDaemonProviderMock.mockReturnValue(provider) + const worktrees = + createDeferred< + { path: string; head: string; branch: string; isBare: boolean; isMainWorktree: boolean }[] + >() + listRepoWorktreesMock.mockReturnValue(worktrees.promise) + + const hydration = hydrate(makeStore([{ id: 'repo-a', connectionId: null }])) + await vi.waitFor(() => expect(listRepoWorktreesMock).toHaveBeenCalledTimes(1)) + unregisterPty(ptyId) + worktrees.resolve([ + { path: '/local/Triton', head: '', branch: '', isBare: false, isMainWorktree: true } + ]) + await hydration + + expect(provider.listSessions).toHaveBeenCalledTimes(2) + expect(listRegisteredPtys()).toHaveLength(0) }) it('skips SSH repos before enumerating worktrees', async () => { @@ -223,6 +299,99 @@ describe('hydrateLocalPtyRegistryAtBoot', () => { expect(entry!.worktreeId).toBe('repo-a::/local/Triton') }) + it('does not register a daemon session whose worktree was removed', async () => { + const { hydrate, listRegisteredPtys } = await loadFresh() + const provider = makeProvider([ + { + sessionId: 'repo-a::/local/removed@@deadbeef', + pid: 4242, + cwd: '/local/removed' + } as unknown as SessionInfo + ]) + getDaemonProviderMock.mockReturnValue(provider) + listRepoWorktreesMock.mockResolvedValue([ + { path: '/local/current', head: '', branch: '', isBare: false, isMainWorktree: true } + ]) + + await hydrate(makeStore([{ id: 'repo-a', connectionId: null }])) + + expect(listRepoWorktreesMock).toHaveBeenCalledTimes(1) + expect(listRegisteredPtys()).toHaveLength(0) + }) + + it('enumerates worktrees only for repos referenced by live daemon sessions', async () => { + const { hydrate, listRegisteredPtys } = await loadFresh() + const repos = Array.from({ length: 100 }, (_, index) => ({ id: `repo-${index}` })) + const activeRepoIds = ['repo-17', 'repo-83'] + const provider = makeProvider( + activeRepoIds.map( + (repoId, index) => + ({ + sessionId: `${repoId}::/local/${repoId}@@0000000${index}`, + pid: 4000 + index, + cwd: `/local/${repoId}` + }) as unknown as SessionInfo + ) + ) + getDaemonProviderMock.mockReturnValue(provider) + listRepoWorktreesMock.mockImplementation(async (repo: Repo) => [ + { + path: `/local/${repo.id}`, + head: '', + branch: '', + isBare: false, + isMainWorktree: true + } + ]) + + await hydrate(makeStore(repos)) + + expect(listRepoWorktreesMock).toHaveBeenCalledTimes(activeRepoIds.length) + expect(listRepoWorktreesMock.mock.calls.map(([repo]) => (repo as Repo).id)).toEqual( + activeRepoIds + ) + expect(listRegisteredPtys()).toHaveLength(activeRepoIds.length) + }) + + it('scans a repo that only becomes visible on the post-enumeration re-read', async () => { + const { hydrate, listRegisteredPtys } = await loadFresh() + + const sessionA = { + sessionId: 'repo-a::/local/repo-a@@00000001', + pid: 4001, + cwd: '/local/repo-a' + } as unknown as SessionInfo + const sessionB = { + sessionId: 'repo-b::/local/repo-b@@00000002', + pid: 4002, + cwd: '/local/repo-b' + } as unknown as SessionInfo + // Why: a briefly unreachable adapter can omit a session from the first + // listing; once it reappears on the re-read its repo must still be + // scanned and the session registered instead of silently dropped. + const listSessions = vi + .fn() + .mockResolvedValueOnce([sessionA]) + .mockResolvedValue([sessionA, sessionB]) + getDaemonProviderMock.mockReturnValue({ listSessions }) + listRepoWorktreesMock.mockImplementation(async (repo: Repo) => [ + { path: `/local/${repo.id}`, head: '', branch: '', isBare: false, isMainWorktree: true } + ]) + + await hydrate(makeStore([{ id: 'repo-a' }, { id: 'repo-b' }])) + + expect(listRepoWorktreesMock.mock.calls.map(([repo]) => (repo as Repo).id)).toEqual([ + 'repo-a', + 'repo-b' + ]) + expect(listSessions).toHaveBeenCalledTimes(3) + const registered = listRegisteredPtys() + expect(registered.map((p) => p.ptyId).sort()).toEqual([ + 'repo-a::/local/repo-a@@00000001', + 'repo-b::/local/repo-b@@00000002' + ]) + }) + it('hydrates large daemon session lists', async () => { const { hydrate, listRegisteredPtys } = await loadFresh() diff --git a/src/main/memory/hydrate-local-pty-registry.ts b/src/main/memory/hydrate-local-pty-registry.ts index 4bb82763ec70..f6563049318f 100644 --- a/src/main/memory/hydrate-local-pty-registry.ts +++ b/src/main/memory/hydrate-local-pty-registry.ts @@ -25,6 +25,7 @@ import type { SessionInfo } from '../daemon/types' import { listRegisteredPtys, registerPty } from './pty-registry' import { listRepoWorktrees } from '../repo-worktrees' import { parsePtySessionId } from '../../shared/pty-session-id-format' +import { splitWorktreeId } from '../../shared/worktree-id' import type { Store } from '../persistence' // Why: `attachMainWindowServices` runs on every macOS dock re-activation @@ -70,34 +71,62 @@ export async function hydrateLocalPtyRegistryAtBoot(store: Pick() + // Why: ask the daemon which repos matter before launching Git worktree + // enumeration. Most configured repos have no preserved session at boot, + // so scanning all of them creates pure background subprocess churn. + const reposById = new Map(store.getRepos().map((repo) => [repo.id, repo])) + // Why: live git enumeration verifies that a referenced local worktree + // still exists instead of resurrecting removed worktrees. + const liveLocalWorktreeIds = new Set() + const resolvedRepoIds = new Set() - for (const repo of repos) { - const connectionId = repo.connectionId ?? null - if (connectionId) { - // Why: SSH PTYs are never registered for local process sampling, so - // avoid startup SSH/git enumeration for repos we will skip anyway. - continue + let sessionInfos = await collectSessionInfos(provider) + let alreadyRegistered = new Set(listRegisteredPtys().map((p) => p.ptyId)) + + // Why: repo selection and registration must come from the same daemon + // snapshot. Git enumeration can take seconds, so after each scan pass we + // re-read daemon and registry state; sessions that exited or were + // authoritatively registered meanwhile are not resurrected or overwritten, + // and a session that only became visible during a slow scan (e.g. a + // briefly unreachable legacy adapter) gets its repo scanned on the next + // pass instead of being silently dropped. Terminates because every pass + // permanently resolves at least one new repo id. + for (;;) { + const newlyReferencedRepos = new Map[number]>() + for (const info of sessionInfos) { + if (alreadyRegistered.has(info.sessionId)) { + continue + } + const { worktreeId } = parsePtySessionId(info.sessionId) + const parsedWorktreeId = worktreeId ? splitWorktreeId(worktreeId) : null + if (!parsedWorktreeId || resolvedRepoIds.has(parsedWorktreeId.repoId)) { + continue + } + const repo = reposById.get(parsedWorktreeId.repoId) + if (!repo || (repo.connectionId ?? null)) { + // Why: unknown repos can't be proven local, and SSH PTYs are never + // registered for local process sampling — resolve without git + // enumeration so neither can extend the loop. + resolvedRepoIds.add(parsedWorktreeId.repoId) + continue + } + newlyReferencedRepos.set(repo.id, repo) } - const worktrees = await listRepoWorktrees(repo) - for (const wt of worktrees) { - const worktreeId = `${repo.id}::${wt.path}` - repoConnectionIdByWorktreeId.set(worktreeId, connectionId) + if (newlyReferencedRepos.size === 0) { + break } - } - - // Why: SessionInfo is read through the adapter's listSessions() so we - // get the pid alongside each id. Routing through every adapter - // (current + legacy) keeps protocol coverage symmetric with the - // orphan-cleanup path. - const sessionInfos = await collectSessionInfos(provider) - const alreadyRegistered = new Set(listRegisteredPtys().map((p) => p.ptyId)) + for (const repo of newlyReferencedRepos.values()) { + resolvedRepoIds.add(repo.id) + const worktrees = await listRepoWorktrees(repo) + for (const wt of worktrees) { + liveLocalWorktreeIds.add(`${repo.id}::${wt.path}`) + } + } + sessionInfos = await collectSessionInfos(provider) + alreadyRegistered = new Set(listRegisteredPtys().map((p) => p.ptyId)) + } for (const info of sessionInfos) { // Why: pid-write ordering — `pty:spawn` is the authoritative // writer for in-session sessions; if that fired before this loop @@ -115,10 +144,7 @@ export async function hydrateLocalPtyRegistryAtBoot(store: Pick { expect(resolved).toBe(target) }) + it('resolves Grok chat_history.jsonl under encodeURIComponent(cwd)/sessionId', async () => { + const root = await makeRoot('orca-native-chat-resolve-grok-') + const grokSessionsDir = join(root, 'grok-sessions') + const sessionDir = join(grokSessionsDir, encodeURIComponent('/tmp/work'), 'sess-grok-1') + await mkdir(sessionDir, { recursive: true }) + const target = join(sessionDir, 'chat_history.jsonl') + await writeFile(target, '{"type":"user","content":"hi"}\n') + + const resolved = await resolveSessionFilePath('grok', 'sess-grok-1', { grokSessionsDir }) + expect(resolved).toBe(target) + }) + + it('resolves Grok chat_history by session id under a long-cwd slug group', async () => { + const root = await makeRoot('orca-native-chat-resolve-grok-long-') + const grokSessionsDir = join(root, 'grok-sessions') + const sessionDir = join(grokSessionsDir, 'slug-hash-ab12', 'sess-long-1') + await mkdir(sessionDir, { recursive: true }) + const target = join(sessionDir, 'chat_history.jsonl') + await writeFile(join(grokSessionsDir, 'slug-hash-ab12', '.cwd'), `/${'x'.repeat(400)}\n`) + await writeFile(target, '{"type":"assistant","content":"ok"}\n') + + await expect(resolveSessionFilePath('grok', 'sess-long-1', { grokSessionsDir })).resolves.toBe( + target + ) + }) + + it('ignores nested Grok decoys outside the direct group/session layout', async () => { + const root = await makeRoot('orca-native-chat-resolve-grok-decoy-') + const grokSessionsDir = join(root, 'grok-sessions') + const decoy = join( + grokSessionsDir, + 'group', + 'other-session', + 'nested', + 'sess-decoy', + 'chat_history.jsonl' + ) + await mkdir(dirname(decoy), { recursive: true }) + await writeFile(decoy, '{}\n') + + await expect( + resolveSessionFilePath('grok', 'sess-decoy', { grokSessionsDir }) + ).resolves.toBeNull() + }) + + it('rejects unsafe Grok session ids before filesystem discovery', async () => { + const root = await makeRoot('orca-native-chat-resolve-grok-invalid-') + const grokSessionsDir = join(root, 'grok-sessions') + await mkdir(grokSessionsDir, { recursive: true }) + + await expect( + resolveSessionFilePath('grok', '../escape', { grokSessionsDir }) + ).resolves.toBeNull() + }) + + it('resolves Grok sessions under GROK_HOME when no override is passed', async () => { + const root = await makeRoot('orca-native-chat-resolve-grok-home-') + const sessionsDir = join(root, 'sessions') + const sessionDir = join(sessionsDir, encodeURIComponent('/repo'), 'sess-env-1') + await mkdir(sessionDir, { recursive: true }) + const target = join(sessionDir, 'chat_history.jsonl') + await writeFile(target, '{}\n') + const previous = process.env.GROK_HOME + process.env.GROK_HOME = root + try { + await expect(resolveSessionFilePath('grok', 'sess-env-1')).resolves.toBe(target) + } finally { + restoreEnv('GROK_HOME', previous) + } + }) + it('matches Codex rollout files by session id suffix', async () => { const root = await makeRoot('orca-native-chat-resolve-codex-') const codexSessionsDir = join(root, 'codex-sessions') diff --git a/src/main/native-chat/session-file-resolver.ts b/src/main/native-chat/session-file-resolver.ts index 3b2cda9965aa..adfa3856f0e7 100644 --- a/src/main/native-chat/session-file-resolver.ts +++ b/src/main/native-chat/session-file-resolver.ts @@ -4,6 +4,10 @@ import { basename, extname, join } from 'node:path' import type { AgentType } from '../../shared/native-chat-types' import { walkSessionFiles } from '../ai-vault/session-scanner-discovery' import { getOrcaManagedCodexHomePath } from '../codex/codex-home-paths' +import { + findGrokChatHistoryBySessionId, + resolveGrokSessionsDir +} from '../../shared/grok-session-paths' // Why: these mirror the path constants in ai-vault/session-scanner.ts. Reads // run in the main process against the runtime's own home directory; over SSH @@ -28,12 +32,18 @@ function codexSessionsDirs(): string[] { return candidates.filter((dir, index) => candidates.indexOf(dir) === index) } +function grokSessionsDir(): string { + return resolveGrokSessionsDir(process.env, homedir()) +} + export type ResolveSessionFileOptions = { /** Override the Claude projects root (used by tests / isolated scans). */ claudeProjectsDir?: string /** Override the Codex sessions roots, searched in order (tests / isolated * scans). Defaults to the orca-managed home then CODEX_HOME/~/.codex. */ codexSessionsDirs?: string[] + /** Override the Grok sessions root (`~/.grok/sessions`). */ + grokSessionsDir?: string /** Authoritative transcript path reported by the agent hook * (`providerSession.transcriptPath`). When set and the file exists, it is used * directly — recent Claude Code names the transcript with a UUID that differs @@ -76,6 +86,9 @@ export async function resolveSessionFilePath( if (agent === 'codex') { return resolveCodexSessionFile(trimmedId, options.codexSessionsDirs ?? codexSessionsDirs()) } + if (agent === 'grok') { + return resolveGrokSessionFile(trimmedId, options.grokSessionsDir ?? grokSessionsDir()) + } return null } @@ -115,3 +128,13 @@ async function resolveCodexSessionFile( } return null } + +async function resolveGrokSessionFile( + sessionId: string, + sessionsDir: string +): Promise { + // Why: Native Chat runs on the main thread; use the bounded async direct-layout + // lookup instead of blocking, then repeating, a recursive full-tree scan. + const history = await findGrokChatHistoryBySessionId(sessionsDir, sessionId) + return history +} diff --git a/src/main/native-chat/transcript-fallback-id.test.ts b/src/main/native-chat/transcript-fallback-id.test.ts new file mode 100644 index 000000000000..8ef46edfcf62 --- /dev/null +++ b/src/main/native-chat/transcript-fallback-id.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { transcriptFallbackId } from './transcript-fallback-id' + +describe('transcriptFallbackId', () => { + it('sorts line positions numerically when timestamps are unavailable', () => { + const ids = [10, 2, 100, 9].map((offset) => transcriptFallbackId('/chat.jsonl', offset)) + + expect(ids.sort()).toEqual([ + transcriptFallbackId('/chat.jsonl', 2), + transcriptFallbackId('/chat.jsonl', 9), + transcriptFallbackId('/chat.jsonl', 10), + transcriptFallbackId('/chat.jsonl', 100) + ]) + }) + + it('sorts later incremental byte ranges after earlier ranges', () => { + const earlier = transcriptFallbackId('/chat.jsonl', 99) + const later = transcriptFallbackId('/chat.jsonl', 100) + + expect(earlier < later).toBe(true) + }) +}) diff --git a/src/main/native-chat/transcript-fallback-id.ts b/src/main/native-chat/transcript-fallback-id.ts new file mode 100644 index 000000000000..6c993159902e --- /dev/null +++ b/src/main/native-chat/transcript-fallback-id.ts @@ -0,0 +1,10 @@ +const TRANSCRIPT_POSITION_WIDTH = 16 + +/** Stable JSONL position id shared by full reads and incremental tailing. */ +export function transcriptFallbackId(filePath: string, byteOffset: number): string { + return `${filePath}:${positionPart(byteOffset)}` +} + +function positionPart(value: number): string { + return value.toString().padStart(TRANSCRIPT_POSITION_WIDTH, '0') +} diff --git a/src/main/native-chat/transcript-line-decoders-claude.ts b/src/main/native-chat/transcript-line-decoders-claude.ts new file mode 100644 index 000000000000..76c8952580e5 --- /dev/null +++ b/src/main/native-chat/transcript-line-decoders-claude.ts @@ -0,0 +1,66 @@ +// Claude JSONL line → NativeChatMessage decoder. + +import type { NativeChatBlock, NativeChatMessage } from '../../shared/native-chat-types' +import { + asRecord, + extractString, + parseJsonObject, + timestampMs +} from '../ai-vault/session-scanner-values' +import { claudeContentBlocks } from './transcript-record-blocks' + +export function decodeClaudeTranscriptLine( + line: string, + fallbackId: string +): NativeChatMessage | null { + const record = parseJsonObject(line) + if (!record) { + return null + } + const role = record.type + if (role !== 'user' && role !== 'assistant') { + return null + } + const message = asRecord(record.message) + const decodedBlocks = claudeContentBlocks(message?.content) + if (decodedBlocks.length === 0) { + return null + } + // Why: Claude structurally marks injected turns, but tool-result records are + // genuine output and must remain visible even when the containing turn is meta. + const isInjectedUserTurn = + role === 'user' && + (record.isMeta === true || record.isSynthetic === true || record.isCompactSummary === true) + const blocks = isInjectedUserTurn + ? decodedBlocks.filter((block) => block.type === 'tool-result') + : decodedBlocks + if (blocks.length === 0) { + return null + } + const messageId = extractString(record.uuid) ?? extractString(message?.id) + return { + id: messageId ?? fallbackId, + role: claudeMessageRole(role, blocks), + blocks, + timestamp: parseTimestamp(record.timestamp), + source: 'transcript' + } +} + +// Claude marks reasoning via `thinking` content blocks; when a message is made +// up solely of reasoning, surface it as a reasoning-role message. +function claudeMessageRole( + role: 'user' | 'assistant', + blocks: NativeChatBlock[] +): NativeChatMessage['role'] { + if (role === 'user') { + const onlyToolResults = blocks.every((block) => block.type === 'tool-result') + return onlyToolResults && blocks.length > 0 ? 'tool' : 'user' + } + return role +} + +function parseTimestamp(value: unknown): number | null { + const parsed = timestampMs(value) + return Number.isFinite(parsed) ? parsed : null +} diff --git a/src/main/native-chat/transcript-line-decoders-codex.ts b/src/main/native-chat/transcript-line-decoders-codex.ts new file mode 100644 index 000000000000..64d04fa5ae3d --- /dev/null +++ b/src/main/native-chat/transcript-line-decoders-codex.ts @@ -0,0 +1,139 @@ +// Codex JSONL line → NativeChatMessage decoder. + +import type { NativeChatBlock, NativeChatMessage } from '../../shared/native-chat-types' +import { + asRecord, + extractString, + parseJsonObject, + timestampMs +} from '../ai-vault/session-scanner-values' +import { claudeContentBlocks, toolResultOutput } from './transcript-record-blocks' + +export function decodeCodexTranscriptLine( + line: string, + fallbackId: string +): NativeChatMessage | null { + const record = parseJsonObject(line) + if (!record) { + return null + } + const payload = asRecord(record.payload) + if (!payload) { + return null + } + const timestamp = parseTimestamp(record.timestamp) + const baseId = extractString(payload.id) ?? fallbackId + + if (record.type === 'response_item') { + return codexResponseItem(payload, baseId, timestamp) + } + if (record.type === 'event_msg') { + return codexEventMessage(payload, baseId, timestamp) + } + return null +} + +function codexResponseItem( + payload: Record, + id: string, + timestamp: number | null +): NativeChatMessage | null { + if (payload.type === 'message') { + const blocks = claudeContentBlocks(payload.content) + if (blocks.length === 0) { + return null + } + const role = + payload.role === 'assistant' ? 'assistant' : payload.role === 'user' ? 'user' : 'system' + return { id, role, blocks, timestamp, source: 'transcript' } + } + if (payload.type === 'reasoning') { + const text = extractString(payload.text) ?? codexSummaryText(payload.summary) + if (!text) { + return null + } + return { + id, + role: 'reasoning', + blocks: [{ type: 'text', text }], + timestamp, + source: 'transcript' + } + } + if (payload.type === 'function_call' || payload.type === 'local_shell_call') { + const name = extractString(payload.name) ?? 'tool' + return { + id, + role: 'assistant', + blocks: [{ type: 'tool-call', name, input: codexCallInput(payload) }], + timestamp, + source: 'transcript' + } + } + if (payload.type === 'function_call_output') { + return { + id, + role: 'tool', + blocks: [codexToolResult(payload.output)], + timestamp, + source: 'transcript' + } + } + return null +} + +function codexEventMessage( + payload: Record, + id: string, + timestamp: number | null +): NativeChatMessage | null { + if (payload.type === 'user_message') { + const text = extractString(payload.message) + return text + ? { id, role: 'user', blocks: [{ type: 'text', text }], timestamp, source: 'transcript' } + : null + } + if (payload.type === 'agent_message') { + const text = extractString(payload.message) + return text + ? { id, role: 'assistant', blocks: [{ type: 'text', text }], timestamp, source: 'transcript' } + : null + } + return null +} + +function codexCallInput(payload: Record): unknown { + if (payload.arguments !== undefined) { + return payload.arguments + } + return payload.input ?? payload.action ?? null +} + +function codexToolResult(output: unknown): NativeChatBlock { + const record = asRecord(output) + const isError = record?.success === false || record?.is_error === true + return { + type: 'tool-result', + output: toolResultOutput(record?.content ?? record?.output ?? output), + ...(isError ? { isError: true } : {}) + } +} + +function codexSummaryText(summary: unknown): string | null { + if (!Array.isArray(summary)) { + return null + } + const parts: string[] = [] + for (const item of summary) { + const text = extractString(asRecord(item)?.text) ?? extractString(item) + if (text) { + parts.push(text) + } + } + return parts.length ? parts.join('\n') : null +} + +function parseTimestamp(value: unknown): number | null { + const parsed = timestampMs(value) + return Number.isFinite(parsed) ? parsed : null +} diff --git a/src/main/native-chat/transcript-line-decoders-grok.ts b/src/main/native-chat/transcript-line-decoders-grok.ts new file mode 100644 index 000000000000..76386453970e --- /dev/null +++ b/src/main/native-chat/transcript-line-decoders-grok.ts @@ -0,0 +1,247 @@ +// Grok chat_history.jsonl line → NativeChatMessage decoder. + +import type { NativeChatBlock, NativeChatMessage } from '../../shared/native-chat-types' +import { + asRecord, + extractString, + parseJsonObject, + timestampMs +} from '../ai-vault/session-scanner-values' +import { claudeContentBlocks, toolResultOutput } from './transcript-record-blocks' + +/** + * Grok `chat_history.jsonl` rows: user/assistant/reasoning/tool records with + * Claude-like content blocks plus Grok-specific `backend_tool_call` / + * `tool_result` shapes. System prompts are skipped. + */ +export function decodeGrokTranscriptLine( + line: string, + fallbackId: string +): NativeChatMessage | null { + const record = parseJsonObject(line) + if (!record) { + return null + } + const type = extractString(record.type) + if (!type) { + return null + } + const timestamp = parseTimestamp(record.timestamp) + const recordId = extractString(record.id) + // Why: Grok rows frequently omit timestamps and only some carry ids; prefix + // every row with its JSONL position so Native Chat preserves transcript order. + const id = recordId ? `${fallbackId}:${recordId}` : fallbackId + + if (type === 'user' || type === 'assistant') { + // Why: Grok records bootstrap context as user rows; only submitted prompts + // belong in the conversation shown to the user. + if ( + type === 'user' && + (hasNonEmptySyntheticReason(record) || isGrokBootstrapContext(record.content)) + ) { + return null + } + const rawBlocks = claudeContentBlocks(record.content) + const blocks = type === 'user' ? rawBlocks.flatMap(normalizeGrokUserQueryBlock) : rawBlocks + if (blocks.length === 0) { + // Empty assistant rows often only hold tool_calls — surface those. + const toolBlocks = grokToolCallBlocks(record.tool_calls) + if (toolBlocks.length === 0) { + return null + } + return { id, role: 'assistant', blocks: toolBlocks, timestamp, source: 'transcript' } + } + if (type === 'assistant') { + const toolBlocks = grokToolCallBlocks(record.tool_calls) + return { + id, + role: 'assistant', + blocks: [...blocks, ...toolBlocks], + timestamp, + source: 'transcript' + } + } + return { id, role: 'user', blocks, timestamp, source: 'transcript' } + } + + if (type === 'reasoning') { + const text = + extractString(record.text) ?? + grokSummaryText(record.summary) ?? + extractString(asRecord(record.content)?.text) + if (!text?.trim()) { + return null + } + return { + id, + role: 'reasoning', + blocks: [{ type: 'text', text }], + timestamp, + source: 'transcript' + } + } + + if (type === 'backend_tool_call' || type === 'tool_call') { + const name = + extractString(asRecord(record.kind)?.tool_type) ?? + extractString(record.name) ?? + extractString(record.tool) ?? + 'tool' + return { + id, + role: 'assistant', + blocks: [{ type: 'tool-call', name, input: record.kind ?? record.arguments ?? record.input }], + timestamp, + source: 'transcript' + } + } + + if (type === 'tool_result') { + const output = toolResultOutput(record.content ?? record.output ?? record.result) + return { + id, + role: 'tool', + blocks: [ + { + type: 'tool-result', + output, + ...(record.is_error === true || record.isError === true ? { isError: true } : {}) + } + ], + timestamp, + source: 'transcript' + } + } + + return null +} + +function grokToolCallBlocks(value: unknown): NativeChatBlock[] { + if (!Array.isArray(value)) { + return [] + } + const blocks: NativeChatBlock[] = [] + for (const item of value) { + const record = asRecord(item) + if (!record) { + continue + } + const name = extractString(record.name) ?? extractString(record.tool) ?? 'tool' + let input: unknown = record.arguments ?? record.input ?? record.args + if (typeof input === 'string') { + try { + input = JSON.parse(input) + } catch { + // keep string + } + } + blocks.push({ type: 'tool-call', name, input }) + } + return blocks +} + +function grokSummaryText(value: unknown): string | null { + if (typeof value === 'string') { + return value + } + if (!Array.isArray(value)) { + return null + } + const parts: string[] = [] + for (const item of value) { + const record = asRecord(item) + const text = extractString(record?.text) ?? extractString(record?.summary_text) + if (text) { + parts.push(text) + } + } + return parts.length > 0 ? parts.join('\n') : null +} + +function hasNonEmptySyntheticReason(record: Record): boolean { + return typeof record.synthetic_reason === 'string' && record.synthetic_reason.trim().length > 0 +} + +function isGrokBootstrapContext(content: unknown): boolean { + const text = standaloneTextContent(content) + if (!text) { + return false + } + const normalized = text.trim().toLowerCase() + if (!normalized.startsWith('')) { + return false + } + const userInfoEnd = normalized.indexOf('') + if (userInfoEnd === -1) { + return false + } + const remainder = normalized.slice(userInfoEnd + ''.length).trim() + // Why: Grok 0.2.93 appends its git snapshot to the user-info bootstrap row; + // reject only that known envelope so real prompts mentioning either tag survive. + return ( + remainder.length === 0 || + (remainder.startsWith('') && remainder.endsWith('')) + ) +} + +function standaloneTextContent(content: unknown): string | null { + if (typeof content === 'string') { + return content + } + if (!Array.isArray(content) || content.length !== 1) { + return null + } + const block = asRecord(content[0]) + return block?.type === 'text' ? (extractString(block.text) ?? null) : null +} + +function normalizeGrokUserQueryBlock(block: NativeChatBlock): NativeChatBlock[] { + if (block.type !== 'text') { + return [block] + } + const stripped = stripGrokUserQueryEnvelope(block.text) + if (!stripped.trim()) { + return [] + } + const pastedImage = splitGrokPastedImageQuery(stripped) + if (!pastedImage) { + return [stripped === block.text ? block : { type: 'text', text: stripped }] + } + return [ + { type: 'image-ref', path: pastedImage.path }, + ...(pastedImage.query ? [{ type: 'text' as const, text: pastedImage.query }] : []) + ] +} + +function splitGrokPastedImageQuery(text: string): { path: string; query: string } | null { + // Why: Grok 0.2.93 persists clipboard images as an absolute temp path directly + // concatenated with the prompt; recover Orca's attachment without exposing it. + const match = text.match( + /^((?:[a-z]:[\\/]|\/|[\\/]{2}[^\\/\r\n]+[\\/][^\\/\r\n]+[\\/])(?:.*?[\\/])?orca-paste-[^\\/\r\n]+?\.png)([\s\S]*)$/i + ) + if (!match?.[1]) { + return null + } + return { path: match[1], query: (match[2] ?? '').trim() } +} + +function stripGrokUserQueryEnvelope(text: string): string { + const opener = '' + const closer = '' + const lower = text.toLowerCase() + const start = lower.indexOf(opener) + if (start === -1) { + return text + } + const bodyStart = start + opener.length + const end = lower.indexOf(closer, bodyStart) + if (end === -1) { + return text.slice(bodyStart).trim() + } + return text.slice(bodyStart, end).trim() +} + +function parseTimestamp(value: unknown): number | null { + const parsed = timestampMs(value) + return Number.isFinite(parsed) ? parsed : null +} diff --git a/src/main/native-chat/transcript-line-decoders.grok.test.ts b/src/main/native-chat/transcript-line-decoders.grok.test.ts new file mode 100644 index 000000000000..13295dcfcdd9 --- /dev/null +++ b/src/main/native-chat/transcript-line-decoders.grok.test.ts @@ -0,0 +1,198 @@ +import { describe, expect, it } from 'vitest' +import { decodeGrokTranscriptLine } from './transcript-line-decoders' + +describe('decodeGrokTranscriptLine', () => { + it('decodes user text and strips wrappers', () => { + const line = JSON.stringify({ + type: 'user', + content: [{ type: 'text', text: '\nFix the bug\n' }], + timestamp: '2026-06-18T00:00:00.000Z' + }) + expect(decodeGrokTranscriptLine(line, 'fb-1')).toEqual({ + id: 'fb-1', + role: 'user', + blocks: [{ type: 'text', text: 'Fix the bug' }], + timestamp: Date.parse('2026-06-18T00:00:00.000Z'), + source: 'transcript' + }) + }) + + it('decodes assistant tool calls on empty content rows', () => { + const line = JSON.stringify({ + type: 'assistant', + content: '', + tool_calls: [{ id: 'c1', name: 'grep', arguments: '{"pattern":"foo"}' }], + id: 'asst-1' + }) + expect(decodeGrokTranscriptLine(line, 'fb-2')).toEqual({ + id: 'fb-2:asst-1', + role: 'assistant', + blocks: [{ type: 'tool-call', name: 'grep', input: { pattern: 'foo' } }], + timestamp: null, + source: 'transcript' + }) + }) + + it.each([ + 'C:\\Users\\me\\AppData\\Local\\Temp\\orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png', + '/tmp/orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png', + 'C:\\orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png', + '/orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png', + '\\\\server\\temp\\orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png' + ])('restores a pasted image and prompt from Grok transcript text for %s', (imagePath) => { + const line = JSON.stringify({ + type: 'user', + content: [ + { + type: 'text', + text: `\n${imagePath}Describe this image\n` + } + ] + }) + + expect(decodeGrokTranscriptLine(line, 'fb-image')).toMatchObject({ + role: 'user', + blocks: [ + { type: 'image-ref', path: imagePath }, + { type: 'text', text: 'Describe this image' } + ] + }) + }) + + it('restores an attachment-only pasted image from Grok transcript text', () => { + const imagePath = '/tmp/orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png' + const line = JSON.stringify({ + type: 'user', + content: [{ type: 'text', text: `${imagePath}` }] + }) + + expect(decodeGrokTranscriptLine(line, 'fb-image-only')).toMatchObject({ + role: 'user', + blocks: [{ type: 'image-ref', path: imagePath }] + }) + }) + + it('preserves ordinary prompts that mention pasted-image filenames', () => { + const text = 'Explain what an orca-paste-123-example.png file is' + const line = JSON.stringify({ + type: 'user', + content: [{ type: 'text', text: `${text}` }] + }) + + expect(decodeGrokTranscriptLine(line, 'fb-image-mention')).toMatchObject({ + role: 'user', + blocks: [{ type: 'text', text }] + }) + }) + + it('preserves assistant text containing a literal user_query tag', () => { + const text = 'Before quoted example after' + const line = JSON.stringify({ type: 'assistant', content: text }) + + expect(decodeGrokTranscriptLine(line, 'fb-assistant-tag')).toMatchObject({ + role: 'assistant', + blocks: [{ type: 'text', text }] + }) + }) + + it.each(['project_instructions', 'system_reminder'])( + 'skips Grok synthetic user rows with reason %s', + (syntheticReason) => { + const line = JSON.stringify({ + type: 'user', + content: [{ type: 'text', text: 'Internal context' }], + synthetic_reason: syntheticReason + }) + + expect(decodeGrokTranscriptLine(line, `fb-${syntheticReason}`)).toBeNull() + } + ) + + it.each([ + 'bootstrap context', + [{ type: 'text', text: 'bootstrap context' }], + [ + { + type: 'text', + text: [ + 'Runtime context', + 'Working tree snapshot' + ].join('\n\n') + } + ] + ])('skips a standalone Grok user_info bootstrap row', (content) => { + expect( + decodeGrokTranscriptLine(JSON.stringify({ type: 'user', content }), 'fb-user-info') + ).toBeNull() + }) + + it('keeps a real query that discusses the user_info tag', () => { + const line = JSON.stringify({ + type: 'user', + content: [ + { + type: 'text', + text: 'Explain the tag' + } + ] + }) + + expect(decodeGrokTranscriptLine(line, 'fb-user-info-query')).toMatchObject({ + role: 'user', + blocks: [{ type: 'text', text: 'Explain the tag' }] + }) + }) + + it('filters Grok bootstrap rows from a real-schema transcript prefix', () => { + const rows = [ + { type: 'system', content: 'System context' }, + { + type: 'user', + content: [{ type: 'text', text: 'Runtime context' }] + }, + { + type: 'user', + content: [{ type: 'text', text: 'Project context' }], + synthetic_reason: 'project_instructions' + }, + { + type: 'user', + content: [{ type: 'text', text: 'Reminder context' }], + synthetic_reason: 'system_reminder' + }, + { + type: 'user', + content: [{ type: 'text', text: 'Visible prompt' }] + }, + { type: 'assistant', content: 'Visible answer' } + ] + + const messages = rows + .map((row, index) => decodeGrokTranscriptLine(JSON.stringify(row), `fb-real-schema-${index}`)) + .filter((message) => message !== null) + + expect(messages).toMatchObject([ + { role: 'user', blocks: [{ type: 'text', text: 'Visible prompt' }] }, + { role: 'assistant', blocks: [{ type: 'text', text: 'Visible answer' }] } + ]) + }) + + it('decodes reasoning summaries', () => { + const line = JSON.stringify({ + type: 'reasoning', + id: 'rs-1', + summary: [{ type: 'summary_text', text: 'Planning the change' }] + }) + expect(decodeGrokTranscriptLine(line, 'fb-3')).toMatchObject({ + id: 'fb-3:rs-1', + role: 'reasoning', + blocks: [{ type: 'text', text: 'Planning the change' }], + source: 'transcript' + }) + }) + + it('skips system prompts', () => { + const line = JSON.stringify({ type: 'system', content: 'You are Grok' }) + expect(decodeGrokTranscriptLine(line, 'fb-4')).toBeNull() + }) +}) diff --git a/src/main/native-chat/transcript-line-decoders.ts b/src/main/native-chat/transcript-line-decoders.ts index 1a428cbb98ae..67b1aaf76aa9 100644 --- a/src/main/native-chat/transcript-line-decoders.ts +++ b/src/main/native-chat/transcript-line-decoders.ts @@ -5,181 +5,10 @@ // or null (unknown/empty records are skipped, never thrown — plan KTD risk: // schema drift). `fallbackId` is used only when the record carries no intrinsic // id; the caller supplies a value unique per line. +// +// Why: agent-specific decoders live in dedicated modules so this barrel stays +// under the max-lines limit while callers keep a single import path. -import type { NativeChatBlock, NativeChatMessage } from '../../shared/native-chat-types' -import { - asRecord, - extractString, - parseJsonObject, - timestampMs -} from '../ai-vault/session-scanner-values' -import { claudeContentBlocks, toolResultOutput } from './transcript-record-blocks' - -export function decodeClaudeTranscriptLine( - line: string, - fallbackId: string -): NativeChatMessage | null { - const record = parseJsonObject(line) - if (!record) { - return null - } - const role = record.type - if (role !== 'user' && role !== 'assistant') { - return null - } - const message = asRecord(record.message) - const blocks = claudeContentBlocks(message?.content) - if (blocks.length === 0) { - return null - } - const messageId = extractString(record.uuid) ?? extractString(message?.id) - return { - id: messageId ?? fallbackId, - role: claudeMessageRole(role, blocks), - blocks, - timestamp: parseTimestamp(record.timestamp), - source: 'transcript' - } -} - -// Claude marks reasoning via `thinking` content blocks; when a message is made -// up solely of reasoning, surface it as a reasoning-role message. -function claudeMessageRole( - role: 'user' | 'assistant', - blocks: NativeChatBlock[] -): NativeChatMessage['role'] { - if (role === 'user') { - const onlyToolResults = blocks.every((block) => block.type === 'tool-result') - return onlyToolResults && blocks.length > 0 ? 'tool' : 'user' - } - return role -} - -export function decodeCodexTranscriptLine( - line: string, - fallbackId: string -): NativeChatMessage | null { - const record = parseJsonObject(line) - if (!record) { - return null - } - const payload = asRecord(record.payload) - if (!payload) { - return null - } - const timestamp = parseTimestamp(record.timestamp) - const baseId = extractString(payload.id) ?? fallbackId - - if (record.type === 'response_item') { - return codexResponseItem(payload, baseId, timestamp) - } - if (record.type === 'event_msg') { - return codexEventMessage(payload, baseId, timestamp) - } - return null -} - -function codexResponseItem( - payload: Record, - id: string, - timestamp: number | null -): NativeChatMessage | null { - if (payload.type === 'message') { - const blocks = claudeContentBlocks(payload.content) - if (blocks.length === 0) { - return null - } - const role = - payload.role === 'assistant' ? 'assistant' : payload.role === 'user' ? 'user' : 'system' - return { id, role, blocks, timestamp, source: 'transcript' } - } - if (payload.type === 'reasoning') { - const text = extractString(payload.text) ?? codexSummaryText(payload.summary) - if (!text) { - return null - } - return { - id, - role: 'reasoning', - blocks: [{ type: 'text', text }], - timestamp, - source: 'transcript' - } - } - if (payload.type === 'function_call' || payload.type === 'local_shell_call') { - const name = extractString(payload.name) ?? 'tool' - return { - id, - role: 'assistant', - blocks: [{ type: 'tool-call', name, input: codexCallInput(payload) }], - timestamp, - source: 'transcript' - } - } - if (payload.type === 'function_call_output') { - return { - id, - role: 'tool', - blocks: [codexToolResult(payload.output)], - timestamp, - source: 'transcript' - } - } - return null -} - -function codexEventMessage( - payload: Record, - id: string, - timestamp: number | null -): NativeChatMessage | null { - if (payload.type === 'user_message') { - const text = extractString(payload.message) - return text - ? { id, role: 'user', blocks: [{ type: 'text', text }], timestamp, source: 'transcript' } - : null - } - if (payload.type === 'agent_message') { - const text = extractString(payload.message) - return text - ? { id, role: 'assistant', blocks: [{ type: 'text', text }], timestamp, source: 'transcript' } - : null - } - return null -} - -function codexCallInput(payload: Record): unknown { - if (payload.arguments !== undefined) { - return payload.arguments - } - return payload.input ?? payload.action ?? null -} - -function codexToolResult(output: unknown): NativeChatBlock { - const record = asRecord(output) - const isError = record?.success === false || record?.is_error === true - return { - type: 'tool-result', - output: toolResultOutput(record?.content ?? record?.output ?? output), - ...(isError ? { isError: true } : {}) - } -} - -function codexSummaryText(summary: unknown): string | null { - if (!Array.isArray(summary)) { - return null - } - const parts: string[] = [] - for (const item of summary) { - const text = extractString(asRecord(item)?.text) ?? extractString(item) - if (text) { - parts.push(text) - } - } - return parts.length ? parts.join('\n') : null -} - -function parseTimestamp(value: unknown): number | null { - const parsed = timestampMs(value) - return Number.isFinite(parsed) ? parsed : null -} +export { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' +export { decodeCodexTranscriptLine } from './transcript-line-decoders-codex' +export { decodeGrokTranscriptLine } from './transcript-line-decoders-grok' diff --git a/src/main/native-chat/transcript-reader.test.ts b/src/main/native-chat/transcript-reader.test.ts index 09c922ca3472..c6c2223c81fe 100644 --- a/src/main/native-chat/transcript-reader.test.ts +++ b/src/main/native-chat/transcript-reader.test.ts @@ -87,6 +87,74 @@ describe('readNativeChatTranscript (claude)', () => { expect(toolResult?.blocks[0]).toEqual({ type: 'tool-result', output: 'file-a\nfile-b' }) }) + it('drops structurally marked injected user turns but keeps their tool results', async () => { + const filePath = await writeFixture('orca-native-chat-claude-meta-', [ + { + type: 'user', + uuid: 'u-real', + timestamp: '2026-06-01T10:00:00.000Z', + message: { role: 'user', content: 'fix the login bug' } + }, + { + type: 'user', + uuid: 'u-meta', + isMeta: true, + timestamp: '2026-06-01T10:00:01.000Z', + message: { + role: 'user', + content: 'Another Claude session sent a message:\nhi' + } + }, + { + type: 'user', + uuid: 'u-compact', + isCompactSummary: true, + timestamp: '2026-06-01T10:00:02.000Z', + message: { + role: 'user', + content: 'This session is being continued from a previous conversation.' + } + }, + { + type: 'user', + uuid: 'u-meta-toolresult', + isMeta: true, + timestamp: '2026-06-01T10:00:03.000Z', + message: { + role: 'user', + content: [{ type: 'tool_result', content: 'ok', is_error: false }] + } + }, + { + type: 'user', + uuid: 'u-meta-mixed', + isMeta: true, + timestamp: '2026-06-01T10:00:04.000Z', + message: { + role: 'user', + content: [ + { type: 'text', text: 'hidden machinery' }, + { type: 'tool_result', content: 'mixed result', is_error: false } + ] + } + } + ]) + const result = await readNativeChatTranscript('claude', 'sess', { filePath }) + if (!('messages' in result)) { + throw new Error('expected messages') + } + expect(result.messages.map((m) => m.id)).toEqual([ + 'u-real', + 'u-meta-toolresult', + 'u-meta-mixed' + ]) + expect(result.messages[1].role).toBe('tool') + expect(result.messages[2]).toMatchObject({ + role: 'tool', + blocks: [{ type: 'tool-result', output: 'mixed result' }] + }) + }) + it('marks thinking-only assistant content as a reasoning surface', async () => { const filePath = await writeFixture('orca-native-chat-claude-think-', [ { diff --git a/src/main/native-chat/transcript-reader.ts b/src/main/native-chat/transcript-reader.ts index c0b5f64bb68d..1dbbd7dd82a7 100644 --- a/src/main/native-chat/transcript-reader.ts +++ b/src/main/native-chat/transcript-reader.ts @@ -1,9 +1,13 @@ import { createReadStream } from 'node:fs' -import { createInterface } from 'node:readline' import type { AgentType, NativeChatMessage } from '../../shared/native-chat-types' import { errorMessage } from '../ai-vault/session-scanner-values' import { resolveSessionFilePath, type ResolveSessionFileOptions } from './session-file-resolver' -import { decodeClaudeTranscriptLine, decodeCodexTranscriptLine } from './transcript-line-decoders' +import { + decodeClaudeTranscriptLine, + decodeCodexTranscriptLine, + decodeGrokTranscriptLine +} from './transcript-line-decoders' +import { decodeTranscriptStream } from './transcript-stream-lines' export type ReadTranscriptResult = { messages: NativeChatMessage[] } | { error: string } @@ -17,8 +21,7 @@ export type ReadTranscriptOptions = ResolveSessionFileOptions & { * the NativeChatMessage model. Unlike the AI-Vault preview scan, this applies * NO message cap. Unknown record types are skipped rather than throwing, so a * single malformed/unrecognized line cannot fail the whole read. The per-line - * record→message mapping is shared with the live tailer (transcript-watch.ts) - * via transcript-line-decoders.ts. + * record-to-message mapping is shared with the live tailer. */ export async function readNativeChatTranscript( agent: AgentType, @@ -36,6 +39,9 @@ export async function readNativeChatTranscript( if (agent === 'codex') { return { messages: await readTranscript(filePath, decodeCodexTranscriptLine) } } + if (agent === 'grok') { + return { messages: await readTranscript(filePath, decodeGrokTranscriptLine) } + } return { error: `Unsupported agent for native chat transcript: ${agent}` } } catch (err) { return { error: errorMessage(err) } @@ -46,21 +52,7 @@ async function readTranscript( filePath: string, decode: (line: string, fallbackId: string) => NativeChatMessage | null ): Promise { - const reader = createInterface({ - input: createReadStream(filePath, { encoding: 'utf-8' }), - crlfDelay: Infinity - }) - const messages: NativeChatMessage[] = [] - let index = 0 - for await (const line of reader) { - // Why: fallback id embeds start offset 0 so it matches the live tailer's id - // for the same record (the tailer's first drain reads from offset 0 too). - // Records that re-emit then collapse by id in the assembler — no dup, no drop. - const message = decode(line, `${filePath}:0:${index}`) - if (message) { - messages.push(message) - } - index++ - } + const stream = createReadStream(filePath, { encoding: 'utf-8' }) + const { messages } = await decodeTranscriptStream(stream, filePath, 0, decode, true) return messages } diff --git a/src/main/native-chat/transcript-stream-lines.test.ts b/src/main/native-chat/transcript-stream-lines.test.ts new file mode 100644 index 000000000000..2bfa6f6f9d23 --- /dev/null +++ b/src/main/native-chat/transcript-stream-lines.test.ts @@ -0,0 +1,49 @@ +import { Readable } from 'node:stream' +import { describe, expect, it } from 'vitest' +import { decodeTranscriptStream } from './transcript-stream-lines' + +const decode = (line: string, id: string) => ({ + id, + role: 'user' as const, + blocks: [{ type: 'text' as const, text: line }], + timestamp: null, + source: 'transcript' as const +}) + +describe('decodeTranscriptStream', () => { + it('uses identical absolute byte ids for full and incremental reads', async () => { + const prefix = '{"first":"é"}\r\n' + const appended = '{"second":true}\n' + const full = await decodeTranscriptStream( + Readable.from([prefix + appended]), + '/chat.jsonl', + 0, + decode, + true + ) + const incremental = await decodeTranscriptStream( + Readable.from([appended]), + '/chat.jsonl', + Buffer.byteLength(prefix, 'utf8'), + decode, + false + ) + + expect(incremental.messages[0]?.id).toBe(full.messages[1]?.id) + }) + + it('does not consume a partial trailing JSONL record', async () => { + const complete = '{"first":true}\n' + const partial = '{"second"' + const result = await decodeTranscriptStream( + Readable.from([complete + partial]), + '/chat.jsonl', + 0, + decode, + false + ) + + expect(result.messages).toHaveLength(1) + expect(result.consumedBytes).toBe(Buffer.byteLength(complete, 'utf8')) + }) +}) diff --git a/src/main/native-chat/transcript-stream-lines.ts b/src/main/native-chat/transcript-stream-lines.ts new file mode 100644 index 000000000000..a764941ad307 --- /dev/null +++ b/src/main/native-chat/transcript-stream-lines.ts @@ -0,0 +1,47 @@ +import type { Readable } from 'node:stream' +import type { NativeChatMessage } from '../../shared/native-chat-types' +import { transcriptFallbackId } from './transcript-fallback-id' + +type TranscriptDecoder = (line: string, fallbackId: string) => NativeChatMessage | null + +export async function decodeTranscriptStream( + stream: Readable, + filePath: string, + start: number, + decode: TranscriptDecoder, + includeTrailingLine: boolean +): Promise<{ messages: NativeChatMessage[]; consumedBytes: number }> { + const messages: NativeChatMessage[] = [] + let pending = '' + let consumedBytes = 0 + + for await (const chunk of stream) { + pending += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8') + let newlineIndex = pending.indexOf('\n') + while (newlineIndex !== -1) { + const segment = pending.slice(0, newlineIndex + 1) + decodeLine(segment.slice(0, -1), consumedBytes) + consumedBytes += Buffer.byteLength(segment, 'utf8') + pending = pending.slice(newlineIndex + 1) + newlineIndex = pending.indexOf('\n') + } + } + + if (includeTrailingLine && pending.length > 0) { + decodeLine(pending, consumedBytes) + consumedBytes += Buffer.byteLength(pending, 'utf8') + } + + return { messages, consumedBytes } + + function decodeLine(rawLine: string, relativeOffset: number): void { + const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine + if (!line) { + return + } + const message = decode(line, transcriptFallbackId(filePath, start + relativeOffset)) + if (message) { + messages.push(message) + } + } +} diff --git a/src/main/native-chat/transcript-watch.ts b/src/main/native-chat/transcript-watch.ts index 919cac24e103..4bbd934f0ebe 100644 --- a/src/main/native-chat/transcript-watch.ts +++ b/src/main/native-chat/transcript-watch.ts @@ -10,10 +10,14 @@ import { watch, type FSWatcher } from 'node:fs' import { open, stat } from 'node:fs/promises' -import type { Readable } from 'node:stream' import type { AgentType, NativeChatMessage } from '../../shared/native-chat-types' import { resolveSessionFilePath, type ResolveSessionFileOptions } from './session-file-resolver' -import { decodeClaudeTranscriptLine, decodeCodexTranscriptLine } from './transcript-line-decoders' +import { + decodeClaudeTranscriptLine, + decodeCodexTranscriptLine, + decodeGrokTranscriptLine +} from './transcript-line-decoders' +import { decodeTranscriptStream } from './transcript-stream-lines' export type SubscribeNativeChatTranscriptArgs = ResolveSessionFileOptions & { agent: AgentType @@ -57,6 +61,9 @@ function lineDecoderForAgent( if (agent === 'codex') { return decodeCodexTranscriptLine } + if (agent === 'grok') { + return decodeGrokTranscriptLine + } return null } @@ -94,53 +101,19 @@ async function readAppendedMessages( end: end - 1, autoClose: false }) - const { messages, consumedBytes } = await decodeStreamLines(stream, filePath, start, decode) + const { messages, consumedBytes } = await decodeTranscriptStream( + stream, + filePath, + start, + decode, + false + ) return { messages, consumedTo: start + consumedBytes } } finally { await handle.close() } } -async function decodeStreamLines( - stream: Readable, - filePath: string, - start: number, - decode: (line: string, fallbackId: string) => NativeChatMessage | null -): Promise<{ messages: NativeChatMessage[]; consumedBytes: number }> { - const text = await readStreamText(stream) - const completeEnd = text.lastIndexOf('\n') - if (completeEnd === -1) { - return { messages: [], consumedBytes: 0 } - } - - // Why: transcript writers can flush mid-record. Only advance through - // newline-terminated JSONL so invalid partial JSON is retried on the next - // append instead of being lost forever. - const completeText = text.slice(0, completeEnd + 1) - const lines = completeText.split('\n') - const messages: NativeChatMessage[] = [] - for (const [index, line] of lines.entries()) { - if (!line) { - continue - } - // Fallback id embeds the byte offset so ids stay stable+unique across - // appends even when a record carries no intrinsic id. - const message = decode(line, `${filePath}:${start}:${index}`) - if (message) { - messages.push(message) - } - } - return { messages, consumedBytes: Buffer.byteLength(completeText, 'utf8') } -} - -async function readStreamText(stream: Readable): Promise { - const chunks: string[] = [] - for await (const chunk of stream) { - chunks.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8')) - } - return chunks.join('') -} - /** * Subscribe to live appends on an agent's transcript file. Returns an * unsubscribe fn that tears the watcher down completely. diff --git a/src/main/observability/bundle.test.ts b/src/main/observability/bundle.test.ts index d532711828ad..347e10258930 100644 --- a/src/main/observability/bundle.test.ts +++ b/src/main/observability/bundle.test.ts @@ -140,6 +140,53 @@ describe('bundle — collection', () => { expect(bundle.payload).not.toContain('"name":"old"') }) + it('merges the daemon lifecycle log, bounded by the same lookback', () => { + const daemonFile = join(dir, 'daemon.log') + writeFileSync(traceFile, makeNDJSON([makeSpan({ name: 'recent' })])) + writeFileSync( + daemonFile, + makeNDJSON([ + { src: 'daemon', ts: new Date().toISOString(), pid: 1, event: 'startup' }, + { + src: 'daemon', + // 1h ago — outside the 30m window, must be dropped. + ts: new Date(Date.now() - 60 * 60 * 1000).toISOString(), + pid: 1, + event: 'session-exited' + } + ]) + ) + const bundle = collectBundle({ + traceFilePath: traceFile, + maxFiles: 10, + daemonLogFilePath: daemonFile, + daemonLogMaxFiles: 3, + lookbackMinutes: 30, + appVersion: '1', + platform: 'darwin', + arch: 'arm64', + osRelease: '24', + orcaChannel: 'dev' + }) + expect(bundle.payload).toContain('"event":"startup"') + expect(bundle.payload).toContain('"name":"recent"') + expect(bundle.payload).not.toContain('"event":"session-exited"') + }) + + it('collects no daemon log lines when no daemon log path is given', () => { + writeFileSync(traceFile, makeNDJSON([makeSpan({ name: 'recent' })])) + const bundle = collectBundle({ + traceFilePath: traceFile, + maxFiles: 10, + appVersion: '1', + platform: 'darwin', + arch: 'arm64', + osRelease: '24', + orcaChannel: 'dev' + }) + expect(bundle.payload).not.toContain('"src":"daemon"') + }) + it('runs the redactor on the merged payload (belt-and-suspenders)', () => { // Simulate a sink-write bug that leaked a secret through. The bundle // pass should still strip it. diff --git a/src/main/observability/bundle.ts b/src/main/observability/bundle.ts index 812e354d51f0..34011d9e4aae 100644 --- a/src/main/observability/bundle.ts +++ b/src/main/observability/bundle.ts @@ -39,6 +39,10 @@ const DEFAULT_LOOKBACK_MINUTES = 30 export type CollectBundleOptions = { readonly traceFilePath: string readonly maxFiles: number + /** Detached-daemon lifecycle log. Its rotated family is merged into the + * bundle so daemon-side failures are diagnosable from a field report. */ + readonly daemonLogFilePath?: string + readonly daemonLogMaxFiles?: number readonly lookbackMinutes?: number readonly appVersion: string readonly platform: string @@ -95,7 +99,8 @@ function* readLinesNewestFirst(text: string): Iterable { */ export function collectBundle(opts: CollectBundleOptions): CollectedBundle { const lookbackMs = (opts.lookbackMinutes ?? DEFAULT_LOOKBACK_MINUTES) * 60 * 1000 - const cutoffNanos = BigInt(Date.now() - lookbackMs) * 1_000_000n + const cutoffMs = Date.now() - lookbackMs + const cutoffNanos = BigInt(cutoffMs) * 1_000_000n const bundleSubmissionId = generateBundleSubmissionId() const header: BundleHeader = { bundle_submission_id: bundleSubmissionId, @@ -123,7 +128,15 @@ export function collectBundle(opts: CollectBundleOptions): CollectedBundle { // older than the cutoff in an older file we can stop entirely. We don't // optimize that yet; the worst case (10 × 10 MB = 100 MB scan) takes // <1 s on a modern SSD and bundles are user-initiated, not hot-path. - const files = listRotatedFiles(opts.traceFilePath, opts.maxFiles) + // Trace spans first (the primary payload), then the daemon lifecycle log. + // Daemon records carry an ISO `ts` instead of `endTimeUnixNano`; both are + // filtered by the same lookback below. + const files = [ + ...listRotatedFiles(opts.traceFilePath, opts.maxFiles), + ...(opts.daemonLogFilePath + ? listRotatedFiles(opts.daemonLogFilePath, opts.daemonLogMaxFiles ?? opts.maxFiles) + : []) + ] outer: for (const file of files) { let text: string try { @@ -153,7 +166,11 @@ export function collectBundle(opts: CollectBundleOptions): CollectedBundle { if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { continue } - const record = parsed as { startTimeUnixNano?: string; endTimeUnixNano?: string } + const record = parsed as { + startTimeUnixNano?: string + endTimeUnixNano?: string + ts?: string + } // Filter by end-time, not start-time. A long-lived span started 35 // minutes ago but ending inside the lookback is exactly what we want // in the bundle for diagnosing "session crashed at minute 32." @@ -166,6 +183,13 @@ export function collectBundle(opts: CollectBundleOptions): CollectedBundle { // Non-numeric end-time — keep it; better to over-include than to // drop a record we couldn't classify. } + } else if (typeof record.ts === 'string') { + // Daemon lifecycle lines timestamp with an ISO `ts`; bound them by the + // same lookback window. Unparseable timestamps are kept (over-include). + const tsMs = Date.parse(record.ts) + if (Number.isFinite(tsMs) && tsMs < cutoffMs) { + continue + } } // Run the redactor a SECOND TIME over the parsed shape, in server mode. diff --git a/src/main/observability/index.ts b/src/main/observability/index.ts index 9ab216d50e1f..791653d272dc 100644 --- a/src/main/observability/index.ts +++ b/src/main/observability/index.ts @@ -28,15 +28,14 @@ // import isolation rule above. The cost of one duplicated array vs. // punching a hole in the architecture is trivially worth it. -import { app } from 'electron' -import { homedir, platform } from 'node:os' -import { join } from 'node:path' import { createLocalFileSink, DEFAULT_MAX_FILES, getRotatedFamilySize, type LocalFileSink } from './local-file-sink' +import { getDaemonLogFilePath, getTraceFilePath } from './logs-directory' +import { DAEMON_LOG_MAX_FILES } from '../daemon/daemon-file-log' import { collectBundle as _collectBundle, type CollectBundleOptions, @@ -128,30 +127,9 @@ export function resolveObservabilityConsent(): ObservabilityConsent { } } -/** Path for the trace NDJSON file. macOS conventional location is - * `~/Library/Application Support/Orca/logs/main.trace.ndjson`; we resolve - * the same intent on Windows / Linux via Electron's `userData` dir. The - * function falls back to homedir when Electron is not available (tests). - */ -export function getTraceFilePath(): string { - let userData: string - try { - userData = app.getPath('userData') - } catch { - // Tests — Electron's `app` may not be initialized. Use a sensible - // OS-conventional fallback so unit tests can construct the path - // without spinning up the full Electron runtime. - const home = homedir() - if (platform() === 'darwin') { - userData = join(home, 'Library', 'Application Support', 'Orca') - } else if (platform() === 'win32') { - userData = join(process.env.APPDATA ?? home, 'Orca') - } else { - userData = join(home, '.config', 'Orca') - } - } - return join(userData, 'logs', 'main.trace.ndjson') -} +// Re-exported so existing importers of the trace path keep working; the +// resolution now lives in one place alongside the daemon log path. +export { getTraceFilePath } from './logs-directory' // ── Module-level state ─────────────────────────────────────────────────── @@ -237,6 +215,11 @@ export function collectDiagnosticBundle( return _collectBundle({ traceFilePath: getTraceFilePath(), maxFiles: DEFAULT_MAX_FILES, + // Why: the detached daemon writes its lifecycle log to a separate file, so + // the bundle collector must be pointed at it explicitly — it does not glob + // the logs directory. + daemonLogFilePath: getDaemonLogFilePath(), + daemonLogMaxFiles: DAEMON_LOG_MAX_FILES, ...meta }) } diff --git a/src/main/observability/logs-directory.ts b/src/main/observability/logs-directory.ts new file mode 100644 index 000000000000..94a1b7baae82 --- /dev/null +++ b/src/main/observability/logs-directory.ts @@ -0,0 +1,41 @@ +// Single source of truth for the app's logs directory and the files inside it. +// macOS convention is `~/Library/Application Support/Orca/logs/`; Windows and +// Linux resolve the same intent via Electron's `userData` dir. Falls back to a +// homedir-derived path when Electron's `app` is unavailable (unit tests). + +import { app } from 'electron' +import { homedir, platform } from 'node:os' +import { join } from 'node:path' + +function getUserDataDir(): string { + try { + return app.getPath('userData') + } catch { + // Tests — Electron's `app` may not be initialized. Use an OS-conventional + // fallback so callers can resolve the path without the Electron runtime. + const home = homedir() + if (platform() === 'darwin') { + return join(home, 'Library', 'Application Support', 'Orca') + } + if (platform() === 'win32') { + return join(process.env.APPDATA ?? home, 'Orca') + } + return join(home, '.config', 'Orca') + } +} + +export function getLogsDirectory(): string { + return join(getUserDataDir(), 'logs') +} + +/** NDJSON trace file written by the main-process error-tracking sink. */ +export function getTraceFilePath(): string { + return join(getLogsDirectory(), 'main.trace.ndjson') +} + +/** NDJSON lifecycle log written by the detached daemon process. Shared here so + * the daemon fork (which passes it as `--log-file`) and the bundle collector + * (which reads it) agree on one path. */ +export function getDaemonLogFilePath(): string { + return join(getLogsDirectory(), 'daemon.log') +} diff --git a/src/main/opencode-usage/scanner.test.ts b/src/main/opencode-usage/scanner.test.ts index c4bd46aae68c..f938dd815b0b 100644 --- a/src/main/opencode-usage/scanner.test.ts +++ b/src/main/opencode-usage/scanner.test.ts @@ -1,12 +1,13 @@ -import { mkdtempSync, rmSync } from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, unlinkSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import Database from '../sqlite/sync-database' import { attributeOpenCodeUsageEvent, parseOpenCodeUsageDatabase, - parseOpenCodeUsageRow + parseOpenCodeUsageRow, + scanOpenCodeUsageDatabases } from './scanner' const WORKTREE = '/workspace/repo' @@ -32,6 +33,50 @@ function worktrees() { ] } +function createSessionTotalsSchema(db: Database.Database): void { + db.exec(` + CREATE TABLE session ( + id TEXT PRIMARY KEY, + directory TEXT, + title TEXT, + model TEXT, + cost REAL, + tokens_input INTEGER, + tokens_output INTEGER, + tokens_reasoning INTEGER, + tokens_cache_read INTEGER, + time_created INTEGER, + time_updated INTEGER + ); + `) +} + +function insertSessionTotalsRow( + db: Database.Database, + sessionId: string, + inputTokens: number +): void { + db.prepare( + `INSERT INTO session ( + id, directory, title, model, cost, + tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, + time_created, time_updated + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ).run( + sessionId, + `${WORKTREE}/packages/app`, + 'Session', + JSON.stringify({ providerID: 'anthropic', id: 'claude-sonnet-4-5' }), + 0.01, + inputTokens, + 100, + 0, + 0, + 1_777_777_700_000, + 1_777_777_800_000 + ) +} + function usageEvent(cwd: string) { return { sessionId: 'session-1', @@ -259,6 +304,17 @@ describe('parseOpenCodeUsageDatabase', () => { }) }) + it('reports the session ids the database counted', async () => { + const { db, path } = createTempDb() + createSessionTotalsSchema(db) + insertSessionTotalsRow(db, 'session-1', 1000) + db.close() + + const parsed = await parseOpenCodeUsageDatabase(path, worktrees()) + + expect(parsed.ownedSessionIds).toEqual(['session-1']) + }) + it('prefers session_message rows over legacy message rows to avoid double counting', async () => { const { db, path } = createTempDb() db.exec(` @@ -324,3 +380,182 @@ describe('parseOpenCodeUsageDatabase', () => { expect(parsed.sessions[0]?.eventCount).toBe(1) }) }) + +describe('scanOpenCodeUsageDatabases', () => { + let dataRoot: string + let openCodeDir: string + let previousXdgDataHome: string | undefined + let previousOpenCodeDb: string | undefined + + beforeEach(() => { + dataRoot = mkdtempSync(join(tmpdir(), 'orca-opencode-usage-scan-')) + openCodeDir = join(dataRoot, 'opencode') + mkdirSync(openCodeDir, { recursive: true }) + previousXdgDataHome = process.env.XDG_DATA_HOME + previousOpenCodeDb = process.env.OPENCODE_DB + process.env.XDG_DATA_HOME = dataRoot + delete process.env.OPENCODE_DB + }) + + afterEach(() => { + if (previousXdgDataHome === undefined) { + delete process.env.XDG_DATA_HOME + } else { + process.env.XDG_DATA_HOME = previousXdgDataHome + } + if (previousOpenCodeDb === undefined) { + delete process.env.OPENCODE_DB + } else { + process.env.OPENCODE_DB = previousOpenCodeDb + } + rmSync(dataRoot, { recursive: true, force: true }) + }) + + function writeSessionTotalsDb(fileName: string, rows: [string, number][]): string { + const path = join(openCodeDir, fileName) + const db = new Database(path) + createSessionTotalsSchema(db) + for (const [sessionId, inputTokens] of rows) { + insertSessionTotalsRow(db, sessionId, inputTokens) + } + db.close() + return path + } + + it('counts a session duplicated into a stale backup database exactly once', async () => { + // The backup holds a stale snapshot of session-1; the canonical db has + // grown since. The canonical totals must win and be counted once. + writeSessionTotalsDb('opencode.db', [ + ['session-1', 1000], + ['session-2', 300] + ]) + writeSessionTotalsDb('opencode-backup.db', [['session-1', 400]]) + + const result = await scanOpenCodeUsageDatabases([], []) + + expect(result.sessions).toHaveLength(2) + const sessionOne = result.sessions.find((session) => session.sessionId === 'session-1') + expect(sessionOne?.totalInputTokens).toBe(1000) + expect(sessionOne?.eventCount).toBe(1) + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1300) + }) + + it('still counts backup-only sessions and stays stable across cached rescans', async () => { + const canonicalPath = writeSessionTotalsDb('opencode.db', [['session-1', 1000]]) + // The backup duplicates session-1 (stale) and preserves session-9, which + // no longer exists in the canonical database. + writeSessionTotalsDb('opencode-backup.db', [ + ['session-1', 400], + ['session-9', 50] + ]) + + const first = await scanOpenCodeUsageDatabases([], []) + expect( + first.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1050) + + const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1050) + + // The canonical db keeps growing while the backup stays cached; session-1 + // must stay owned by the canonical db. + const db = new Database(canonicalPath) + insertSessionTotalsRow(db, 'session-2', 200) + db.close() + + const third = await scanOpenCodeUsageDatabases([], second.processedDatabases) + expect( + third.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1250) + const sessionOne = third.sessions.find((session) => session.sessionId === 'session-1') + expect(sessionOne?.totalInputTokens).toBe(1000) + expect(sessionOne?.eventCount).toBe(1) + }) + + it('reuses a fully-duplicate backup instead of reparsing it when the live db changes', async () => { + // The backup only holds stale copies of sessions the canonical db already + // owns, so it owns nothing. When the live db changes it must not be + // demoted back into the parse set — there is no claim to reclaim. + const canonicalPath = writeSessionTotalsDb('opencode.db', [['session-1', 1000]]) + writeSessionTotalsDb('opencode-backup.db', [['session-1', 400]]) + + const first = await scanOpenCodeUsageDatabases([], []) + const firstBackup = first.processedDatabases.find((database) => + database.path.endsWith('opencode-backup.db') + ) + expect(firstBackup?.ownedSessionIds).toEqual([]) + + const db = new Database(canonicalPath) + insertSessionTotalsRow(db, 'session-2', 200) + db.close() + + const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) + const secondBackup = second.processedDatabases.find((database) => + database.path.endsWith('opencode-backup.db') + ) + // A reused cache entry is the same object; a reparse would produce a new one. + expect(secondBackup).toBe(firstBackup) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1200) + }) + + it('lets the live database reclaim sessions after a sticky backup-only claim', async () => { + // First scan only has the backup (e.g. live db temporarily missing), so it + // owns session-1 at the stale snapshot. When opencode.db reappears with + // higher totals it must reclaim the session instead of staying frozen. + writeSessionTotalsDb('opencode-backup.db', [['session-1', 400]]) + + const first = await scanOpenCodeUsageDatabases([], []) + expect( + first.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(400) + expect(first.processedDatabases[0]?.ownedSessionIds).toEqual(['session-1']) + + writeSessionTotalsDb('opencode.db', [ + ['session-1', 1000], + ['session-2', 200] + ]) + + const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1200) + const sessionOne = second.sessions.find((session) => session.sessionId === 'session-1') + expect(sessionOne?.totalInputTokens).toBe(1000) + expect(sessionOne?.eventCount).toBe(1) + }) + + it('reclaims sessions when the owning live database is deleted', async () => { + const canonicalPath = writeSessionTotalsDb('opencode.db', [ + ['session-1', 1000], + ['session-2', 200] + ]) + writeSessionTotalsDb('opencode-backup.db', [ + ['session-1', 400], + ['session-9', 50] + ]) + + const first = await scanOpenCodeUsageDatabases([], []) + expect( + first.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1250) + + unlinkSync(canonicalPath) + + const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(450) + expect(second.sessions.map((session) => session.sessionId).sort()).toEqual([ + 'session-1', + 'session-9' + ]) + const sessionOne = second.sessions.find((session) => session.sessionId === 'session-1') + expect(sessionOne?.totalInputTokens).toBe(400) + }) +}) diff --git a/src/main/opencode-usage/scanner.ts b/src/main/opencode-usage/scanner.ts index 8a61886886f2..57a95df3a62b 100644 --- a/src/main/opencode-usage/scanner.ts +++ b/src/main/opencode-usage/scanner.ts @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs' import { readdir, realpath, stat } from 'node:fs/promises' import { homedir } from 'node:os' -import { isAbsolute, join, posix, win32 } from 'node:path' +import { basename, isAbsolute, join, posix, win32 } from 'node:path' import type { Repo } from '../../shared/types' import { areWorktreePathsEqual } from '../ipc/worktree-logic' import Database from '../sqlite/sync-database' @@ -121,6 +121,18 @@ export async function listOpenCodeDatabases(): Promise { } } +function compareOpenCodeClaimPriority(left: string, right: string): number { + // Why: the canonical opencode.db is the live database; it must claim + // duplicated sessions ahead of stale sibling copies. Remaining ties use + // path order so ownership is deterministic across rescans. + const leftRank = basename(left).toLowerCase() === 'opencode.db' ? 0 : 1 + const rightRank = basename(right).toLowerCase() === 'opencode.db' ? 0 : 1 + if (leftRank !== rightRank) { + return leftRank - rightRank + } + return left < right ? -1 : left > right ? 1 : 0 +} + export async function getProcessedDatabaseInfo( dbPath: string ): Promise { @@ -831,18 +843,32 @@ function mergeDailyAggregates( export async function parseOpenCodeUsageDatabase( dbPath: string, - worktrees: (OpenCodeUsageWorktreeRef & { canonicalPath: string })[] + worktrees: (OpenCodeUsageWorktreeRef & { canonicalPath: string })[], + options: { claimSession?: (sessionId: string) => boolean } = {} ): Promise { const processedDatabase = await getProcessedDatabaseInfo(dbPath) const db = new Database(dbPath, { readonly: true, fileMustExist: true }) try { db.pragma('query_only = ON') const events: OpenCodeUsageAttributedEvent[] = [] + const claimedBySessionId = new Map() + let hasDeferredClaims = false for (const row of selectUsageRows(db)) { const parsed = parseOpenCodeUsageRow(row) if (!parsed) { continue } + // Why: a stale sibling copy of opencode.db carries the same sessions, so + // each session must be counted from exactly one database (#8006). + let owned = claimedBySessionId.get(parsed.sessionId) + if (owned === undefined) { + owned = options.claimSession ? options.claimSession(parsed.sessionId) : true + claimedBySessionId.set(parsed.sessionId, owned) + } + if (!owned) { + hasDeferredClaims = true + continue + } const attributed = await attributeOpenCodeUsageEvent(parsed, worktrees) if (attributed) { events.push(attributed) @@ -850,7 +876,11 @@ export async function parseOpenCodeUsageDatabase( } return { ...processedDatabase, - ...aggregateOpenCodeUsage(events) + ...aggregateOpenCodeUsage(events), + ownedSessionIds: [...claimedBySessionId.entries()] + .filter(([, owned]) => owned) + .map(([sessionId]) => sessionId), + hasDeferredClaims } } finally { db.close() @@ -869,29 +899,112 @@ export async function scanOpenCodeUsageDatabases( const previousByPath = new Map( previousProcessedDatabases.map((database) => [database.path, database]) ) - const processedDatabases: OpenCodeUsagePersistedDatabase[] = [] const worktreesWithCanonicalPaths = await buildWorktreesWithCanonicalPaths(worktrees) - const sessionsById = new Map() - const dailyByKey = new Map() - for (const [index, dbPath] of dbPaths.entries()) { + const currentPaths = new Set(dbPaths) + // Why: when a database that owned sessions is deleted, remaining siblings + // still contain those sessions but their caches record them as unowned. + // Only databases that previously deferred claims can reclaim. + const lostOwnerPath = previousProcessedDatabases.some( + (database) => + !currentPaths.has(database.path) && + Array.isArray(database.ownedSessionIds) && + database.ownedSessionIds.length > 0 + ) + + const reusedByPath = new Map() + const pathsToParse: string[] = [] + for (const dbPath of dbPaths) { const databaseInfo = await getProcessedDatabaseInfo(dbPath) const previous = previousByPath.get(dbPath) + // When an owner disappears, only deferred-claim databases need reparse. + const mustReclaimDeferred = lostOwnerPath && previous?.hasDeferredClaims !== false const canReuse = - previous && previous.mtimeMs === databaseInfo.mtimeMs && previous.size === databaseInfo.size - const processed = canReuse - ? previous - : await parseOpenCodeUsageDatabase(dbPath, worktreesWithCanonicalPaths) + !mustReclaimDeferred && + previous && + previous.mtimeMs === databaseInfo.mtimeMs && + previous.size === databaseInfo.size && + Array.isArray(previous.ownedSessionIds) && + typeof previous.hasDeferredClaims === 'boolean' + if (canReuse) { + reusedByPath.set(dbPath, previous) + } else { + pathsToParse.push(dbPath) + } + } - processedDatabases.push(processed) - mergeSessions(sessionsById, processed.sessions) - mergeDailyAggregates(dailyByKey, processed.dailyAggregates) + // Why: a sticky backup claim from a scan where opencode.db was missing would + // otherwise freeze a still-growing session at the backup snapshot when the + // live db reappears. Reparse a lower-priority sibling only when it still owns + // sessions a higher-priority path could reclaim; a sibling that owns nothing + // (the common case once the live db has claimed every shared session) has no + // claim to give back, so reparsing it every time the live db changes is pure + // work. + const demotedReusePaths: string[] = [] + for (const [dbPath, reused] of reusedByPath) { + if ((reused.ownedSessionIds?.length ?? 0) === 0) { + continue + } + const higherPriorityParsing = pathsToParse.some( + (candidate) => compareOpenCodeClaimPriority(candidate, dbPath) < 0 + ) + if (higherPriorityParsing) { + demotedReusePaths.push(dbPath) + } + } + for (const dbPath of demotedReusePaths) { + reusedByPath.delete(dbPath) + pathsToParse.push(dbPath) + } + + // Why: `opencode-*.db` siblings are typically stale copies of `opencode.db` + // (backups), so mergeSessions would double every duplicated session (#8006). + // Each session is counted from exactly one database. The canonical live db + // claims first so a stale backup cannot freeze a still-growing session at + // its snapshot totals; cached databases keep the claims they persisted. + const sessionOwnerById = new Map() + for (const dbPath of [...reusedByPath.keys()].sort(compareOpenCodeClaimPriority)) { + const previous = reusedByPath.get(dbPath) + for (const sessionId of previous?.ownedSessionIds ?? []) { + if (!sessionOwnerById.has(sessionId)) { + sessionOwnerById.set(sessionId, dbPath) + } + } + } + + const parsedByPath = new Map() + const orderedPathsToParse = [...pathsToParse].sort(compareOpenCodeClaimPriority) + for (const [index, dbPath] of orderedPathsToParse.entries()) { + const processed = await parseOpenCodeUsageDatabase(dbPath, worktreesWithCanonicalPaths, { + claimSession: (sessionId) => { + const owner = sessionOwnerById.get(sessionId) + if (owner !== undefined && owner !== dbPath) { + return false + } + sessionOwnerById.set(sessionId, dbPath) + return true + } + }) + parsedByPath.set(dbPath, processed) if ((index + 1) % YIELD_EVERY_DATABASES === 0) { await yieldToEventLoop() } } + const processedDatabases: OpenCodeUsagePersistedDatabase[] = [] + const sessionsById = new Map() + const dailyByKey = new Map() + for (const dbPath of dbPaths) { + const processed = reusedByPath.get(dbPath) ?? parsedByPath.get(dbPath) + if (!processed) { + continue + } + processedDatabases.push(processed) + mergeSessions(sessionsById, processed.sessions) + mergeDailyAggregates(dailyByKey, processed.dailyAggregates) + } + return { processedDatabases, sessions: finalizeSessions(sessionsById), diff --git a/src/main/opencode-usage/store.test.ts b/src/main/opencode-usage/store.test.ts index bca001390c29..aea35628f602 100644 --- a/src/main/opencode-usage/store.test.ts +++ b/src/main/opencode-usage/store.test.ts @@ -19,7 +19,7 @@ import { OpenCodeUsageStore, normalizePersistedState } from './store' function getDefaultState(): OpenCodeUsagePersistedState { return { - schemaVersion: 1, + schemaVersion: 2, worktreeFingerprint: null, processedDatabases: [], sessions: [], @@ -283,7 +283,9 @@ describe('OpenCodeUsageStore', () => { mtimeMs: 1, size: 2, sessions: [makeSession()], - dailyAggregates: [makeDaily()] + dailyAggregates: [makeDaily()], + ownedSessionIds: ['session-1'], + hasDeferredClaims: false } ], sessions: [makeSession()], @@ -300,7 +302,9 @@ describe('OpenCodeUsageStore', () => { mtimeMs: 1, size: 2, sessions: [], - dailyAggregates: [] + dailyAggregates: [], + ownedSessionIds: [], + hasDeferredClaims: false } ] }).processedDatabases diff --git a/src/main/opencode-usage/store.ts b/src/main/opencode-usage/store.ts index abfe2ca740ad..b926f32651c6 100644 --- a/src/main/opencode-usage/store.ts +++ b/src/main/opencode-usage/store.ts @@ -18,7 +18,9 @@ import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-w import type { OpenCodeUsageDailyAggregate, OpenCodeUsagePersistedState } from './types' import { createWorktreeRefs, scanOpenCodeUsageDatabases } from './scanner' -const SCHEMA_VERSION = 1 +// Why: v2 adds per-database session ownership (stale sibling-copy dedupe). +// Older caches were built without it and can carry doubled sessions (#8006). +const SCHEMA_VERSION = 2 const STALE_MS = 5 * 60_000 let _openCodeUsageFile: string | null = null diff --git a/src/main/opencode-usage/types.ts b/src/main/opencode-usage/types.ts index ed7f3d2143c9..cf8d2c6a8d07 100644 --- a/src/main/opencode-usage/types.ts +++ b/src/main/opencode-usage/types.ts @@ -86,6 +86,13 @@ export type OpenCodeUsageDailyAggregate = { export type OpenCodeUsagePersistedDatabase = OpenCodeUsageProcessedDatabase & { sessions: OpenCodeUsageSession[] dailyAggregates: OpenCodeUsageDailyAggregate[] + /** Session ids this database counted. Sibling copies (opencode-backup.db) + * duplicate sessions; ownership keeps each session counted by exactly one + * cached database across incremental scans. */ + ownedSessionIds: string[] + /** True when this database saw sessions already claimed by another database. + * When that owner disappears, only deferred databases need reparse. */ + hasDeferredClaims: boolean } export type OpenCodeUsagePersistedState = { diff --git a/src/main/orca-profiles/profile-cloud-auth-config.test.ts b/src/main/orca-profiles/profile-cloud-auth-config.test.ts new file mode 100644 index 000000000000..d18ff159fd58 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-auth-config.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it, vi } from 'vitest' +import { + allowsPlaintextOrcaCloudSession, + getOrcaCloudAuthConfig, + isOrcaCloudDevAuthEnabled +} from './profile-cloud-auth-config' + +vi.mock('electron', () => ({ + app: { + isPackaged: false + } +})) + +describe('Orca cloud auth config', () => { + it('reports unconfigured without both API URL and client ID', () => { + expect(getOrcaCloudAuthConfig({})).toEqual({ + configured: false, + setupMessage: 'Orca Cloud sign-in is not configured for this build.' + }) + }) + + it('builds default desktop auth endpoints from the API URL', () => { + const state = getOrcaCloudAuthConfig({ + ORCA_CLOUD_API_URL: 'https://orca-cloud.example/', + ORCA_CLOUD_CLIENT_ID: 'desktop-client' + }) + + expect(state).toEqual({ + configured: true, + config: { + apiBaseUrl: 'https://orca-cloud.example', + authorizeEndpoint: 'https://orca-cloud.example/v1/desktop/auth/authorize', + sessionEndpoint: 'https://orca-cloud.example/v1/desktop/auth/session', + refreshEndpoint: 'https://orca-cloud.example/v1/desktop/auth/refresh', + capabilitiesEndpoint: 'https://orca-cloud.example/v1/desktop/auth/capabilities', + profileEndpoint: 'https://orca-cloud.example/v1/desktop/auth/profile', + orgEndpoint: 'https://orca-cloud.example/v1/desktop/auth/org', + logoutEndpoint: 'https://orca-cloud.example/v1/desktop/auth/logout', + clientId: 'desktop-client', + scope: 'openid profile email offline_access' + } + }) + }) + + it('allows loopback HTTP endpoints for local desktop auth development', () => { + const state = getOrcaCloudAuthConfig({ + ORCA_CLOUD_API_URL: 'http://localhost:4100', + ORCA_CLOUD_CLIENT_ID: 'desktop-client' + }) + + expect(state.configured).toBe(true) + }) + + it('rejects loopback HTTP endpoints in packaged builds', () => { + expect( + getOrcaCloudAuthConfig( + { + ORCA_CLOUD_API_URL: 'http://localhost:4100', + ORCA_CLOUD_CLIENT_ID: 'desktop-client' + }, + true + ) + ).toMatchObject({ configured: false }) + + const httpsState = getOrcaCloudAuthConfig( + { + ORCA_CLOUD_API_URL: 'https://orca-cloud.example', + ORCA_CLOUD_CLIENT_ID: 'desktop-client' + }, + true + ) + expect(httpsState.configured).toBe(true) + }) + + it('rejects non-HTTPS non-loopback API URLs', () => { + expect( + getOrcaCloudAuthConfig({ + ORCA_CLOUD_API_URL: 'http://orca-cloud.example', + ORCA_CLOUD_CLIENT_ID: 'desktop-client' + }) + ).toMatchObject({ configured: false }) + }) + + it('allows dev plaintext sessions only outside production', () => { + expect( + allowsPlaintextOrcaCloudSession({ + ORCA_CLOUD_ALLOW_PLAINTEXT_SESSION: '1', + NODE_ENV: 'development' + }) + ).toBe(true) + expect( + allowsPlaintextOrcaCloudSession({ + ORCA_CLOUD_ALLOW_PLAINTEXT_SESSION: '1', + NODE_ENV: 'production' + }) + ).toBe(false) + }) + + it('ignores dev flags in packaged builds even without NODE_ENV', () => { + // Why: packaged main bundles never define NODE_ENV, so packaged-ness must + // gate the escape hatches on its own. + expect(allowsPlaintextOrcaCloudSession({ ORCA_CLOUD_ALLOW_PLAINTEXT_SESSION: '1' }, true)).toBe( + false + ) + expect(isOrcaCloudDevAuthEnabled({ ORCA_CLOUD_DEV_AUTH: '1' }, true)).toBe(false) + }) + + it('allows local dev auth only outside production', () => { + expect( + isOrcaCloudDevAuthEnabled({ + ORCA_CLOUD_DEV_AUTH: '1', + NODE_ENV: 'development' + }) + ).toBe(true) + expect( + isOrcaCloudDevAuthEnabled({ + ORCA_CLOUD_DEV_AUTH: '1', + NODE_ENV: 'production' + }) + ).toBe(false) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-auth-config.ts b/src/main/orca-profiles/profile-cloud-auth-config.ts new file mode 100644 index 000000000000..15f9c2e6d242 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-auth-config.ts @@ -0,0 +1,115 @@ +import { app } from 'electron' + +export type OrcaCloudAuthConfig = { + apiBaseUrl: string + authorizeEndpoint: string + sessionEndpoint: string + refreshEndpoint: string + capabilitiesEndpoint: string + profileEndpoint: string + orgEndpoint: string + logoutEndpoint: string + clientId: string + scope: string +} + +const DEFAULT_SCOPE = 'openid profile email offline_access' + +// Why: packaged main bundles never define NODE_ENV, so packaged-ness is the +// only reliable production signal for gating dev-only auth escape hatches. +function isPackagedOrcaBuild(): boolean { + try { + return app?.isPackaged === true + } catch { + return false + } +} + +function cleanUrl(value: string | undefined, allowLoopbackHttp: boolean): string | null { + const trimmed = value?.trim() + if (!trimmed) { + return null + } + try { + const parsed = new URL(trimmed) + const loopbackHost = + parsed.hostname === '127.0.0.1' || + parsed.hostname === 'localhost' || + parsed.hostname === '[::1]' + if (parsed.protocol !== 'https:' && !(loopbackHost && allowLoopbackHttp)) { + return null + } + return parsed.toString().replace(/\/$/, '') + } catch { + return null + } +} + +function endpoint(baseUrl: string, path: string): string { + return new URL(path, `${baseUrl}/`).toString() +} + +export function getOrcaCloudAuthConfig( + env: NodeJS.ProcessEnv = process.env, + packaged: boolean = isPackagedOrcaBuild() +): { configured: true; config: OrcaCloudAuthConfig } | { configured: false; setupMessage: string } { + // Why: loopback HTTP endpoints are a local-development convenience only; + // packaged builds must not accept plain-HTTP token endpoints via env vars. + const allowLoopbackHttp = !packaged + const cleanEndpointUrl = (value: string | undefined): string | null => + cleanUrl(value, allowLoopbackHttp) + const apiBaseUrl = cleanEndpointUrl(env.ORCA_CLOUD_API_URL) + const clientId = env.ORCA_CLOUD_CLIENT_ID?.trim() + if (!apiBaseUrl || !clientId) { + return { + configured: false, + setupMessage: 'Orca Cloud sign-in is not configured for this build.' + } + } + + const authBaseUrl = cleanEndpointUrl(env.ORCA_CLOUD_AUTH_URL) ?? apiBaseUrl + return { + configured: true, + config: { + apiBaseUrl, + authorizeEndpoint: + cleanEndpointUrl(env.ORCA_CLOUD_AUTHORIZE_URL) ?? + endpoint(authBaseUrl, '/v1/desktop/auth/authorize'), + sessionEndpoint: + cleanEndpointUrl(env.ORCA_CLOUD_SESSION_URL) ?? + endpoint(apiBaseUrl, '/v1/desktop/auth/session'), + refreshEndpoint: + cleanEndpointUrl(env.ORCA_CLOUD_REFRESH_URL) ?? + endpoint(apiBaseUrl, '/v1/desktop/auth/refresh'), + capabilitiesEndpoint: + cleanEndpointUrl(env.ORCA_CLOUD_CAPABILITIES_URL) ?? + endpoint(apiBaseUrl, '/v1/desktop/auth/capabilities'), + profileEndpoint: + cleanEndpointUrl(env.ORCA_CLOUD_PROFILE_URL) ?? + endpoint(apiBaseUrl, '/v1/desktop/auth/profile'), + orgEndpoint: + cleanEndpointUrl(env.ORCA_CLOUD_ORG_URL) ?? endpoint(apiBaseUrl, '/v1/desktop/auth/org'), + logoutEndpoint: + cleanEndpointUrl(env.ORCA_CLOUD_LOGOUT_URL) ?? + endpoint(apiBaseUrl, '/v1/desktop/auth/logout'), + clientId, + scope: env.ORCA_CLOUD_AUTH_SCOPE?.trim() || DEFAULT_SCOPE + } + } +} + +export function allowsPlaintextOrcaCloudSession( + env: NodeJS.ProcessEnv = process.env, + packaged: boolean = isPackagedOrcaBuild() +): boolean { + return ( + env.ORCA_CLOUD_ALLOW_PLAINTEXT_SESSION === '1' && env.NODE_ENV !== 'production' && !packaged + ) +} + +export function isOrcaCloudDevAuthEnabled( + env: NodeJS.ProcessEnv = process.env, + packaged: boolean = isPackagedOrcaBuild() +): boolean { + return env.ORCA_CLOUD_DEV_AUTH === '1' && env.NODE_ENV !== 'production' && !packaged +} diff --git a/src/main/orca-profiles/profile-cloud-auth-status.ts b/src/main/orca-profiles/profile-cloud-auth-status.ts new file mode 100644 index 000000000000..400498d223e6 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-auth-status.ts @@ -0,0 +1,56 @@ +import type { OrcaProfileAuthStatus } from '../../shared/orca-profiles' +import type { ActiveOrcaProfileState } from './profile-index-store' +import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from './profile-cloud-auth-config' +import { readOrcaCloudSession } from './profile-cloud-session-store' + +export function getOrcaProfileAuthStatusFromProfile( + active: ActiveOrcaProfileState, + userDataPath: string +): OrcaProfileAuthStatus { + const configState = getOrcaCloudAuthConfig() + const devAuthEnabled = isOrcaCloudDevAuthEnabled() + const configured = configState.configured || devAuthEnabled + const cloud = active.profile.cloud + if (!cloud) { + return { + activeProfileId: active.profile.id, + configured, + state: configured ? 'local' : 'unconfigured', + persistence: 'none', + setupMessage: configured ? undefined : configState.setupMessage + } + } + + const session = readOrcaCloudSession(active.profile.id, userDataPath) + if (!configured) { + return { + activeProfileId: active.profile.id, + configured: false, + state: 'unconfigured', + persistence: session.status === 'found' ? session.persistence : 'none', + cloud, + credentialError: session.status === 'decrypt-failed' ? session.error : undefined, + setupMessage: configState.setupMessage + } + } + if (session.status === 'found') { + return { + activeProfileId: active.profile.id, + configured, + state: 'connected', + persistence: session.persistence, + cloud, + organizations: session.session.organizations, + capabilities: session.session.capabilities + } + } + + return { + activeProfileId: active.profile.id, + configured, + state: 'reconnect-required', + persistence: 'none', + cloud, + credentialError: session.status === 'decrypt-failed' ? session.error : undefined + } +} diff --git a/src/main/orca-profiles/profile-cloud-client.test.ts b/src/main/orca-profiles/profile-cloud-client.test.ts new file mode 100644 index 000000000000..f24ba0bb5bf3 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-client.test.ts @@ -0,0 +1,249 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' +import type { OrcaCloudSession } from './profile-cloud-session-store' +import { + createOrcaCloudProfile, + exchangeOrcaCloudAuthCode, + refreshOrcaCloudCapabilities, + refreshOrcaCloudSession, + selectOrcaCloudOrg +} from './profile-cloud-client' + +const fetchMock = vi.fn() + +const config: OrcaCloudAuthConfig = { + apiBaseUrl: 'https://orca-cloud.example', + authorizeEndpoint: 'https://orca-cloud.example/v1/desktop/auth/authorize', + sessionEndpoint: 'https://orca-cloud.example/v1/desktop/auth/session', + refreshEndpoint: 'https://orca-cloud.example/v1/desktop/auth/refresh', + capabilitiesEndpoint: 'https://orca-cloud.example/v1/desktop/auth/capabilities', + profileEndpoint: 'https://orca-cloud.example/v1/desktop/auth/profile', + orgEndpoint: 'https://orca-cloud.example/v1/desktop/auth/org', + logoutEndpoint: 'https://orca-cloud.example/v1/desktop/auth/logout', + clientId: 'desktop-client', + scope: 'openid profile email offline_access' +} + +const session: OrcaCloudSession = { + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: 999, + capabilities: { flags: { share: true }, refreshedAt: 1 } +} + +function mockFetchJson(value: unknown): void { + fetchMock.mockResolvedValue({ + ok: true, + json: async () => value + }) +} + +describe('Orca cloud client', () => { + beforeEach(() => { + fetchMock.mockReset() + vi.stubGlobal('fetch', fetchMock) + }) + + it('normalizes session exchange organizations', async () => { + mockFetchJson({ + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: 999, + cloud: { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com' + }, + organizations: [ + { orgId: 'org-1', name: 'Acme', role: 'Admin' }, + { orgId: '', name: 'Ignored' } + ], + capabilities: { + flags: { share: true }, + refreshedAt: 123 + } + }) + + await expect( + exchangeOrcaCloudAuthCode(config, { + code: 'code', + codeVerifier: 'verifier', + nonce: 'nonce', + redirectUri: 'http://127.0.0.1:4100/auth/callback', + state: 'state', + localProfileId: 'local-default' + }) + ).resolves.toMatchObject({ + organizations: [{ orgId: 'org-1', name: 'Acme', role: 'Admin' }] + }) + expect(fetchMock).toHaveBeenCalledWith( + config.sessionEndpoint, + expect.objectContaining({ + body: JSON.stringify({ + code: 'code', + codeVerifier: 'verifier', + nonce: 'nonce', + redirectUri: 'http://127.0.0.1:4100/auth/callback', + state: 'state', + localProfileId: 'local-default' + }) + }) + ) + }) + + it('normalizes organization selection response metadata', async () => { + mockFetchJson({ + cloud: { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com', + activeOrgId: 'org-2', + activeOrgName: 'Personal' + }, + organizations: [ + { orgId: 'org-1', name: 'Acme' }, + { orgId: 'org-2', name: 'Personal' } + ], + capabilities: { + flags: { share: false, sso: true }, + refreshedAt: 456 + } + }) + + await expect(selectOrcaCloudOrg(config, session, 'org-2')).resolves.toEqual({ + cloud: expect.objectContaining({ activeOrgId: 'org-2', activeOrgName: 'Personal' }), + organizations: [ + { orgId: 'org-1', name: 'Acme', role: undefined }, + { orgId: 'org-2', name: 'Personal', role: undefined } + ], + capabilities: { flags: { share: false, sso: true }, refreshedAt: 456 } + }) + expect(fetchMock).toHaveBeenCalledWith( + config.orgEndpoint, + expect.objectContaining({ + headers: expect.objectContaining({ authorization: 'Bearer access-token' }) + }) + ) + }) + + it('creates cloud profiles with a profile-scoped session response', async () => { + mockFetchJson({ + accessToken: 'new-access-token', + refreshToken: 'new-refresh-token', + expiresAt: 1000, + cloud: { + cloudProfileId: 'cloud-profile-2', + userId: 'user-1', + email: 'nina@example.com', + activeOrgId: 'org-1', + activeOrgName: 'Acme' + }, + organizations: [{ orgId: 'org-1', name: 'Acme' }], + capabilities: { + flags: { share: true }, + refreshedAt: 789 + } + }) + + await expect( + createOrcaCloudProfile(config, session, { orgId: 'org-1', name: 'Acme' }) + ).resolves.toMatchObject({ + accessToken: 'new-access-token', + refreshToken: 'new-refresh-token', + cloud: expect.objectContaining({ cloudProfileId: 'cloud-profile-2' }), + organizations: [{ orgId: 'org-1', name: 'Acme', role: undefined }] + }) + expect(fetchMock).toHaveBeenCalledWith( + config.profileEndpoint, + expect.objectContaining({ + body: JSON.stringify({ orgId: 'org-1', name: 'Acme' }) + }) + ) + }) + + it('refreshes session material without exposing refresh tokens in URLs', async () => { + mockFetchJson({ + accessToken: 'rotated-access-token', + refreshToken: 'rotated-refresh-token', + expiresAt: 2000, + cloud: { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com' + }, + capabilities: { + flags: { share: true }, + refreshedAt: 999 + } + }) + + await expect(refreshOrcaCloudSession(config, session)).resolves.toMatchObject({ + accessToken: 'rotated-access-token', + refreshToken: 'rotated-refresh-token' + }) + expect(fetchMock).toHaveBeenCalledWith( + config.refreshEndpoint, + expect.objectContaining({ + body: JSON.stringify({ refreshToken: 'refresh-token' }) + }) + ) + }) + + it('refreshes capability flags and optional org metadata with the current access token', async () => { + mockFetchJson({ + cloud: { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com' + }, + organizations: [], + capabilities: { + flags: { share: false, team: true }, + refreshedAt: 1001 + } + }) + + await expect(refreshOrcaCloudCapabilities(config, session)).resolves.toEqual({ + cloud: expect.objectContaining({ cloudProfileId: 'cloud-profile-1' }), + organizations: [], + capabilities: { + flags: { share: false, team: true }, + refreshedAt: 1001 + } + }) + expect(fetchMock).toHaveBeenCalledWith( + config.capabilitiesEndpoint, + expect.objectContaining({ + headers: expect.objectContaining({ authorization: 'Bearer access-token' }) + }) + ) + }) + + it('trims cloud metadata and drops blank active org fields', async () => { + mockFetchJson({ + cloud: { + cloudProfileId: ' cloud-profile-1 ', + userId: ' user-1 ', + email: ' nina@example.com ', + displayName: ' Nina ', + activeOrgId: ' ', + activeOrgName: '' + }, + capabilities: { + flags: {}, + refreshedAt: 1002 + } + }) + + await expect(refreshOrcaCloudCapabilities(config, session)).resolves.toMatchObject({ + cloud: { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com', + displayName: 'Nina', + activeOrgId: undefined, + activeOrgName: undefined + } + }) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-client.ts b/src/main/orca-profiles/profile-cloud-client.ts new file mode 100644 index 000000000000..81d88f72e226 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-client.ts @@ -0,0 +1,263 @@ +import type { + OrcaCloudCapabilities, + OrcaCloudOrgSummary, + OrcaProfileCloudSummary +} from '../../shared/orca-profiles' +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' +import type { OrcaCloudSession } from './profile-cloud-session-store' +import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' + +type ExchangeCodeArgs = { + code: string + codeVerifier: string + nonce: string + redirectUri: string + state: string + localProfileId: string +} + +type CreateCloudProfileArgs = { + orgId?: string + name?: string +} + +type SelectOrgResponse = { + cloud: OrcaProfileCloudSummary + organizations?: OrcaCloudOrgSummary[] + capabilities: OrcaCloudCapabilities +} + +type CapabilityRefreshResponse = { + cloud?: OrcaProfileCloudSummary + organizations?: OrcaCloudOrgSummary[] + capabilities: OrcaCloudCapabilities +} + +export class OrcaCloudRequestError extends Error { + // Why: `errorCode` carries the server's JSON `{error}` discriminator (e.g. + // 'already_member', 'cannot_remove_self') so callers can distinguish the + // precise 4xx cause without re-reading the response body. + constructor( + public readonly statusCode: number, + public readonly errorCode?: string + ) { + super(`orca_cloud_request_failed_${statusCode}`) + this.name = 'OrcaCloudRequestError' + } +} + +function assertString(value: unknown, field: string): string { + if (typeof value !== 'string') { + throw new Error(`invalid_orca_cloud_${field}`) + } + const trimmed = value.trim() + if (!trimmed) { + throw new Error(`invalid_orca_cloud_${field}`) + } + return trimmed +} + +function optionalString(value: unknown): string | undefined { + if (typeof value !== 'string') { + return undefined + } + const trimmed = value.trim() + return trimmed || undefined +} + +function assertNumber(value: unknown, field: string): number { + if (typeof value !== 'number' || !Number.isFinite(value)) { + throw new Error(`invalid_orca_cloud_${field}`) + } + return value +} + +function normalizeCapabilities(value: unknown): OrcaCloudCapabilities { + if (!value || typeof value !== 'object') { + return { flags: {}, refreshedAt: Date.now() } + } + const record = value as Record + const rawFlags = record.flags + const flags: Record = {} + if (rawFlags && typeof rawFlags === 'object' && !Array.isArray(rawFlags)) { + for (const [key, flag] of Object.entries(rawFlags)) { + if (typeof flag === 'boolean') { + flags[key] = flag + } + } + } + return { + flags, + refreshedAt: + typeof record.refreshedAt === 'number' && Number.isFinite(record.refreshedAt) + ? record.refreshedAt + : Date.now() + } +} + +function normalizeOrganizations(value: unknown): OrcaCloudOrgSummary[] | undefined { + if (!Array.isArray(value)) { + return undefined + } + const organizations: OrcaCloudOrgSummary[] = [] + for (const item of value) { + if (!item || typeof item !== 'object') { + continue + } + const record = item as Record + if (typeof record.orgId !== 'string' || typeof record.name !== 'string') { + continue + } + const orgId = record.orgId.trim() + const name = record.name.trim() + if (!orgId || !name) { + continue + } + organizations.push({ + orgId, + name, + role: typeof record.role === 'string' && record.role.trim() ? record.role.trim() : undefined + }) + } + return organizations +} + +function normalizeCloudSummary(value: unknown): OrcaProfileCloudSummary { + if (!value || typeof value !== 'object') { + throw new Error('invalid_orca_cloud_profile') + } + const record = value as Record + return { + cloudProfileId: assertString(record.cloudProfileId, 'profile_id'), + userId: assertString(record.userId, 'user_id'), + email: assertString(record.email, 'email'), + displayName: optionalString(record.displayName), + activeOrgId: optionalString(record.activeOrgId), + activeOrgName: optionalString(record.activeOrgName), + linkedAt: + typeof record.linkedAt === 'number' && Number.isFinite(record.linkedAt) + ? record.linkedAt + : Date.now() + } +} + +function normalizeSessionResponse(value: unknown): OrcaCloudSessionExchangeResponse { + if (!value || typeof value !== 'object') { + throw new Error('invalid_orca_cloud_session') + } + const record = value as Record + return { + accessToken: assertString(record.accessToken, 'access_token'), + refreshToken: assertString(record.refreshToken, 'refresh_token'), + expiresAt: assertNumber(record.expiresAt, 'expires_at'), + cloud: normalizeCloudSummary(record.cloud), + organizations: normalizeOrganizations(record.organizations), + capabilities: normalizeCapabilities(record.capabilities) + } +} + +const CLOUD_REQUEST_TIMEOUT_MS = 30_000 + +async function postJson(url: string, body: unknown, accessToken?: string): Promise { + const response = await fetch(url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + ...(accessToken ? { authorization: `Bearer ${accessToken}` } : {}) + }, + body: JSON.stringify(body), + // Why: these are fixed first-party token endpoints; following a redirect + // would re-send refresh tokens/code verifiers to another origin, and a + // stalled server must not hang the renderer's awaited IPC call forever. + redirect: 'error', + signal: AbortSignal.timeout(CLOUD_REQUEST_TIMEOUT_MS) + }) + if (!response.ok) { + throw new OrcaCloudRequestError(response.status) + } + return (await response.json()) as T +} + +export async function exchangeOrcaCloudAuthCode( + config: OrcaCloudAuthConfig, + args: ExchangeCodeArgs +): Promise { + return normalizeSessionResponse( + await postJson(config.sessionEndpoint, { + code: args.code, + codeVerifier: args.codeVerifier, + nonce: args.nonce, + redirectUri: args.redirectUri, + state: args.state, + localProfileId: args.localProfileId + }) + ) +} + +export async function refreshOrcaCloudCapabilities( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession +): Promise { + const response = await postJson<{ + cloud?: unknown + organizations?: unknown + capabilities: unknown + }>(config.capabilitiesEndpoint, {}, session.accessToken) + return { + cloud: response.cloud === undefined ? undefined : normalizeCloudSummary(response.cloud), + organizations: normalizeOrganizations(response.organizations), + capabilities: normalizeCapabilities(response.capabilities) + } +} + +export async function refreshOrcaCloudSession( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession +): Promise { + return normalizeSessionResponse( + await postJson(config.refreshEndpoint, { + refreshToken: session.refreshToken + }) + ) +} + +export async function createOrcaCloudProfile( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession, + args: CreateCloudProfileArgs +): Promise { + return normalizeSessionResponse( + await postJson( + config.profileEndpoint, + { + orgId: args.orgId, + name: args.name + }, + session.accessToken + ) + ) +} + +export async function selectOrcaCloudOrg( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession, + orgId: string +): Promise { + const response = await postJson<{ + cloud: unknown + organizations?: unknown + capabilities: unknown + }>(config.orgEndpoint, { orgId }, session.accessToken) + return { + cloud: normalizeCloudSummary(response.cloud), + organizations: normalizeOrganizations(response.organizations), + capabilities: normalizeCapabilities(response.capabilities) + } +} + +export async function revokeOrcaCloudSession( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession +): Promise { + await postJson(config.logoutEndpoint, { refreshToken: session.refreshToken }, session.accessToken) +} diff --git a/src/main/orca-profiles/profile-cloud-dev-auth.ts b/src/main/orca-profiles/profile-cloud-dev-auth.ts new file mode 100644 index 000000000000..137696e17ce9 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-dev-auth.ts @@ -0,0 +1,67 @@ +import { randomUUID } from 'node:crypto' +import type { OrcaCloudCapabilities, OrcaCloudOrgSummary } from '../../shared/orca-profiles' +import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' + +const DEV_SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000 + +function cleanEnvString(value: string | undefined, fallback: string): string { + const trimmed = value?.trim() + return trimmed || fallback +} + +function defaultDevOrganizations(): OrcaCloudOrgSummary[] { + return [ + { orgId: 'dev-personal', name: 'Personal', role: 'Owner' }, + { orgId: 'dev-acme', name: 'Acme Dev', role: 'Admin' } + ] +} + +function devCapabilities(): OrcaCloudCapabilities { + return { + flags: { + share: true, + team: true, + 'share.create': true, + 'share.manage': true, + 'relay.use': true, + 'team.member': true, + 'enterprise.sso': true + }, + refreshedAt: Date.now() + } +} + +function devToken(prefix: string): string { + return `${prefix}-${randomUUID()}` +} + +export function createDevOrcaCloudSession( + args: { + localProfileId?: string + cloudProfileId?: string + orgId?: string + } = {} +): OrcaCloudSessionExchangeResponse { + const organizations = defaultDevOrganizations() + const selectedOrg = organizations.find((organization) => organization.orgId === args.orgId) + const cloudProfileId = + args.cloudProfileId ?? + (args.localProfileId ? `dev-cloud-${args.localProfileId}` : `dev-cloud-${randomUUID()}`) + + return { + accessToken: devToken('dev-access'), + refreshToken: devToken('dev-refresh'), + expiresAt: Date.now() + DEV_SESSION_TTL_MS, + cloud: { + cloudProfileId, + userId: cleanEnvString(process.env.ORCA_CLOUD_DEV_USER_ID, 'dev-user'), + email: cleanEnvString(process.env.ORCA_CLOUD_DEV_EMAIL, 'dev@orca.local'), + displayName: cleanEnvString(process.env.ORCA_CLOUD_DEV_DISPLAY_NAME, 'Orca Dev'), + activeOrgId: selectedOrg?.orgId, + activeOrgName: selectedOrg?.name, + linkedAt: Date.now() + }, + organizations, + capabilities: devCapabilities() + } +} diff --git a/src/main/orca-profiles/profile-cloud-dev-org-members.ts b/src/main/orca-profiles/profile-cloud-dev-org-members.ts new file mode 100644 index 000000000000..4f61e03df6a0 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-dev-org-members.ts @@ -0,0 +1,130 @@ +import type { + OrcaOrgMember, + OrcaOrgMembersRoster, + OrcaOrgPendingInvite, + OrcaProfileOrgMemberChangeRoleArgs, + OrcaProfileOrgMemberInviteArgs, + OrcaProfileOrgMemberMutationResult, + OrcaProfileOrgMemberRemoveArgs, + OrcaProfileOrgInviteRevokeArgs +} from '../../shared/orca-profiles' + +// Why: dev-auth mode has no server, so the whole teammate UI is exercised +// against this in-memory per-org roster. It mirrors the shape the real client +// returns (self as owner, one signed-in teammate, one never-signed-in teammate, +// one pending invite) and the mutation endpoints' status semantics. +type DevOrgRoster = { + members: OrcaOrgMember[] + pendingInvites: OrcaOrgPendingInvite[] +} + +const devRostersByOrg = new Map() + +function cleanEnvString(value: string | undefined, fallback: string): string { + const trimmed = value?.trim() + return trimmed || fallback +} + +function devSelf(): OrcaOrgMember { + return { + userId: cleanEnvString(process.env.ORCA_CLOUD_DEV_USER_ID, 'dev-user'), + email: cleanEnvString(process.env.ORCA_CLOUD_DEV_EMAIL, 'dev@orca.local'), + displayName: cleanEnvString(process.env.ORCA_CLOUD_DEV_DISPLAY_NAME, 'Orca Dev'), + role: 'owner' + } +} + +function seedDevRoster(): DevOrgRoster { + return { + members: [ + devSelf(), + { + userId: 'dev-teammate-1', + email: 'teammate@orca.local', + displayName: 'Dev Teammate', + role: 'admin' + }, + // Why: userId null exercises the "hasn't signed in to Orca yet" disabled row. + { userId: null, email: 'invited-member@orca.local', displayName: undefined, role: 'member' } + ], + pendingInvites: [{ email: 'pending@orca.local', role: 'member', createdAt: Date.now() }] + } +} + +function getDevRoster(orgId: string): DevOrgRoster { + const existing = devRostersByOrg.get(orgId) + if (existing) { + return existing + } + const seeded = seedDevRoster() + devRostersByOrg.set(orgId, seeded) + return seeded +} + +export function listDevOrcaCloudOrgMembers(orgId: string): OrcaOrgMembersRoster { + const roster = getDevRoster(orgId) + return { + members: roster.members.map((member) => ({ ...member })), + pendingInvites: roster.pendingInvites.map((invite) => ({ ...invite })), + viewerRole: 'owner', + canManageMembers: true + } +} + +export function inviteDevOrcaCloudOrgMember( + args: OrcaProfileOrgMemberInviteArgs +): OrcaProfileOrgMemberMutationResult { + const roster = getDevRoster(args.orgId) + const email = args.email.toLowerCase() + if (roster.members.some((member) => member.email.toLowerCase() === email)) { + return { status: 'conflict', reason: 'already_member' } + } + if (roster.pendingInvites.some((invite) => invite.email.toLowerCase() === email)) { + return { status: 'conflict', reason: 'already_invited' } + } + roster.pendingInvites.push({ email: args.email, role: args.role, createdAt: Date.now() }) + return { status: 'ok' } +} + +export function revokeDevOrcaCloudOrgInvite( + args: OrcaProfileOrgInviteRevokeArgs +): OrcaProfileOrgMemberMutationResult { + const roster = getDevRoster(args.orgId) + const email = args.email.toLowerCase() + const index = roster.pendingInvites.findIndex((invite) => invite.email.toLowerCase() === email) + if (index === -1) { + return { status: 'not-found' } + } + roster.pendingInvites.splice(index, 1) + return { status: 'ok' } +} + +export function changeDevOrcaCloudOrgMemberRole( + args: OrcaProfileOrgMemberChangeRoleArgs +): OrcaProfileOrgMemberMutationResult { + const roster = getDevRoster(args.orgId) + if (args.userId === devSelf().userId) { + return { status: 'invalid', reason: 'cannot_change_own_role' } + } + const member = roster.members.find((candidate) => candidate.userId === args.userId) + if (!member) { + return { status: 'not-found' } + } + member.role = args.role + return { status: 'ok' } +} + +export function removeDevOrcaCloudOrgMember( + args: OrcaProfileOrgMemberRemoveArgs +): OrcaProfileOrgMemberMutationResult { + const roster = getDevRoster(args.orgId) + if (args.userId === devSelf().userId) { + return { status: 'invalid', reason: 'cannot_remove_self' } + } + const index = roster.members.findIndex((candidate) => candidate.userId === args.userId) + if (index === -1) { + return { status: 'not-found' } + } + roster.members.splice(index, 1) + return { status: 'ok' } +} diff --git a/src/main/orca-profiles/profile-cloud-dev-service.test.ts b/src/main/orca-profiles/profile-cloud-dev-service.test.ts new file mode 100644 index 000000000000..8801320d13f2 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-dev-service.test.ts @@ -0,0 +1,142 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +const { + beginOrcaCloudPkceFlowMock, + exchangeOrcaCloudAuthCodeMock, + revokeOrcaCloudSessionMock, + safeStorageMock +} = vi.hoisted(() => ({ + beginOrcaCloudPkceFlowMock: vi.fn(), + exchangeOrcaCloudAuthCodeMock: vi.fn(), + revokeOrcaCloudSessionMock: vi.fn(), + safeStorageMock: { + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + isEncryptionAvailable: vi.fn(() => true) + } +})) + +let userDataPath = '' + +vi.mock('electron', () => ({ + app: { + getPath: () => userDataPath + }, + safeStorage: safeStorageMock +})) + +vi.mock('./profile-cloud-pkce', () => ({ + beginOrcaCloudPkceFlow: beginOrcaCloudPkceFlowMock +})) + +vi.mock('./profile-cloud-client', () => ({ + createOrcaCloudProfile: vi.fn(), + exchangeOrcaCloudAuthCode: exchangeOrcaCloudAuthCodeMock, + refreshOrcaCloudCapabilities: vi.fn(), + refreshOrcaCloudSession: vi.fn(), + revokeOrcaCloudSession: revokeOrcaCloudSessionMock, + selectOrcaCloudOrg: vi.fn() +})) + +import { + connectCurrentOrcaProfile, + createCloudLinkedOrcaProfile, + getCurrentOrcaProfileAuthStatus, + selectCurrentOrcaProfileOrg, + signOutCurrentOrcaProfile +} from './profile-cloud-service' + +describe('Orca cloud dev auth service', () => { + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-cloud-dev-auth-')) + beginOrcaCloudPkceFlowMock.mockReset() + exchangeOrcaCloudAuthCodeMock.mockReset() + revokeOrcaCloudSessionMock.mockReset() + safeStorageMock.decryptString.mockReset() + safeStorageMock.encryptString.mockReset() + safeStorageMock.isEncryptionAvailable.mockReset() + safeStorageMock.decryptString.mockImplementation((value: Buffer) => value.toString('utf-8')) + safeStorageMock.encryptString.mockImplementation((value: string) => Buffer.from(value, 'utf-8')) + safeStorageMock.isEncryptionAvailable.mockReturnValue(true) + vi.unstubAllEnvs() + vi.stubEnv('NODE_ENV', 'development') + vi.stubEnv('ORCA_CLOUD_DEV_AUTH', '1') + vi.stubEnv('ORCA_CLOUD_API_URL', '') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', '') + }) + + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('connects the active profile without PKCE or cloud endpoints', async () => { + expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ + configured: true, + state: 'local' + }) + + const result = await connectCurrentOrcaProfile(userDataPath) + + expect(result.status).toBe('connected') + expect(beginOrcaCloudPkceFlowMock).not.toHaveBeenCalled() + expect(exchangeOrcaCloudAuthCodeMock).not.toHaveBeenCalled() + expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ + configured: true, + state: 'connected', + persistence: 'encrypted', + cloud: { + cloudProfileId: 'dev-cloud-local-default', + email: 'dev@orca.local' + }, + capabilities: { + flags: expect.objectContaining({ 'share.create': true }) + } + }) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).organizations).toHaveLength(2) + }) + + it('selects dev organizations and creates org-scoped cloud profiles locally', async () => { + await connectCurrentOrcaProfile(userDataPath) + + const selected = await selectCurrentOrcaProfileOrg(userDataPath, 'dev-acme') + const created = await createCloudLinkedOrcaProfile(userDataPath, { + orgId: 'dev-acme', + name: 'Acme Dev' + }) + + expect(selected.status).toBe('selected') + expect(getCurrentOrcaProfileAuthStatus(userDataPath).cloud).toMatchObject({ + activeOrgId: 'dev-acme', + activeOrgName: 'Acme Dev' + }) + expect(created.status).toBe('created') + if (created.status === 'created') { + expect(created.profile).toMatchObject({ + name: 'Acme Dev', + kind: 'cloud-linked', + cloud: expect.objectContaining({ + activeOrgId: 'dev-acme', + activeOrgName: 'Acme Dev' + }) + }) + } + }) + + it('signs out locally without calling the cloud logout endpoint', async () => { + await connectCurrentOrcaProfile(userDataPath) + + const result = await signOutCurrentOrcaProfile(userDataPath) + + expect(result.status).toBe('signed-out') + expect(revokeOrcaCloudSessionMock).not.toHaveBeenCalled() + expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ + configured: true, + state: 'local', + persistence: 'none' + }) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-dev-service.ts b/src/main/orca-profiles/profile-cloud-dev-service.ts new file mode 100644 index 000000000000..bb7a6e3599cd --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-dev-service.ts @@ -0,0 +1,92 @@ +import type { + CreateCloudLinkedOrcaProfileArgs, + OrcaProfileListState +} from '../../shared/orca-profiles' +import type { ActiveOrcaProfileState } from './profile-index-store' +import { createCloudLinkedOrcaProfileRecord, linkOrcaProfileToCloud } from './profile-cloud-index' +import { readOrcaCloudSession, saveOrcaCloudSessionExchange } from './profile-cloud-session-store' +import { createDevOrcaCloudSession } from './profile-cloud-dev-auth' + +type DevProfileListResult = OrcaProfileListState + +type DevCreateProfileResult = + | { + status: 'created' + list: ReturnType + } + | { status: 'reconnect-required' } + +type DevMutationResult = + | { + status: 'updated' + list: DevProfileListResult + } + | { status: 'reconnect-required' } + +export function connectDevOrcaCloudProfile( + active: ActiveOrcaProfileState, + userDataPath: string +): DevProfileListResult { + const session = createDevOrcaCloudSession({ localProfileId: active.profile.id }) + saveOrcaCloudSessionExchange(active.profile.id, userDataPath, session) + return linkOrcaProfileToCloud(active.profile.id, session.cloud, userDataPath) +} + +export function createDevCloudLinkedOrcaProfile( + active: ActiveOrcaProfileState, + userDataPath: string, + args: CreateCloudLinkedOrcaProfileArgs +): DevCreateProfileResult { + if (readOrcaCloudSession(active.profile.id, userDataPath).status !== 'found') { + return { status: 'reconnect-required' } + } + const session = createDevOrcaCloudSession({ orgId: args.orgId }) + const list = createCloudLinkedOrcaProfileRecord(session.cloud, { name: args.name }, userDataPath) + saveOrcaCloudSessionExchange(list.profile.id, userDataPath, session) + return { status: 'created', list } +} + +export function refreshDevOrcaCloudProfile( + active: ActiveOrcaProfileState, + userDataPath: string +): DevMutationResult { + if ( + !active.profile.cloud || + readOrcaCloudSession(active.profile.id, userDataPath).status !== 'found' + ) { + return { status: 'reconnect-required' } + } + const session = createDevOrcaCloudSession({ + localProfileId: active.profile.id, + cloudProfileId: active.profile.cloud.cloudProfileId, + orgId: active.profile.cloud.activeOrgId + }) + saveOrcaCloudSessionExchange(active.profile.id, userDataPath, session) + return { + status: 'updated', + list: linkOrcaProfileToCloud(active.profile.id, session.cloud, userDataPath) + } +} + +export function selectDevOrcaCloudOrg( + active: ActiveOrcaProfileState, + userDataPath: string, + orgId: string +): DevMutationResult { + if ( + !active.profile.cloud || + readOrcaCloudSession(active.profile.id, userDataPath).status !== 'found' + ) { + return { status: 'reconnect-required' } + } + const session = createDevOrcaCloudSession({ + localProfileId: active.profile.id, + cloudProfileId: active.profile.cloud.cloudProfileId, + orgId + }) + saveOrcaCloudSessionExchange(active.profile.id, userDataPath, session) + return { + status: 'updated', + list: linkOrcaProfileToCloud(active.profile.id, session.cloud, userDataPath) + } +} diff --git a/src/main/orca-profiles/profile-cloud-index.ts b/src/main/orca-profiles/profile-cloud-index.ts new file mode 100644 index 000000000000..3d6843fcbb2e --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-index.ts @@ -0,0 +1,143 @@ +import { randomUUID } from 'node:crypto' +import { mkdirSync } from 'node:fs' +import type { + OrcaProfileCloudSummary, + OrcaProfileListState, + OrcaProfileSummary +} from '../../shared/orca-profiles' +import { + getOrcaProfileDirectory, + getOrcaProfileIndexPath, + loadOrCreateProfileIndex, + writeProfileIndex +} from './profile-index-store' + +export type CreateCloudLinkedOrcaProfileRecordResult = OrcaProfileListState & { + profile: OrcaProfileSummary +} + +function sanitizeProfileName(value: unknown, fallback: string): string { + const trimmed = typeof value === 'string' ? value.trim() : '' + return (trimmed || fallback).slice(0, 80) +} + +function profileInitial(name: string): string { + return (name.match(/[A-Za-z0-9]/)?.[0] ?? 'C').toUpperCase() +} + +function toCloudLinkedProfile( + profile: OrcaProfileSummary, + cloud: OrcaProfileCloudSummary, + now: number +): OrcaProfileSummary { + return { + ...profile, + kind: 'cloud-linked', + cloud, + updatedAt: now, + lastOpenedAt: now + } +} + +function toLocalProfile(profile: OrcaProfileSummary, now: number): OrcaProfileSummary { + const { cloud: _cloud, ...localProfile } = profile + return { + ...localProfile, + kind: 'local', + updatedAt: now, + lastOpenedAt: now + } +} + +export function createCloudLinkedOrcaProfileRecord( + cloud: OrcaProfileCloudSummary, + args: { name?: string }, + userDataPath: string +): CreateCloudLinkedOrcaProfileRecordResult { + const index = loadOrCreateProfileIndex(userDataPath) + const now = Date.now() + const fallbackName = cloud.activeOrgName ?? cloud.displayName ?? cloud.email + const name = sanitizeProfileName(args.name, fallbackName) + const profile: OrcaProfileSummary = { + id: `cloud-${randomUUID()}`, + name, + avatar: { + kind: 'initials', + initials: profileInitial(name), + color: 'neutral' + }, + kind: 'cloud-linked', + createdAt: now, + updatedAt: now, + lastOpenedAt: now, + cloud + } + const nextIndex = { + ...index, + profiles: [...index.profiles, profile] + } + mkdirSync(getOrcaProfileDirectory(profile.id, userDataPath), { recursive: true }) + writeProfileIndex(getOrcaProfileIndexPath(userDataPath), nextIndex) + return { + activeProfileId: nextIndex.activeProfileId, + profiles: nextIndex.profiles, + profile + } +} + +export function linkOrcaProfileToCloud( + profileId: string, + cloud: OrcaProfileCloudSummary, + userDataPath: string +): OrcaProfileListState { + const index = loadOrCreateProfileIndex(userDataPath) + const now = Date.now() + let found = false + const profiles = index.profiles.map((profile) => { + if (profile.id !== profileId) { + return profile + } + found = true + return toCloudLinkedProfile(profile, cloud, now) + }) + if (!found) { + throw new Error('unknown_orca_profile') + } + const nextIndex = { + ...index, + profiles + } + writeProfileIndex(getOrcaProfileIndexPath(userDataPath), nextIndex) + return { + activeProfileId: nextIndex.activeProfileId, + profiles: nextIndex.profiles + } +} + +export function unlinkOrcaProfileFromCloud( + profileId: string, + userDataPath: string +): OrcaProfileListState { + const index = loadOrCreateProfileIndex(userDataPath) + const now = Date.now() + let found = false + const profiles = index.profiles.map((profile) => { + if (profile.id !== profileId) { + return profile + } + found = true + return toLocalProfile(profile, now) + }) + if (!found) { + throw new Error('unknown_orca_profile') + } + const nextIndex = { + ...index, + profiles + } + writeProfileIndex(getOrcaProfileIndexPath(userDataPath), nextIndex) + return { + activeProfileId: nextIndex.activeProfileId, + profiles: nextIndex.profiles + } +} diff --git a/src/main/orca-profiles/profile-cloud-org-members-client.test.ts b/src/main/orca-profiles/profile-cloud-org-members-client.test.ts new file mode 100644 index 000000000000..bc3792742d23 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-org-members-client.test.ts @@ -0,0 +1,150 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' +import type { OrcaCloudSession } from './profile-cloud-session-store' +import { OrcaCloudRequestError } from './profile-cloud-client' +import { + changeOrcaCloudOrgMemberRole, + inviteOrcaCloudOrgMember, + listOrcaCloudOrgMembers, + removeOrcaCloudOrgMember, + revokeOrcaCloudOrgInvite +} from './profile-cloud-org-members-client' + +const fetchMock = vi.fn() + +const config: OrcaCloudAuthConfig = { + apiBaseUrl: 'https://orca-cloud.example', + authorizeEndpoint: 'https://orca-cloud.example/v1/desktop/auth/authorize', + sessionEndpoint: 'https://orca-cloud.example/v1/desktop/auth/session', + refreshEndpoint: 'https://orca-cloud.example/v1/desktop/auth/refresh', + capabilitiesEndpoint: 'https://orca-cloud.example/v1/desktop/auth/capabilities', + profileEndpoint: 'https://orca-cloud.example/v1/desktop/auth/profile', + orgEndpoint: 'https://orca-cloud.example/v1/desktop/auth/org', + logoutEndpoint: 'https://orca-cloud.example/v1/desktop/auth/logout', + clientId: 'desktop-client', + scope: 'openid profile email offline_access' +} + +const session: OrcaCloudSession = { + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: 999, + capabilities: { flags: {}, refreshedAt: 1 } +} + +function mockJsonResponse(value: unknown, init: { ok?: boolean; status?: number } = {}): void { + fetchMock.mockResolvedValue({ + ok: init.ok ?? true, + status: init.status ?? 200, + json: async () => value + }) +} + +describe('Orca cloud org members client', () => { + beforeEach(() => { + fetchMock.mockReset() + vi.stubGlobal('fetch', fetchMock) + }) + + it('normalizes the roster, dropping malformed rows and defaulting the viewer role', async () => { + mockJsonResponse({ + members: [ + { userId: 'user-1', email: 'nina@example.com', displayName: 'Nina', role: 'admin' }, + { userId: null, email: 'pending-user@example.com', role: 'member' }, + { userId: 'user-3', email: 'weird@example.com', role: 'superadmin' }, + { userId: 'user-4' } + ], + pendingInvites: [{ email: 'invitee@example.com', role: 'member', createdAt: 1712000000000 }], + viewerRole: 'not-a-role', + canManageMembers: true + }) + + await expect(listOrcaCloudOrgMembers(config, session, 'org-1')).resolves.toEqual({ + members: [ + { userId: 'user-1', email: 'nina@example.com', displayName: 'Nina', role: 'admin' }, + { userId: null, email: 'pending-user@example.com', displayName: undefined, role: 'member' }, + { userId: 'user-3', email: 'weird@example.com', displayName: undefined, role: 'member' } + ], + pendingInvites: [{ email: 'invitee@example.com', role: 'member', createdAt: 1712000000000 }], + viewerRole: 'member', + canManageMembers: true + }) + expect(fetchMock).toHaveBeenCalledWith( + 'https://orca-cloud.example/v1/desktop/orgs/org-1/members', + expect.objectContaining({ + method: 'GET', + headers: expect.objectContaining({ authorization: 'Bearer access-token' }) + }) + ) + }) + + it('percent-encodes the org id in the request URL', async () => { + mockJsonResponse({ + members: [], + pendingInvites: [], + viewerRole: 'owner', + canManageMembers: true + }) + await listOrcaCloudOrgMembers(config, session, 'org/with space') + expect(fetchMock).toHaveBeenCalledWith( + 'https://orca-cloud.example/v1/desktop/orgs/org%2Fwith%20space/members', + expect.any(Object) + ) + }) + + it('posts invites with an email and role body', async () => { + mockJsonResponse({ ok: true }) + await inviteOrcaCloudOrgMember(config, session, { + orgId: 'org-1', + email: 'new@example.com', + role: 'admin' + }) + expect(fetchMock).toHaveBeenCalledWith( + 'https://orca-cloud.example/v1/desktop/orgs/org-1/invites', + expect.objectContaining({ + method: 'POST', + body: JSON.stringify({ email: 'new@example.com', role: 'admin' }) + }) + ) + }) + + it('carries the server error code on a 409 conflict', async () => { + mockJsonResponse({ error: 'already_invited' }, { ok: false, status: 409 }) + await expect( + inviteOrcaCloudOrgMember(config, session, { + orgId: 'org-1', + email: 'dupe@example.com', + role: 'member' + }) + ).rejects.toMatchObject({ statusCode: 409, errorCode: 'already_invited' }) + }) + + it('surfaces a 403 as an OrcaCloudRequestError without an error code when the body is empty', async () => { + fetchMock.mockResolvedValue({ + ok: false, + status: 403, + json: async () => { + throw new Error('no body') + } + }) + await expect( + changeOrcaCloudOrgMemberRole(config, session, { + orgId: 'org-1', + userId: 'user-2', + role: 'admin' + }) + ).rejects.toBeInstanceOf(OrcaCloudRequestError) + await expect( + removeOrcaCloudOrgMember(config, session, { orgId: 'org-1', userId: 'user-2' }) + ).rejects.toMatchObject({ statusCode: 403, errorCode: undefined }) + }) + + it('posts invite revocations by email', async () => { + mockJsonResponse({ ok: true }) + await revokeOrcaCloudOrgInvite(config, session, { orgId: 'org-1', email: 'gone@example.com' }) + expect(fetchMock).toHaveBeenCalledWith( + 'https://orca-cloud.example/v1/desktop/orgs/org-1/invites/revoke', + expect.objectContaining({ body: JSON.stringify({ email: 'gone@example.com' }) }) + ) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-org-members-client.ts b/src/main/orca-profiles/profile-cloud-org-members-client.ts new file mode 100644 index 000000000000..cd1b106e4895 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-org-members-client.ts @@ -0,0 +1,209 @@ +import type { + OrcaOrgMember, + OrcaOrgMembersRoster, + OrcaOrgPendingInvite, + OrcaOrgRole +} from '../../shared/orca-profiles' +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' +import type { OrcaCloudSession } from './profile-cloud-session-store' +import { OrcaCloudRequestError } from './profile-cloud-client' + +const CLOUD_REQUEST_TIMEOUT_MS = 30_000 +const ORG_ROLES: readonly OrcaOrgRole[] = ['owner', 'admin', 'member'] + +function isOrgRole(value: unknown): value is OrcaOrgRole { + return typeof value === 'string' && (ORG_ROLES as readonly string[]).includes(value) +} + +function normalizeRole(value: unknown, fallback: OrcaOrgRole): OrcaOrgRole { + return isOrgRole(value) ? value : fallback +} + +function optionalString(value: unknown): string | undefined { + if (typeof value !== 'string') { + return undefined + } + const trimmed = value.trim() + return trimmed || undefined +} + +function normalizeTimestamp(value: unknown): number { + if (typeof value === 'number' && Number.isFinite(value)) { + return value + } + if (typeof value === 'string') { + const parsed = Date.parse(value) + if (Number.isFinite(parsed)) { + return parsed + } + } + return Date.now() +} + +function normalizeMember(value: unknown): OrcaOrgMember | null { + if (!value || typeof value !== 'object') { + return null + } + const record = value as Record + const email = optionalString(record.email) + if (!email) { + return null + } + const userId = optionalString(record.userId) + return { + userId: userId ?? null, + email, + displayName: optionalString(record.displayName), + role: normalizeRole(record.role, 'member') + } +} + +function normalizePendingInvite(value: unknown): OrcaOrgPendingInvite | null { + if (!value || typeof value !== 'object') { + return null + } + const record = value as Record + const email = optionalString(record.email) + if (!email) { + return null + } + return { + email, + role: normalizeRole(record.role, 'member'), + createdAt: normalizeTimestamp(record.createdAt) + } +} + +function normalizeRoster(value: unknown): OrcaOrgMembersRoster { + if (!value || typeof value !== 'object') { + throw new Error('invalid_orca_org_members_roster') + } + const record = value as Record + const members = Array.isArray(record.members) + ? record.members + .map(normalizeMember) + .filter((member): member is OrcaOrgMember => member !== null) + : [] + const pendingInvites = Array.isArray(record.pendingInvites) + ? record.pendingInvites + .map(normalizePendingInvite) + .filter((invite): invite is OrcaOrgPendingInvite => invite !== null) + : [] + return { + members, + pendingInvites, + // Why: default to the least-privileged role so a malformed viewerRole can + // never widen the client-side management affordance; the server still + // enforces authorization on every mutation. + viewerRole: normalizeRole(record.viewerRole, 'member'), + canManageMembers: record.canManageMembers === true + } +} + +function orgMembersUrl(config: OrcaCloudAuthConfig, orgId: string, path: string): string { + return `${config.apiBaseUrl}/v1/desktop/orgs/${encodeURIComponent(orgId)}${path}` +} + +async function extractErrorCode(response: Response): Promise { + try { + const body = (await response.json()) as unknown + if ( + body && + typeof body === 'object' && + typeof (body as { error?: unknown }).error === 'string' + ) { + return (body as { error: string }).error.trim() || undefined + } + } catch { + // Non-JSON error body; the status code alone drives the caller's mapping. + } + return undefined +} + +// Why: these are fixed first-party endpoints bearing the profile's access token; +// following a redirect would leak that token to another origin, and a stalled +// server must not hang the renderer's awaited IPC call forever. +function requestInit(method: 'GET' | 'POST', accessToken: string, body?: unknown): RequestInit { + return { + method, + headers: { + ...(body === undefined ? {} : { 'content-type': 'application/json' }), + authorization: `Bearer ${accessToken}` + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + redirect: 'error', + signal: AbortSignal.timeout(CLOUD_REQUEST_TIMEOUT_MS) + } +} + +async function requestOrgMembers( + url: string, + init: RequestInit, + parse: (value: unknown) => T +): Promise { + const response = await fetch(url, init) + if (!response.ok) { + throw new OrcaCloudRequestError(response.status, await extractErrorCode(response)) + } + return parse((await response.json()) as unknown) +} + +export async function listOrcaCloudOrgMembers( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession, + orgId: string +): Promise { + return requestOrgMembers( + orgMembersUrl(config, orgId, '/members'), + requestInit('GET', session.accessToken), + normalizeRoster + ) +} + +export async function inviteOrcaCloudOrgMember( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession, + args: { orgId: string; email: string; role: OrcaOrgRole } +): Promise { + await requestOrgMembers( + orgMembersUrl(config, args.orgId, '/invites'), + requestInit('POST', session.accessToken, { email: args.email, role: args.role }), + () => undefined + ) +} + +export async function revokeOrcaCloudOrgInvite( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession, + args: { orgId: string; email: string } +): Promise { + await requestOrgMembers( + orgMembersUrl(config, args.orgId, '/invites/revoke'), + requestInit('POST', session.accessToken, { email: args.email }), + () => undefined + ) +} + +export async function changeOrcaCloudOrgMemberRole( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession, + args: { orgId: string; userId: string; role: OrcaOrgRole } +): Promise { + await requestOrgMembers( + orgMembersUrl(config, args.orgId, '/members/role'), + requestInit('POST', session.accessToken, { userId: args.userId, role: args.role }), + () => undefined + ) +} + +export async function removeOrcaCloudOrgMember( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession, + args: { orgId: string; userId: string } +): Promise { + await requestOrgMembers( + orgMembersUrl(config, args.orgId, '/members/remove'), + requestInit('POST', session.accessToken, { userId: args.userId }), + () => undefined + ) +} diff --git a/src/main/orca-profiles/profile-cloud-org-members-service.test.ts b/src/main/orca-profiles/profile-cloud-org-members-service.test.ts new file mode 100644 index 000000000000..8d4011d79ff7 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-org-members-service.test.ts @@ -0,0 +1,259 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { OrcaOrgMembersRoster } from '../../shared/orca-profiles' +import { OrcaCloudRequestError } from './profile-cloud-client' + +const { + runWithFreshOrcaCloudSessionMock, + listOrcaCloudOrgMembersMock, + inviteOrcaCloudOrgMemberMock, + revokeOrcaCloudOrgInviteMock, + changeOrcaCloudOrgMemberRoleMock, + removeOrcaCloudOrgMemberMock +} = vi.hoisted(() => ({ + runWithFreshOrcaCloudSessionMock: vi.fn(), + listOrcaCloudOrgMembersMock: vi.fn(), + inviteOrcaCloudOrgMemberMock: vi.fn(), + revokeOrcaCloudOrgInviteMock: vi.fn(), + changeOrcaCloudOrgMemberRoleMock: vi.fn(), + removeOrcaCloudOrgMemberMock: vi.fn() +})) + +let userDataPath = '' + +vi.mock('electron', () => ({ + app: { getPath: () => userDataPath } +})) + +vi.mock('./profile-cloud-session-refresh', () => ({ + runWithFreshOrcaCloudSessionMock, + runWithFreshOrcaCloudSession: runWithFreshOrcaCloudSessionMock +})) + +vi.mock('./profile-cloud-org-members-client', () => ({ + listOrcaCloudOrgMembers: listOrcaCloudOrgMembersMock, + inviteOrcaCloudOrgMember: inviteOrcaCloudOrgMemberMock, + revokeOrcaCloudOrgInvite: revokeOrcaCloudOrgInviteMock, + changeOrcaCloudOrgMemberRole: changeOrcaCloudOrgMemberRoleMock, + removeOrcaCloudOrgMember: removeOrcaCloudOrgMemberMock +})) + +import { + changeOrcaProfileOrgMemberRole, + inviteOrcaProfileOrgMember, + listOrcaProfileOrgMembers, + removeOrcaProfileOrgMember, + revokeOrcaProfileOrgInvite +} from './profile-cloud-org-members-service' + +const fakeSession = { + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: Date.now() + 3_600_000, + capabilities: { flags: {}, refreshedAt: 1 } +} + +// Why: mirror the real contract — invoke the operation with a live session and +// surface its resolved value; business 4xx are returned by the operation as +// values, never thrown, so the session layer never sees them. +function runOperationDirectly(): void { + runWithFreshOrcaCloudSessionMock.mockImplementation( + async ( + _config: unknown, + _active: unknown, + _path: unknown, + op: (session: unknown) => unknown + ) => ({ + status: 'ok', + value: await op(fakeSession) + }) + ) +} + +function configureCloudEnv(): void { + vi.stubEnv('ORCA_CLOUD_API_URL', 'https://orca-cloud.example') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', 'desktop-client') +} + +const roster: OrcaOrgMembersRoster = { + members: [{ userId: 'user-1', email: 'nina@example.com', role: 'owner' }], + pendingInvites: [], + viewerRole: 'owner', + canManageMembers: true +} + +describe('Orca cloud org members service (configured)', () => { + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-org-members-')) + runWithFreshOrcaCloudSessionMock.mockReset() + listOrcaCloudOrgMembersMock.mockReset() + inviteOrcaCloudOrgMemberMock.mockReset() + revokeOrcaCloudOrgInviteMock.mockReset() + changeOrcaCloudOrgMemberRoleMock.mockReset() + removeOrcaCloudOrgMemberMock.mockReset() + vi.unstubAllEnvs() + vi.stubEnv('ORCA_CLOUD_DEV_AUTH', '') + vi.stubEnv('ORCA_CLOUD_API_URL', '') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', '') + }) + + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('reports unconfigured when cloud sign-in is not set up', async () => { + await expect(listOrcaProfileOrgMembers(userDataPath, 'org-1')).resolves.toEqual({ + status: 'unconfigured' + }) + expect(runWithFreshOrcaCloudSessionMock).not.toHaveBeenCalled() + }) + + it('returns the roster from the client', async () => { + configureCloudEnv() + runOperationDirectly() + listOrcaCloudOrgMembersMock.mockResolvedValue(roster) + + await expect(listOrcaProfileOrgMembers(userDataPath, 'org-1')).resolves.toEqual({ + status: 'ok', + roster + }) + expect(listOrcaCloudOrgMembersMock).toHaveBeenCalledWith( + expect.any(Object), + fakeSession, + 'org-1' + ) + }) + + it('maps a 409 already_member invite conflict', async () => { + configureCloudEnv() + runOperationDirectly() + inviteOrcaCloudOrgMemberMock.mockRejectedValue(new OrcaCloudRequestError(409, 'already_member')) + + await expect( + inviteOrcaProfileOrgMember(userDataPath, { orgId: 'org-1', email: 'a@b.com', role: 'member' }) + ).resolves.toEqual({ status: 'conflict', reason: 'already_member' }) + }) + + it('maps a 403 role change to forbidden', async () => { + configureCloudEnv() + runOperationDirectly() + changeOrcaCloudOrgMemberRoleMock.mockRejectedValue(new OrcaCloudRequestError(403)) + + await expect( + changeOrcaProfileOrgMemberRole(userDataPath, { + orgId: 'org-1', + userId: 'user-2', + role: 'admin' + }) + ).resolves.toEqual({ status: 'forbidden' }) + }) + + it('maps a 400 cannot_remove_self to an invalid result', async () => { + configureCloudEnv() + runOperationDirectly() + removeOrcaCloudOrgMemberMock.mockRejectedValue( + new OrcaCloudRequestError(400, 'cannot_remove_self') + ) + + await expect( + removeOrcaProfileOrgMember(userDataPath, { orgId: 'org-1', userId: 'user-1' }) + ).resolves.toEqual({ status: 'invalid', reason: 'cannot_remove_self' }) + }) + + it('maps a 404 revoke to not-found', async () => { + configureCloudEnv() + runOperationDirectly() + revokeOrcaCloudOrgInviteMock.mockRejectedValue(new OrcaCloudRequestError(404)) + + await expect( + revokeOrcaProfileOrgInvite(userDataPath, { orgId: 'org-1', email: 'gone@b.com' }) + ).resolves.toEqual({ status: 'not-found' }) + }) + + it('reports reconnect-required when the session layer cannot refresh', async () => { + configureCloudEnv() + runWithFreshOrcaCloudSessionMock.mockResolvedValue({ status: 'reconnect-required' }) + + await expect(listOrcaProfileOrgMembers(userDataPath, 'org-1')).resolves.toEqual({ + status: 'reconnect-required' + }) + }) +}) + +describe('Orca cloud org members service (dev auth)', () => { + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-org-members-dev-')) + runWithFreshOrcaCloudSessionMock.mockReset() + vi.unstubAllEnvs() + vi.stubEnv('ORCA_CLOUD_DEV_AUTH', '1') + }) + + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('serves an in-memory roster the caller can manage', async () => { + const result = await listOrcaProfileOrgMembers(userDataPath, 'dev-list-org') + if (result.status !== 'ok') { + throw new Error(`Expected ok, got ${result.status}`) + } + expect(result.roster.canManageMembers).toBe(true) + expect(result.roster.viewerRole).toBe('owner') + expect(result.roster.members[0]).toMatchObject({ role: 'owner' }) + expect(result.roster.members.some((member) => member.userId === null)).toBe(true) + expect(result.roster.pendingInvites.length).toBeGreaterThan(0) + expect(runWithFreshOrcaCloudSessionMock).not.toHaveBeenCalled() + }) + + it('mutates the dev roster across invite and revoke', async () => { + const orgId = 'dev-mutate-org' + await expect( + inviteOrcaProfileOrgMember(userDataPath, { + orgId, + email: 'fresh@orca.local', + role: 'member' + }) + ).resolves.toEqual({ status: 'ok' }) + + const afterInvite = await listOrcaProfileOrgMembers(userDataPath, orgId) + if (afterInvite.status !== 'ok') { + throw new Error('expected ok') + } + expect(afterInvite.roster.pendingInvites.some((i) => i.email === 'fresh@orca.local')).toBe(true) + + await expect( + inviteOrcaProfileOrgMember(userDataPath, { + orgId, + email: 'fresh@orca.local', + role: 'member' + }) + ).resolves.toEqual({ status: 'conflict', reason: 'already_invited' }) + + await expect( + revokeOrcaProfileOrgInvite(userDataPath, { orgId, email: 'fresh@orca.local' }) + ).resolves.toEqual({ status: 'ok' }) + await expect( + revokeOrcaProfileOrgInvite(userDataPath, { orgId, email: 'fresh@orca.local' }) + ).resolves.toEqual({ status: 'not-found' }) + }) + + it('blocks changing the dev owner (self) role', async () => { + const orgId = 'dev-self-org' + const list = await listOrcaProfileOrgMembers(userDataPath, orgId) + if (list.status !== 'ok') { + throw new Error('expected ok') + } + const self = list.roster.members.find((member) => member.role === 'owner') + await expect( + changeOrcaProfileOrgMemberRole(userDataPath, { + orgId, + userId: self?.userId ?? 'dev-user', + role: 'member' + }) + ).resolves.toEqual({ status: 'invalid', reason: 'cannot_change_own_role' }) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-org-members-service.ts b/src/main/orca-profiles/profile-cloud-org-members-service.ts new file mode 100644 index 000000000000..d115059a08fa --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-org-members-service.ts @@ -0,0 +1,212 @@ +import type { + OrcaProfileOrgInviteRevokeArgs, + OrcaProfileOrgMemberChangeRoleArgs, + OrcaProfileOrgMemberInviteArgs, + OrcaProfileOrgMemberMutationResult, + OrcaProfileOrgMemberRemoveArgs, + OrcaProfileOrgMembersListResult +} from '../../shared/orca-profiles' +import type { ActiveOrcaProfileState } from './profile-index-store' +import { ensureActiveOrcaProfile } from './profile-index-store' +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' +import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from './profile-cloud-auth-config' +import type { OrcaCloudSession } from './profile-cloud-session-store' +import { OrcaCloudRequestError } from './profile-cloud-client' +import { runWithFreshOrcaCloudSession } from './profile-cloud-session-refresh' +import { + changeOrcaCloudOrgMemberRole, + inviteOrcaCloudOrgMember, + listOrcaCloudOrgMembers, + removeOrcaCloudOrgMember, + revokeOrcaCloudOrgInvite +} from './profile-cloud-org-members-client' +import { + changeDevOrcaCloudOrgMemberRole, + inviteDevOrcaCloudOrgMember, + listDevOrcaCloudOrgMembers, + removeDevOrcaCloudOrgMember, + revokeDevOrcaCloudOrgInvite +} from './profile-cloud-dev-org-members' + +type OrgCallResult = + | { status: 'ok'; value: T } + | { status: 'reconnect-required' } + | { status: 'request-error'; error: OrcaCloudRequestError } + | { status: 'failed'; error: string } + +// Why: only a 401 means the token itself is stale and should drive a session +// refresh/reconnect. 403/404/409/400 are business or permission outcomes the UI +// must interpret, so they are surfaced as values rather than thrown — otherwise +// runWithFreshOrcaCloudSession would treat a 403 as an auth failure and burn a +// pointless token refresh + retry before giving up. +async function runOrgMemberCall( + config: OrcaCloudAuthConfig, + active: ActiveOrcaProfileState, + userDataPath: string, + call: (session: OrcaCloudSession) => Promise +): Promise> { + try { + const operation = await runWithFreshOrcaCloudSession( + config, + active, + userDataPath, + async (session) => { + try { + return { ok: true as const, value: await call(session) } + } catch (error) { + if (error instanceof OrcaCloudRequestError && error.statusCode !== 401) { + return { ok: false as const, error } + } + throw error + } + } + ) + if (operation.status !== 'ok') { + return { status: 'reconnect-required' } + } + const outcome = operation.value + return outcome.ok + ? { status: 'ok', value: outcome.value } + : { status: 'request-error', error: outcome.error } + } catch (error) { + return { status: 'failed', error: error instanceof Error ? error.message : String(error) } + } +} + +function mapMutationRequestError(error: OrcaCloudRequestError): OrcaProfileOrgMemberMutationResult { + switch (error.statusCode) { + case 403: + return { status: 'forbidden' } + case 404: + return { status: 'not-found' } + case 409: + return { + status: 'conflict', + reason: error.errorCode === 'already_member' ? 'already_member' : 'already_invited' + } + case 400: + return { + status: 'invalid', + reason: + error.errorCode === 'cannot_remove_self' ? 'cannot_remove_self' : 'cannot_change_own_role' + } + default: + return { status: 'failed', error: error.message } + } +} + +function mapMutationResult(result: OrgCallResult): OrcaProfileOrgMemberMutationResult { + switch (result.status) { + case 'ok': + return { status: 'ok' } + case 'reconnect-required': + return { status: 'reconnect-required' } + case 'request-error': + return mapMutationRequestError(result.error) + case 'failed': + return { status: 'failed', error: result.error } + } +} + +export async function listOrcaProfileOrgMembers( + userDataPath: string, + orgId: string +): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + if (isOrcaCloudDevAuthEnabled()) { + return { status: 'ok', roster: listDevOrcaCloudOrgMembers(orgId) } + } + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { status: 'unconfigured' } + } + const result = await runOrgMemberCall(configState.config, active, userDataPath, (session) => + listOrcaCloudOrgMembers(configState.config, session, orgId) + ) + switch (result.status) { + case 'ok': + return { status: 'ok', roster: result.value } + case 'reconnect-required': + return { status: 'reconnect-required' } + case 'request-error': + return { status: 'failed', error: result.error.message } + case 'failed': + return { status: 'failed', error: result.error } + } +} + +export async function inviteOrcaProfileOrgMember( + userDataPath: string, + args: OrcaProfileOrgMemberInviteArgs +): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + if (isOrcaCloudDevAuthEnabled()) { + return inviteDevOrcaCloudOrgMember(args) + } + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { status: 'unconfigured' } + } + return mapMutationResult( + await runOrgMemberCall(configState.config, active, userDataPath, (session) => + inviteOrcaCloudOrgMember(configState.config, session, args) + ) + ) +} + +export async function revokeOrcaProfileOrgInvite( + userDataPath: string, + args: OrcaProfileOrgInviteRevokeArgs +): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + if (isOrcaCloudDevAuthEnabled()) { + return revokeDevOrcaCloudOrgInvite(args) + } + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { status: 'unconfigured' } + } + return mapMutationResult( + await runOrgMemberCall(configState.config, active, userDataPath, (session) => + revokeOrcaCloudOrgInvite(configState.config, session, args) + ) + ) +} + +export async function changeOrcaProfileOrgMemberRole( + userDataPath: string, + args: OrcaProfileOrgMemberChangeRoleArgs +): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + if (isOrcaCloudDevAuthEnabled()) { + return changeDevOrcaCloudOrgMemberRole(args) + } + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { status: 'unconfigured' } + } + return mapMutationResult( + await runOrgMemberCall(configState.config, active, userDataPath, (session) => + changeOrcaCloudOrgMemberRole(configState.config, session, args) + ) + ) +} + +export async function removeOrcaProfileOrgMember( + userDataPath: string, + args: OrcaProfileOrgMemberRemoveArgs +): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + if (isOrcaCloudDevAuthEnabled()) { + return removeDevOrcaCloudOrgMember(args) + } + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { status: 'unconfigured' } + } + return mapMutationResult( + await runOrgMemberCall(configState.config, active, userDataPath, (session) => + removeOrcaCloudOrgMember(configState.config, session, args) + ) + ) +} diff --git a/src/main/orca-profiles/profile-cloud-pkce.test.ts b/src/main/orca-profiles/profile-cloud-pkce.test.ts new file mode 100644 index 000000000000..03f6e5894b36 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-pkce.test.ts @@ -0,0 +1,127 @@ +import { get } from 'node:http' +import { describe, expect, it, beforeEach, vi } from 'vitest' +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' + +const { openExternalMock } = vi.hoisted(() => ({ + openExternalMock: vi.fn() +})) + +vi.mock('electron', () => ({ + shell: { + openExternal: openExternalMock + } +})) + +import { beginOrcaCloudPkceFlow } from './profile-cloud-pkce' + +type HttpResponse = { + body: string + statusCode: number | undefined +} + +const config: OrcaCloudAuthConfig = { + apiBaseUrl: 'https://orca-cloud.example', + authorizeEndpoint: 'https://orca-cloud.example/v1/desktop/auth/authorize', + sessionEndpoint: 'https://orca-cloud.example/v1/desktop/auth/session', + refreshEndpoint: 'https://orca-cloud.example/v1/desktop/auth/refresh', + capabilitiesEndpoint: 'https://orca-cloud.example/v1/desktop/auth/capabilities', + profileEndpoint: 'https://orca-cloud.example/v1/desktop/auth/profile', + orgEndpoint: 'https://orca-cloud.example/v1/desktop/auth/org', + logoutEndpoint: 'https://orca-cloud.example/v1/desktop/auth/logout', + clientId: 'desktop-client', + scope: 'openid profile email offline_access' +} + +function readHttp(url: string): Promise { + return new Promise((resolve, reject) => { + const request = get(url, (response) => { + response.setEncoding('utf-8') + let body = '' + response.on('data', (chunk: string) => { + body += chunk + }) + response.on('end', () => { + resolve({ body, statusCode: response.statusCode }) + }) + }) + request.on('error', reject) + }) +} + +function callbackUrl(redirectUri: string, params: Record): string { + const url = new URL(redirectUri) + for (const [key, value] of Object.entries(params)) { + url.searchParams.set(key, value) + } + return url.toString() +} + +async function startedFlow(): Promise<{ + authUrl: URL + flow: ReturnType + nonce: string + redirectUri: string + state: string +}> { + const flow = beginOrcaCloudPkceFlow(config, 'local-default') + await vi.waitFor(() => expect(openExternalMock).toHaveBeenCalledTimes(1)) + const authUrl = new URL(String(openExternalMock.mock.calls[0]?.[0])) + const nonce = authUrl.searchParams.get('nonce') + const redirectUri = authUrl.searchParams.get('redirect_uri') + const state = authUrl.searchParams.get('state') + if (!nonce || !redirectUri || !state) { + throw new Error('Expected PKCE flow to create nonce, redirect_uri, and state') + } + return { authUrl, flow, nonce, redirectUri, state } +} + +describe('Orca cloud PKCE flow', () => { + beforeEach(() => { + openExternalMock.mockReset() + openExternalMock.mockResolvedValue(undefined) + }) + + it('keeps the loopback listener alive after an invalid callback', async () => { + const { flow, redirectUri, state } = await startedFlow() + + const invalidResponse = await readHttp( + callbackUrl(redirectUri, { code: 'wrong-code', state: 'wrong-state' }) + ) + expect(invalidResponse.statusCode).toBe(400) + + const validResponse = await readHttp(callbackUrl(redirectUri, { code: 'real-code', state })) + expect(validResponse.statusCode).toBe(200) + await expect(flow).resolves.toMatchObject({ + code: 'real-code', + redirectUri, + state + }) + }) + + it('rejects a provider error that matches the flow state', async () => { + const { flow, redirectUri, state } = await startedFlow() + const observedFlow = flow.catch((error: unknown) => error) + + const response = await readHttp(callbackUrl(redirectUri, { error: 'access_denied', state })) + + expect(response.statusCode).toBe(400) + await expect(observedFlow).resolves.toMatchObject({ message: 'orca_cloud_auth_denied' }) + }) + + it('adds desktop PKCE parameters to the authorize URL', async () => { + const { authUrl, flow, nonce, redirectUri, state } = await startedFlow() + + expect(authUrl.searchParams.get('client_id')).toBe('desktop-client') + expect(authUrl.searchParams.get('response_type')).toBe('code') + expect(authUrl.searchParams.get('redirect_uri')).toBe(redirectUri) + expect(authUrl.searchParams.get('scope')).toBe('openid profile email offline_access') + expect(authUrl.searchParams.get('nonce')).toBe(nonce) + expect(authUrl.searchParams.get('state')).toBe(state) + expect(authUrl.searchParams.get('code_challenge')).toMatch(/^[A-Za-z0-9_-]+$/) + expect(authUrl.searchParams.get('code_challenge_method')).toBe('S256') + expect(authUrl.searchParams.get('local_profile_id')).toBe('local-default') + + await readHttp(callbackUrl(redirectUri, { code: 'real-code', state })) + await expect(flow).resolves.toMatchObject({ code: 'real-code', nonce }) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-pkce.ts b/src/main/orca-profiles/profile-cloud-pkce.ts new file mode 100644 index 000000000000..8adf3f3e5877 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-pkce.ts @@ -0,0 +1,142 @@ +import { createHash, randomBytes } from 'node:crypto' +import { createServer, type Server, type ServerResponse } from 'node:http' +import { shell } from 'electron' +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' + +export type OrcaCloudAuthorizationCode = { + code: string + codeVerifier: string + nonce: string + redirectUri: string + state: string +} + +const AUTH_TIMEOUT_MS = 5 * 60 * 1000 + +function base64Url(buffer: Buffer): string { + return buffer.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '') +} + +function createCodeVerifier(): string { + return base64Url(randomBytes(32)) +} + +function createCodeChallenge(verifier: string): string { + return base64Url(createHash('sha256').update(verifier).digest()) +} + +function closeServer(server: Server): void { + try { + // Why: keep-alive sockets from the browser can delay 'close' (and the + // timeout cleanup) until the browser drops the connection. + server.closeAllConnections?.() + server.close() + } catch { + // Already closed. + } +} + +export function beginOrcaCloudPkceFlow( + config: OrcaCloudAuthConfig, + localProfileId: string +): Promise { + const codeVerifier = createCodeVerifier() + const nonce = base64Url(randomBytes(32)) + const state = base64Url(randomBytes(32)) + + return new Promise((resolve, reject) => { + let settled = false + let redirectUri = '' + + function rejectFlow(error: Error): void { + if (settled) { + return + } + settled = true + reject(error) + closeServer(server) + } + + function resolveFlow(code: string): void { + if (settled) { + return + } + settled = true + resolve({ + code, + codeVerifier, + nonce, + redirectUri, + state + }) + closeServer(server) + } + + function writeInvalidCallback(response: ServerResponse): void { + response.writeHead(400) + response.end('Invalid Orca sign-in response.') + } + + const server = createServer((request, response) => { + try { + const url = new URL(request.url ?? '/', 'http://127.0.0.1') + if (url.pathname !== '/auth/callback') { + response.writeHead(404) + response.end('Not found') + return + } + const code = url.searchParams.get('code') + const returnedState = url.searchParams.get('state') + if (returnedState !== state) { + // Why: stray loopback probes must not be able to cancel the user's login. + writeInvalidCallback(response) + return + } + if (url.searchParams.has('error')) { + response.writeHead(400) + response.end('Orca sign-in was cancelled.') + rejectFlow(new Error('orca_cloud_auth_denied')) + return + } + if (!code) { + writeInvalidCallback(response) + return + } + response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) + response.end('Orca

    You can return to Orca.

    ') + resolveFlow(code) + } catch (error) { + rejectFlow(error instanceof Error ? error : new Error('orca_cloud_auth_callback_failed')) + } + }) + + const timeout = setTimeout(() => { + rejectFlow(new Error('orca_cloud_auth_timeout')) + }, AUTH_TIMEOUT_MS) + server.once('close', () => clearTimeout(timeout)) + server.once('error', rejectFlow) + server.listen(0, '127.0.0.1', () => { + const address = server.address() + if (!address || typeof address === 'string') { + rejectFlow(new Error('orca_cloud_auth_loopback_unavailable')) + return + } + redirectUri = `http://127.0.0.1:${address.port}/auth/callback` + const authorizeUrl = new URL(config.authorizeEndpoint) + authorizeUrl.searchParams.set('client_id', config.clientId) + authorizeUrl.searchParams.set('response_type', 'code') + authorizeUrl.searchParams.set('redirect_uri', redirectUri) + authorizeUrl.searchParams.set('scope', config.scope) + authorizeUrl.searchParams.set('nonce', nonce) + authorizeUrl.searchParams.set('state', state) + authorizeUrl.searchParams.set('code_challenge', createCodeChallenge(codeVerifier)) + authorizeUrl.searchParams.set('code_challenge_method', 'S256') + authorizeUrl.searchParams.set('local_profile_id', localProfileId) + void shell.openExternal(authorizeUrl.toString()).catch((error) => { + rejectFlow( + error instanceof Error ? error : new Error('orca_cloud_auth_browser_open_failed') + ) + }) + }) + }) +} diff --git a/src/main/orca-profiles/profile-cloud-service-auth-retry.test.ts b/src/main/orca-profiles/profile-cloud-service-auth-retry.test.ts new file mode 100644 index 000000000000..9db1d8309865 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-service-auth-retry.test.ts @@ -0,0 +1,247 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { + OrcaCloudCapabilities, + OrcaCloudOrgSummary, + OrcaProfileCloudSummary +} from '../../shared/orca-profiles' +import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' + +const { + beginOrcaCloudPkceFlowMock, + createOrcaCloudProfileMock, + exchangeOrcaCloudAuthCodeMock, + refreshOrcaCloudCapabilitiesMock, + refreshOrcaCloudSessionMock, + selectOrcaCloudOrgMock, + OrcaCloudRequestErrorMock, + safeStorageMock +} = vi.hoisted(() => ({ + beginOrcaCloudPkceFlowMock: vi.fn(), + createOrcaCloudProfileMock: vi.fn(), + exchangeOrcaCloudAuthCodeMock: vi.fn(), + refreshOrcaCloudCapabilitiesMock: vi.fn(), + refreshOrcaCloudSessionMock: vi.fn(), + selectOrcaCloudOrgMock: vi.fn(), + OrcaCloudRequestErrorMock: class OrcaCloudRequestError extends Error { + constructor(public readonly statusCode: number) { + super(`orca_cloud_request_failed_${statusCode}`) + this.name = 'OrcaCloudRequestError' + } + }, + safeStorageMock: { + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + isEncryptionAvailable: vi.fn(() => true) + } +})) + +let userDataPath = '' + +vi.mock('electron', () => ({ + app: { + getPath: () => userDataPath + }, + safeStorage: safeStorageMock +})) + +vi.mock('./profile-cloud-pkce', () => ({ + beginOrcaCloudPkceFlow: beginOrcaCloudPkceFlowMock +})) + +vi.mock('./profile-cloud-client', () => ({ + OrcaCloudRequestError: OrcaCloudRequestErrorMock, + createOrcaCloudProfile: createOrcaCloudProfileMock, + exchangeOrcaCloudAuthCode: exchangeOrcaCloudAuthCodeMock, + refreshOrcaCloudCapabilities: refreshOrcaCloudCapabilitiesMock, + refreshOrcaCloudSession: refreshOrcaCloudSessionMock, + revokeOrcaCloudSession: vi.fn(), + selectOrcaCloudOrg: selectOrcaCloudOrgMock +})) + +import { + connectCurrentOrcaProfile, + createCloudLinkedOrcaProfile, + getCurrentOrcaProfileAuthStatus, + refreshCurrentOrcaProfileAuth, + selectCurrentOrcaProfileOrg +} from './profile-cloud-service' + +const cloudSummary: OrcaProfileCloudSummary = { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com', + displayName: 'Nina', + linkedAt: 10 +} + +const capabilities: OrcaCloudCapabilities = { + flags: { share: true }, + refreshedAt: 11 +} + +const organizations: OrcaCloudOrgSummary[] = [ + { orgId: 'org-1', name: 'Acme', role: 'Admin' }, + { orgId: 'org-2', name: 'Personal' } +] + +function futureExpiresAt(): number { + return Date.now() + 3_600_000 +} + +function configureCloudEnv(): void { + vi.stubEnv('ORCA_CLOUD_API_URL', 'https://orca-cloud.example') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', 'desktop-client') +} + +function mockSuccessfulConnect(): void { + beginOrcaCloudPkceFlowMock.mockResolvedValue({ + code: 'auth-code', + codeVerifier: 'code-verifier', + nonce: 'nonce', + redirectUri: 'http://127.0.0.1:4100/auth/callback', + state: 'state' + }) + exchangeOrcaCloudAuthCodeMock.mockResolvedValue({ + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: futureExpiresAt(), + cloud: cloudSummary, + organizations, + capabilities + } satisfies OrcaCloudSessionExchangeResponse) +} + +function mockSuccessfulSessionRefresh(): void { + refreshOrcaCloudSessionMock.mockResolvedValue({ + accessToken: 'rotated-access-token', + refreshToken: 'rotated-refresh-token', + expiresAt: futureExpiresAt(), + cloud: cloudSummary, + organizations, + capabilities + } satisfies OrcaCloudSessionExchangeResponse) +} + +describe('Orca cloud profile auth-failure retry', () => { + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-cloud-service-auth-retry-')) + beginOrcaCloudPkceFlowMock.mockReset() + createOrcaCloudProfileMock.mockReset() + exchangeOrcaCloudAuthCodeMock.mockReset() + refreshOrcaCloudCapabilitiesMock.mockReset() + refreshOrcaCloudSessionMock.mockReset() + selectOrcaCloudOrgMock.mockReset() + safeStorageMock.decryptString.mockReset() + safeStorageMock.encryptString.mockReset() + safeStorageMock.isEncryptionAvailable.mockReset() + safeStorageMock.decryptString.mockImplementation((value: Buffer) => value.toString('utf-8')) + safeStorageMock.encryptString.mockImplementation((value: string) => Buffer.from(value, 'utf-8')) + safeStorageMock.isEncryptionAvailable.mockReturnValue(true) + vi.unstubAllEnvs() + vi.stubEnv('ORCA_CLOUD_API_URL', '') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', '') + }) + + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('refreshes and retries cloud profile creation after an auth failure', async () => { + configureCloudEnv() + mockSuccessfulConnect() + mockSuccessfulSessionRefresh() + await connectCurrentOrcaProfile(userDataPath) + createOrcaCloudProfileMock + .mockRejectedValueOnce(new OrcaCloudRequestErrorMock(401)) + .mockResolvedValue({ + accessToken: 'new-access-token', + refreshToken: 'new-refresh-token', + expiresAt: futureExpiresAt(), + cloud: { ...cloudSummary, cloudProfileId: 'cloud-profile-2' }, + organizations, + capabilities + } satisfies OrcaCloudSessionExchangeResponse) + + const result = await createCloudLinkedOrcaProfile(userDataPath, { name: 'Acme' }) + + expect(result.status).toBe('created') + expect(createOrcaCloudProfileMock).toHaveBeenNthCalledWith( + 2, + expect.any(Object), + expect.objectContaining({ accessToken: 'rotated-access-token' }), + { name: 'Acme' } + ) + }) + + it('refreshes and retries capability refresh after an auth failure', async () => { + configureCloudEnv() + mockSuccessfulConnect() + mockSuccessfulSessionRefresh() + await connectCurrentOrcaProfile(userDataPath) + refreshOrcaCloudCapabilitiesMock + .mockRejectedValueOnce(new OrcaCloudRequestErrorMock(403)) + .mockResolvedValue({ + capabilities: { flags: { share: false }, refreshedAt: 26 } satisfies OrcaCloudCapabilities + }) + + const result = await refreshCurrentOrcaProfileAuth(userDataPath) + + expect(result.status).toBe('refreshed') + expect(refreshOrcaCloudCapabilitiesMock).toHaveBeenNthCalledWith( + 2, + expect.any(Object), + expect.objectContaining({ accessToken: 'rotated-access-token' }) + ) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).capabilities).toEqual({ + flags: { share: false }, + refreshedAt: 26 + }) + }) + + it('requires reconnect when a retried capability refresh is still unauthorized', async () => { + configureCloudEnv() + mockSuccessfulConnect() + mockSuccessfulSessionRefresh() + await connectCurrentOrcaProfile(userDataPath) + refreshOrcaCloudCapabilitiesMock + .mockRejectedValueOnce(new OrcaCloudRequestErrorMock(401)) + .mockRejectedValueOnce(new OrcaCloudRequestErrorMock(401)) + + const result = await refreshCurrentOrcaProfileAuth(userDataPath) + + expect(result.status).toBe('reconnect-required') + expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ + state: 'reconnect-required', + persistence: 'none', + cloud: cloudSummary + }) + }) + + it('refreshes and retries organization selection after an auth failure', async () => { + configureCloudEnv() + mockSuccessfulConnect() + mockSuccessfulSessionRefresh() + await connectCurrentOrcaProfile(userDataPath) + selectOrcaCloudOrgMock + .mockRejectedValueOnce(new OrcaCloudRequestErrorMock(401)) + .mockResolvedValue({ + cloud: { ...cloudSummary, activeOrgId: 'org-1', activeOrgName: 'Acme' }, + organizations, + capabilities + }) + + const result = await selectCurrentOrcaProfileOrg(userDataPath, 'org-1') + + expect(result.status).toBe('selected') + expect(selectOrcaCloudOrgMock).toHaveBeenNthCalledWith( + 2, + expect.any(Object), + expect.objectContaining({ accessToken: 'rotated-access-token' }), + 'org-1' + ) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-service-refresh.test.ts b/src/main/orca-profiles/profile-cloud-service-refresh.test.ts new file mode 100644 index 000000000000..075573eea3a7 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-service-refresh.test.ts @@ -0,0 +1,254 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { + OrcaCloudCapabilities, + OrcaCloudOrgSummary, + OrcaProfileCloudSummary +} from '../../shared/orca-profiles' +import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' + +const { + beginOrcaCloudPkceFlowMock, + createOrcaCloudProfileMock, + exchangeOrcaCloudAuthCodeMock, + refreshOrcaCloudCapabilitiesMock, + refreshOrcaCloudSessionMock, + OrcaCloudRequestErrorMock, + safeStorageMock +} = vi.hoisted(() => ({ + beginOrcaCloudPkceFlowMock: vi.fn(), + createOrcaCloudProfileMock: vi.fn(), + exchangeOrcaCloudAuthCodeMock: vi.fn(), + refreshOrcaCloudCapabilitiesMock: vi.fn(), + refreshOrcaCloudSessionMock: vi.fn(), + OrcaCloudRequestErrorMock: class OrcaCloudRequestError extends Error { + constructor(public readonly statusCode: number) { + super(`orca_cloud_request_failed_${statusCode}`) + this.name = 'OrcaCloudRequestError' + } + }, + safeStorageMock: { + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + isEncryptionAvailable: vi.fn(() => true) + } +})) + +let userDataPath = '' + +vi.mock('electron', () => ({ + app: { + getPath: () => userDataPath + }, + safeStorage: safeStorageMock +})) + +vi.mock('./profile-cloud-pkce', () => ({ + beginOrcaCloudPkceFlow: beginOrcaCloudPkceFlowMock +})) + +vi.mock('./profile-cloud-client', () => ({ + OrcaCloudRequestError: OrcaCloudRequestErrorMock, + createOrcaCloudProfile: createOrcaCloudProfileMock, + exchangeOrcaCloudAuthCode: exchangeOrcaCloudAuthCodeMock, + refreshOrcaCloudCapabilities: refreshOrcaCloudCapabilitiesMock, + refreshOrcaCloudSession: refreshOrcaCloudSessionMock, + revokeOrcaCloudSession: vi.fn(), + selectOrcaCloudOrg: vi.fn() +})) + +import { + connectCurrentOrcaProfile, + createCloudLinkedOrcaProfile, + getCurrentOrcaProfileAuthStatus, + refreshCurrentOrcaProfileAuth +} from './profile-cloud-service' + +const cloudSummary: OrcaProfileCloudSummary = { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com', + displayName: 'Nina', + linkedAt: 10 +} + +const capabilities: OrcaCloudCapabilities = { + flags: { share: true }, + refreshedAt: 11 +} + +const organizations: OrcaCloudOrgSummary[] = [ + { orgId: 'org-1', name: 'Acme', role: 'Admin' }, + { orgId: 'org-2', name: 'Personal' } +] + +function futureExpiresAt(): number { + return Date.now() + 3_600_000 +} + +function configureCloudEnv(): void { + vi.stubEnv('ORCA_CLOUD_API_URL', 'https://orca-cloud.example') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', 'desktop-client') +} + +function mockSuccessfulConnect(expiresAt = futureExpiresAt()): void { + beginOrcaCloudPkceFlowMock.mockResolvedValue({ + code: 'auth-code', + codeVerifier: 'code-verifier', + nonce: 'nonce', + redirectUri: 'http://127.0.0.1:4100/auth/callback', + state: 'state' + }) + exchangeOrcaCloudAuthCodeMock.mockResolvedValue({ + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt, + cloud: cloudSummary, + organizations, + capabilities + } satisfies OrcaCloudSessionExchangeResponse) +} + +describe('Orca cloud profile service session refresh', () => { + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-cloud-service-refresh-')) + beginOrcaCloudPkceFlowMock.mockReset() + createOrcaCloudProfileMock.mockReset() + exchangeOrcaCloudAuthCodeMock.mockReset() + refreshOrcaCloudCapabilitiesMock.mockReset() + refreshOrcaCloudSessionMock.mockReset() + safeStorageMock.decryptString.mockReset() + safeStorageMock.encryptString.mockReset() + safeStorageMock.isEncryptionAvailable.mockReset() + safeStorageMock.decryptString.mockImplementation((value: Buffer) => value.toString('utf-8')) + safeStorageMock.encryptString.mockImplementation((value: string) => Buffer.from(value, 'utf-8')) + safeStorageMock.isEncryptionAvailable.mockReturnValue(true) + vi.unstubAllEnvs() + vi.stubEnv('ORCA_CLOUD_API_URL', '') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', '') + }) + + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('refreshes an expired access token before creating cloud profiles', async () => { + configureCloudEnv() + mockSuccessfulConnect(Date.now() - 1_000) + await connectCurrentOrcaProfile(userDataPath) + refreshOrcaCloudSessionMock.mockResolvedValue({ + accessToken: 'rotated-access-token', + refreshToken: 'rotated-refresh-token', + expiresAt: futureExpiresAt(), + cloud: cloudSummary, + organizations, + capabilities + } satisfies OrcaCloudSessionExchangeResponse) + createOrcaCloudProfileMock.mockResolvedValue({ + accessToken: 'new-access-token', + refreshToken: 'new-refresh-token', + expiresAt: futureExpiresAt(), + cloud: { + ...cloudSummary, + cloudProfileId: 'cloud-profile-2', + activeOrgId: 'org-1', + activeOrgName: 'Acme' + }, + organizations, + capabilities + } satisfies OrcaCloudSessionExchangeResponse) + + const result = await createCloudLinkedOrcaProfile(userDataPath, { + orgId: 'org-1', + name: 'Acme' + }) + + expect(result.status).toBe('created') + expect(refreshOrcaCloudSessionMock).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ refreshToken: 'refresh-token' }) + ) + expect(createOrcaCloudProfileMock).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ accessToken: 'rotated-access-token' }), + { orgId: 'org-1', name: 'Acme' } + ) + }) + + it('refreshes capability flags for the connected profile', async () => { + configureCloudEnv() + mockSuccessfulConnect() + await connectCurrentOrcaProfile(userDataPath) + refreshOrcaCloudCapabilitiesMock.mockResolvedValue({ + capabilities: { + flags: { share: false, team: true }, + refreshedAt: 25 + } + }) + + const result = await refreshCurrentOrcaProfileAuth(userDataPath) + + expect(result.status).toBe('refreshed') + expect(refreshOrcaCloudCapabilitiesMock).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ accessToken: 'access-token' }) + ) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).capabilities).toEqual({ + flags: { share: false, team: true }, + refreshedAt: 25 + }) + }) + + it('clears stale active org metadata when capability refresh returns no active org', async () => { + configureCloudEnv() + mockSuccessfulConnect() + exchangeOrcaCloudAuthCodeMock.mockResolvedValue({ + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: futureExpiresAt(), + cloud: { ...cloudSummary, activeOrgId: 'org-1', activeOrgName: 'Acme' }, + organizations, + capabilities + } satisfies OrcaCloudSessionExchangeResponse) + await connectCurrentOrcaProfile(userDataPath) + refreshOrcaCloudCapabilitiesMock.mockResolvedValue({ + cloud: cloudSummary, + organizations: [], + capabilities: { + flags: { share: false }, + refreshedAt: 31 + } + }) + + const result = await refreshCurrentOrcaProfileAuth(userDataPath) + const status = getCurrentOrcaProfileAuthStatus(userDataPath) + + expect(result.status).toBe('refreshed') + expect(status.cloud?.activeOrgId).toBeUndefined() + expect(status.cloud?.activeOrgName).toBeUndefined() + expect(status.organizations).toEqual([]) + expect(status.capabilities).toEqual({ + flags: { share: false }, + refreshedAt: 31 + }) + }) + + it('requires reconnect when an expired refresh token is rejected', async () => { + configureCloudEnv() + mockSuccessfulConnect(Date.now() - 1_000) + await connectCurrentOrcaProfile(userDataPath) + refreshOrcaCloudSessionMock.mockRejectedValue(new OrcaCloudRequestErrorMock(401)) + + const result = await refreshCurrentOrcaProfileAuth(userDataPath) + + expect(result.status).toBe('reconnect-required') + expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ + state: 'reconnect-required', + persistence: 'none', + cloud: cloudSummary + }) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-service.test.ts b/src/main/orca-profiles/profile-cloud-service.test.ts new file mode 100644 index 000000000000..552a2ee8ea12 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-service.test.ts @@ -0,0 +1,285 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { + OrcaCloudCapabilities, + OrcaCloudOrgSummary, + OrcaProfileCloudSummary +} from '../../shared/orca-profiles' +import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' + +const { + beginOrcaCloudPkceFlowMock, + createOrcaCloudProfileMock, + exchangeOrcaCloudAuthCodeMock, + revokeOrcaCloudSessionMock, + selectOrcaCloudOrgMock, + safeStorageMock +} = vi.hoisted(() => ({ + beginOrcaCloudPkceFlowMock: vi.fn(), + createOrcaCloudProfileMock: vi.fn(), + exchangeOrcaCloudAuthCodeMock: vi.fn(), + revokeOrcaCloudSessionMock: vi.fn(), + selectOrcaCloudOrgMock: vi.fn(), + safeStorageMock: { + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + isEncryptionAvailable: vi.fn(() => true) + } +})) + +let userDataPath = '' + +vi.mock('electron', () => ({ + app: { + getPath: () => userDataPath + }, + safeStorage: safeStorageMock +})) + +vi.mock('./profile-cloud-pkce', () => ({ + beginOrcaCloudPkceFlow: beginOrcaCloudPkceFlowMock +})) + +vi.mock('./profile-cloud-client', () => ({ + createOrcaCloudProfile: createOrcaCloudProfileMock, + exchangeOrcaCloudAuthCode: exchangeOrcaCloudAuthCodeMock, + revokeOrcaCloudSession: revokeOrcaCloudSessionMock, + selectOrcaCloudOrg: selectOrcaCloudOrgMock +})) + +import { + connectCurrentOrcaProfile, + createCloudLinkedOrcaProfile, + getCurrentOrcaProfileAuthStatus, + selectCurrentOrcaProfileOrg, + signOutCurrentOrcaProfile +} from './profile-cloud-service' + +const cloudSummary: OrcaProfileCloudSummary = { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com', + displayName: 'Nina', + linkedAt: 10 +} + +const capabilities: OrcaCloudCapabilities = { + flags: { share: true }, + refreshedAt: 11 +} + +const organizations: OrcaCloudOrgSummary[] = [ + { orgId: 'org-1', name: 'Acme', role: 'Admin' }, + { orgId: 'org-2', name: 'Personal' } +] + +function configureCloudEnv(): void { + vi.stubEnv('ORCA_CLOUD_API_URL', 'https://orca-cloud.example') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', 'desktop-client') +} + +function futureExpiresAt(): number { + return Date.now() + 3_600_000 +} + +function mockSuccessfulConnect(expiresAt = futureExpiresAt()): void { + beginOrcaCloudPkceFlowMock.mockResolvedValue({ + code: 'auth-code', + codeVerifier: 'code-verifier', + nonce: 'nonce', + redirectUri: 'http://127.0.0.1:4100/auth/callback', + state: 'state' + }) + exchangeOrcaCloudAuthCodeMock.mockResolvedValue({ + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt, + cloud: cloudSummary, + organizations, + capabilities + } satisfies OrcaCloudSessionExchangeResponse) +} + +describe('Orca cloud profile service', () => { + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-cloud-service-')) + beginOrcaCloudPkceFlowMock.mockReset() + createOrcaCloudProfileMock.mockReset() + exchangeOrcaCloudAuthCodeMock.mockReset() + revokeOrcaCloudSessionMock.mockReset() + selectOrcaCloudOrgMock.mockReset() + safeStorageMock.decryptString.mockReset() + safeStorageMock.encryptString.mockReset() + safeStorageMock.isEncryptionAvailable.mockReset() + safeStorageMock.decryptString.mockImplementation((value: Buffer) => value.toString('utf-8')) + safeStorageMock.encryptString.mockImplementation((value: string) => Buffer.from(value, 'utf-8')) + safeStorageMock.isEncryptionAvailable.mockReturnValue(true) + revokeOrcaCloudSessionMock.mockResolvedValue(undefined) + vi.unstubAllEnvs() + vi.stubEnv('ORCA_CLOUD_API_URL', '') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', '') + }) + + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('reports local unconfigured auth without cloud setup', () => { + expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ + activeProfileId: 'local-default', + configured: false, + state: 'unconfigured', + persistence: 'none' + }) + }) + + it('connects the active local profile without replacing its local profile ID', async () => { + configureCloudEnv() + mockSuccessfulConnect() + + const result = await connectCurrentOrcaProfile(userDataPath) + + if (result.status !== 'connected') { + throw new Error(`Expected connected result, got ${result.status}`) + } + expect(result.activeProfileId).toBe('local-default') + expect(result.profiles[0]).toMatchObject({ + id: 'local-default', + kind: 'cloud-linked', + cloud: cloudSummary + }) + expect(exchangeOrcaCloudAuthCodeMock).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ localProfileId: 'local-default', nonce: 'nonce' }) + ) + expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ + state: 'connected', + persistence: 'encrypted', + cloud: cloudSummary, + organizations, + capabilities + }) + }) + + it('treats provider-denied sign-in as a cancelled connect attempt', async () => { + configureCloudEnv() + beginOrcaCloudPkceFlowMock.mockRejectedValue(new Error('orca_cloud_auth_denied')) + + const result = await connectCurrentOrcaProfile(userDataPath) + + expect(result.status).toBe('cancelled') + expect(exchangeOrcaCloudAuthCodeMock).not.toHaveBeenCalled() + expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ + state: 'local', + persistence: 'none' + }) + }) + + it('does not report a saved cloud session as connected when cloud config is unavailable', async () => { + configureCloudEnv() + mockSuccessfulConnect() + await connectCurrentOrcaProfile(userDataPath) + vi.stubEnv('ORCA_CLOUD_API_URL', '') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', '') + + expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ + configured: false, + state: 'unconfigured', + persistence: 'encrypted', + cloud: cloudSummary, + setupMessage: 'Orca Cloud sign-in is not configured for this build.' + }) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).organizations).toBeUndefined() + expect(getCurrentOrcaProfileAuthStatus(userDataPath).capabilities).toBeUndefined() + }) + + it('signs out by removing cloud metadata while keeping the local profile', async () => { + configureCloudEnv() + mockSuccessfulConnect() + await connectCurrentOrcaProfile(userDataPath) + + const result = await signOutCurrentOrcaProfile(userDataPath) + + expect(result.status).toBe('signed-out') + expect(result.activeProfileId).toBe('local-default') + expect(result.profiles[0]).toMatchObject({ id: 'local-default', kind: 'local' }) + expect(result.profiles[0]?.cloud).toBeUndefined() + expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ + state: 'local', + persistence: 'none' + }) + expect(revokeOrcaCloudSessionMock).toHaveBeenCalledOnce() + }) + + it('creates a new empty cloud-linked profile with its own cloud session', async () => { + configureCloudEnv() + mockSuccessfulConnect() + await connectCurrentOrcaProfile(userDataPath) + createOrcaCloudProfileMock.mockResolvedValue({ + accessToken: 'new-access-token', + refreshToken: 'new-refresh-token', + expiresAt: 1000, + cloud: { + ...cloudSummary, + cloudProfileId: 'cloud-profile-2', + activeOrgId: 'org-1', + activeOrgName: 'Acme' + }, + organizations, + capabilities: { flags: { share: true, team: true }, refreshedAt: 13 } + } satisfies OrcaCloudSessionExchangeResponse) + + const result = await createCloudLinkedOrcaProfile(userDataPath, { + orgId: 'org-1', + name: 'Acme' + }) + + if (result.status !== 'created') { + throw new Error(`Expected created result, got ${result.status}`) + } + expect(result.profile).toMatchObject({ + id: expect.stringMatching(/^cloud-/), + name: 'Acme', + kind: 'cloud-linked', + cloud: expect.objectContaining({ cloudProfileId: 'cloud-profile-2' }) + }) + expect(createOrcaCloudProfileMock).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ accessToken: 'access-token' }), + { orgId: 'org-1', name: 'Acme' } + ) + }) + + it('selects an organization for a connected profile', async () => { + configureCloudEnv() + mockSuccessfulConnect() + await connectCurrentOrcaProfile(userDataPath) + const orgCloudSummary = { + ...cloudSummary, + activeOrgId: 'org-1', + activeOrgName: 'Acme' + } + selectOrcaCloudOrgMock.mockResolvedValue({ + cloud: orgCloudSummary, + organizations, + capabilities: { flags: { share: true, sso: true }, refreshedAt: 12 } + }) + + const result = await selectCurrentOrcaProfileOrg(userDataPath, 'org-1') + + expect(result.status).toBe('selected') + expect(selectOrcaCloudOrgMock).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ accessToken: 'access-token' }), + 'org-1' + ) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).cloud).toMatchObject({ + activeOrgId: 'org-1', + activeOrgName: 'Acme' + }) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).organizations).toEqual(organizations) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts new file mode 100644 index 000000000000..df735a812202 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -0,0 +1,300 @@ +import type { + ConnectCurrentOrcaProfileResult, + CreateCloudLinkedOrcaProfileArgs, + CreateCloudLinkedOrcaProfileResult, + OrcaProfileAuthStatus, + RefreshCurrentOrcaProfileAuthResult, + SelectOrcaProfileOrgResult, + SignOutCurrentOrcaProfileResult +} from '../../shared/orca-profiles' +import { ensureActiveOrcaProfile, getOrcaProfileListState } from './profile-index-store' +import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from './profile-cloud-auth-config' +import { + clearOrcaCloudSession, + readOrcaCloudSession, + saveOrcaCloudSession, + saveOrcaCloudSessionExchange +} from './profile-cloud-session-store' +import { + createOrcaCloudProfile, + exchangeOrcaCloudAuthCode, + refreshOrcaCloudCapabilities, + revokeOrcaCloudSession, + selectOrcaCloudOrg +} from './profile-cloud-client' +import { beginOrcaCloudPkceFlow } from './profile-cloud-pkce' +import { + createCloudLinkedOrcaProfileRecord, + linkOrcaProfileToCloud, + unlinkOrcaProfileFromCloud +} from './profile-cloud-index' +import { runWithFreshOrcaCloudSession } from './profile-cloud-session-refresh' +import { + connectDevOrcaCloudProfile, + createDevCloudLinkedOrcaProfile, + refreshDevOrcaCloudProfile, + selectDevOrcaCloudOrg +} from './profile-cloud-dev-service' +import { getOrcaProfileAuthStatusFromProfile } from './profile-cloud-auth-status' + +function isUserCancelledAuthError(message: string): boolean { + return message === 'orca_cloud_auth_timeout' || message === 'orca_cloud_auth_denied' +} + +function activeAuth( + active: ReturnType, + userDataPath: string +): OrcaProfileAuthStatus { + return getOrcaProfileAuthStatusFromProfile(active, userDataPath) +} + +export function getCurrentOrcaProfileAuthStatus(userDataPath: string): OrcaProfileAuthStatus { + return getOrcaProfileAuthStatusFromProfile(ensureActiveOrcaProfile(userDataPath), userDataPath) +} + +export async function connectCurrentOrcaProfile( + userDataPath: string +): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + if (isOrcaCloudDevAuthEnabled()) { + const list = connectDevOrcaCloudProfile(active, userDataPath) + return { + status: 'connected', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + activeProfileId: list.activeProfileId, + profiles: list.profiles + } + } + + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { + status: 'unconfigured', + auth: activeAuth(active, userDataPath) + } + } + + try { + const code = await beginOrcaCloudPkceFlow(configState.config, active.profile.id) + const exchange = await exchangeOrcaCloudAuthCode(configState.config, { + ...code, + localProfileId: active.profile.id + }) + saveOrcaCloudSessionExchange(active.profile.id, userDataPath, exchange) + const list = linkOrcaProfileToCloud(active.profile.id, exchange.cloud, userDataPath) + return { + status: 'connected', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + activeProfileId: list.activeProfileId, + profiles: list.profiles + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + if (isUserCancelledAuthError(message)) { + return { + status: 'cancelled', + auth: getCurrentOrcaProfileAuthStatus(userDataPath) + } + } + return { + status: 'failed', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + error: message + } + } +} + +export async function signOutCurrentOrcaProfile( + userDataPath: string +): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + const configState = getOrcaCloudAuthConfig() + const session = readOrcaCloudSession(active.profile.id, userDataPath) + if (!isOrcaCloudDevAuthEnabled() && configState.configured && session.status === 'found') { + await revokeOrcaCloudSession(configState.config, session.session).catch(() => undefined) + } + clearOrcaCloudSession(active.profile.id, userDataPath) + const list = unlinkOrcaProfileFromCloud(active.profile.id, userDataPath) + return { + status: 'signed-out', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + activeProfileId: list.activeProfileId, + profiles: list.profiles + } +} + +export async function createCloudLinkedOrcaProfile( + userDataPath: string, + args: CreateCloudLinkedOrcaProfileArgs +): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + if (isOrcaCloudDevAuthEnabled()) { + const result = createDevCloudLinkedOrcaProfile(active, userDataPath, args) + if (result.status !== 'created') { + return { status: 'reconnect-required', auth: activeAuth(active, userDataPath) } + } + return { + status: 'created', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + activeProfileId: result.list.activeProfileId, + profiles: result.list.profiles, + profile: result.list.profile + } + } + + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { status: 'unconfigured', auth: activeAuth(active, userDataPath) } + } + try { + const operation = await runWithFreshOrcaCloudSession( + configState.config, + active, + userDataPath, + (session) => createOrcaCloudProfile(configState.config, session, args) + ) + if (operation.status !== 'ok') { + return { status: 'reconnect-required', auth: activeAuth(active, userDataPath) } + } + const created = operation.value + const list = createCloudLinkedOrcaProfileRecord( + created.cloud, + { name: args.name }, + userDataPath + ) + saveOrcaCloudSessionExchange(list.profile.id, userDataPath, created) + return { + status: 'created', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + activeProfileId: list.activeProfileId, + profiles: list.profiles, + profile: list.profile + } + } catch (error) { + return { + status: 'failed', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + error: error instanceof Error ? error.message : String(error) + } + } +} + +export async function refreshCurrentOrcaProfileAuth( + userDataPath: string +): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + if (!active.profile.cloud) { + return { status: 'local', auth: activeAuth(active, userDataPath) } + } + if (isOrcaCloudDevAuthEnabled()) { + const result = refreshDevOrcaCloudProfile(active, userDataPath) + if (result.status !== 'updated') { + return { status: 'reconnect-required', auth: getCurrentOrcaProfileAuthStatus(userDataPath) } + } + return { + status: 'refreshed', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + activeProfileId: result.list.activeProfileId, + profiles: result.list.profiles + } + } + + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { status: 'unconfigured', auth: activeAuth(active, userDataPath) } + } + try { + const operation = await runWithFreshOrcaCloudSession( + configState.config, + active, + userDataPath, + (session) => refreshOrcaCloudCapabilities(configState.config, session) + ) + if (operation.status !== 'ok') { + return { status: 'reconnect-required', auth: getCurrentOrcaProfileAuthStatus(userDataPath) } + } + const refresh = operation.value + const session = readOrcaCloudSession(active.profile.id, userDataPath) + if (session.status !== 'found') { + return { status: 'reconnect-required', auth: getCurrentOrcaProfileAuthStatus(userDataPath) } + } + saveOrcaCloudSession(active.profile.id, userDataPath, { + ...session.session, + organizations: refresh.organizations ?? session.session.organizations, + capabilities: refresh.capabilities + }) + const list = refresh.cloud + ? linkOrcaProfileToCloud(active.profile.id, refresh.cloud, userDataPath) + : getOrcaProfileListState(userDataPath) + return { + status: 'refreshed', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + activeProfileId: list.activeProfileId, + profiles: list.profiles + } + } catch (error) { + return { + status: 'failed', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + error: error instanceof Error ? error.message : String(error) + } + } +} + +export async function selectCurrentOrcaProfileOrg( + userDataPath: string, + orgId: string +): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + if (isOrcaCloudDevAuthEnabled()) { + const result = selectDevOrcaCloudOrg(active, userDataPath, orgId) + if (result.status !== 'updated') { + return { status: 'reconnect-required', auth: activeAuth(active, userDataPath) } + } + return { + status: 'selected', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + activeProfileId: result.list.activeProfileId, + profiles: result.list.profiles + } + } + + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { status: 'unconfigured', auth: activeAuth(active, userDataPath) } + } + try { + const operation = await runWithFreshOrcaCloudSession( + configState.config, + active, + userDataPath, + (session) => selectOrcaCloudOrg(configState.config, session, orgId) + ) + if (operation.status !== 'ok') { + return { status: 'reconnect-required', auth: activeAuth(active, userDataPath) } + } + const selected = operation.value + const session = readOrcaCloudSession(active.profile.id, userDataPath) + if (session.status !== 'found') { + return { status: 'reconnect-required', auth: activeAuth(active, userDataPath) } + } + saveOrcaCloudSession(active.profile.id, userDataPath, { + ...session.session, + organizations: selected.organizations ?? session.session.organizations, + capabilities: selected.capabilities + }) + const list = linkOrcaProfileToCloud(active.profile.id, selected.cloud, userDataPath) + return { + status: 'selected', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + activeProfileId: list.activeProfileId, + profiles: list.profiles + } + } catch (error) { + return { + status: 'failed', + auth: getCurrentOrcaProfileAuthStatus(userDataPath), + error: error instanceof Error ? error.message : String(error) + } + } +} diff --git a/src/main/orca-profiles/profile-cloud-session-exchange.ts b/src/main/orca-profiles/profile-cloud-session-exchange.ts new file mode 100644 index 000000000000..d3dff43816fd --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-session-exchange.ts @@ -0,0 +1,14 @@ +import type { + OrcaCloudCapabilities, + OrcaCloudOrgSummary, + OrcaProfileCloudSummary +} from '../../shared/orca-profiles' + +export type OrcaCloudSessionExchangeResponse = { + accessToken: string + refreshToken: string + expiresAt: number + cloud: OrcaProfileCloudSummary + organizations?: OrcaCloudOrgSummary[] + capabilities: OrcaCloudCapabilities +} diff --git a/src/main/orca-profiles/profile-cloud-session-refresh.ts b/src/main/orca-profiles/profile-cloud-session-refresh.ts new file mode 100644 index 000000000000..404cba47bd47 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-session-refresh.ts @@ -0,0 +1,178 @@ +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' +import type { ActiveOrcaProfileState } from './profile-index-store' +import { + clearOrcaCloudSession, + type OrcaCloudSession, + readOrcaCloudSession, + saveOrcaCloudSession +} from './profile-cloud-session-store' +import { OrcaCloudRequestError, refreshOrcaCloudSession } from './profile-cloud-client' +import { linkOrcaProfileToCloud } from './profile-cloud-index' + +const CLOUD_SESSION_REFRESH_SKEW_MS = 60_000 + +export type FreshCloudSessionResult = + | { status: 'found'; session: OrcaCloudSession } + | { status: 'reconnect-required' } + +export type CloudSessionOperationResult = + | { status: 'ok'; value: T } + | { status: 'reconnect-required' } + +function shouldRefreshCloudSession(session: OrcaCloudSession, now = Date.now()): boolean { + return session.expiresAt <= now + CLOUD_SESSION_REFRESH_SKEW_MS +} + +export function isOrcaCloudAuthFailure(error: unknown): boolean { + return ( + error instanceof OrcaCloudRequestError && (error.statusCode === 401 || error.statusCode === 403) + ) +} + +const inflightCloudSessionRefreshes = new Map>() + +function cloudSessionRefreshKey(profileId: string, userDataPath: string): string { + return `${userDataPath}\0${profileId}` +} + +// Why: with refresh-token rotation, only the session that actually failed may +// clear the store; otherwise a loser of a concurrent refresh race would wipe +// the winner's freshly rotated session. +function clearCloudSessionIfUnchanged( + profileId: string, + userDataPath: string, + failed: OrcaCloudSession +): void { + const current = readOrcaCloudSession(profileId, userDataPath) + if (current.status === 'found' && current.session.refreshToken !== failed.refreshToken) { + return + } + clearOrcaCloudSession(profileId, userDataPath) +} + +async function refreshStoredCloudSession( + config: OrcaCloudAuthConfig, + active: ActiveOrcaProfileState, + userDataPath: string, + session: OrcaCloudSession +): Promise { + // Why: refresh tokens rotate, so concurrent refreshes must single-flight; + // a second POST with the same refresh token can trip server reuse detection + // and revoke the whole token family. + const key = cloudSessionRefreshKey(active.profile.id, userDataPath) + const inflight = inflightCloudSessionRefreshes.get(key) + if (inflight) { + return inflight + } + const task = (async () => { + const current = readOrcaCloudSession(active.profile.id, userDataPath) + if (current.status === 'found' && current.session.refreshToken !== session.refreshToken) { + // Another caller already rotated this session; reuse its result. + return current.session + } + const refreshed = await refreshOrcaCloudSession(config, session) + const nextSession = { + accessToken: refreshed.accessToken, + refreshToken: refreshed.refreshToken, + expiresAt: refreshed.expiresAt, + organizations: refreshed.organizations, + capabilities: refreshed.capabilities + } + saveOrcaCloudSession(active.profile.id, userDataPath, nextSession) + linkOrcaProfileToCloud(active.profile.id, refreshed.cloud, userDataPath) + return nextSession + })() + inflightCloudSessionRefreshes.set(key, task) + try { + return await task + } finally { + inflightCloudSessionRefreshes.delete(key) + } +} + +export async function readFreshOrcaCloudSession( + config: OrcaCloudAuthConfig, + active: ActiveOrcaProfileState, + userDataPath: string +): Promise { + const session = readOrcaCloudSession(active.profile.id, userDataPath) + if (session.status !== 'found') { + return { status: 'reconnect-required' } + } + if (!shouldRefreshCloudSession(session.session)) { + return { status: 'found', session: session.session } + } + try { + return { + status: 'found', + session: await refreshStoredCloudSession(config, active, userDataPath, session.session) + } + } catch (error) { + if (isOrcaCloudAuthFailure(error)) { + clearCloudSessionIfUnchanged(active.profile.id, userDataPath, session.session) + return { status: 'reconnect-required' } + } + throw error + } +} + +export async function forceRefreshOrcaCloudSession( + config: OrcaCloudAuthConfig, + active: ActiveOrcaProfileState, + userDataPath: string, + session: OrcaCloudSession +): Promise { + try { + return { + status: 'found', + session: await refreshStoredCloudSession(config, active, userDataPath, session) + } + } catch (error) { + if (isOrcaCloudAuthFailure(error)) { + clearCloudSessionIfUnchanged(active.profile.id, userDataPath, session) + return { status: 'reconnect-required' } + } + throw error + } +} + +export async function runWithFreshOrcaCloudSession( + config: OrcaCloudAuthConfig, + active: ActiveOrcaProfileState, + userDataPath: string, + operation: (session: OrcaCloudSession) => Promise +): Promise> { + const session = await readFreshOrcaCloudSession(config, active, userDataPath) + if (session.status !== 'found') { + return { status: 'reconnect-required' } + } + try { + return { status: 'ok', value: await operation(session.session) } + } catch (error) { + if (!isOrcaCloudAuthFailure(error)) { + throw error + } + const refreshed = await forceRefreshOrcaCloudSession( + config, + active, + userDataPath, + session.session + ) + if (refreshed.status !== 'found') { + return { status: 'reconnect-required' } + } + try { + return { status: 'ok', value: await operation(refreshed.session) } + } catch (retryError) { + // Why: a 401 after a successful refresh means the session itself is + // rejected. A 403 is an authorization (permission) failure — signing + // the user out for it would destroy a valid session, so let it surface + // as a failed operation instead. + if (retryError instanceof OrcaCloudRequestError && retryError.statusCode === 401) { + clearCloudSessionIfUnchanged(active.profile.id, userDataPath, refreshed.session) + return { status: 'reconnect-required' } + } + throw retryError + } + } +} diff --git a/src/main/orca-profiles/profile-cloud-session-store.test.ts b/src/main/orca-profiles/profile-cloud-session-store.test.ts new file mode 100644 index 000000000000..ca32f0529f12 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-session-store.test.ts @@ -0,0 +1,172 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { OrcaCloudSession } from './profile-cloud-session-store' + +const safeStorageMock = vi.hoisted(() => ({ + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + isEncryptionAvailable: vi.fn(() => true) +})) + +let userDataPath = '' + +vi.mock('electron', () => ({ + app: { + getPath: () => userDataPath + }, + safeStorage: safeStorageMock +})) + +async function loadSessionStore() { + vi.resetModules() + return import('./profile-cloud-session-store') +} + +function makeSession(): OrcaCloudSession { + return { + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: 9_999, + organizations: [ + { orgId: 'org-1', name: 'Acme', role: 'Admin' }, + { orgId: 'org-2', name: 'Personal' } + ], + capabilities: { + flags: { share: true }, + refreshedAt: 123 + } + } +} + +function writePlaintextSessionFile(profileId: string, session: OrcaCloudSession): void { + const profileDirectory = join(userDataPath, 'profiles', profileId) + mkdirSync(profileDirectory, { recursive: true }) + writeFileSync( + join(profileDirectory, 'account-session.json.enc'), + JSON.stringify( + { + version: 1, + format: 'dev-plaintext-v1', + savedAt: 1, + session + }, + null, + 2 + ), + 'utf-8' + ) +} + +describe('Orca cloud session store', () => { + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-cloud-session-')) + vi.unstubAllEnvs() + safeStorageMock.decryptString.mockClear() + safeStorageMock.encryptString.mockClear() + safeStorageMock.isEncryptionAvailable.mockClear() + safeStorageMock.isEncryptionAvailable.mockReturnValue(true) + }) + + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('persists encrypted sessions and reports encrypted persistence from memory and disk', async () => { + const store = await loadSessionStore() + const session = makeSession() + + expect(store.saveOrcaCloudSession('profile-1', userDataPath, session)).toBe('encrypted') + expect(store.readOrcaCloudSession('profile-1', userDataPath)).toEqual({ + status: 'found', + session, + persistence: 'encrypted' + }) + + const reloaded = await loadSessionStore() + expect(reloaded.readOrcaCloudSession('profile-1', userDataPath)).toEqual({ + status: 'found', + session, + persistence: 'encrypted' + }) + }) + + it('falls back to memory-only when encryption is unavailable and plaintext is not allowed', async () => { + safeStorageMock.isEncryptionAvailable.mockReturnValue(false) + const store = await loadSessionStore() + const session = makeSession() + + expect(store.saveOrcaCloudSession('profile-1', userDataPath, session)).toBe('memory-only') + expect(store.readOrcaCloudSession('profile-1', userDataPath)).toEqual({ + status: 'found', + session, + persistence: 'memory-only' + }) + + const reloaded = await loadSessionStore() + expect(reloaded.readOrcaCloudSession('profile-1', userDataPath)).toEqual({ + status: 'missing', + persistence: 'none' + }) + }) + + it('scopes memory-only sessions by user-data path and profile ID', async () => { + safeStorageMock.isEncryptionAvailable.mockReturnValue(false) + const otherUserDataPath = mkdtempSync(join(tmpdir(), 'orca-cloud-session-other-')) + const store = await loadSessionStore() + const session = makeSession() + const otherSession = { ...session, accessToken: 'other-access-token' } + + try { + store.saveOrcaCloudSession('local-default', userDataPath, session) + store.saveOrcaCloudSession('local-default', otherUserDataPath, otherSession) + + expect(store.readOrcaCloudSession('local-default', userDataPath)).toMatchObject({ + status: 'found', + session + }) + expect(store.readOrcaCloudSession('local-default', otherUserDataPath)).toMatchObject({ + status: 'found', + session: otherSession + }) + } finally { + rmSync(otherUserDataPath, { recursive: true, force: true }) + } + }) + + it('writes explicit dev plaintext only when the dev escape hatch is enabled', async () => { + safeStorageMock.isEncryptionAvailable.mockReturnValue(false) + vi.stubEnv('ORCA_CLOUD_ALLOW_PLAINTEXT_SESSION', '1') + vi.stubEnv('NODE_ENV', 'development') + const store = await loadSessionStore() + const session = makeSession() + + expect(store.saveOrcaCloudSession('profile-1', userDataPath, session)).toBe('dev-plaintext') + + const saved = JSON.parse( + readFileSync(store.getOrcaCloudSessionPath('profile-1', userDataPath), 'utf-8') + ) as { format: string } + expect(saved.format).toBe('dev-plaintext-v1') + + const reloaded = await loadSessionStore() + expect(reloaded.readOrcaCloudSession('profile-1', userDataPath)).toEqual({ + status: 'found', + session, + persistence: 'dev-plaintext' + }) + }) + + it('rejects dev plaintext files when the escape hatch is disabled', async () => { + safeStorageMock.isEncryptionAvailable.mockReturnValue(false) + writePlaintextSessionFile('profile-1', makeSession()) + const store = await loadSessionStore() + + expect(store.readOrcaCloudSession('profile-1', userDataPath)).toEqual({ + status: 'decrypt-failed', + persistence: 'none', + error: 'Unsafe session format.' + }) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-session-store.ts b/src/main/orca-profiles/profile-cloud-session-store.ts new file mode 100644 index 000000000000..a8914b8f7a3e --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-session-store.ts @@ -0,0 +1,209 @@ +import { existsSync, readFileSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { safeStorage } from 'electron' +import { writeSecureJsonFile } from '../../shared/secure-file' +import type { + OrcaCloudCapabilities, + OrcaCloudOrgSummary, + OrcaCloudSessionPersistence +} from '../../shared/orca-profiles' +import { getOrcaProfileDirectory } from './profile-storage-paths' +import { allowsPlaintextOrcaCloudSession } from './profile-cloud-auth-config' +import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' + +export type OrcaCloudSession = { + accessToken: string + refreshToken: string + expiresAt: number + capabilities: OrcaCloudCapabilities + organizations?: OrcaCloudOrgSummary[] +} + +export type OrcaCloudSessionReadResult = + | { status: 'found'; session: OrcaCloudSession; persistence: OrcaCloudSessionPersistence } + | { status: 'missing'; persistence: 'none' } + | { status: 'decrypt-failed'; persistence: 'none'; error: string } + +type PersistedEncryptedSession = { + version: 1 + format: 'electron-safe-storage-v1' + savedAt: number + ciphertext: string +} + +type PersistedPlaintextSession = { + version: 1 + format: 'dev-plaintext-v1' + savedAt: number + session: OrcaCloudSession +} + +type CachedOrcaCloudSession = { + session: OrcaCloudSession + persistence: Exclude +} + +const memorySessions = new Map() + +function sessionCacheKey(profileId: string, userDataPath: string): string { + return `${userDataPath}\0${profileId}` +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function isOrcaCloudSession(value: unknown): value is OrcaCloudSession { + if (!isObject(value) || !isObject(value.capabilities) || !isObject(value.capabilities.flags)) { + return false + } + if (value.organizations !== undefined && !isOrcaCloudOrganizations(value.organizations)) { + return false + } + return ( + typeof value.accessToken === 'string' && + value.accessToken.length > 0 && + typeof value.refreshToken === 'string' && + value.refreshToken.length > 0 && + typeof value.expiresAt === 'number' && + Number.isFinite(value.expiresAt) && + typeof value.capabilities.refreshedAt === 'number' && + Number.isFinite(value.capabilities.refreshedAt) + ) +} + +function isOrcaCloudOrganizations(value: unknown): value is OrcaCloudOrgSummary[] { + if (!Array.isArray(value)) { + return false + } + return value.every((organization) => { + if (!isObject(organization)) { + return false + } + return ( + typeof organization.orgId === 'string' && + organization.orgId.length > 0 && + typeof organization.name === 'string' && + organization.name.length > 0 && + (organization.role === undefined || typeof organization.role === 'string') + ) + }) +} + +export function getOrcaCloudSessionPath(profileId: string, userDataPath: string): string { + return join(getOrcaProfileDirectory(profileId, userDataPath), 'account-session.json.enc') +} + +export function saveOrcaCloudSession( + profileId: string, + userDataPath: string, + session: OrcaCloudSession +): OrcaCloudSessionPersistence { + const cacheKey = sessionCacheKey(profileId, userDataPath) + if (safeStorage.isEncryptionAvailable()) { + const encrypted: PersistedEncryptedSession = { + version: 1, + format: 'electron-safe-storage-v1', + savedAt: Date.now(), + ciphertext: safeStorage.encryptString(JSON.stringify(session)).toString('base64') + } + writeSecureJsonFile(getOrcaCloudSessionPath(profileId, userDataPath), encrypted) + memorySessions.set(cacheKey, { session, persistence: 'encrypted' }) + return 'encrypted' + } + + if (allowsPlaintextOrcaCloudSession()) { + const plaintext: PersistedPlaintextSession = { + version: 1, + format: 'dev-plaintext-v1', + savedAt: Date.now(), + session + } + writeSecureJsonFile(getOrcaCloudSessionPath(profileId, userDataPath), plaintext) + memorySessions.set(cacheKey, { session, persistence: 'dev-plaintext' }) + return 'dev-plaintext' + } + + // Why: Orca account refresh tokens must not silently fall back to plaintext + // in production. Memory-only keeps cloud features usable until restart. + memorySessions.set(cacheKey, { session, persistence: 'memory-only' }) + return 'memory-only' +} + +export function saveOrcaCloudSessionExchange( + profileId: string, + userDataPath: string, + exchange: OrcaCloudSessionExchangeResponse +): OrcaCloudSessionPersistence { + return saveOrcaCloudSession(profileId, userDataPath, { + accessToken: exchange.accessToken, + refreshToken: exchange.refreshToken, + expiresAt: exchange.expiresAt, + organizations: exchange.organizations, + capabilities: exchange.capabilities + }) +} + +export function readOrcaCloudSession( + profileId: string, + userDataPath: string +): OrcaCloudSessionReadResult { + const cacheKey = sessionCacheKey(profileId, userDataPath) + const memorySession = memorySessions.get(cacheKey) + if (memorySession) { + return { + status: 'found', + session: memorySession.session, + persistence: memorySession.persistence + } + } + + const path = getOrcaCloudSessionPath(profileId, userDataPath) + if (!existsSync(path)) { + return { status: 'missing', persistence: 'none' } + } + + try { + const parsed = JSON.parse(readFileSync(path, 'utf-8')) as + | PersistedEncryptedSession + | PersistedPlaintextSession + if (parsed.version !== 1) { + return { status: 'decrypt-failed', persistence: 'none', error: 'Unsupported session format.' } + } + if (parsed.format === 'electron-safe-storage-v1') { + if (!safeStorage.isEncryptionAvailable()) { + return { + status: 'decrypt-failed', + persistence: 'none', + error: 'OS-backed encryption is unavailable.' + } + } + const decrypted = safeStorage.decryptString(Buffer.from(parsed.ciphertext, 'base64')) + const session = JSON.parse(decrypted) as OrcaCloudSession + if (!isOrcaCloudSession(session)) { + return { status: 'decrypt-failed', persistence: 'none', error: 'Invalid saved session.' } + } + memorySessions.set(cacheKey, { session, persistence: 'encrypted' }) + return { status: 'found', session, persistence: 'encrypted' } + } + if (parsed.format === 'dev-plaintext-v1' && allowsPlaintextOrcaCloudSession()) { + if (!isOrcaCloudSession(parsed.session)) { + return { status: 'decrypt-failed', persistence: 'none', error: 'Invalid saved session.' } + } + memorySessions.set(cacheKey, { session: parsed.session, persistence: 'dev-plaintext' }) + return { status: 'found', session: parsed.session, persistence: 'dev-plaintext' } + } + return { status: 'decrypt-failed', persistence: 'none', error: 'Unsafe session format.' } + } catch { + return { + status: 'decrypt-failed', + persistence: 'none', + error: 'Could not decrypt saved Orca account session.' + } + } +} + +export function clearOrcaCloudSession(profileId: string, userDataPath: string): void { + memorySessions.delete(sessionCacheKey(profileId, userDataPath)) + rmSync(getOrcaCloudSessionPath(profileId, userDataPath), { force: true }) +} diff --git a/src/main/orca-profiles/profile-index-store.test.ts b/src/main/orca-profiles/profile-index-store.test.ts new file mode 100644 index 000000000000..a2d3446a99cc --- /dev/null +++ b/src/main/orca-profiles/profile-index-store.test.ts @@ -0,0 +1,198 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { + DEFAULT_LOCAL_ORCA_PROFILE_ID, + DEFAULT_LOCAL_ORCA_PROFILE_NAME, + ORCA_PROFILE_INDEX_SCHEMA_VERSION, + type OrcaProfileIndex +} from '../../shared/orca-profiles' + +const testState = { dir: '' } + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.dir + } +})) + +async function loadProfileIndexStore() { + vi.resetModules() + return import('./profile-index-store') +} + +function readJson(path: string): unknown { + return JSON.parse(readFileSync(path, 'utf-8')) +} + +describe('profile index store', () => { + beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-profile-test-')) + }) + + afterEach(() => { + rmSync(testState.dir, { recursive: true, force: true }) + }) + + it('creates the default local profile and copies legacy state without deleting it', async () => { + const legacyState = { schemaVersion: 1, repos: [{ id: 'repo-1' }] } + const legacyBackup = { schemaVersion: 1, repos: [{ id: 'backup-repo' }] } + const legacyBrowserSessionMeta = { + defaultSource: { browserFamily: 'chrome', importedAt: 1 }, + profiles: [] + } + writeFileSync(join(testState.dir, 'orca-data.json'), JSON.stringify(legacyState), 'utf-8') + writeFileSync( + join(testState.dir, 'orca-data.json.bak.0'), + JSON.stringify(legacyBackup), + 'utf-8' + ) + writeFileSync( + join(testState.dir, 'browser-session-meta.json'), + JSON.stringify(legacyBrowserSessionMeta), + 'utf-8' + ) + + const { ensureActiveOrcaProfile, getOrcaProfileIndexPath } = await loadProfileIndexStore() + const activeProfile = ensureActiveOrcaProfile() + + expect(activeProfile.profile.id).toBe(DEFAULT_LOCAL_ORCA_PROFILE_ID) + expect(activeProfile.profile.name).toBe(DEFAULT_LOCAL_ORCA_PROFILE_NAME) + expect(activeProfile.dataFile).toBe( + join(testState.dir, 'profiles', DEFAULT_LOCAL_ORCA_PROFILE_ID, 'orca-data.json') + ) + expect(readJson(activeProfile.dataFile)).toEqual(legacyState) + expect(readJson(`${activeProfile.dataFile}.bak.0`)).toEqual(legacyBackup) + expect( + readJson( + join(testState.dir, 'profiles', DEFAULT_LOCAL_ORCA_PROFILE_ID, 'browser-session-meta.json') + ) + ).toEqual(legacyBrowserSessionMeta) + expect(existsSync(join(testState.dir, 'orca-data.json'))).toBe(true) + + expect(readJson(getOrcaProfileIndexPath())).toMatchObject({ + schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, + activeProfileId: DEFAULT_LOCAL_ORCA_PROFILE_ID, + profiles: [expect.objectContaining({ id: DEFAULT_LOCAL_ORCA_PROFILE_ID, kind: 'local' })] + }) + }) + + it('uses an existing active profile data file without overwriting it from legacy state', async () => { + const profileId = 'work-profile' + const profileDirectory = join(testState.dir, 'profiles', profileId) + const profileData = { schemaVersion: 1, repos: [{ id: 'profile-repo' }] } + mkdirSync(profileDirectory, { recursive: true }) + writeFileSync(join(profileDirectory, 'orca-data.json'), JSON.stringify(profileData), 'utf-8') + writeFileSync( + join(testState.dir, 'orca-data.json'), + JSON.stringify({ schemaVersion: 1, repos: [{ id: 'legacy-repo' }] }), + 'utf-8' + ) + const index: OrcaProfileIndex = { + schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, + activeProfileId: profileId, + profiles: [ + { + id: profileId, + name: 'Work', + avatar: { kind: 'initials', initials: 'W', color: 'neutral' }, + kind: 'local', + createdAt: 1, + updatedAt: 1, + lastOpenedAt: 1 + } + ] + } + writeFileSync(join(testState.dir, 'orca-profile-index.json'), JSON.stringify(index), 'utf-8') + + const { ensureActiveOrcaProfile } = await loadProfileIndexStore() + const activeProfile = ensureActiveOrcaProfile() + + expect(activeProfile.profile.id).toBe(profileId) + expect(activeProfile.dataFile).toBe(join(profileDirectory, 'orca-data.json')) + expect(readJson(activeProfile.dataFile)).toEqual(profileData) + }) + + it('creates an empty local profile without copying legacy state into it', async () => { + writeFileSync( + join(testState.dir, 'orca-data.json'), + JSON.stringify({ schemaVersion: 1, repos: [{ id: 'legacy-repo' }] }), + 'utf-8' + ) + + const { createLocalOrcaProfile, getOrcaProfileDataFile, getOrcaProfileListState } = + await loadProfileIndexStore() + const created = createLocalOrcaProfile({ name: ' Work ' }) + + expect(created.profile.name).toBe('Work') + expect(created.profile.id).toMatch(/^local-/) + expect(created.activeProfileId).toBe(DEFAULT_LOCAL_ORCA_PROFILE_ID) + expect(created.profiles.map((profile) => profile.id)).toContain(created.profile.id) + expect(existsSync(getOrcaProfileDataFile(created.profile.id))).toBe(false) + expect(getOrcaProfileListState().profiles.map((profile) => profile.id)).toContain( + created.profile.id + ) + }) + + it('switches the active profile and updates last-opened metadata', async () => { + const { createLocalOrcaProfile, setActiveOrcaProfile } = await loadProfileIndexStore() + const created = createLocalOrcaProfile({ name: 'Work' }) + + const switched = setActiveOrcaProfile(created.profile.id) + + expect(switched.activeProfileId).toBe(created.profile.id) + expect(switched.profiles.find((profile) => profile.id === created.profile.id)).toMatchObject({ + id: created.profile.id, + lastOpenedAt: expect.any(Number) + }) + }) + + it('rejects switching to an unknown profile', async () => { + const { setActiveOrcaProfile } = await loadProfileIndexStore() + + expect(() => setActiveOrcaProfile('missing-profile')).toThrow('unknown_orca_profile') + }) + + it('recovers a corrupted profile index from the backup copy', async () => { + const store = await loadProfileIndexStore() + store.ensureActiveOrcaProfile() + const created = store.createLocalOrcaProfile({ name: 'Work' }) + // Trigger one more write so the backup captures the two-profile index. + store.setActiveOrcaProfile(created.profile.id) + + const indexPath = store.getOrcaProfileIndexPath() + expect(existsSync(`${indexPath}.bak`)).toBe(true) + writeFileSync(indexPath, '{ not json', 'utf-8') + + const recovered = store.getOrcaProfileListState() + expect(recovered.profiles.map((profile) => profile.id)).toContain(created.profile.id) + expect(recovered.profiles.length).toBeGreaterThanOrEqual(2) + }) + + it('rejects profile ids that are not safe path segments', async () => { + const store = await loadProfileIndexStore() + const indexPath = store.getOrcaProfileIndexPath() + const index: OrcaProfileIndex = { + schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, + activeProfileId: '../../escape', + profiles: [ + { + id: '../../escape', + name: 'Evil', + avatar: { kind: 'initials', initials: 'E', color: 'neutral' }, + kind: 'local', + createdAt: 1, + updatedAt: 1, + lastOpenedAt: 1 + } + ] + } + mkdirSync(testState.dir, { recursive: true }) + writeFileSync(indexPath, JSON.stringify(index), 'utf-8') + + // The tampered entry is filtered; startup falls back to a fresh default. + const state = store.ensureActiveOrcaProfile() + expect(state.profile.id).toBe(DEFAULT_LOCAL_ORCA_PROFILE_ID) + }) +}) diff --git a/src/main/orca-profiles/profile-index-store.ts b/src/main/orca-profiles/profile-index-store.ts new file mode 100644 index 000000000000..903e7a85ff8d --- /dev/null +++ b/src/main/orca-profiles/profile-index-store.ts @@ -0,0 +1,327 @@ +import { + copyFileSync, + existsSync, + mkdirSync, + readFileSync, + renameSync, + writeFileSync +} from 'node:fs' +import { randomUUID } from 'node:crypto' +import { dirname } from 'node:path' +import type { GlobalSettings } from '../../shared/types' +import { + createDefaultLocalOrcaProfile, + DEFAULT_LOCAL_ORCA_PROFILE_ID, + DEFAULT_LOCAL_ORCA_PROFILE_NAME, + ORCA_PROFILE_INDEX_SCHEMA_VERSION, + type CreateLocalOrcaProfileArgs, + type CreateLocalOrcaProfileResult, + type OrcaProfileIndex, + type OrcaProfileListState, + type OrcaProfileSummary +} from '../../shared/orca-profiles' +import { + getOrcaProfileBrowserSessionMetaFile, + getOrcaProfileDataFile, + getOrcaProfileDirectory, + getOrcaProfileIndexPath, + getProfileUserDataPath, + LEGACY_BACKUP_COUNT, + legacyBackupPath, + legacyBrowserSessionMetaPath, + legacyDataFilePath, + profileBackupPath +} from './profile-storage-paths' + +export { + getOrcaProfileBrowserSessionMetaFile, + getOrcaProfileDataFile, + getOrcaProfileDirectory, + getOrcaProfileIndexPath, + getOrcaProfilesDirectory, + initOrcaProfilePaths +} from './profile-storage-paths' + +export type ActiveOrcaProfileState = { + index: OrcaProfileIndex + profile: OrcaProfileSummary + dataFile: string + profileDirectory: string +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function isProfileSummary(value: unknown): value is OrcaProfileSummary { + if (!isObject(value)) { + return false + } + const avatar = value.avatar + const cloud = value.cloud + return ( + typeof value.id === 'string' && + // Why: IDs from the on-disk index become filesystem path segments; a + // tampered index must not be able to escape the profiles directory. + /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value.id) && + typeof value.name === 'string' && + value.name.length > 0 && + (value.kind === 'local' || value.kind === 'cloud-linked') && + typeof value.createdAt === 'number' && + typeof value.updatedAt === 'number' && + typeof value.lastOpenedAt === 'number' && + isObject(avatar) && + avatar.kind === 'initials' && + typeof avatar.initials === 'string' && + avatar.color === 'neutral' && + (cloud === undefined || isObject(cloud)) + ) +} + +function normalizeProfileIndex(raw: unknown): OrcaProfileIndex | null { + if (!isObject(raw) || !Array.isArray(raw.profiles)) { + return null + } + const profiles = raw.profiles.filter(isProfileSummary) + const activeProfileId = + typeof raw.activeProfileId === 'string' && + profiles.some((profile) => profile.id === raw.activeProfileId) + ? raw.activeProfileId + : profiles[0]?.id + if (!activeProfileId) { + return null + } + return { + schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, + activeProfileId, + profiles + } +} + +function sanitizeProfileName(value: unknown): string { + const trimmed = typeof value === 'string' ? value.trim() : '' + return trimmed.length > 0 ? trimmed.slice(0, 80) : 'New Profile' +} + +function readProfileIndexFile(indexPath: string): OrcaProfileIndex | null { + try { + return normalizeProfileIndex(JSON.parse(readFileSync(indexPath, 'utf-8'))) + } catch { + return null + } +} + +export function readProfileIndex(indexPath: string): OrcaProfileIndex | null { + // Why: a torn/corrupt index must not silently reset the app to a single + // default profile — that would orphan every other profile's data directory. + return readProfileIndexFile(indexPath) ?? readProfileIndexFile(`${indexPath}.bak`) +} + +export function writeProfileIndex(indexPath: string, index: OrcaProfileIndex): void { + mkdirSync(dirname(indexPath), { recursive: true }) + // Why: only a still-parseable current index may refresh the backup; + // copying a corrupt file over the backup would destroy the recovery copy. + if (existsSync(indexPath) && readProfileIndexFile(indexPath)) { + try { + copyFileSync(indexPath, `${indexPath}.bak`) + } catch { + // Best-effort backup; the primary write below still proceeds. + } + } + const tmpPath = `${indexPath}.tmp` + writeFileSync(tmpPath, JSON.stringify(index, null, 2), 'utf-8') + renameSync(tmpPath, indexPath) +} + +function copyIfPresent(source: string, target: string): void { + if (!existsSync(source) || existsSync(target)) { + return + } + mkdirSync(dirname(target), { recursive: true }) + // Why: tmp+rename so a crash mid-copy cannot leave a truncated target that + // the exists() guard above would then treat as a completed migration. + const tmpTarget = `${target}.tmp` + copyFileSync(source, tmpTarget) + renameSync(tmpTarget, target) +} + +function copyLegacyStateToProfile(userDataPath: string, profileId: string): void { + const profileDataFile = getOrcaProfileDataFile(profileId, userDataPath) + copyIfPresent(legacyDataFilePath(userDataPath), profileDataFile) + copyIfPresent( + legacyBrowserSessionMetaPath(userDataPath), + getOrcaProfileBrowserSessionMetaFile(profileId, userDataPath) + ) + for (let i = 0; i < LEGACY_BACKUP_COUNT; i++) { + copyIfPresent(legacyBackupPath(userDataPath, i), profileBackupPath(profileDataFile, i)) + } +} + +// Why: a brand-new profile has no data file, which the telemetry cohort +// migration reads as a fresh install and defaults to opted-in. Copying the +// active profile's consent block keeps an opted-out user opted out (and keeps +// one installId per install) when they create additional profiles. +export function seedNewOrcaProfileTelemetryConsent( + profileId: string, + telemetry: GlobalSettings['telemetry'], + userDataPath = getProfileUserDataPath() +): void { + if (!telemetry) { + return + } + const dataFile = getOrcaProfileDataFile(profileId, userDataPath) + if (existsSync(dataFile)) { + return + } + mkdirSync(dirname(dataFile), { recursive: true }) + const tmpPath = `${dataFile}.tmp` + writeFileSync(tmpPath, JSON.stringify({ settings: { telemetry } }, null, 2), 'utf-8') + renameSync(tmpPath, dataFile) +} + +function createInitialProfileIndex(now = Date.now()): OrcaProfileIndex { + const profile = createDefaultLocalOrcaProfile(now) + return { + schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, + activeProfileId: profile.id, + profiles: [profile] + } +} + +export function loadOrCreateProfileIndex(userDataPath: string): OrcaProfileIndex { + const indexPath = getOrcaProfileIndexPath(userDataPath) + const index = existsSync(indexPath) ? readProfileIndex(indexPath) : null + if (index) { + return index + } + const nextIndex = createInitialProfileIndex() + writeProfileIndex(indexPath, nextIndex) + return nextIndex +} + +function getActiveProfile(index: OrcaProfileIndex): OrcaProfileSummary { + return ( + index.profiles.find((profile) => profile.id === index.activeProfileId) ?? + index.profiles[0] ?? + createDefaultLocalOrcaProfile(Date.now()) + ) +} + +export function ensureActiveOrcaProfile( + userDataPath = getProfileUserDataPath() +): ActiveOrcaProfileState { + const indexPath = getOrcaProfileIndexPath(userDataPath) + let index = existsSync(indexPath) ? readProfileIndex(indexPath) : null + let shouldWriteIndex = false + + if (!index) { + index = createInitialProfileIndex() + shouldWriteIndex = true + } + + const activeProfile = getActiveProfile(index) + if (activeProfile.id !== index.activeProfileId) { + index = { ...index, activeProfileId: activeProfile.id } + shouldWriteIndex = true + } + + const profileDirectory = getOrcaProfileDirectory(activeProfile.id, userDataPath) + mkdirSync(profileDirectory, { recursive: true }) + if (activeProfile.id === DEFAULT_LOCAL_ORCA_PROFILE_ID) { + copyLegacyStateToProfile(userDataPath, activeProfile.id) + } + + if (shouldWriteIndex) { + writeProfileIndex(indexPath, index) + } + + return { + index, + profile: activeProfile, + dataFile: getOrcaProfileDataFile(activeProfile.id, userDataPath), + profileDirectory + } +} + +export function isDefaultLocalOrcaProfileId(profileId: string): boolean { + return profileId === DEFAULT_LOCAL_ORCA_PROFILE_ID +} + +export function getOrcaProfileListState( + userDataPath = getProfileUserDataPath() +): OrcaProfileListState { + const { index } = ensureActiveOrcaProfile(userDataPath) + return { + activeProfileId: index.activeProfileId, + profiles: index.profiles + } +} + +export function createLocalOrcaProfile( + args: CreateLocalOrcaProfileArgs = {}, + userDataPath = getProfileUserDataPath() +): CreateLocalOrcaProfileResult { + const index = loadOrCreateProfileIndex(userDataPath) + const now = Date.now() + const name = sanitizeProfileName(args.name) + const profile: OrcaProfileSummary = { + id: `local-${randomUUID()}`, + name, + avatar: { + kind: 'initials', + initials: ( + name.match(/[A-Za-z0-9]/)?.[0] ?? DEFAULT_LOCAL_ORCA_PROFILE_NAME[0] + ).toUpperCase(), + color: 'neutral' + }, + kind: 'local', + createdAt: now, + updatedAt: now, + lastOpenedAt: now + } + const nextIndex: OrcaProfileIndex = { + ...index, + profiles: [...index.profiles, profile] + } + mkdirSync(getOrcaProfileDirectory(profile.id, userDataPath), { recursive: true }) + writeProfileIndex(getOrcaProfileIndexPath(userDataPath), nextIndex) + return { + activeProfileId: nextIndex.activeProfileId, + profiles: nextIndex.profiles, + profile + } +} + +export function setActiveOrcaProfile( + profileId: string, + userDataPath = getProfileUserDataPath() +): OrcaProfileListState { + const index = loadOrCreateProfileIndex(userDataPath) + const now = Date.now() + let found = false + const profiles = index.profiles.map((profile) => { + if (profile.id !== profileId) { + return profile + } + found = true + return { + ...profile, + updatedAt: now, + lastOpenedAt: now + } + }) + if (!found) { + throw new Error('unknown_orca_profile') + } + const nextIndex: OrcaProfileIndex = { + ...index, + activeProfileId: profileId, + profiles + } + mkdirSync(getOrcaProfileDirectory(profileId, userDataPath), { recursive: true }) + writeProfileIndex(getOrcaProfileIndexPath(userDataPath), nextIndex) + return { + activeProfileId: nextIndex.activeProfileId, + profiles: nextIndex.profiles + } +} diff --git a/src/main/orca-profiles/profile-project-presence.test.ts b/src/main/orca-profiles/profile-project-presence.test.ts new file mode 100644 index 000000000000..ebbc05b8e148 --- /dev/null +++ b/src/main/orca-profiles/profile-project-presence.test.ts @@ -0,0 +1,145 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { getDefaultPersistedState } from '../../shared/constants' +import { + ORCA_PROFILE_INDEX_SCHEMA_VERSION, + type OrcaProfileIndex, + type OrcaProfileKind +} from '../../shared/orca-profiles' +import type { PersistedState, Repo } from '../../shared/types' + +const testState = { dir: '' } + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.dir + } +})) + +async function loadPresenceModule() { + vi.resetModules() + return import('./profile-project-presence') +} + +function profile( + id: string, + name: string, + kind: OrcaProfileKind = 'local' +): OrcaProfileIndex['profiles'][number] { + return { + id, + name, + avatar: { kind: 'initials', initials: name[0], color: 'neutral' }, + kind, + createdAt: 1, + updatedAt: 1, + lastOpenedAt: 1 + } +} + +function writeIndex(activeProfileId = 'personal'): void { + const index: OrcaProfileIndex = { + schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, + activeProfileId, + profiles: [profile('personal', 'Personal'), profile('work', 'Work')] + } + writeFileSync(join(testState.dir, 'orca-profile-index.json'), JSON.stringify(index), 'utf-8') +} + +function writeProfileState(profileId: string, repos: Repo[]): void { + const state: PersistedState = { + ...getDefaultPersistedState('/Users/tester'), + repos + } + const dataFile = join(testState.dir, 'profiles', profileId, 'orca-data.json') + mkdirSync(dirname(dataFile), { recursive: true }) + writeFileSync(dataFile, JSON.stringify(state), 'utf-8') +} + +function makeRepo(overrides: Partial = {}): Repo { + return { + id: 'repo-1', + path: '/workspace/orca', + displayName: 'Orca', + badgeColor: '#33aa99', + addedAt: 100, + kind: 'git', + connectionId: null, + ...overrides + } +} + +describe('profile project presence', () => { + beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-profile-presence-')) + writeIndex() + }) + + afterEach(() => { + rmSync(testState.dir, { recursive: true, force: true }) + }) + + it('finds matching projects in other profiles while excluding the active profile', async () => { + writeProfileState('personal', [ + makeRepo({ id: 'personal-repo', path: 'C:\\Code\\Orca', displayName: 'Personal Orca' }) + ]) + writeProfileState('work', [ + makeRepo({ id: 'work-repo', path: 'C:\\Code\\Orca', displayName: 'Work Orca' }) + ]) + + const { findOrcaProfileProjectsByPath } = await loadPresenceModule() + const result = findOrcaProfileProjectsByPath( + { + path: 'c:/code/orca/', + executionHostId: 'local', + excludeProfileId: 'personal' + }, + testState.dir + ) + + expect(result.projects).toEqual([ + { + profileId: 'work', + profileName: 'Work', + profileKind: 'local', + repoId: 'work-repo', + repoName: 'Work Orca' + } + ]) + }) + + it('keeps SSH projects separate from local projects with the same path', async () => { + writeProfileState('personal', [ + makeRepo({ id: 'local-repo', path: '/srv/orca', displayName: 'Local Orca' }) + ]) + writeProfileState('work', [ + makeRepo({ + id: 'ssh-repo', + path: '/srv/orca', + displayName: 'SSH Orca', + connectionId: 'builder', + executionHostId: 'ssh:builder' + }) + ]) + + const { findOrcaProfileProjectsByPath } = await loadPresenceModule() + const result = findOrcaProfileProjectsByPath( + { + path: '/srv/orca', + connectionId: 'builder', + executionHostId: 'ssh:builder' + }, + testState.dir + ) + + expect(result.projects).toEqual([ + expect.objectContaining({ + profileId: 'work', + repoId: 'ssh-repo', + repoName: 'SSH Orca' + }) + ]) + }) +}) diff --git a/src/main/orca-profiles/profile-project-presence.ts b/src/main/orca-profiles/profile-project-presence.ts new file mode 100644 index 000000000000..23f54884dee2 --- /dev/null +++ b/src/main/orca-profiles/profile-project-presence.ts @@ -0,0 +1,51 @@ +import type { + FindOrcaProfileProjectsByPathArgs, + FindOrcaProfileProjectsByPathResult +} from '../../shared/orca-profiles' +import { getOrcaProfileListState } from './profile-index-store' +import { readProfileState } from './profile-project-state-file' +import { repoPhysicalKey } from './profile-project-worktree-identity' + +function cleanOptionalString(value: string | null | undefined): string | null { + const trimmed = value?.trim() + return trimmed ? trimmed : null +} + +export function findOrcaProfileProjectsByPath( + args: FindOrcaProfileProjectsByPathArgs, + userDataPath: string +): FindOrcaProfileProjectsByPathResult { + const path = args.path.trim() + if (!path) { + throw new Error('invalid_orca_profile_project_path') + } + + const excludeProfileId = cleanOptionalString(args.excludeProfileId) + const candidateKey = repoPhysicalKey({ + path, + connectionId: cleanOptionalString(args.connectionId), + executionHostId: args.executionHostId ?? undefined + }) + const projects: FindOrcaProfileProjectsByPathResult['projects'] = [] + + for (const profile of getOrcaProfileListState(userDataPath).profiles) { + if (profile.id === excludeProfileId) { + continue + } + const state = readProfileState(profile.id, userDataPath) + for (const repo of state.repos) { + if (repoPhysicalKey(repo) !== candidateKey) { + continue + } + projects.push({ + profileId: profile.id, + profileName: profile.name, + profileKind: profile.kind, + repoId: repo.id, + repoName: repo.displayName || repo.path + }) + } + } + + return { projects } +} diff --git a/src/main/orca-profiles/profile-project-session-state.ts b/src/main/orca-profiles/profile-project-session-state.ts new file mode 100644 index 000000000000..0d80880a19d5 --- /dev/null +++ b/src/main/orca-profiles/profile-project-session-state.ts @@ -0,0 +1,155 @@ +import { getDefaultWorkspaceSession } from '../../shared/constants' +import type { ExecutionHostId } from '../../shared/execution-host' +import type { WorkspaceSessionState } from '../../shared/types' +import { parseWorkspaceKey } from '../../shared/workspace-scope' +import { + isRepoWorktreeId, + ownerKeyBelongsToRepo, + removeRepoWorktreeRecord +} from './profile-project-worktree-identity' + +export function mergeHostWorkspaceSessions( + existing: Partial> | undefined, + incoming: Partial> +): Partial> { + const next: Partial> = { ...existing } + for (const [hostId, session] of Object.entries(incoming)) { + if (!session) { + continue + } + next[hostId as ExecutionHostId] = mergeWorkspaceSessions( + next[hostId as ExecutionHostId], + session + ) + } + return next +} + +export function mergeWorkspaceSessions( + existing: WorkspaceSessionState | undefined, + incoming: WorkspaceSessionState +): WorkspaceSessionState { + const base = existing ?? getDefaultWorkspaceSession() + return { + ...base, + tabsByWorktree: { ...base.tabsByWorktree, ...incoming.tabsByWorktree }, + terminalLayoutsByTabId: { + ...base.terminalLayoutsByTabId, + ...incoming.terminalLayoutsByTabId + }, + openFilesByWorktree: { ...base.openFilesByWorktree, ...incoming.openFilesByWorktree }, + browserTabsByWorktree: { + ...base.browserTabsByWorktree, + ...incoming.browserTabsByWorktree + }, + browserPagesByWorkspace: { + ...base.browserPagesByWorkspace, + ...incoming.browserPagesByWorkspace + }, + activeBrowserTabIdByWorktree: { + ...base.activeBrowserTabIdByWorktree, + ...incoming.activeBrowserTabIdByWorktree + }, + activeFileIdByWorktree: { + ...base.activeFileIdByWorktree, + ...incoming.activeFileIdByWorktree + }, + activeTabTypeByWorktree: { + ...base.activeTabTypeByWorktree, + ...incoming.activeTabTypeByWorktree + }, + activeTabIdByWorktree: { ...base.activeTabIdByWorktree, ...incoming.activeTabIdByWorktree }, + unifiedTabs: { ...base.unifiedTabs, ...incoming.unifiedTabs }, + tabGroups: { ...base.tabGroups, ...incoming.tabGroups }, + tabGroupLayouts: { ...base.tabGroupLayouts, ...incoming.tabGroupLayouts }, + activeGroupIdByWorktree: { + ...base.activeGroupIdByWorktree, + ...incoming.activeGroupIdByWorktree + }, + lastVisitedAtByWorktreeId: { + ...base.lastVisitedAtByWorktreeId, + ...incoming.lastVisitedAtByWorktreeId + }, + defaultTerminalTabsAppliedByWorktreeId: { + ...base.defaultTerminalTabsAppliedByWorktreeId, + ...incoming.defaultTerminalTabsAppliedByWorktreeId + }, + activeWorktreeIdsOnShutdown: [ + ...(base.activeWorktreeIdsOnShutdown ?? []), + ...(incoming.activeWorktreeIdsOnShutdown ?? []) + ], + activeWorktreeId: base.activeWorktreeId ?? incoming.activeWorktreeId, + activeWorkspaceKey: base.activeWorkspaceKey ?? incoming.activeWorkspaceKey, + activeTabId: base.activeTabId ?? incoming.activeTabId + } +} + +export function removeRepoFromHostWorkspaceSessions( + sessions: Partial> | undefined, + repoId: string +): Partial> { + const next: Partial> = {} + for (const [hostId, session] of Object.entries(sessions ?? {})) { + next[hostId as ExecutionHostId] = removeRepoFromWorkspaceSession(session, repoId) + } + return next +} + +export function removeRepoFromWorkspaceSession( + session: WorkspaceSessionState | undefined, + repoId: string +): WorkspaceSessionState { + const next = structuredClone(session ?? getDefaultWorkspaceSession()) + const removedTerminalTabIds = new Set() + for (const [ownerKey, tabs] of Object.entries(next.tabsByWorktree)) { + if (!ownerKeyBelongsToRepo(ownerKey, repoId)) { + continue + } + tabs.forEach((tab) => removedTerminalTabIds.add(tab.id)) + delete next.tabsByWorktree[ownerKey] + } + for (const tabId of removedTerminalTabIds) { + delete next.terminalLayoutsByTabId[tabId] + } + next.openFilesByWorktree = removeRepoWorktreeRecord(next.openFilesByWorktree, repoId) + next.activeFileIdByWorktree = removeRepoWorktreeRecord(next.activeFileIdByWorktree, repoId) + const removedBrowserWorkspaceIds = new Set() + for (const [ownerKey, workspaces] of Object.entries(next.browserTabsByWorktree ?? {})) { + if (!ownerKeyBelongsToRepo(ownerKey, repoId)) { + continue + } + workspaces.forEach((workspace) => removedBrowserWorkspaceIds.add(workspace.id)) + delete next.browserTabsByWorktree![ownerKey] + } + if (next.browserPagesByWorkspace) { + for (const workspaceId of removedBrowserWorkspaceIds) { + delete next.browserPagesByWorkspace[workspaceId] + } + } + next.activeBrowserTabIdByWorktree = removeRepoWorktreeRecord( + next.activeBrowserTabIdByWorktree, + repoId + ) + next.activeTabTypeByWorktree = removeRepoWorktreeRecord(next.activeTabTypeByWorktree, repoId) + next.activeTabIdByWorktree = removeRepoWorktreeRecord(next.activeTabIdByWorktree, repoId) + next.unifiedTabs = removeRepoWorktreeRecord(next.unifiedTabs, repoId) + next.tabGroups = removeRepoWorktreeRecord(next.tabGroups, repoId) + next.tabGroupLayouts = removeRepoWorktreeRecord(next.tabGroupLayouts, repoId) + next.activeGroupIdByWorktree = removeRepoWorktreeRecord(next.activeGroupIdByWorktree, repoId) + next.lastVisitedAtByWorktreeId = removeRepoWorktreeRecord(next.lastVisitedAtByWorktreeId, repoId) + next.defaultTerminalTabsAppliedByWorktreeId = removeRepoWorktreeRecord( + next.defaultTerminalTabsAppliedByWorktreeId, + repoId + ) + if (next.activeWorktreeId && isRepoWorktreeId(repoId, next.activeWorktreeId)) { + next.activeWorktreeId = null + } + const activeScope = next.activeWorkspaceKey ? parseWorkspaceKey(next.activeWorkspaceKey) : null + if (activeScope?.type === 'worktree' && isRepoWorktreeId(repoId, activeScope.worktreeId)) { + next.activeWorkspaceKey = null + } + next.activeWorktreeIdsOnShutdown = next.activeWorktreeIdsOnShutdown?.filter( + (worktreeId) => !isRepoWorktreeId(repoId, worktreeId) + ) + return next +} diff --git a/src/main/orca-profiles/profile-project-session-transfer.ts b/src/main/orca-profiles/profile-project-session-transfer.ts new file mode 100644 index 000000000000..8380e31301bd --- /dev/null +++ b/src/main/orca-profiles/profile-project-session-transfer.ts @@ -0,0 +1,215 @@ +import { getDefaultWorkspaceSession } from '../../shared/constants' +import type { ExecutionHostId } from '../../shared/execution-host' +import type { + BrowserPage, + BrowserWorkspace, + PersistedOpenFile, + Tab, + TabGroup, + TerminalTab, + WorkspaceSessionState +} from '../../shared/types' +import { parseWorkspaceKey, worktreeWorkspaceKey } from '../../shared/workspace-scope' +import { + isRepoWorktreeId, + rekeyOwnerKey, + rekeyWorktreeId +} from './profile-project-worktree-identity' + +export function extractHostSessionsForTransfer( + sessions: Partial> | undefined, + oldRepoId: string, + newRepoId: string +): Partial> { + const next: Partial> = {} + for (const [hostId, session] of Object.entries(sessions ?? {})) { + if (!session) { + continue + } + const transferred = extractSessionForTransfer(session, oldRepoId, newRepoId) + if (hasTransferredSessionState(transferred)) { + next[hostId as ExecutionHostId] = transferred + } + } + return next +} + +function hasTransferredSessionState(session: WorkspaceSessionState): boolean { + return ( + Object.keys(session.tabsByWorktree).length > 0 || + Object.keys(session.openFilesByWorktree ?? {}).length > 0 || + Object.keys(session.browserTabsByWorktree ?? {}).length > 0 || + Object.keys(session.unifiedTabs ?? {}).length > 0 || + Object.keys(session.tabGroups ?? {}).length > 0 + ) +} + +export function extractSessionForTransfer( + session: WorkspaceSessionState | undefined, + oldRepoId: string, + newRepoId: string +): WorkspaceSessionState { + const source = session ?? getDefaultWorkspaceSession() + const transferred = getDefaultWorkspaceSession() + const copiedTerminalTabIds = new Set() + const copiedBrowserWorkspaceIds = new Set() + const mapOwnerRecord = ( + record: Record | undefined, + mapValue: (value: T) => T + ): Record => { + const next: Record = {} + for (const [ownerKey, value] of Object.entries(record ?? {})) { + const nextOwnerKey = rekeyOwnerKey(oldRepoId, newRepoId, ownerKey) + if (nextOwnerKey) { + next[nextOwnerKey] = mapValue(value) + } + } + return next + } + transferred.tabsByWorktree = mapOwnerRecord(source.tabsByWorktree, (tabs) => + tabs.map((tab) => { + copiedTerminalTabIds.add(tab.id) + return rekeyTerminalTab(tab, oldRepoId, newRepoId) + }) + ) + transferred.openFilesByWorktree = mapOwnerRecord(source.openFilesByWorktree, (files) => + files.map((file) => rekeyOpenFile(file, oldRepoId, newRepoId)) + ) + transferred.activeFileIdByWorktree = mapOwnerRecord(source.activeFileIdByWorktree, (value) => + structuredClone(value) + ) + transferred.browserTabsByWorktree = mapOwnerRecord(source.browserTabsByWorktree, (tabs) => + tabs.map((tab) => { + copiedBrowserWorkspaceIds.add(tab.id) + return rekeyBrowserWorkspace(tab, oldRepoId, newRepoId) + }) + ) + transferred.browserPagesByWorkspace = copyBrowserPages( + source.browserPagesByWorkspace, + copiedBrowserWorkspaceIds, + oldRepoId, + newRepoId + ) + transferred.activeBrowserTabIdByWorktree = mapOwnerRecord( + source.activeBrowserTabIdByWorktree, + (value) => structuredClone(value) + ) + transferred.activeTabTypeByWorktree = mapOwnerRecord(source.activeTabTypeByWorktree, (value) => + structuredClone(value) + ) + transferred.activeTabIdByWorktree = mapOwnerRecord(source.activeTabIdByWorktree, (value) => + structuredClone(value) + ) + transferred.unifiedTabs = mapOwnerRecord(source.unifiedTabs, (tabs) => + tabs.map((tab) => rekeyUnifiedTab(tab, oldRepoId, newRepoId)) + ) + transferred.tabGroups = mapOwnerRecord(source.tabGroups, (groups) => + groups.map((group) => rekeyTabGroup(group, oldRepoId, newRepoId)) + ) + transferred.tabGroupLayouts = mapOwnerRecord(source.tabGroupLayouts, (value) => + structuredClone(value) + ) + transferred.activeGroupIdByWorktree = mapOwnerRecord(source.activeGroupIdByWorktree, (value) => + structuredClone(value) + ) + transferred.lastVisitedAtByWorktreeId = mapOwnerRecord( + source.lastVisitedAtByWorktreeId, + (value) => structuredClone(value) + ) + transferred.defaultTerminalTabsAppliedByWorktreeId = mapOwnerRecord( + source.defaultTerminalTabsAppliedByWorktreeId, + (value) => structuredClone(value) + ) + transferred.terminalLayoutsByTabId = {} + for (const tabId of copiedTerminalTabIds) { + const layout = source.terminalLayoutsByTabId[tabId] + if (layout) { + transferred.terminalLayoutsByTabId[tabId] = structuredClone(layout) + } + } + transferred.activeWorktreeIdsOnShutdown = source.activeWorktreeIdsOnShutdown + ?.filter((worktreeId) => isRepoWorktreeId(oldRepoId, worktreeId)) + .map((worktreeId) => rekeyWorktreeId(oldRepoId, newRepoId, worktreeId)) + if (source.activeWorktreeId && isRepoWorktreeId(oldRepoId, source.activeWorktreeId)) { + transferred.activeWorktreeId = rekeyWorktreeId(oldRepoId, newRepoId, source.activeWorktreeId) + } + const activeScope = source.activeWorkspaceKey + ? parseWorkspaceKey(source.activeWorkspaceKey) + : null + if (activeScope?.type === 'worktree' && isRepoWorktreeId(oldRepoId, activeScope.worktreeId)) { + transferred.activeWorkspaceKey = worktreeWorkspaceKey( + rekeyWorktreeId(oldRepoId, newRepoId, activeScope.worktreeId) + ) + } + return transferred +} + +function rekeyTerminalTab(tab: TerminalTab, oldRepoId: string, newRepoId: string): TerminalTab { + return { + ...structuredClone(tab), + worktreeId: rekeyWorktreeId(oldRepoId, newRepoId, tab.worktreeId) + } +} + +function rekeyOpenFile( + file: PersistedOpenFile, + oldRepoId: string, + newRepoId: string +): PersistedOpenFile { + return { + ...structuredClone(file), + worktreeId: rekeyWorktreeId(oldRepoId, newRepoId, file.worktreeId) + } +} + +function rekeyBrowserWorkspace( + workspace: BrowserWorkspace, + oldRepoId: string, + newRepoId: string +): BrowserWorkspace { + return { + ...structuredClone(workspace), + worktreeId: rekeyWorktreeId(oldRepoId, newRepoId, workspace.worktreeId), + // Why: both the session profile and the resolved partition string are + // source-profile-scoped; carrying either across would point the restored + // pane at a partition the target profile's allowlist rejects. + sessionProfileId: null, + sessionPartition: null + } +} + +function rekeyBrowserPage(page: BrowserPage, oldRepoId: string, newRepoId: string): BrowserPage { + return { + ...structuredClone(page), + worktreeId: rekeyWorktreeId(oldRepoId, newRepoId, page.worktreeId) + } +} + +function copyBrowserPages( + pagesByWorkspace: Record | undefined, + workspaceIds: ReadonlySet, + oldRepoId: string, + newRepoId: string +): Record { + const next: Record = {} + for (const [workspaceId, pages] of Object.entries(pagesByWorkspace ?? {})) { + if (workspaceIds.has(workspaceId)) { + next[workspaceId] = pages.map((page) => rekeyBrowserPage(page, oldRepoId, newRepoId)) + } + } + return next +} + +function rekeyUnifiedTab(tab: Tab, oldRepoId: string, newRepoId: string): Tab { + return { + ...structuredClone(tab), + worktreeId: rekeyWorktreeId(oldRepoId, newRepoId, tab.worktreeId) + } +} + +function rekeyTabGroup(group: TabGroup, oldRepoId: string, newRepoId: string): TabGroup { + return { + ...structuredClone(group), + worktreeId: rekeyWorktreeId(oldRepoId, newRepoId, group.worktreeId) + } +} diff --git a/src/main/orca-profiles/profile-project-source-removal.ts b/src/main/orca-profiles/profile-project-source-removal.ts new file mode 100644 index 000000000000..edb923e62938 --- /dev/null +++ b/src/main/orca-profiles/profile-project-source-removal.ts @@ -0,0 +1,66 @@ +import type { WorkspaceKey } from '../../shared/types' +import { parseWorkspaceKey } from '../../shared/workspace-scope' +import { + rebuildRepoBackedProjectState, + type TransferProfileState +} from './profile-project-state-file' +import { + removeRepoFromHostWorkspaceSessions, + removeRepoFromWorkspaceSession +} from './profile-project-session-state' +import { isRepoWorktreeId, removeRepoWorktreeRecord } from './profile-project-worktree-identity' + +export function removeSourceRepo( + state: TransferProfileState, + repoId: string +): TransferProfileState { + const next: TransferProfileState = { + ...state, + repos: state.repos.filter((repo) => repo.id !== repoId), + sparsePresetsByRepo: { ...state.sparsePresetsByRepo }, + worktreeMeta: { ...state.worktreeMeta }, + worktreeLineageById: { ...state.worktreeLineageById }, + workspaceLineageByChildKey: { ...state.workspaceLineageByChildKey }, + workspaceSession: removeRepoFromWorkspaceSession(state.workspaceSession, repoId), + workspaceSessionsByHostId: removeRepoFromHostWorkspaceSessions( + state.workspaceSessionsByHostId, + repoId + ), + ui: { + ...state.ui, + lastActiveRepoId: state.ui.lastActiveRepoId === repoId ? null : state.ui.lastActiveRepoId, + lastActiveWorktreeId: + state.ui.lastActiveWorktreeId && isRepoWorktreeId(repoId, state.ui.lastActiveWorktreeId) + ? null + : state.ui.lastActiveWorktreeId, + filterRepoIds: state.ui.filterRepoIds?.filter((id) => id !== repoId) ?? [], + showDotfilesByWorktree: removeRepoWorktreeRecord(state.ui.showDotfilesByWorktree, repoId) + } + } + delete next.sparsePresetsByRepo[repoId] + removeRepoWorktreeMetadata(next, repoId) + return rebuildRepoBackedProjectState(next) +} + +function removeRepoWorktreeMetadata(state: TransferProfileState, repoId: string): void { + for (const key of Object.keys(state.worktreeMeta)) { + if (isRepoWorktreeId(repoId, key)) { + delete state.worktreeMeta[key] + } + } + for (const [key, lineage] of Object.entries(state.worktreeLineageById)) { + if (isRepoWorktreeId(repoId, key) || isRepoWorktreeId(repoId, lineage.parentWorktreeId)) { + delete state.worktreeLineageById[key] + } + } + for (const [key, lineage] of Object.entries(state.workspaceLineageByChildKey)) { + const child = parseWorkspaceKey(key) + const parent = parseWorkspaceKey(lineage.parentWorkspaceKey) + if ( + (child?.type === 'worktree' && isRepoWorktreeId(repoId, child.worktreeId)) || + (parent?.type === 'worktree' && isRepoWorktreeId(repoId, parent.worktreeId)) + ) { + delete state.workspaceLineageByChildKey[key as WorkspaceKey] + } + } +} diff --git a/src/main/orca-profiles/profile-project-state-file.ts b/src/main/orca-profiles/profile-project-state-file.ts new file mode 100644 index 000000000000..4169fea6ffc4 --- /dev/null +++ b/src/main/orca-profiles/profile-project-state-file.ts @@ -0,0 +1,139 @@ +import { randomUUID } from 'node:crypto' +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' +import { homedir } from 'node:os' +import { dirname } from 'node:path' +import { getDefaultPersistedState, getDefaultWorkspaceSession } from '../../shared/constants' +import type { ExecutionHostId } from '../../shared/execution-host' +import { projectHostSetupProjectionFromRepos } from '../../shared/project-host-setup-projection' +import type { + PersistedState, + Project, + ProjectHostSetup, + Repo, + SparsePreset, + WorkspaceSessionState +} from '../../shared/types' +import { getOrcaProfileDataFile } from './profile-index-store' + +export type TransferProfileState = PersistedState + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function arrayOrEmpty(value: unknown): T[] { + return Array.isArray(value) ? (value as T[]) : [] +} + +function recordOrEmpty(value: unknown): Record { + return isRecord(value) ? (value as Record) : {} +} + +export function readProfileState(profileId: string, userDataPath: string): TransferProfileState { + const defaults = getDefaultPersistedState(homedir()) + const dataFile = getOrcaProfileDataFile(profileId, userDataPath) + if (!existsSync(dataFile)) { + return structuredClone(defaults) + } + const parsed = JSON.parse(readFileSync(dataFile, 'utf-8')) as Partial + return rebuildRepoBackedProjectState({ + ...defaults, + ...parsed, + repos: arrayOrEmpty(parsed.repos), + projects: arrayOrEmpty(parsed.projects), + projectHostSetups: arrayOrEmpty(parsed.projectHostSetups), + projectGroups: arrayOrEmpty(parsed.projectGroups), + folderWorkspaces: arrayOrEmpty(parsed.folderWorkspaces), + sparsePresetsByRepo: recordOrEmpty(parsed.sparsePresetsByRepo), + worktreeMeta: recordOrEmpty(parsed.worktreeMeta), + worktreeLineageById: recordOrEmpty(parsed.worktreeLineageById), + workspaceLineageByChildKey: recordOrEmpty(parsed.workspaceLineageByChildKey), + settings: isRecord(parsed.settings) + ? { ...defaults.settings, ...parsed.settings } + : defaults.settings, + ui: isRecord(parsed.ui) ? { ...defaults.ui, ...parsed.ui } : defaults.ui, + githubCache: isRecord(parsed.githubCache) + ? { + pr: recordOrEmpty((parsed.githubCache as PersistedState['githubCache']).pr), + issue: recordOrEmpty((parsed.githubCache as PersistedState['githubCache']).issue) + } + : defaults.githubCache, + workspaceSession: isRecord(parsed.workspaceSession) + ? { ...getDefaultWorkspaceSession(), ...parsed.workspaceSession } + : defaults.workspaceSession, + workspaceSessionsByHostId: isRecord(parsed.workspaceSessionsByHostId) + ? (parsed.workspaceSessionsByHostId as Partial< + Record + >) + : {}, + sshTargets: arrayOrEmpty(parsed.sshTargets), + sshRemotePtyLeases: arrayOrEmpty(parsed.sshRemotePtyLeases), + migrationUnsupportedPtyEntries: arrayOrEmpty(parsed.migrationUnsupportedPtyEntries), + legacyPaneKeyAliasEntries: arrayOrEmpty(parsed.legacyPaneKeyAliasEntries), + automations: arrayOrEmpty(parsed.automations), + automationRuns: arrayOrEmpty(parsed.automationRuns), + onboarding: isRecord(parsed.onboarding) + ? { ...defaults.onboarding, ...parsed.onboarding } + : defaults.onboarding, + featureInteractionTelemetryBuckets: isRecord(parsed.featureInteractionTelemetryBuckets) + ? parsed.featureInteractionTelemetryBuckets + : defaults.featureInteractionTelemetryBuckets + }) +} + +export function writeProfileState( + profileId: string, + userDataPath: string, + state: TransferProfileState +): void { + const dataFile = getOrcaProfileDataFile(profileId, userDataPath) + mkdirSync(dirname(dataFile), { recursive: true }) + const tmpPath = `${dataFile}.${process.pid}.${randomUUID()}.tmp` + writeFileSync(tmpPath, JSON.stringify(state, null, 2), 'utf-8') + renameSync(tmpPath, dataFile) +} + +function isRepoBackedProjectHostSetup( + setup: ProjectHostSetup, + currentRepoIds: ReadonlySet +): boolean { + return Boolean(setup.repoId && currentRepoIds.has(setup.repoId)) +} + +export function rebuildRepoBackedProjectState(state: TransferProfileState): TransferProfileState { + const projection = projectHostSetupProjectionFromRepos(state.repos) + const existingProjectsById = new Map(state.projects.map((project) => [project.id, project])) + const currentRepoIds = new Set(state.repos.map((repo) => repo.id)) + const projectedProjectIds = new Set(projection.projects.map((project) => project.id)) + const projectedSetupIds = new Set(projection.setups.map((setup) => setup.id)) + const independentSetups = state.projectHostSetups.filter((setup) => { + if (projectedSetupIds.has(setup.id)) { + return false + } + return !isRepoBackedProjectHostSetup(setup, currentRepoIds) + }) + const independentProjectIds = new Set(independentSetups.map((setup) => setup.projectId)) + const independentProjects = state.projects + .filter( + (project) => independentProjectIds.has(project.id) && !projectedProjectIds.has(project.id) + ) + .map((project) => ({ + ...project, + sourceRepoIds: project.sourceRepoIds.filter((repoId) => currentRepoIds.has(repoId)) + })) + const projectedProjects = projection.projects.map((project) => { + const existingProject = existingProjectsById.get(project.id) + return existingProject?.localWindowsRuntimePreference + ? { + ...project, + localWindowsRuntimePreference: existingProject.localWindowsRuntimePreference, + updatedAt: Math.max(project.updatedAt, existingProject.updatedAt) + } + : project + }) + return { + ...state, + projects: [...projectedProjects, ...independentProjects], + projectHostSetups: [...projection.setups, ...independentSetups] + } +} diff --git a/src/main/orca-profiles/profile-project-transfer-payload.ts b/src/main/orca-profiles/profile-project-transfer-payload.ts new file mode 100644 index 000000000000..68075a71a11f --- /dev/null +++ b/src/main/orca-profiles/profile-project-transfer-payload.ts @@ -0,0 +1,294 @@ +import { randomUUID } from 'node:crypto' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../shared/execution-host' +import { projectHostSetupProjectionFromRepos } from '../../shared/project-host-setup-projection' +import type { SshTarget } from '../../shared/ssh-types' +import type { PersistedState, Repo, SparsePreset, WorkspaceKey } from '../../shared/types' +import { parseWorkspaceKey } from '../../shared/workspace-scope' +import type { TransferProfileState } from './profile-project-state-file' +import { rebuildRepoBackedProjectState } from './profile-project-state-file' +import { mergeHostWorkspaceSessions, mergeWorkspaceSessions } from './profile-project-session-state' +import { + extractHostSessionsForTransfer, + extractSessionForTransfer +} from './profile-project-session-transfer' +import { + isRepoWorktreeId, + rekeyWorktreeId, + rekeyWorkspaceKey +} from './profile-project-worktree-identity' + +export type TransferPayload = { + repo: Repo + sparsePresets: SparsePreset[] + worktreeMeta: PersistedState['worktreeMeta'] + worktreeLineageById: PersistedState['worktreeLineageById'] + workspaceLineageByChildKey: PersistedState['workspaceLineageByChildKey'] + workspaceSession?: PersistedState['workspaceSession'] + workspaceSessionsByHostId?: Partial> + sshTargets: SshTarget[] + targetProjectId: string | null +} + +export function createTargetRepo( + sourceRepo: Repo, + targetState: TransferProfileState, + copy: boolean +): Repo { + const targetRepoId = + !copy && !targetState.repos.some((repo) => repo.id === sourceRepo.id) + ? sourceRepo.id + : createUniqueRepoId(targetState) + const repo: Repo = { + ...sourceRepo, + id: targetRepoId, + projectGroupId: null, + addedAt: copy ? Date.now() : sourceRepo.addedAt + } + delete repo.projectGroupOrder + return repo +} + +function createUniqueRepoId(state: TransferProfileState): string { + const existingRepoIds = new Set(state.repos.map((repo) => repo.id)) + let candidate = randomUUID() + while (existingRepoIds.has(candidate)) { + candidate = randomUUID() + } + return candidate +} + +function collectTransferWorktreeIds(state: TransferProfileState, repoId: string): Set { + const ids = new Set() + const add = (value: string | null | undefined): void => { + if (value && isRepoWorktreeId(repoId, value)) { + ids.add(value) + } + } + Object.keys(state.worktreeMeta).forEach(add) + for (const lineage of Object.values(state.worktreeLineageById)) { + add(lineage.worktreeId) + add(lineage.parentWorktreeId) + } + for (const [key, lineage] of Object.entries(state.workspaceLineageByChildKey)) { + const child = parseWorkspaceKey(key) + const parent = parseWorkspaceKey(lineage.parentWorkspaceKey) + if (child?.type === 'worktree') { + add(child.worktreeId) + } + if (parent?.type === 'worktree') { + add(parent.worktreeId) + } + } + collectSessionWorktreeIds(state.workspaceSession, repoId, ids) + for (const session of Object.values(state.workspaceSessionsByHostId ?? {})) { + collectSessionWorktreeIds(session, repoId, ids) + } + Object.keys(state.ui?.showDotfilesByWorktree ?? {}).forEach(add) + return ids +} + +function collectSessionWorktreeIds( + session: PersistedState['workspaceSession'] | undefined, + repoId: string, + ids: Set +): void { + if (!session) { + return + } + const add = (value: string | null | undefined): void => { + if (value && isRepoWorktreeId(repoId, value)) { + ids.add(value) + } + } + const addOwnerKeys = (record: Record | undefined): void => { + for (const key of Object.keys(record ?? {})) { + if (isRepoWorktreeId(repoId, key)) { + ids.add(key) + } + const parsed = parseWorkspaceKey(key) + if (parsed?.type === 'worktree' && isRepoWorktreeId(repoId, parsed.worktreeId)) { + ids.add(parsed.worktreeId) + } + } + } + addOwnerKeys(session.tabsByWorktree) + addOwnerKeys(session.openFilesByWorktree) + addOwnerKeys(session.browserTabsByWorktree) + addOwnerKeys(session.activeBrowserTabIdByWorktree) + addOwnerKeys(session.activeTabTypeByWorktree) + addOwnerKeys(session.activeTabIdByWorktree) + addOwnerKeys(session.unifiedTabs) + addOwnerKeys(session.tabGroups) + addOwnerKeys(session.tabGroupLayouts) + addOwnerKeys(session.activeGroupIdByWorktree) + addOwnerKeys(session.lastVisitedAtByWorktreeId) + addOwnerKeys(session.defaultTerminalTabsAppliedByWorktreeId) + addOwnerKeys(session.activeFileIdByWorktree) + add(session.activeWorktreeId) + const activeScope = session.activeWorkspaceKey + ? parseWorkspaceKey(session.activeWorkspaceKey) + : null + if (activeScope?.type === 'worktree') { + add(activeScope.worktreeId) + } +} + +function rekeyWorktreeIdRecord( + record: Record, + worktreeIds: ReadonlySet, + oldRepoId: string, + newRepoId: string, + mapValue: (value: T) => T = (value) => structuredClone(value) +): Record { + const next: Record = {} + for (const [oldKey, value] of Object.entries(record)) { + if (worktreeIds.has(oldKey)) { + next[rekeyWorktreeId(oldRepoId, newRepoId, oldKey)] = mapValue(value) + } + } + return next +} + +function rekeyLineageRecord( + record: PersistedState['worktreeLineageById'], + worktreeIds: ReadonlySet, + oldRepoId: string, + newRepoId: string +): PersistedState['worktreeLineageById'] { + const next: PersistedState['worktreeLineageById'] = {} + for (const [oldKey, lineage] of Object.entries(record)) { + if (!worktreeIds.has(oldKey) && !worktreeIds.has(lineage.parentWorktreeId)) { + continue + } + const newKey = rekeyWorktreeId(oldRepoId, newRepoId, oldKey) + next[newKey] = { + ...structuredClone(lineage), + worktreeId: rekeyWorktreeId(oldRepoId, newRepoId, lineage.worktreeId), + parentWorktreeId: rekeyWorktreeId(oldRepoId, newRepoId, lineage.parentWorktreeId) + } + } + return next +} + +function rekeyWorkspaceLineageRecord( + record: PersistedState['workspaceLineageByChildKey'], + oldRepoId: string, + newRepoId: string +): PersistedState['workspaceLineageByChildKey'] { + const next: PersistedState['workspaceLineageByChildKey'] = {} + for (const [oldKey, lineage] of Object.entries(record)) { + const newChildKey = rekeyWorkspaceKey(oldRepoId, newRepoId, oldKey as WorkspaceKey) + const newParentKey = rekeyWorkspaceKey(oldRepoId, newRepoId, lineage.parentWorkspaceKey) + if (newChildKey === oldKey && newParentKey === lineage.parentWorkspaceKey) { + continue + } + next[newChildKey] = { + ...structuredClone(lineage), + childWorkspaceKey: newChildKey, + parentWorkspaceKey: newParentKey + } + } + return next +} + +export function createTransferPayload(args: { + sourceState: TransferProfileState + sourceRepo: Repo + targetRepo: Repo + includeSessions: boolean +}): TransferPayload { + const { sourceState, sourceRepo, targetRepo, includeSessions } = args + const oldRepoId = sourceRepo.id + const newRepoId = targetRepo.id + const worktreeIds = collectTransferWorktreeIds(sourceState, oldRepoId) + const targetProjection = projectHostSetupProjectionFromRepos([targetRepo]) + const targetProjectId = + targetProjection.setups[0]?.projectId ?? targetProjection.projects[0]?.id ?? null + return { + repo: targetRepo, + sparsePresets: (sourceState.sparsePresetsByRepo[oldRepoId] ?? []).map((preset) => ({ + ...structuredClone(preset), + repoId: newRepoId + })), + worktreeMeta: rekeyWorktreeIdRecord( + sourceState.worktreeMeta, + worktreeIds, + oldRepoId, + newRepoId, + (meta) => ({ + ...structuredClone(meta), + ...(targetProjectId ? { projectId: targetProjectId } : {}), + hostId: getRepoExecutionHostId(targetRepo), + projectHostSetupId: targetRepo.id + }) + ), + worktreeLineageById: rekeyLineageRecord( + sourceState.worktreeLineageById, + worktreeIds, + oldRepoId, + newRepoId + ), + workspaceLineageByChildKey: rekeyWorkspaceLineageRecord( + sourceState.workspaceLineageByChildKey, + oldRepoId, + newRepoId + ), + ...(includeSessions + ? { + workspaceSession: extractSessionForTransfer( + sourceState.workspaceSession, + oldRepoId, + newRepoId + ), + workspaceSessionsByHostId: extractHostSessionsForTransfer( + sourceState.workspaceSessionsByHostId, + oldRepoId, + newRepoId + ) + } + : {}), + sshTargets: sourceRepo.connectionId + ? sourceState.sshTargets.filter((target) => target.id === sourceRepo.connectionId) + : [], + targetProjectId + } +} + +export function applyPayloadToTarget( + targetState: TransferProfileState, + payload: TransferPayload +): TransferProfileState { + const next: TransferProfileState = { + ...targetState, + repos: [...targetState.repos, payload.repo], + sparsePresetsByRepo: { + ...targetState.sparsePresetsByRepo, + ...(payload.sparsePresets.length > 0 ? { [payload.repo.id]: payload.sparsePresets } : {}) + }, + worktreeMeta: { ...targetState.worktreeMeta, ...payload.worktreeMeta }, + worktreeLineageById: { ...targetState.worktreeLineageById, ...payload.worktreeLineageById }, + workspaceLineageByChildKey: { + ...targetState.workspaceLineageByChildKey, + ...payload.workspaceLineageByChildKey + }, + sshTargets: mergeSshTargets(targetState.sshTargets, payload.sshTargets) + } + if (payload.workspaceSession) { + next.workspaceSession = mergeWorkspaceSessions( + targetState.workspaceSession, + payload.workspaceSession + ) + } + if (payload.workspaceSessionsByHostId) { + next.workspaceSessionsByHostId = mergeHostWorkspaceSessions( + targetState.workspaceSessionsByHostId, + payload.workspaceSessionsByHostId + ) + } + return rebuildRepoBackedProjectState(next) +} + +function mergeSshTargets(existing: SshTarget[], incoming: SshTarget[]): SshTarget[] { + const existingIds = new Set(existing.map((target) => target.id)) + return [...existing, ...incoming.filter((target) => !existingIds.has(target.id))] +} diff --git a/src/main/orca-profiles/profile-project-transfer.test.ts b/src/main/orca-profiles/profile-project-transfer.test.ts new file mode 100644 index 000000000000..3c3a4643387d --- /dev/null +++ b/src/main/orca-profiles/profile-project-transfer.test.ts @@ -0,0 +1,301 @@ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest' +import { getDefaultPersistedState } from '../../shared/constants' +import { + ORCA_PROFILE_INDEX_SCHEMA_VERSION, + type OrcaProfileIndex +} from '../../shared/orca-profiles' +import type { PersistedState, Repo, WorktreeMeta } from '../../shared/types' +import type { SshTarget } from '../../shared/ssh-types' + +const testState = { dir: '' } + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.dir + } +})) + +async function loadTransferModule() { + vi.resetModules() + return import('./profile-project-transfer') +} + +function profile(id: string, name: string): OrcaProfileIndex['profiles'][number] { + return { + id, + name, + avatar: { kind: 'initials', initials: name[0], color: 'neutral' }, + kind: 'local', + createdAt: 1, + updatedAt: 1, + lastOpenedAt: 1 + } +} + +function writeIndex(activeProfileId = 'personal'): void { + const index: OrcaProfileIndex = { + schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, + activeProfileId, + profiles: [profile('personal', 'Personal'), profile('work', 'Work')] + } + writeFileSync(join(testState.dir, 'orca-profile-index.json'), JSON.stringify(index), 'utf-8') +} + +function profileDataPath(profileId: string): string { + return join(testState.dir, 'profiles', profileId, 'orca-data.json') +} + +function writeProfileState(profileId: string, state: PersistedState): void { + const dataFile = profileDataPath(profileId) + mkdirSync(join(dataFile, '..'), { recursive: true }) + writeFileSync(dataFile, JSON.stringify(state, null, 2), 'utf-8') +} + +function readProfileState(profileId: string): PersistedState { + return JSON.parse(readFileSync(profileDataPath(profileId), 'utf-8')) as PersistedState +} + +function makeRepo(overrides: Partial = {}): Repo { + return { + id: 'repo-1', + path: '/workspace/orca', + displayName: 'Orca', + badgeColor: '#33aa99', + addedAt: 100, + kind: 'git', + connectionId: null, + ...overrides + } +} + +function makeWorktreeMeta(overrides: Partial = {}): WorktreeMeta { + return { + displayName: 'Feature', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 10, + lastActivityAt: 123, + ...overrides + } +} + +function makeState(overrides: Partial = {}): PersistedState { + const defaults = getDefaultPersistedState('/Users/tester') + return { + ...defaults, + ...overrides, + settings: { ...defaults.settings, ...overrides.settings }, + ui: { ...defaults.ui, ...overrides.ui }, + workspaceSession: { ...defaults.workspaceSession, ...overrides.workspaceSession } + } +} + +describe('profile project transfer', () => { + beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-profile-transfer-')) + writeIndex() + }) + + afterEach(() => { + rmSync(testState.dir, { recursive: true, force: true }) + }) + + it('copies a project into another profile with a new repo id and re-keyed metadata', async () => { + const sourceWorktreeId = 'repo-1::/workspace/orca-feature' + writeProfileState( + 'personal', + makeState({ + repos: [makeRepo()], + sparsePresetsByRepo: { + 'repo-1': [ + { + id: 'preset-1', + repoId: 'repo-1', + name: 'UI', + directories: ['src/renderer'], + createdAt: 1, + updatedAt: 1 + } + ] + }, + worktreeMeta: { + [sourceWorktreeId]: makeWorktreeMeta({ projectHostSetupId: 'repo-1' }) + }, + workspaceSession: { + ...getDefaultPersistedState('/Users/tester').workspaceSession, + tabsByWorktree: { + [sourceWorktreeId]: [ + { + id: 'tab-1', + ptyId: 'pty-1', + worktreeId: sourceWorktreeId, + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + } + } + }) + ) + writeProfileState('work', makeState()) + + const { transferOrcaProfileProject } = await loadTransferModule() + const result = transferOrcaProfileProject( + { + sourceProfileId: 'personal', + targetProfileId: 'work', + repoId: 'repo-1', + mode: 'copy' + }, + testState.dir + ) + + expect(result.status).toBe('transferred') + expect(result.status === 'transferred' ? result.targetRepoId : '').not.toBe('repo-1') + const targetRepoId = result.status === 'transferred' ? result.targetRepoId : '' + const target = readProfileState('work') + const targetWorktreeId = `${targetRepoId}::/workspace/orca-feature` + expect(target.repos).toEqual([ + expect.objectContaining({ id: targetRepoId, path: '/workspace/orca' }) + ]) + expect(target.worktreeMeta[targetWorktreeId]).toMatchObject({ + displayName: 'Feature', + projectHostSetupId: targetRepoId, + hostId: 'local' + }) + expect(target.sparsePresetsByRepo[targetRepoId]).toEqual([ + expect.objectContaining({ id: 'preset-1', repoId: targetRepoId }) + ]) + expect(target.workspaceSession.tabsByWorktree).toEqual({}) + expect(readProfileState('personal').repos.map((repo) => repo.id)).toEqual(['repo-1']) + }) + + it('moves a project, preserving SSH identity and restorable workspace session state', async () => { + const sourceWorktreeId = 'repo-ssh::/srv/orca-feature' + const sshTarget: SshTarget = { + id: 'ssh-1', + label: 'Builder', + host: 'builder.example.com', + port: 22, + username: 'dev' + } + writeProfileState( + 'personal', + makeState({ + repos: [ + makeRepo({ + id: 'repo-ssh', + path: '/srv/orca', + connectionId: 'ssh-1', + executionHostId: 'ssh:ssh-1' + }) + ], + sshTargets: [sshTarget], + worktreeMeta: { + [sourceWorktreeId]: makeWorktreeMeta({ projectHostSetupId: 'repo-ssh' }) + }, + workspaceSession: { + ...getDefaultPersistedState('/Users/tester').workspaceSession, + browserTabsByWorktree: { + [sourceWorktreeId]: [ + { + id: 'browser-1', + worktreeId: sourceWorktreeId, + sessionProfileId: 'source-browser-profile', + sessionPartition: 'persist:orca-profile-personal-deadbeef-browser-default', + url: 'https://example.com', + title: 'Example', + loading: false, + faviconUrl: null, + canGoBack: false, + canGoForward: false, + loadError: null, + createdAt: 1 + } + ] + } + } + }) + ) + writeProfileState('work', makeState()) + + const { transferOrcaProfileProject } = await loadTransferModule() + const result = transferOrcaProfileProject( + { + sourceProfileId: 'personal', + targetProfileId: 'work', + repoId: 'repo-ssh', + mode: 'move' + }, + testState.dir + ) + + expect(result).toMatchObject({ + status: 'transferred', + sourceRepoId: 'repo-ssh', + targetRepoId: 'repo-ssh' + }) + const source = readProfileState('personal') + const target = readProfileState('work') + expect(source.repos).toEqual([]) + expect(source.worktreeMeta).toEqual({}) + expect(target.repos[0]).toMatchObject({ + id: 'repo-ssh', + path: '/srv/orca', + connectionId: 'ssh-1', + executionHostId: 'ssh:ssh-1' + }) + expect(target.sshTargets).toEqual([sshTarget]) + expect(target.workspaceSession.browserTabsByWorktree?.[sourceWorktreeId]?.[0]).toMatchObject({ + worktreeId: sourceWorktreeId, + sessionProfileId: null, + sessionPartition: null + }) + }) + + it('rejects a duplicate physical project inside the target profile', async () => { + writeProfileState( + 'personal', + makeState({ + repos: [makeRepo({ path: 'C:\\Work\\Orca\\' })] + }) + ) + writeProfileState( + 'work', + makeState({ + repos: [makeRepo({ id: 'repo-existing', path: 'c:/work/orca' })] + }) + ) + + const { transferOrcaProfileProject } = await loadTransferModule() + const result = transferOrcaProfileProject( + { + sourceProfileId: 'personal', + targetProfileId: 'work', + repoId: 'repo-1', + mode: 'copy' + }, + testState.dir + ) + + expect(result).toEqual({ + status: 'duplicate-target', + sourceProfileId: 'personal', + targetProfileId: 'work', + sourceRepoId: 'repo-1', + duplicateRepoId: 'repo-existing' + }) + expect(readProfileState('work').repos.map((repo) => repo.id)).toEqual(['repo-existing']) + }) +}) diff --git a/src/main/orca-profiles/profile-project-transfer.ts b/src/main/orca-profiles/profile-project-transfer.ts new file mode 100644 index 000000000000..75022d3ad656 --- /dev/null +++ b/src/main/orca-profiles/profile-project-transfer.ts @@ -0,0 +1,77 @@ +import type { + TransferOrcaProfileProjectArgs, + TransferOrcaProfileProjectResult +} from '../../shared/orca-profiles' +import { getOrcaProfileListState } from './profile-index-store' +import { readProfileState, writeProfileState } from './profile-project-state-file' +import { removeSourceRepo } from './profile-project-source-removal' +import { + applyPayloadToTarget, + createTargetRepo, + createTransferPayload +} from './profile-project-transfer-payload' +import { repoPhysicalKey } from './profile-project-worktree-identity' + +function assertKnownProfiles(args: TransferOrcaProfileProjectArgs, userDataPath: string): void { + const profiles = getOrcaProfileListState(userDataPath).profiles + const ids = new Set(profiles.map((profile) => profile.id)) + if (!ids.has(args.sourceProfileId)) { + throw new Error('unknown_source_orca_profile') + } + if (!ids.has(args.targetProfileId)) { + throw new Error('unknown_target_orca_profile') + } + if (args.sourceProfileId === args.targetProfileId) { + throw new Error('matching_orca_profile_transfer') + } +} + +export function transferOrcaProfileProject( + args: TransferOrcaProfileProjectArgs, + userDataPath: string +): TransferOrcaProfileProjectResult { + assertKnownProfiles(args, userDataPath) + const sourceState = readProfileState(args.sourceProfileId, userDataPath) + const targetState = readProfileState(args.targetProfileId, userDataPath) + const sourceRepo = sourceState.repos.find((repo) => repo.id === args.repoId) + if (!sourceRepo) { + throw new Error('unknown_source_repo') + } + const duplicate = targetState.repos.find( + (repo) => repoPhysicalKey(repo) === repoPhysicalKey(sourceRepo) + ) + if (duplicate) { + return { + status: 'duplicate-target', + sourceProfileId: args.sourceProfileId, + targetProfileId: args.targetProfileId, + sourceRepoId: sourceRepo.id, + duplicateRepoId: duplicate.id + } + } + + const targetRepo = createTargetRepo(sourceRepo, targetState, args.mode === 'copy') + const payload = createTransferPayload({ + sourceState, + sourceRepo, + targetRepo, + includeSessions: args.mode === 'move' + }) + writeProfileState(args.targetProfileId, userDataPath, applyPayloadToTarget(targetState, payload)) + if (args.mode === 'move') { + writeProfileState( + args.sourceProfileId, + userDataPath, + removeSourceRepo(sourceState, sourceRepo.id) + ) + } + return { + status: 'transferred', + mode: args.mode, + sourceProfileId: args.sourceProfileId, + targetProfileId: args.targetProfileId, + sourceRepoId: sourceRepo.id, + targetRepoId: targetRepo.id, + targetProjectId: payload.targetProjectId + } +} diff --git a/src/main/orca-profiles/profile-project-worktree-identity.ts b/src/main/orca-profiles/profile-project-worktree-identity.ts new file mode 100644 index 000000000000..9bb4fa9fc272 --- /dev/null +++ b/src/main/orca-profiles/profile-project-worktree-identity.ts @@ -0,0 +1,77 @@ +import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' +import { getRepoExecutionHostId } from '../../shared/execution-host' +import type { Repo, WorkspaceKey } from '../../shared/types' +import { parseWorkspaceKey, worktreeWorkspaceKey } from '../../shared/workspace-scope' +import { WORKTREE_ID_SEPARATOR } from '../../shared/worktree-id' + +export function repoPhysicalKey( + repo: Pick +): string { + return [ + getRepoExecutionHostId(repo), + repo.connectionId?.trim() ?? '', + normalizeRuntimePathForComparison(repo.path) + ].join('\0') +} + +export function isRepoWorktreeId(repoId: string, worktreeId: string): boolean { + return worktreeId === repoId || worktreeId.startsWith(`${repoId}${WORKTREE_ID_SEPARATOR}`) +} + +export function rekeyWorktreeId(oldRepoId: string, newRepoId: string, worktreeId: string): string { + if (worktreeId === oldRepoId) { + return newRepoId + } + const prefix = `${oldRepoId}${WORKTREE_ID_SEPARATOR}` + return worktreeId.startsWith(prefix) + ? `${newRepoId}${WORKTREE_ID_SEPARATOR}${worktreeId.slice(prefix.length)}` + : worktreeId +} + +export function rekeyWorkspaceKey( + oldRepoId: string, + newRepoId: string, + workspaceKey: WorkspaceKey +): WorkspaceKey { + const parsed = parseWorkspaceKey(workspaceKey) + if (parsed?.type !== 'worktree' || !isRepoWorktreeId(oldRepoId, parsed.worktreeId)) { + return workspaceKey + } + return worktreeWorkspaceKey(rekeyWorktreeId(oldRepoId, newRepoId, parsed.worktreeId)) +} + +export function rekeyOwnerKey( + oldRepoId: string, + newRepoId: string, + ownerKey: string +): string | null { + if (isRepoWorktreeId(oldRepoId, ownerKey)) { + return rekeyWorktreeId(oldRepoId, newRepoId, ownerKey) + } + const parsed = parseWorkspaceKey(ownerKey) + if (parsed?.type === 'worktree' && isRepoWorktreeId(oldRepoId, parsed.worktreeId)) { + return worktreeWorkspaceKey(rekeyWorktreeId(oldRepoId, newRepoId, parsed.worktreeId)) + } + return null +} + +export function ownerKeyBelongsToRepo(ownerKey: string, repoId: string): boolean { + if (isRepoWorktreeId(repoId, ownerKey)) { + return true + } + const parsed = parseWorkspaceKey(ownerKey) + return parsed?.type === 'worktree' && isRepoWorktreeId(repoId, parsed.worktreeId) +} + +export function removeRepoWorktreeRecord( + record: Record | undefined, + repoId: string +): Record { + const next = { ...record } + for (const key of Object.keys(next)) { + if (ownerKeyBelongsToRepo(key, repoId)) { + delete next[key] + } + } + return next +} diff --git a/src/main/orca-profiles/profile-storage-paths.ts b/src/main/orca-profiles/profile-storage-paths.ts new file mode 100644 index 000000000000..5f8dc0df2411 --- /dev/null +++ b/src/main/orca-profiles/profile-storage-paths.ts @@ -0,0 +1,72 @@ +import { app } from 'electron' +import { join } from 'node:path' + +const LEGACY_DATA_FILE_NAME = 'orca-data.json' +const LEGACY_BROWSER_SESSION_META_FILE_NAME = 'browser-session-meta.json' +const PROFILE_INDEX_FILE_NAME = 'orca-profile-index.json' +const PROFILE_DATA_FILE_NAME = 'orca-data.json' +const PROFILE_BROWSER_SESSION_META_FILE_NAME = 'browser-session-meta.json' +const PROFILE_DIRECTORY_NAME = 'profiles' + +export const LEGACY_BACKUP_COUNT = 5 + +let profileUserDataPath: string | null = null + +export function initOrcaProfilePaths(): void { + profileUserDataPath = app.getPath('userData') +} + +export function getProfileUserDataPath(): string { + if (!profileUserDataPath) { + profileUserDataPath = app.getPath('userData') + } + return profileUserDataPath +} + +export function getOrcaProfileIndexPath(userDataPath = getProfileUserDataPath()): string { + return join(userDataPath, PROFILE_INDEX_FILE_NAME) +} + +export function getOrcaProfilesDirectory(userDataPath = getProfileUserDataPath()): string { + return join(userDataPath, PROFILE_DIRECTORY_NAME) +} + +export function getOrcaProfileDirectory( + profileId: string, + userDataPath = getProfileUserDataPath() +): string { + return join(getOrcaProfilesDirectory(userDataPath), profileId) +} + +export function getOrcaProfileDataFile( + profileId: string, + userDataPath = getProfileUserDataPath() +): string { + return join(getOrcaProfileDirectory(profileId, userDataPath), PROFILE_DATA_FILE_NAME) +} + +export function getOrcaProfileBrowserSessionMetaFile( + profileId: string, + userDataPath = getProfileUserDataPath() +): string { + return join( + getOrcaProfileDirectory(profileId, userDataPath), + PROFILE_BROWSER_SESSION_META_FILE_NAME + ) +} + +export function legacyDataFilePath(userDataPath: string): string { + return join(userDataPath, LEGACY_DATA_FILE_NAME) +} + +export function legacyBrowserSessionMetaPath(userDataPath: string): string { + return join(userDataPath, LEGACY_BROWSER_SESSION_META_FILE_NAME) +} + +export function legacyBackupPath(userDataPath: string, index: number): string { + return `${legacyDataFilePath(userDataPath)}.bak.${index}` +} + +export function profileBackupPath(profileDataFile: string, index: number): string { + return `${profileDataFile}.bak.${index}` +} diff --git a/src/main/orca-profiles/profile-ui-scope.test.ts b/src/main/orca-profiles/profile-ui-scope.test.ts new file mode 100644 index 000000000000..0ed1f31de0d5 --- /dev/null +++ b/src/main/orca-profiles/profile-ui-scope.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest' +import { isMultiProfileUiEnabled } from './profile-ui-scope' + +describe('isMultiProfileUiEnabled', () => { + it('enables multi-profile UI only when the flag is exactly "1"', () => { + expect(isMultiProfileUiEnabled({ ORCA_MULTI_PROFILE_UI: '1' })).toBe(true) + }) + + it('defaults to the single-profile account menu', () => { + expect(isMultiProfileUiEnabled({})).toBe(false) + expect(isMultiProfileUiEnabled({ ORCA_MULTI_PROFILE_UI: '0' })).toBe(false) + expect(isMultiProfileUiEnabled({ ORCA_MULTI_PROFILE_UI: 'true' })).toBe(false) + }) +}) diff --git a/src/main/orca-profiles/profile-ui-scope.ts b/src/main/orca-profiles/profile-ui-scope.ts new file mode 100644 index 000000000000..937f4af2abd2 --- /dev/null +++ b/src/main/orca-profiles/profile-ui-scope.ts @@ -0,0 +1,6 @@ +// Why: multi-profile management is downscoped to an accounts-first UX, not +// removed — the full switcher stays reachable behind this product-scope toggle +// (safe in packaged builds; it is not a security escape hatch). +export function isMultiProfileUiEnabled(env: NodeJS.ProcessEnv = process.env): boolean { + return env.ORCA_MULTI_PROFILE_UI === '1' +} diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts index d4862d9dcae4..a0d3f760779b 100644 --- a/src/main/persistence.test.ts +++ b/src/main/persistence.test.ts @@ -337,6 +337,31 @@ describe('Store', () => { expect(store.getRepos()).toEqual([]) }, 15_000) + it('loads state from an explicit profile data file path', async () => { + const profileDataDirectory = join(testState.dir, 'profiles', 'local-default') + const profileDataFile = join(profileDataDirectory, 'orca-data.json') + mkdirSync(profileDataDirectory, { recursive: true }) + writeDataFile({ + schemaVersion: 1, + repos: [makeRepo({ id: 'legacy-root-repo', path: '/legacy' })] + }) + writeFileSync( + profileDataFile, + JSON.stringify({ + schemaVersion: 1, + repos: [makeRepo({ id: 'profile-repo', path: '/profile' })] + }), + 'utf-8' + ) + + vi.resetModules() + const { Store, initDataPath } = await import('./persistence') + initDataPath() + const store = new Store({ dataFile: profileDataFile }) + + expect(store.getRepos().map((repo) => repo.id)).toEqual(['profile-repo']) + }, 15_000) + it('backfills project host setup compatibility records from legacy repos on load', async () => { writeDataFile({ schemaVersion: 1, @@ -502,7 +527,7 @@ describe('Store', () => { expect(settings.experimentalActivity).toBe(false) expect(settings.experimentalActivityDefaultedOffForAllUsers).toBe(true) expect(settings.experimentalTerminalAttention).toBe(false) - expect(settings.experimentalNewWorktreeCardStyle).toBe(true) + expect(settings.experimentalNewWorktreeCardStyle).toBe(false) expect(settings.floatingTerminalEnabled).toBe(true) expect(settings.floatingTerminalDefaultedForAllUsers).toBe(true) expect(settings.notifications.customSoundPath).toBeNull() @@ -510,6 +535,20 @@ describe('Store', () => { expect(settings.notifications.suppressWhenFocused).toBe(true) }) + it('repairs a persisted terminal line height outside xterm bounds', async () => { + const persisted = getDefaultPersistedState(testState.dir) + writeDataFile({ + ...persisted, + settings: { ...persisted.settings, terminalLineHeight: 0.85 } + }) + + const store = await createStore() + + expect(store.getSettings().terminalLineHeight).toBe(1) + store.flush() + expect((readDataFile() as PersistedState).settings.terminalLineHeight).toBe(1) + }) + it('returns default UI state when no data file exists', async () => { const store = await createStore() const ui = store.getUI() @@ -633,7 +672,7 @@ describe('Store', () => { expect(store.getUI().setupGuideSidebarDismissed).toBe(false) }) - it('defaults new worktree card style on while onboarding is open', async () => { + it('keeps new worktree card style off while onboarding is open', async () => { writeDataFile({ settings: {}, onboarding: { @@ -648,7 +687,7 @@ describe('Store', () => { const store = await createStore() - expect(store.getSettings().experimentalNewWorktreeCardStyle).toBe(true) + expect(store.getSettings().experimentalNewWorktreeCardStyle).toBe(false) }) it('preserves explicit new worktree card style opt-out while onboarding is open', async () => { @@ -671,6 +710,20 @@ describe('Store', () => { expect(store.getSettings().experimentalNewWorktreeCardStyle).toBe(false) }) + it('preserves explicit new worktree card style opt-in on load', async () => { + writeDataFile({ + schemaVersion: 1, + settings: { + experimentalNewWorktreeCardStyle: true + }, + ui: {} + }) + + const store = await createStore() + + expect(store.getSettings().experimentalNewWorktreeCardStyle).toBe(true) + }) + it('keeps new worktree card style off for existing users backfilled as completed', async () => { writeDataFile({ schemaVersion: 1, @@ -1646,6 +1699,128 @@ describe('Store', () => { expect(migratedRun?.sourceContext).toEqual(migratedAutomation?.sourceContext) }) + it('shrinks an oversized automationRuns file on load without any later mutation', async () => { + const seed = await createStore() + seed.addRepo( + makeRepo({ + upstream: { owner: 'stablyai', repo: 'orca' }, + connectionId: 'builder' + }) + ) + const automation = seed.createAutomation({ + name: 'Every minute', + prompt: 'Run checks', + agentId: 'claude', + projectId: 'r1', + workspaceMode: 'new_per_run', + timezone: 'UTC', + rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', + dtstart: new Date('2026-05-13T00:00:00Z').getTime() + }) + seed.createAutomationRun(automation, new Date('2026-05-13T09:00:00Z').getTime()) + seed.flush() + + // Why: a fresh store never stamps the one-shot UI migration flags, so a + // second load+flush settles them — otherwise they, not the prune, mark dirty. + const warm = await createStore() + warm.flush() + + const persisted = readDataFile() as { automationRuns: Record[] } + const template = persisted.automationRuns[0] + persisted.automationRuns = Array.from({ length: 250 }, (_, i) => { + const legacy: Record = { + ...template, + id: `legacy-run-${i}`, + // Only final runs are evictable; the real-world blowup was skipped_precheck rows. + status: 'skipped_precheck', + createdAt: 1_000 + i, + scheduledFor: 1_000 + i + } + // A real legacy file predates runNumber; backfill must run BEFORE the prune + // so survivors keep their true ordinals instead of restarting at 1. + delete legacy.runNumber + return legacy + }) + writeDataFile(persisted) + + vi.useFakeTimers() + try { + const reloaded = await createStore() + expect(reloaded.listAutomationRuns(automation.id)).toHaveLength(100) + + // The load-path prune must mark state dirty on its own; nothing else here saves. + vi.advanceTimersByTime(1000) + await reloaded.waitForPendingWrite() + } finally { + vi.useRealTimers() + } + + const healed = readDataFile() as { automationRuns: Record[] } + expect(healed.automationRuns).toHaveLength(100) + expect(healed.automationRuns.at(-1)?.id).toBe('legacy-run-249') + // Survivors carry their true lifetime ordinals (151..250), not restarted ones. + expect(healed.automationRuns[0]?.runNumber).toBe(151) + expect(healed.automationRuns.at(-1)?.runNumber).toBe(250) + }) + + it('does not strand an in-flight run whose completion lands after the retention cap', async () => { + const store = await createStore() + store.addRepo( + makeRepo({ + upstream: { owner: 'stablyai', repo: 'orca' }, + connectionId: 'builder' + }) + ) + const automation = store.createAutomation({ + name: 'Every minute', + prompt: 'Run checks', + agentId: 'claude', + projectId: 'r1', + workspaceMode: 'new_per_run', + timezone: 'UTC', + rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', + dtstart: new Date('2026-05-13T00:00:00Z').getTime() + }) + const base = new Date('2026-05-13T09:00:00Z').getTime() + const inFlight = store.createAutomationRun(automation, base) + store.updateAutomationRun({ + runId: inFlight.id, + status: 'dispatched', + workspaceId: null, + error: null + }) + + // 120 later runs reach a final status while the first one is still dispatched. + let firstCompletedId = '' + for (let i = 1; i <= 120; i++) { + const later = store.createAutomationRun(automation, base + i * 60_000) + firstCompletedId ||= later.id + store.updateAutomationRun({ + runId: later.id, + status: 'completed', + workspaceId: null, + error: null + }) + } + + // The late completion must still find its row. + const completed = store.updateAutomationRun({ + runId: inFlight.id, + status: 'completed', + workspaceId: null, + error: null + }) + expect(completed.id).toBe(inFlight.id) + + const runs = store.listAutomationRuns(automation.id) + expect(runs.some((run) => run.id === inFlight.id)).toBe(true) + // Final runs beyond the cap were still evicted. The store can briefly hold + // cap + 2: the last-created run finalizes after the prune at its creation, + // and the late completion lands without a prune of its own. + expect(runs.some((run) => run.id === firstCompletedId)).toBe(false) + expect(runs.length).toBeLessThanOrEqual(102) + }) + it('persists automation precheck config and run results', async () => { const store = await createStore() store.addRepo(makeRepo()) @@ -2988,6 +3163,16 @@ describe('Store', () => { expect(updated?.projectGroupOrder).toBe(1) }) + it('updates repo execution host identity', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'r1' })) + + const updated = store.updateRepo('r1', { executionHostId: 'runtime:env-1' }) + + expect(updated?.executionHostId).toBe('runtime:env-1') + expect(store.getRepo('r1')?.executionHostId).toBe('runtime:env-1') + }) + it('getRepo returns undefined for nonexistent id', async () => { const store = await createStore() expect(store.getRepo('nonexistent')).toBeUndefined() @@ -3058,6 +3243,270 @@ describe('Store', () => { expect(store.getWorktreeLineage('r2::/other')).toBeDefined() }) + // ── 6b. removeProjectForHost is host-scoped ─────────────────────────── + + it('removeProjectForHost removes only the target host row for a shared repo id', async () => { + const store = await createStore() + // Same repo id on both local and an SSH host. + store.addRepo(makeRepo({ id: 'shared', path: '/local/repo' })) + store.addRepo( + makeRepo({ + id: 'shared', + path: '/remote/repo', + connectionId: 'ssh-old', + executionHostId: 'ssh:ssh-old' + }) + ) + store.setWorktreeMeta('shared::/local/repo/wt', { displayName: 'local-wt', hostId: 'local' }) + store.setWorktreeMeta('shared::/remote/repo/wt', { + displayName: 'remote-wt', + hostId: 'ssh:ssh-old' + }) + + store.removeProjectForHost('shared', 'ssh:ssh-old') + + const remaining = store.getRepos().filter((r) => r.id === 'shared') + expect(remaining).toHaveLength(1) + expect(remaining[0].path).toBe('/local/repo') + // Local worktree meta survives; the SSH host's meta is pruned. + expect(store.getWorktreeMeta('shared::/local/repo/wt')).toBeDefined() + expect(store.getWorktreeMeta('shared::/remote/repo/wt')).toBeUndefined() + }) + + it('removeProjectForHost prunes the SSH host meta (tagged hostId) for a shared id', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'shared', path: '/local/repo' })) + store.addRepo( + makeRepo({ + id: 'shared', + path: '/remote/repo', + connectionId: 'ssh-old', + executionHostId: 'ssh:ssh-old' + }) + ) + // SSH worktree meta correctly carries hostId (the normal, stamped case). + store.setWorktreeMeta('shared::/remote/repo/wt', { + displayName: 'remote-wt', + hostId: 'ssh:ssh-old' + }) + // A hostId-less meta under the same id is treated as local and left behind + // (conservative: never deletes the wrong host's meta). + store.setWorktreeMeta('shared::/local/repo/wt', { displayName: 'local-wt' }) + + store.removeProjectForHost('shared', 'ssh:ssh-old') + + expect(store.getWorktreeMeta('shared::/remote/repo/wt')).toBeUndefined() + expect(store.getWorktreeMeta('shared::/local/repo/wt')).toBeDefined() + }) + + it('removeProjectForHost prunes everything when the id exists on no other host', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'only', connectionId: 'ssh-x', executionHostId: 'ssh:ssh-x' })) + store.setWorktreeMeta('only::/repo/wt', { displayName: 'wt', hostId: 'ssh:ssh-x' }) + + store.removeProjectForHost('only', 'ssh:ssh-x') + + expect(store.getRepo('only')).toBeUndefined() + expect(store.getWorktreeMeta('only::/repo/wt')).toBeUndefined() + }) + + // ── 6c. reassignSshTargetId re-adopts orphaned workspaces ───────────── + + it('reassignSshTargetId re-points repos and worktree metas onto the new id', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'r1', connectionId: 'ssh-old', executionHostId: 'ssh:ssh-old' })) + store.setWorktreeMeta('r1::/repo/wt', { displayName: 'wt', hostId: 'ssh:ssh-old' }) + + const count = store.reassignSshTargetId('ssh-old', 'ssh-new') + + expect(count).toBe(1) + const repo = store.getRepo('r1')! + expect(repo.connectionId).toBe('ssh-new') + expect(repo.executionHostId).toBe('ssh:ssh-new') + expect(store.getWorktreeMeta('r1::/repo/wt')!.hostId).toBe('ssh:ssh-new') + }) + + it('reassignSshTargetId leaves repos on other hosts untouched', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'local-repo', path: '/local' })) + store.addRepo( + makeRepo({ + id: 'ssh-repo', + path: '/remote', + connectionId: 'ssh-old', + executionHostId: 'ssh:ssh-old' + }) + ) + + const count = store.reassignSshTargetId('ssh-old', 'ssh-new') + + expect(count).toBe(1) + expect(store.getRepo('local-repo')!.connectionId).toBeUndefined() + expect(store.getRepo('ssh-repo')!.connectionId).toBe('ssh-new') + }) + + it('reassignSshTargetId re-points a repo that only carries connectionId (no executionHostId)', async () => { + const store = await createStore() + // SSH repos created via addRemoteRepoFromPath leave executionHostId unset. + store.addRepo(makeRepo({ id: 'r1', connectionId: 'ssh-old' })) + + const count = store.reassignSshTargetId('ssh-old', 'ssh-new') + + expect(count).toBe(1) + const repo = store.getRepo('r1')! + expect(repo.connectionId).toBe('ssh-new') + // Must not stamp an executionHostId where there wasn't one. + expect(repo.executionHostId).toBeUndefined() + }) + + it('reassignSshTargetId persists a worktree-meta-only re-point (no matching repo)', async () => { + const store = await createStore() + // A meta on the old SSH host with no corresponding repo row — the re-point + // must still be saved, not left in memory only. + store.setWorktreeMeta('r1::/remote/wt', { displayName: 'wt', hostId: 'ssh:ssh-old' }) + + const count = store.reassignSshTargetId('ssh-old', 'ssh-new') + expect(count).toBe(0) // no repo matched + store.flush() + + const reloaded = await createStore() + expect(reloaded.getWorktreeMeta('r1::/remote/wt')?.hostId).toBe('ssh:ssh-new') + }) + + it('reassignSshTargetId migrates session pty ids, reconnect list, leases, and host scope', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'r1', connectionId: 'ssh-old', executionHostId: 'ssh:ssh-old' })) + store.setWorkspaceSession({ + activeRepoId: 'r1', + activeWorktreeId: 'r1::/wt', + activeTabId: 'tab1', + tabsByWorktree: { + 'r1::/wt': [makeTerminalTab({ id: 'tab1', ptyId: 'ssh:ssh-old@@pty-2' })] + }, + terminalLayoutsByTabId: {}, + remoteSessionIdsByTabId: { tab1: 'ssh:ssh-old@@pty-2' }, + activeConnectionIdsAtShutdown: ['ssh-old'] + }) + store.upsertSshRemotePtyLease({ targetId: 'ssh-old', ptyId: 'pty-2', state: 'detached' }) + store.updateUI({ + workspaceHostScope: 'ssh:ssh-old', + visibleWorkspaceHostIds: ['local', 'ssh:ssh-old'], + workspaceHostOrder: ['ssh:ssh-old', 'local'] + }) + + store.reassignSshTargetId('ssh-old', 'ssh-new') + store.flush() + + const reloaded = await createStore() + const session = reloaded.getWorkspaceSession() + expect(session.tabsByWorktree['r1::/wt'][0].ptyId).toBe('ssh:ssh-new@@pty-2') + expect(session.remoteSessionIdsByTabId).toEqual({ tab1: 'ssh:ssh-new@@pty-2' }) + expect(session.activeConnectionIdsAtShutdown).toEqual(['ssh-new']) + expect(reloaded.getSshRemotePtyLeases('ssh-new')).toHaveLength(1) + expect(reloaded.getSshRemotePtyLeases('ssh-old')).toHaveLength(0) + const ui = reloaded.getUI() + expect(ui.workspaceHostScope).toBe('ssh:ssh-new') + expect(ui.visibleWorkspaceHostIds).toEqual(['local', 'ssh:ssh-new']) + expect(ui.workspaceHostOrder).toEqual(['ssh:ssh-new', 'local']) + }) + + it('reassignSshTargetId re-keys a session partition stored under the old ssh host id', async () => { + const store = await createStore() + store.setWorkspaceSession( + { + activeRepoId: null, + activeWorktreeId: null, + activeTabId: null, + tabsByWorktree: { + 'r1::/wt': [makeTerminalTab({ id: 'tab1', ptyId: 'ssh:ssh-old@@pty-9' })] + }, + terminalLayoutsByTabId: {} + }, + 'ssh:ssh-old' + ) + + store.reassignSshTargetId('ssh-old', 'ssh-new') + store.flush() + + const reloaded = await createStore() + // Old-key partition is gone; the re-keyed one carries migrated pty ids. + expect(reloaded.getWorkspaceSession('ssh:ssh-old').tabsByWorktree).toEqual({}) + expect(reloaded.getWorkspaceSession('ssh:ssh-new').tabsByWorktree['r1::/wt'][0].ptyId).toBe( + 'ssh:ssh-new@@pty-9' + ) + }) + + it('reassignSshTargetId keeps the live partition when both host keys exist', async () => { + const store = await createStore() + const baseSession = { + activeRepoId: null, + activeWorktreeId: null, + activeTabId: null, + terminalLayoutsByTabId: {} + } + store.setWorkspaceSession( + { ...baseSession, tabsByWorktree: { 'r1::/dead': [] } }, + 'ssh:ssh-old' + ) + store.setWorkspaceSession( + { ...baseSession, tabsByWorktree: { 'r1::/live': [] } }, + 'ssh:ssh-new' + ) + + store.reassignSshTargetId('ssh-old', 'ssh-new') + + expect(store.getWorkspaceSession('ssh:ssh-old').tabsByWorktree).toEqual({}) + expect(store.getWorkspaceSession('ssh:ssh-new').tabsByWorktree).toEqual({ 'r1::/live': [] }) + }) + + it('reassignSshTargetId re-points an independent provisioned host setup', async () => { + const store = await createStore() + store.addRepo({ + ...makeRepo({ id: 'r1', displayName: 'Cloud Project' }), + upstream: { owner: 'stablyai', repo: 'cloud-project' } + }) + store.createProjectHostSetup({ + projectId: 'github:stablyai/cloud-project', + hostId: 'ssh:ssh-old', + setupId: 'cloud-project::ssh-old', + setupMethod: 'provisioned' + }) + + // Meta-only re-adoption (no repo pinned to the old id) must still migrate + // the provisioned setup, or new worktrees would be born on a dead host id. + store.reassignSshTargetId('ssh-old', 'ssh-new') + + const setups = store.getProjectHostSetups() + const provisioned = setups.find((entry) => entry.id === 'cloud-project::ssh-old') + expect(provisioned?.hostId).toBe('ssh:ssh-new') + }) + + it('reassignSshTargetId drops a stale setup when the new host already has one', async () => { + const store = await createStore() + store.addRepo({ + ...makeRepo({ id: 'r1', displayName: 'Cloud Project' }), + upstream: { owner: 'stablyai', repo: 'cloud-project' } + }) + store.createProjectHostSetup({ + projectId: 'github:stablyai/cloud-project', + hostId: 'ssh:ssh-old', + setupId: 'setup-old', + setupMethod: 'provisioned' + }) + store.createProjectHostSetup({ + projectId: 'github:stablyai/cloud-project', + hostId: 'ssh:ssh-new', + setupId: 'setup-new', + setupMethod: 'provisioned' + }) + + store.reassignSshTargetId('ssh-old', 'ssh-new') + + const setups = store.getProjectHostSetups() + expect(setups.find((entry) => entry.id === 'setup-old')).toBeUndefined() + expect(setups.find((entry) => entry.id === 'setup-new')?.hostId).toBe('ssh:ssh-new') + }) + // ── 7. updateRepo ────────────────────────────────────────────────── it('updateRepo modifies the repo in place', async () => { @@ -4735,6 +5184,33 @@ describe('Store', () => { expect(restarted.getGitHubCache().pr['o/r#7']).toEqual({ fetchedAt: 7 }) }) + it('keeps GitHub cache sidecars scoped to explicit profile data files', async () => { + const profileADir = join(testState.dir, 'profiles', 'a') + const profileBDir = join(testState.dir, 'profiles', 'b') + const profileADataFile = join(profileADir, 'orca-data.json') + const profileBDataFile = join(profileBDir, 'orca-data.json') + mkdirSync(profileADir, { recursive: true }) + mkdirSync(profileBDir, { recursive: true }) + + vi.resetModules() + const { Store, initDataPath } = await import('./persistence') + initDataPath() + const profileAStore = new Store({ dataFile: profileADataFile }) + profileAStore.setGitHubCache({ pr: { 'o/r#a': { fetchedAt: 10 } as never }, issue: {} }) + profileAStore.flush() + + const profileBStore = new Store({ dataFile: profileBDataFile }) + expect(profileBStore.getGitHubCache().pr['o/r#a']).toBeUndefined() + profileBStore.setGitHubCache({ pr: { 'o/r#b': { fetchedAt: 20 } as never }, issue: {} }) + profileBStore.flush() + + const restartedProfileA = new Store({ dataFile: profileADataFile }) + const restartedProfileB = new Store({ dataFile: profileBDataFile }) + expect(restartedProfileA.getGitHubCache().pr['o/r#a']).toEqual({ fetchedAt: 10 }) + expect(restartedProfileA.getGitHubCache().pr['o/r#b']).toBeUndefined() + expect(restartedProfileB.getGitHubCache().pr['o/r#b']).toEqual({ fetchedAt: 20 }) + }) + it('keeps a legacy in-file cache as the seed and strips it from disk', async () => { writeDataFile({ githubCache: { pr: { legacy: { fetchedAt: 1 } }, issue: {} } }) @@ -6106,6 +6582,49 @@ describe('Store', () => { expect(ref ? store.readTerminalScrollbackSnapshot(ref) : null).toBe('remote-scrollback') }) + it('stores terminal scrollback snapshots beside explicit profile data files', async () => { + const profileDataDirectory = join(testState.dir, 'profiles', 'local-default') + const profileDataFile = join(profileDataDirectory, 'orca-data.json') + mkdirSync(profileDataDirectory, { recursive: true }) + + vi.resetModules() + const { Store, initDataPath } = await import('./persistence') + initDataPath() + const store = new Store({ dataFile: profileDataFile }) + store.addRepo(makeRepo({ id: 'remote-repo', connectionId: 'ssh-target-1' })) + const session = makeSessionWithTerminalBuffers() + store.setWorkspaceSession({ + ...session, + tabsByWorktree: { 'remote-repo::/remote': session.tabsByWorktree['remote-repo::/remote'] }, + terminalLayoutsByTabId: { 'remote-tab': session.terminalLayoutsByTabId['remote-tab'] } + }) + + const ref = + store.getWorkspaceSession().terminalLayoutsByTabId['remote-tab'].scrollbackRefsByLeafId?.[ + TEST_LEAF_2 + ] + expect(ref).toEqual(expect.stringMatching(/^v1-[0-9a-f]{32}$/)) + expect(existsSync(join(profileDataDirectory, 'terminal-scrollback', `${ref}.bin`))).toBe(true) + expect(existsSync(join(testState.dir, 'terminal-scrollback', `${ref}.bin`))).toBe(false) + }) + + it('reads legacy terminal scrollback snapshots for explicit profile data files', async () => { + const profileDataDirectory = join(testState.dir, 'profiles', 'local-default') + const profileDataFile = join(profileDataDirectory, 'orca-data.json') + const ref = 'v1-11111111111111111111111111111111' + const legacySnapshotDir = join(testState.dir, 'terminal-scrollback') + mkdirSync(profileDataDirectory, { recursive: true }) + mkdirSync(legacySnapshotDir, { recursive: true }) + writeFileSync(join(legacySnapshotDir, `${ref}.bin`), 'legacy-scrollback', 'utf-8') + + vi.resetModules() + const { Store, initDataPath } = await import('./persistence') + initDataPath() + const store = new Store({ dataFile: profileDataFile }) + + expect(store.readTerminalScrollbackSnapshot(ref)).toBe('legacy-scrollback') + }) + it('caps oversized browser history when setting workspace session', async () => { const store = await createStore() const oversizedSession = makeSessionWithBrowserHistory(500) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 5bad9510e65a..d4b68e7f4b48 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -82,6 +82,7 @@ import { MOBILE_PAIRING_USERDATA_FILES } from './runtime/mobile-pairing-files' import { hardenExistingSecureFile } from '../shared/secure-file' import { LEGACY_DEFAULT_SSH_RELAY_GRACE_PERIOD_SECONDS, + type RemovedSshTargetTombstone, type SshRemotePtyLease, type SshTarget } from '../shared/ssh-types' @@ -108,9 +109,14 @@ import { normalizeExecutionHostOrder, normalizeExecutionHostId, normalizeVisibleExecutionHostIds, + toSshExecutionHostId, type ExecutionHostId } from '../shared/execution-host' import { toRelaySshPtyId } from './providers/ssh-pty-id' +import { + migrateUiHostScopeSshTargetId, + migrateWorkspaceSessionSshTargetId +} from './ssh/ssh-target-id-migration' import { isWslUncPath } from '../shared/wsl-paths' import { isTerminalLeafId, @@ -124,6 +130,11 @@ import { } from './agent-hooks/migration-unsupported-pty-state' import { agentHookServer } from './agent-hooks/server' import { pruneLocalTerminalScrollbackBuffers } from '../shared/workspace-session-terminal-buffers' +import { + backfillAutomationRunNumbers, + nextAutomationRunNumber, + pruneAutomationRuns +} from '../shared/automation-run-retention' import { pruneWorkspaceSessionBrowserHistory } from '../shared/workspace-session-browser-history' import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR, @@ -197,6 +208,7 @@ import { normalizeTuiAgentEnvRecord } from '../shared/tui-agent-launch-defaults' import { normalizeTerminalCursorStyleDefault } from '../shared/terminal-cursor-style-settings' +import { normalizeTerminalLineHeight } from '../shared/terminal-line-height-settings' import { normalizeUiLanguage } from '../shared/ui-language' import { normalizeBrowserPageZoomLevel } from '../shared/browser-page-zoom' import { persistedUIValuesEqual } from '../shared/persisted-ui-equality' @@ -213,8 +225,10 @@ import { import { collectTerminalScrollbackSnapshotRefs, deleteTerminalScrollbackSnapshotSync, + getProfileTerminalScrollbackSnapshotRoot, migrateWorkspaceSessionTerminalScrollbackSnapshots, - readTerminalScrollbackSnapshotSync + readTerminalScrollbackSnapshotSync, + type TerminalScrollbackSnapshotStorage } from './terminal-scrollback-snapshots' import { track } from './telemetry/client' import { getCohortAtEmit } from './telemetry/cohort-classifier' @@ -336,8 +350,8 @@ function getDataFile(): string { // the content-hash guard by design). It lives in memory during the session // and is snapshotted here best-effort at quit so PR/issue badges still paint // instantly on the next launch. Loss of this file costs nothing. -function getGithubCacheFile(): string { - return join(dirname(getDataFile()), 'orca-github-cache.json') +function getGithubCacheFile(dataFile = getDataFile()): string { + return join(dirname(dataFile), 'orca-github-cache.json') } // Why: worktrees deleted outside Orca (git CLI worktree remove, rm -rf, @@ -416,9 +430,9 @@ function gcStaleWorktreeMeta(state: PersistedState): number { return removed } -function readGithubCacheSnapshot(): PersistedState['githubCache'] | null { +function readGithubCacheSnapshot(dataFile: string): PersistedState['githubCache'] | null { try { - const parsed = JSON.parse(readFileSync(getGithubCacheFile(), 'utf-8')) as unknown + const parsed = JSON.parse(readFileSync(getGithubCacheFile(dataFile), 'utf-8')) as unknown const isPlainRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value) if ( @@ -1342,10 +1356,6 @@ function resolveSetupGuideSidebarDismissedOnLoad( return onboarding.closedAt !== null || persistedDismissed === true } -function shouldDefaultNewWorktreeCardStyleOn(onboarding: OnboardingState): boolean { - return onboarding.closedAt === null -} - // Why: read a settings field that was removed from GlobalSettings but can // still exist on disk. One-shot use for the inline-agents migration. function readDeprecatedExperimentFlag(parsed: PersistedState | undefined): boolean { @@ -2181,6 +2191,10 @@ function remapAcknowledgedAgentPaneKeys( // handful of Claude sessions a daemon can realistically keep alive. const MAX_CLAUDE_LIVE_PTY_SESSION_IDS = 200 +// Why: bound the removed-SSH-target history so remove/re-add churn can't grow +// the state file without limit. Re-adoption only needs recent removals. +const MAX_REMOVED_SSH_TARGET_TOMBSTONES = 50 + function normalizeClaudeLivePtySessionIds(value: unknown): string[] { if (!Array.isArray(value)) { return [] @@ -2564,7 +2578,8 @@ function backfillFolderScopeConnectionIds(state: PersistedState): { function deleteRemovedTerminalScrollbackSnapshots( prior: WorkspaceSessionState | undefined, - next: WorkspaceSessionState + next: WorkspaceSessionState, + storage?: TerminalScrollbackSnapshotStorage ): void { if (!prior) { return @@ -2572,16 +2587,26 @@ function deleteRemovedTerminalScrollbackSnapshots( const nextRefs = collectTerminalScrollbackSnapshotRefs(next) for (const ref of collectTerminalScrollbackSnapshotRefs(prior)) { if (!nextRefs.has(ref)) { - deleteTerminalScrollbackSnapshotSync(ref) + deleteTerminalScrollbackSnapshotSync(ref, storage) } } } +export type StoreOptions = { + dataFile?: string +} + export class Store { private state: PersistedState + private readonly dataFile: string + private readonly terminalScrollbackSnapshotStorage: TerminalScrollbackSnapshotStorage private writeTimer: ReturnType | null = null private pendingWrite: Promise | null = null private writeGeneration = 0 + // Why: after a profile transfer rewrites this store's file on disk behind + // its back, the stale in-memory state must never be persisted again — a + // late sync flush before the relaunch would resurrect the moved project. + private writesFrozen = false // Why: hash of the plaintext state as of the last successful write. Saves // triggered by mutations that net out to identical state skip the full // 1.6MB pretty-print + tmp write + rename. Hashing plaintext (not the @@ -2601,7 +2626,16 @@ export class Store { >() private uiChangeListeners = new Set<(ui: PersistedState['ui']) => void>() - constructor() { + constructor(options: StoreOptions = {}) { + // Why: profile switching creates more than one possible state path. Capture + // the path per Store instance so late async writes cannot follow a global path. + this.dataFile = options.dataFile ?? getDataFile() + const profileSnapshotRoot = getProfileTerminalScrollbackSnapshotRoot(this.dataFile) + const legacySnapshotRoot = getProfileTerminalScrollbackSnapshotRoot(getDataFile()) + this.terminalScrollbackSnapshotStorage = { + snapshotRoot: profileSnapshotRoot, + fallbackSnapshotRoot: legacySnapshotRoot === profileSnapshotRoot ? null : legacySnapshotRoot + } const loaded = this.load() const normalized = normalizePersistedPaneIdentityState(loaded) this.state = normalized.state @@ -2810,7 +2844,7 @@ export class Store { // would be absent on every pre-telemetry install and misclassify existing // users as fresh, flipping them to default-on in violation of the // social contract we installed them under. - const dataFile = getDataFile() + const dataFile = this.dataFile const fileExistedOnLoad = existsSync(dataFile) logPersistenceStartupMilestone('persistence-load-start', { fileExists: fileExistedOnLoad @@ -2959,6 +2993,15 @@ export class Store { parsed.settings ) const migratedTerminalCursorStyle = normalizeTerminalCursorStyleDefault(parsed.settings) + const migratedTerminalLineHeight = normalizeTerminalLineHeight( + parsed.settings?.terminalLineHeight + ) + if ( + parsed.settings?.terminalLineHeight !== undefined && + parsed.settings.terminalLineHeight !== migratedTerminalLineHeight + ) { + this.loadNeedsSave = true + } const rawTaskProviderSettings = normalizeTaskProviderSettings({ visibleTaskProviders: parsed.settings?.visibleTaskProviders, defaultTaskSource: parsed.settings?.defaultTaskSource @@ -3035,16 +3078,6 @@ export class Store { if (!parsed.onboarding) { this.loadNeedsSave = true } - const defaultNewWorktreeCardStyle = - shouldDefaultNewWorktreeCardStyleOn(normalizedOnboarding) - const migratedExperimentalNewWorktreeCardStyle = - parsed.settings?.experimentalNewWorktreeCardStyle ?? defaultNewWorktreeCardStyle - if ( - parsed.settings?.experimentalNewWorktreeCardStyle === undefined && - defaultNewWorktreeCardStyle - ) { - this.loadNeedsSave = true - } const normalizedProjectGroups = normalizeProjectGroups(parsed.projectGroups) const loadedCompactWorktreeCards = parsed.settings?.compactWorktreeCards ?? @@ -3076,6 +3109,12 @@ export class Store { ), settings: { ...defaults.settings, + // Why (#7977): a persisted experimentalNewWorktreeCardStyle:true is + // kept even though the default is now false. The v1.4.130 open- + // onboarding auto-default wrote the same plain boolean as a real + // opt-in, so a rollback migration would also revert genuine opt-ins; + // product intent was only to change the default, and the setting + // stays user-toggleable. ...stripLegacyTerminalScrollbackBytes(parsed.settings), // Why: v1.3.42 renamed the cosmetic sidekick setting to pet. Carry // the old persisted flag forward once so enabled users don't lose it. @@ -3095,12 +3134,10 @@ export class Store { primarySelectionDefaultedForTerminalDefaults || stampPrimarySelectionTerminalDefaults, ...migratedAutoRenameBranchFromWork, ...migratedTerminalCursorStyle, + terminalLineHeight: migratedTerminalLineHeight, ...migratedTerminalTuiScrollSensitivity.settings, experimentalActivity: migratedExperimentalActivity, experimentalActivityDefaultedOffForAllUsers: true, - // Why: open first-run onboarding is the local fresh-install signal; - // closed/backfilled onboarding identifies existing profiles. - experimentalNewWorktreeCardStyle: migratedExperimentalNewWorktreeCardStyle, // Why: compact worktree cards graduated from Experimental; preserve // the old opt-in for profiles written during the rollout. compactWorktreeCards: loadedCompactWorktreeCards, @@ -3355,7 +3392,18 @@ export class Store { parsed.legacyPaneKeyAliasEntries ), automations: Array.isArray(parsed.automations) ? parsed.automations : [], - automationRuns: Array.isArray(parsed.automationRuns) ? parsed.automationRuns : [], + automationRuns: (() => { + if (!Array.isArray(parsed.automationRuns)) { + return [] + } + const runs = pruneAutomationRuns(backfillAutomationRunNumbers(parsed.automationRuns)) + // Why: nothing else on the load path marks state dirty, so without + // this an oversized legacy file only shrinks at the next unrelated save. + if (runs.length !== parsed.automationRuns.length) { + this.loadNeedsSave = true + } + return runs + })(), onboarding: normalizedOnboarding } } @@ -3385,24 +3433,16 @@ export class Store { } if (result === null) { - const defaults = getDefaultPersistedState(homedir()) - const isFreshDefaultProfile = - !fileExistedOnLoad && shouldDefaultNewWorktreeCardStyleOn(defaults.onboarding) - result = { - ...defaults, - settings: { - ...defaults.settings, - // Why: a corrupt existing data file also falls back to defaults; only - // the absent-file path is a true fresh install. - experimentalNewWorktreeCardStyle: isFreshDefaultProfile - } - } + result = getDefaultPersistedState(homedir()) } const workspaceSession = pruneWorkspaceSessionBrowserHistory( pruneLocalTerminalScrollbackBuffers(result.workspaceSession, result.repos) ) - const migratedScrollback = migrateWorkspaceSessionTerminalScrollbackSnapshots(workspaceSession) + const migratedScrollback = migrateWorkspaceSessionTerminalScrollbackSnapshots( + workspaceSession, + this.terminalScrollbackSnapshotStorage + ) if (migratedScrollback.changed) { this.loadNeedsSave = true } @@ -3458,7 +3498,7 @@ export class Store { // poll refresh happens this session — the seed survives the migration. this.githubCacheDirty = true } else { - migrated.githubCache = readGithubCacheSnapshot() ?? migrated.githubCache + migrated.githubCache = readGithubCacheSnapshot(this.dataFile) ?? migrated.githubCache } logPersistenceStartupMilestone('persistence-load-done', { @@ -3606,6 +3646,9 @@ export class Store { // Why: async writes avoid blocking the main Electron thread on every // debounced save during active use. private async writeToDiskAsync(): Promise { + if (this.writesFrozen) { + return + } const gen = this.writeGeneration const stateHash = this.computeStateHash() // Why: a mutation burst that nets out to already-persisted state (or a @@ -3614,7 +3657,7 @@ export class Store { return } const payload = this.buildStateToSave() - const dataFile = getDataFile() + const dataFile = this.dataFile const dir = dirname(dataFile) await mkdir(dir, { recursive: true }).catch(() => {}) const tmpFile = `${dataFile}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp` @@ -3659,6 +3702,9 @@ export class Store { // Why: synchronous variant kept only for flush() at shutdown, where the // process may exit before an async write completes. private writeToDiskSync(opts: { force?: boolean } = {}): void { + if (this.writesFrozen) { + return + } const stateHash = this.computeStateHash() // Why: skipping is safe under flushOrThrow's durability contract — a // matching hash means this exact state is already the file's content. @@ -3668,7 +3714,7 @@ export class Store { if (!opts.force && stateHash === this.lastWrittenStateHash) { return } - const dataFile = getDataFile() + const dataFile = this.dataFile const dir = dirname(dataFile) if (!existsSync(dir)) { mkdirSync(dir, { recursive: true }) @@ -4172,30 +4218,84 @@ export class Store { // Why: presets are repo-scoped, so removing the repo means the presets // can never be referenced again — drop them with the parent. delete this.state.sparsePresetsByRepo[id] - // Clean up worktree meta for this repo + this.pruneWorktreeStateForRepo(id, null) + this.scheduleSave() + } + + // Why: the same repo id can exist on more than one execution host (local, an + // SSH target, a re-added SSH target). Forgetting one host's copy must remove + // only that host's repo row and worktree metadata — never the local or + // another host's records that happen to share the id. + removeProjectForHost(id: string, hostId: ExecutionHostId): void { + this.state.repos = this.state.repos.filter( + (r) => !(r.id === id && getRepoExecutionHostId(r) === hostId) + ) + const idStillPresent = this.state.repos.some((r) => r.id === id) + // Why: presets are repo-id-scoped (not host-scoped); only drop them once the + // last host's copy of this repo is gone, or a surviving host loses its presets. + if (!idStillPresent) { + delete this.state.sparsePresetsByRepo[id] + } + this.syncProjectHostSetupCompatibilityState() + // Why: if the id survives on another host, prune only this host's worktree + // metas; otherwise prune everything for the id (matches removeProject). + this.pruneWorktreeStateForRepo(id, idStillPresent ? hostId : null) + this.scheduleSave() + } + + // Clean up worktree meta, lineage, and workspace lineage for a repo id. + // When hostId is null, prune all of the repo's entries; when a hostId is + // given, prune only entries whose meta.hostId resolves to that host (a + // missing hostId is treated as local). + private pruneWorktreeStateForRepo(id: string, hostId: ExecutionHostId | null): void { const prefix = `${id}::` + // Why: snapshot host membership up front. Lineage pruning below checks the + // meta.hostId of worktree keys that may already have been deleted from + // worktreeMeta in the first loop, so reading hostId live would misclassify + // an SSH worktree as local once its meta is gone. + const hostMembership = new Map() + const belongsToHost = (key: string): boolean => { + if (!key.startsWith(prefix)) { + return false + } + if (hostId === null) { + return true + } + const cached = hostMembership.get(key) + if (cached !== undefined) { + return cached + } + // Why default to local: worktree metas created on/after host-ownership + // stamping carry hostId. A metas without it predates that and is treated as + // local, so a host-scoped (non-local) prune conservatively leaves it — it + // may leak a stale entry for a legacy SSH worktree sharing a repo id with a + // local repo, but it never deletes the wrong host's live meta. + const metaHostId = this.state.worktreeMeta[key]?.hostId ?? LOCAL_EXECUTION_HOST_ID + const result = metaHostId === hostId + hostMembership.set(key, result) + return result + } for (const key of Object.keys(this.state.worktreeMeta)) { - if (key.startsWith(prefix)) { + if (belongsToHost(key)) { delete this.state.worktreeMeta[key] } } for (const [childId, lineage] of Object.entries(this.state.worktreeLineageById)) { - if (childId.startsWith(prefix) || lineage.parentWorktreeId.startsWith(prefix)) { + if (belongsToHost(childId) || belongsToHost(lineage.parentWorktreeId)) { delete this.state.worktreeLineageById[childId] } } for (const [childKey, lineage] of Object.entries(this.state.workspaceLineageByChildKey)) { const childScope = parseWorkspaceKey(childKey) const parentScope = parseWorkspaceKey(lineage.parentWorkspaceKey) - if (childScope?.type === 'worktree' && childScope.worktreeId.startsWith(prefix)) { + if (childScope?.type === 'worktree' && belongsToHost(childScope.worktreeId)) { delete this.state.workspaceLineageByChildKey[childKey as WorkspaceKey] continue } - if (parentScope?.type === 'worktree' && parentScope.worktreeId.startsWith(prefix)) { + if (parentScope?.type === 'worktree' && belongsToHost(parentScope.worktreeId)) { delete this.state.workspaceLineageByChildKey[childKey as WorkspaceKey] } } - this.scheduleSave() } updateRepo( @@ -4212,6 +4312,7 @@ export class Store { | 'worktreeBaseRef' | 'worktreeBasePath' | 'kind' + | 'executionHostId' | 'symlinkPaths' | 'issueSourcePreference' | 'forkSyncMode' @@ -4616,12 +4717,15 @@ export class Store { return existing } const now = Date.now() - const runNumber = - (this.state.automationRuns ?? []).filter((run) => run.automationId === automation.id).length + - 1 + // Why: retention prunes old runs, so the count of retained runs is no longer + // the run's ordinal — carry the number forward from the newest survivor. + const runNumber = nextAutomationRunNumber( + (this.state.automationRuns ?? []).filter((run) => run.automationId === automation.id) + ) const run: AutomationRun = { id: randomUUID(), automationId: automation.id, + runNumber, runContext: automation.runContext ?? null, sourceContext: automation.sourceContext ?? null, title: `${automation.name} run ${runNumber}`, @@ -4643,7 +4747,7 @@ export class Store { dispatchedAt: null, createdAt: now } - this.state.automationRuns = [...(this.state.automationRuns ?? []), run] + this.state.automationRuns = pruneAutomationRuns([...(this.state.automationRuns ?? []), run]) if (trigger === 'manual') { this.recordFeatureInteraction('automation-run') } @@ -5468,7 +5572,7 @@ export class Store { } readTerminalScrollbackSnapshot(ref: string): string | null { - return readTerminalScrollbackSnapshotSync(ref) + return readTerminalScrollbackSnapshotSync(ref, this.terminalScrollbackSnapshotStorage) } /** Resolve the worktree a terminal tab belongs to, from the session's @@ -5642,9 +5746,12 @@ export class Store { } } session = pruneLocalTerminalScrollbackBuffers(session, this.state.repos) - const migratedScrollback = migrateWorkspaceSessionTerminalScrollbackSnapshots(session) + const migratedScrollback = migrateWorkspaceSessionTerminalScrollbackSnapshots( + session, + this.terminalScrollbackSnapshotStorage + ) session = migratedScrollback.session - deleteRemovedTerminalScrollbackSnapshots(prior, session) + deleteRemovedTerminalScrollbackSnapshots(prior, session, this.terminalScrollbackSnapshotStorage) this.state.workspaceSession = session this.scheduleSave() } @@ -6006,6 +6113,140 @@ export class Store { } } + getRemovedSshTargetTombstones(): RemovedSshTargetTombstone[] { + return [...(this.state.removedSshTargetTombstones ?? [])] + } + + addRemovedSshTargetTombstone(tombstone: RemovedSshTargetTombstone): void { + const existing = this.state.removedSshTargetTombstones ?? [] + // Why: dedupe by oldTargetId so a remove/re-remove of the same id can't + // stack duplicate tombstones. Newest wins. + const filtered = existing.filter((t) => t.oldTargetId !== tombstone.oldTargetId) + // Cap the history so pathological churn can't grow the state file unbounded. + this.state.removedSshTargetTombstones = [...filtered, tombstone].slice( + -MAX_REMOVED_SSH_TARGET_TOMBSTONES + ) + this.scheduleSave() + } + + removeRemovedSshTargetTombstone(oldTargetId: string): void { + const existing = this.state.removedSshTargetTombstones + if (!existing?.some((t) => t.oldTargetId === oldTargetId)) { + return + } + this.state.removedSshTargetTombstones = existing.filter((t) => t.oldTargetId !== oldTargetId) + this.scheduleSave() + } + + /** + * Re-point every repo and worktree meta pinned to a removed SSH target id + * onto a re-added target's id, so orphaned workspaces reattach to the live + * host instead of remaining un-removable ghosts. Returns the number of repos + * re-pointed (0 when nothing referenced the old id). + */ + reassignSshTargetId(oldTargetId: string, newTargetId: string): number { + if (oldTargetId === newTargetId) { + return 0 + } + const oldHostId = toSshExecutionHostId(oldTargetId) + const newHostId = toSshExecutionHostId(newTargetId) + let repoCount = 0 + for (const repo of this.state.repos) { + const matchesConnection = repo.connectionId === oldTargetId + const matchesHost = repo.executionHostId === oldHostId + if (!matchesConnection && !matchesHost) { + continue + } + if (matchesConnection) { + repo.connectionId = newTargetId + } + // Why: only rewrite executionHostId when it was actually set to the old + // SSH host. SSH repos created via addRemoteRepoFromPath leave it unset and + // derive the host from connectionId, so we must not stamp a value where + // there wasn't one. + if (matchesHost) { + repo.executionHostId = newHostId + } + repoCount++ + } + // Re-point worktree metas whose hostId pointed at the old SSH host. + let metaChanged = false + for (const meta of Object.values(this.state.worktreeMeta)) { + if (meta.hostId === oldHostId) { + meta.hostId = newHostId + metaChanged = true + } + } + // Why: the old id also survives in session pty ids, the startup reconnect + // list, sleeping-agent records, host setups, host-scope UI, and pty leases; + // any un-migrated carrier later throws `SSH target not found` (STA-1468). + let carrierChanged = migrateWorkspaceSessionSshTargetId( + this.state.workspaceSession, + oldTargetId, + newTargetId + ) + for (const session of Object.values(this.state.workspaceSessionsByHostId ?? {})) { + if (session && migrateWorkspaceSessionSshTargetId(session, oldTargetId, newTargetId)) { + carrierChanged = true + } + } + // Why: partitions are read by host id, so one stored under the removed id + // would be orphaned. No writer keys partitions by ssh host today, but the + // schema tolerates it — re-key rather than strand it. If the new key + // already has a partition, that one is live; drop the dead old one. + const partitions = this.state.workspaceSessionsByHostId + const oldPartition = partitions?.[oldHostId] + if (partitions && oldPartition) { + delete partitions[oldHostId] + partitions[newHostId] ??= oldPartition + carrierChanged = true + } + if (migrateUiHostScopeSshTargetId(this.state.ui, oldTargetId, newTargetId)) { + carrierChanged = true + } + for (const lease of this.state.sshRemotePtyLeases ?? []) { + if (lease.targetId === oldTargetId) { + lease.targetId = newTargetId + carrierChanged = true + } + } + let setupsChanged = false + const keptSetups: ProjectHostSetup[] = [] + for (const setup of this.state.projectHostSetups) { + if (setup.hostId !== oldHostId) { + keptSetups.push(setup) + continue + } + const duplicate = this.state.projectHostSetups.some( + (entry) => + entry !== setup && entry.projectId === setup.projectId && entry.hostId === newHostId + ) + // Why: a setup already exists for the re-added host — the old row is a + // stale ghost that would violate the (projectId, hostId) uniqueness. + if (duplicate) { + setupsChanged = true + continue + } + setup.hostId = newHostId + setup.updatedAt = Date.now() + keptSetups.push(setup) + setupsChanged = true + } + if (setupsChanged) { + this.state.projectHostSetups = keptSetups + } + // Why: repo-row and host-setup rewrites can affect host-setup compatibility, + // but meta-only rewrites cannot — keep that sync under this gate. Persist + // whenever anything changed, so partial re-points aren't lost on quit. + if (repoCount > 0 || setupsChanged) { + this.syncProjectHostSetupCompatibilityState() + } + if (repoCount > 0 || metaChanged || carrierChanged || setupsChanged) { + this.scheduleSave() + } + return repoCount + } + // ── SSH Remote PTY Leases ────────────────────────────────────────── getSshRemotePtyLeases(targetId?: string): SshRemotePtyLease[] { @@ -6215,13 +6456,24 @@ export class Store { this.writeGithubCacheSnapshotSync() } + // Why: called after a project move rewrote this store's data file directly. + // From that point until relaunch, the in-memory state is stale and any + // write (debounced, sync, or shutdown flush) would undo the transfer. + freezeWrites(): void { + this.writesFrozen = true + if (this.writeTimer) { + clearTimeout(this.writeTimer) + this.writeTimer = null + } + } + // Why best-effort: the sidecar is a refetchable cache — a failed write only // costs a cold badge paint on next launch, never data. private writeGithubCacheSnapshotSync(): void { if (!this.githubCacheDirty) { return } - const cacheFile = getGithubCacheFile() + const cacheFile = getGithubCacheFile(this.dataFile) const tmpFile = `${cacheFile}.${process.pid}.tmp` try { writeFileSync(tmpFile, JSON.stringify(this.state.githubCache), 'utf-8') diff --git a/src/main/pi/agent-status-extension-source.test.ts b/src/main/pi/agent-status-extension-source.test.ts new file mode 100644 index 000000000000..097967861927 --- /dev/null +++ b/src/main/pi/agent-status-extension-source.test.ts @@ -0,0 +1,317 @@ +import { runInNewContext } from 'node:vm' +// TypeScript 7 is a native CLI; transpile tests still need the legacy JavaScript API. +import ts from 'typescript-api' +import { describe, expect, it, vi } from 'vitest' + +import { getPiAgentStatusExtensionSource } from './agent-status-extension-source' + +type HookHandler = (event?: unknown) => Promise | void + +type FakeCurlChild = { + on: ReturnType + stdin: { + on: ReturnType + end: ReturnType + } +} + +type Harness = { + fetchMock: ReturnType + spawnMock: ReturnType + spawnedChildren: FakeCurlChild[] + fsMock: { + existsSync: ReturnType + readFileSync: ReturnType + } + handlers: Record + callHook: (name: string, event?: unknown) => Promise +} + +const BASE_ENV = { + ORCA_PANE_KEY: 'pane-1', + ORCA_AGENT_LAUNCH_TOKEN: 'launch-1', + ORCA_TAB_ID: 'tab-1', + ORCA_WORKTREE_ID: 'tree-1', + ORCA_AGENT_HOOK_PORT: '4321', + ORCA_AGENT_HOOK_TOKEN: 'token-1', + ORCA_AGENT_HOOK_ENV: 'env-1', + ORCA_AGENT_HOOK_VERSION: '1.2.3' +} satisfies Record + +function createHarness(args: { + kind: 'pi' | 'omp' + env?: Record + title?: string + argv?: string[] + existsSync?: (path: string) => boolean + readFileSync?: (path: string, encoding: string) => string + fetchImpl?: (...params: Parameters) => Promise +}): Harness { + const fetchMock = vi.fn( + args.fetchImpl ?? + (async () => ({ + ok: true + })) + ) + + const spawnedChildren: FakeCurlChild[] = [] + const spawnMock = vi.fn(() => { + const child: FakeCurlChild = { + on: vi.fn(), + stdin: { + on: vi.fn(), + end: vi.fn() + } + } + spawnedChildren.push(child) + return child + }) + + const fsMock = { + existsSync: vi.fn(args.existsSync ?? (() => false)), + readFileSync: vi.fn( + args.readFileSync ?? + ((path: string) => { + throw Object.assign(new Error(`ENOENT: ${path}`), { code: 'ENOENT' }) + }) + ) + } + + const module = { + exports: {} as { default?: (pi: { on: (name: string, handler: HookHandler) => void }) => void } + } + const requireMock = vi.fn((specifier: string) => { + if (specifier === 'fs') { + return fsMock + } + if (specifier === 'child_process') { + return { spawn: spawnMock } + } + throw new Error(`unexpected require(${specifier})`) + }) + + const processMock = { + env: { + ...BASE_ENV, + ...args.env + }, + title: args.title ?? 'node', + argv: args.argv ?? ['node', '/usr/bin/orca'] + } + + const context = { + module, + exports: module.exports, + require: requireMock, + process: processMock, + fetch: fetchMock, + console: { + warn: vi.fn(), + error: vi.fn(), + log: vi.fn() + }, + Promise, + Buffer, + URL, + setTimeout, + clearTimeout + } as Record + context.globalThis = context + + const source = getPiAgentStatusExtensionSource(args.kind) + const output = ts.transpileModule(source, { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020 + } + }).outputText + runInNewContext(output, context) + + const register = module.exports.default + if (!register) { + throw new Error('expected default export from generated source') + } + + const handlers: Record = {} + register({ + on(name: string, handler: HookHandler) { + handlers[name] = handler + } + }) + + return { + fetchMock, + spawnMock, + spawnedChildren, + fsMock, + handlers, + callHook: async (name, event) => { + await handlers[name]?.(event) + } + } +} + +describe('getPiAgentStatusExtensionSource', () => { + it('routes an OMP executable through /hook/omp', async () => { + const harness = createHarness({ + kind: 'pi', + title: 'omp', + existsSync: () => false + }) + + await harness.callHook('agent_start') + + expect(harness.fetchMock).toHaveBeenCalledTimes(1) + expect(harness.fetchMock.mock.calls[0]?.[0]).toBe('http://127.0.0.1:4321/hook/omp') + expect(harness.spawnMock).not.toHaveBeenCalled() + }) + + it('keeps native fetch as the only path even when the runtime looks like WSL', async () => { + const harness = createHarness({ + kind: 'omp', + env: { WSL_DISTRO_NAME: 'Ubuntu' }, + existsSync: () => true + }) + + await harness.callHook('agent_start') + + expect(harness.fetchMock).toHaveBeenCalledTimes(1) + expect(harness.spawnMock).not.toHaveBeenCalled() + }) + + it('falls back to Windows curl from WSL when fetch fails', async () => { + const harness = createHarness({ + kind: 'omp', + env: { WSL_DISTRO_NAME: 'Ubuntu' }, + existsSync: (path) => path === '/mnt/c/Windows/System32/curl.exe', + fetchImpl: vi.fn(async () => { + throw new Error('loopback unreachable') + }) + }) + + await harness.callHook('agent_start') + + expect(harness.fetchMock).toHaveBeenCalledTimes(1) + expect(harness.spawnMock).toHaveBeenCalledTimes(1) + + const [command, args, options] = harness.spawnMock.mock.calls[0] ?? [] + expect(command).toBe('/mnt/c/Windows/System32/curl.exe') + expect(args).toEqual([ + '-sS', + '--connect-timeout', + '3', + '--max-time', + '10', + '--noproxy', + '127.0.0.1', + '-o', + 'NUL', + '-X', + 'POST', + '-H', + 'Content-Type: application/json', + '-H', + 'X-Orca-Agent-Hook-Token: token-1', + '--data-binary', + '@-', + 'http://127.0.0.1:4321/hook/omp' + ]) + // Why: delivery must be fire-and-forget off the pi event loop — no + // blocking wait — with the payload fed via stdin, never argv. + expect(options).toEqual({ stdio: ['pipe', 'ignore', 'ignore'] }) + const child = harness.spawnedChildren[0] + expect(child?.on).toHaveBeenCalledWith('error', expect.any(Function)) + expect(child?.stdin.on).toHaveBeenCalledWith('error', expect.any(Function)) + expect(child?.stdin.end).toHaveBeenCalledWith( + JSON.stringify({ + paneKey: 'pane-1', + launchToken: 'launch-1', + tabId: 'tab-1', + worktreeId: 'tree-1', + env: 'env-1', + version: '1.2.3', + payload: { hook_event_name: 'agent_start' } + }) + ) + }) + + it('probes WSL evidence and the curl path once per process', async () => { + const harness = createHarness({ + kind: 'omp', + existsSync: (path) => path === '/mnt/c/Windows/System32/curl.exe', + readFileSync: (path) => { + if (path === '/proc/sys/kernel/osrelease') { + return 'microsoft-standard-WSL2' + } + throw Object.assign(new Error(`ENOENT: ${path}`), { code: 'ENOENT' }) + }, + fetchImpl: vi.fn(async () => { + throw new Error('loopback unreachable') + }) + }) + + await harness.callHook('agent_start') + await harness.callHook('agent_end') + + expect(harness.spawnMock).toHaveBeenCalledTimes(2) + // Why: WSL-ness and curl.exe presence are process-lifetime constants; + // the per-event failure path must not re-probe /proc or /mnt/c. + const procReads = harness.fsMock.readFileSync.mock.calls.filter(([path]) => + String(path).startsWith('/proc/') + ) + expect(procReads).toHaveLength(1) + expect(harness.fsMock.existsSync).toHaveBeenCalledTimes(1) + }) + + it('stays fail-open on ordinary Linux', async () => { + const harness = createHarness({ + kind: 'omp', + existsSync: () => true, + fetchImpl: vi.fn(async () => { + throw new Error('loopback unreachable') + }) + }) + + await harness.callHook('agent_start') + + expect(harness.fetchMock).toHaveBeenCalledTimes(1) + expect(harness.spawnMock).not.toHaveBeenCalled() + }) + + it('does not treat WSLENV alone as WSL evidence', async () => { + const harness = createHarness({ + kind: 'omp', + env: { WSLENV: 'FOO/u' }, + existsSync: () => true, + readFileSync: (path) => { + if (path === '/proc/sys/kernel/osrelease' || path === '/proc/version') { + return 'Linux 6.8.0 generic' + } + throw Object.assign(new Error(`ENOENT: ${path}`), { code: 'ENOENT' }) + }, + fetchImpl: vi.fn(async () => { + throw new Error('loopback unreachable') + }) + }) + + await harness.callHook('agent_start') + + expect(harness.fetchMock).toHaveBeenCalledTimes(1) + expect(harness.spawnMock).not.toHaveBeenCalled() + }) + + it('remains fail-open when the Windows curl bridge is missing', async () => { + const harness = createHarness({ + kind: 'omp', + env: { WSL_DISTRO_NAME: 'Ubuntu' }, + existsSync: () => false, + fetchImpl: vi.fn(async () => { + throw new Error('loopback unreachable') + }) + }) + + await expect(harness.callHook('agent_start')).resolves.toBeUndefined() + expect(harness.fetchMock).toHaveBeenCalledTimes(1) + expect(harness.spawnMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/pi/agent-status-extension-source.ts b/src/main/pi/agent-status-extension-source.ts index 48172dfbf0c7..a607199e81da 100644 --- a/src/main/pi/agent-status-extension-source.ts +++ b/src/main/pi/agent-status-extension-source.ts @@ -130,6 +130,88 @@ export function getPiAgentStatusExtensionSource(kind: PiAgentKind = 'pi'): strin ' } catch {', ' // Why: status reporting must never fail the pi run just because Orca', ' // is unavailable or the loopback request failed (e.g. Orca restart).', + ' if (!isWslRuntime()) return', + ' postViaWindowsCurl(url, coords, body)', + ' }', + '}', + '', + '// Why: WSL-ness and curl.exe presence cannot change within a process', + '// lifetime; re-probing /proc and /mnt/c on every failed event would add', + '// filesystem work to the per-event path.', + 'let cachedIsWslRuntime: boolean | null = null', + 'let cachedWindowsCurlPath: string | null | undefined', + '', + 'function isWslRuntime(): boolean {', + ' if (cachedIsWslRuntime !== null) return cachedIsWslRuntime', + ' cachedIsWslRuntime = detectWslRuntime()', + ' return cachedIsWslRuntime', + '}', + '', + 'function detectWslRuntime(): boolean {', + ' if (process.env.WSL_DISTRO_NAME) return true', + ' try {', + " const fs = require('fs')", + " for (const path of ['/proc/sys/kernel/osrelease', '/proc/version']) {", + ' try {', + " const contents = String(fs.readFileSync(path, 'utf8'))", + ' if (/microsoft|wsl/i.test(contents)) return true', + ' } catch {', + ' // Why: probe the next runtime hint when a proc file is absent or unreadable.', + ' }', + ' }', + ' } catch {', + ' return false', + ' }', + ' return false', + '}', + '', + 'function resolveWindowsCurlPath(): string | null {', + ' if (cachedWindowsCurlPath !== undefined) return cachedWindowsCurlPath', + ' try {', + " const fs = require('fs')", + " const curlPath = '/mnt/c/Windows/System32/curl.exe'", + ' cachedWindowsCurlPath = fs.existsSync(curlPath) ? curlPath : null', + ' } catch {', + ' cachedWindowsCurlPath = null', + ' }', + ' return cachedWindowsCurlPath', + '}', + '', + '// Why: WSL loopback is not the Windows loopback, so a WSL-side POST cannot', + '// reach Orca. curl.exe runs on the Windows side, where 127.0.0.1 IS the', + '// listener Orca binds. Fire-and-forget: blocking on the spawn would stall', + '// the pi event loop (and the TUI) on every hook event.', + 'function postViaWindowsCurl(url: string, coords: { token: string }, body: string): void {', + ' const curlPath = resolveWindowsCurlPath()', + ' if (!curlPath) return', + ' try {', + " const { spawn } = require('child_process')", + ' const child = spawn(', + ' curlPath,', + ' [', + " '-sS',", + ' // Why: the spawn is detached from the event loop, so these bounds', + ' // size a background process, not TUI latency. WSL->Win32 interop', + ' // connects can exceed 0.5s on loaded machines (observed 3/3 drops', + ' // to a healthy listener); size for delivery, not snappiness.', + " '--connect-timeout', '3',", + " '--max-time', '10',", + " '--noproxy', '127.0.0.1',", + " '-o', 'NUL',", + " '-X', 'POST',", + " '-H', 'Content-Type: application/json',", + " '-H', `X-Orca-Agent-Hook-Token: ${coords.token}`,", + " '--data-binary', '@-',", + ' url', + ' ],', + " { stdio: ['pipe', 'ignore', 'ignore'] }", + ' )', + " child.on('error', () => {})", + " child.stdin.on('error', () => {})", + ' child.stdin.end(body)', + ' } catch {', + ' // Why: the bridge is best-effort; a failed spawn must not surface', + ' // inside the pi TUI.', ' }', '}', '', diff --git a/src/main/pi/legacy-omp-overlay-migration.ts b/src/main/pi/legacy-omp-overlay-migration.ts new file mode 100644 index 000000000000..88baf78ea9f3 --- /dev/null +++ b/src/main/pi/legacy-omp-overlay-migration.ts @@ -0,0 +1,242 @@ +import { cpSync, lstatSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs' +import type { Dirent, Stats } from 'node:fs' +import { dirname, join } from 'node:path' +import { ORCA_PI_AGENT_STATUS_EXTENSION_FILE } from './agent-status-extension-source' +import { ORCA_PI_PREFILL_EXTENSION_FILE } from './prefill-extension-source' +import { ORCA_PI_EXTENSION_FILE } from './titlebar-extension-source' +import { isSafeDescendCandidate } from '../pty/overlay-mirror' + +const LEGACY_PI_OVERLAY_MANIFEST_FILE = '.orca-pi-overlay-manifest.json' +const LEGACY_OMP_OVERLAY_MIGRATION_MARKER_FILE = '.orca-omp-overlay-migration-complete' +const PI_AGENT_SETTINGS_FILE = 'settings.json' +const SQLITE_DATABASE_EXTENSION = '.db' +const SQLITE_SIDECAR_SUFFIXES = ['-wal', '-shm', '-journal'] as const +const MANAGED_EXTENSION_FILES = new Set([ + ORCA_PI_EXTENSION_FILE, + ORCA_PI_PREFILL_EXTENSION_FILE, + ORCA_PI_AGENT_STATUS_EXTENSION_FILE +]) + +type DeferredSidecar = { + baseTargetPath: string + entry: Dirent + nextSegments: string[] +} + +function getPathStats(path: string): Stats | undefined { + try { + return lstatSync(path) + } catch { + return undefined + } +} + +function getSqliteSidecarBaseName(name: string): string | undefined { + for (const suffix of SQLITE_SIDECAR_SUFFIXES) { + if (!name.endsWith(suffix)) { + continue + } + const baseName = name.slice(0, -suffix.length) + return baseName.endsWith(SQLITE_DATABASE_EXTENSION) ? baseName : undefined + } + return undefined +} + +function shouldSkipLegacyOverlayEntry(pathSegments: string[]): boolean { + const name = pathSegments.at(-1) + if (!name) { + return true + } + if (pathSegments.length === 1) { + return ( + name === LEGACY_PI_OVERLAY_MANIFEST_FILE || + name === LEGACY_OMP_OVERLAY_MIGRATION_MARKER_FILE || + name === PI_AGENT_SETTINGS_FILE + ) + } + return ( + pathSegments.length === 2 && + pathSegments[0] === 'extensions' && + MANAGED_EXTENSION_FILES.has(name) + ) +} + +function copyLegacyFile( + overlayPath: string, + targetPath: string, + copiedFilePaths: Set +): boolean { + if (getPathStats(targetPath)) { + return true + } + try { + mkdirSync(dirname(targetPath), { recursive: true }) + cpSync(overlayPath, targetPath, { + errorOnExist: true, + force: false, + preserveTimestamps: true + }) + copiedFilePaths.add(targetPath) + return true + } catch { + return false + } +} + +function removeCopiedFiles(paths: string[], copiedFilePaths: Set): void { + for (const path of paths) { + if (!copiedFilePaths.delete(path)) { + continue + } + try { + unlinkSync(path) + } catch { + // Best-effort: withholding the marker lets later spawns retry. + } + } +} + +function copyDeferredSidecars( + overlayDir: string, + sourceAgentDir: string, + copiedFilePaths: Set, + deferredSidecars: DeferredSidecar[] +): boolean { + let completed = true + const copiedSidecarsByBase = new Map() + for (const { baseTargetPath, entry, nextSegments } of deferredSidecars) { + if (!copiedFilePaths.has(baseTargetPath)) { + continue + } + + const overlayPath = join(overlayDir, entry.name) + const targetPath = join(sourceAgentDir, ...nextSegments) + const stats = getPathStats(overlayPath) + if (!stats) { + removeCopiedFiles( + [baseTargetPath, ...(copiedSidecarsByBase.get(baseTargetPath) ?? [])], + copiedFilePaths + ) + completed = false + continue + } + if (stats.isSymbolicLink() || !stats.isFile()) { + continue + } + const wasCopied = copiedFilePaths.has(targetPath) + if (!copyLegacyFile(overlayPath, targetPath, copiedFilePaths)) { + removeCopiedFiles( + [baseTargetPath, ...(copiedSidecarsByBase.get(baseTargetPath) ?? [])], + copiedFilePaths + ) + completed = false + continue + } + if (!wasCopied && copiedFilePaths.has(targetPath)) { + copiedSidecarsByBase.set(baseTargetPath, [ + ...(copiedSidecarsByBase.get(baseTargetPath) ?? []), + targetPath + ]) + } + } + return completed +} + +function copyMissingLegacyOmpOverlayEntries( + overlayDir: string, + sourceAgentDir: string, + pathSegments: string[] = [], + copiedFilePaths: Set = new Set() +): boolean { + let completed = true + let entries: Dirent[] + try { + entries = readdirSync(overlayDir, { withFileTypes: true }) + } catch { + return false + } + + const deferredSidecars: DeferredSidecar[] = [] + for (const entry of entries) { + const nextSegments = [...pathSegments, entry.name] + if (shouldSkipLegacyOverlayEntry(nextSegments)) { + continue + } + + const sidecarBaseName = getSqliteSidecarBaseName(entry.name) + if (sidecarBaseName) { + deferredSidecars.push({ + baseTargetPath: join(sourceAgentDir, ...pathSegments, sidecarBaseName), + entry, + nextSegments + }) + continue + } + + const overlayPath = join(overlayDir, entry.name) + const targetPath = join(sourceAgentDir, ...nextSegments) + const stats = getPathStats(overlayPath) + if (!stats) { + completed = false + continue + } + if (stats.isSymbolicLink()) { + continue + } + if (stats.isDirectory()) { + const targetStats = getPathStats(targetPath) + if (targetStats && !isSafeDescendCandidate(targetStats)) { + continue + } + if (!targetStats) { + try { + mkdirSync(targetPath, { recursive: true }) + } catch { + completed = false + continue + } + } + completed = + copyMissingLegacyOmpOverlayEntries( + overlayPath, + sourceAgentDir, + nextSegments, + copiedFilePaths + ) && completed + continue + } + if (!stats.isFile()) { + continue + } + completed = copyLegacyFile(overlayPath, targetPath, copiedFilePaths) && completed + } + + return ( + copyDeferredSidecars(overlayDir, sourceAgentDir, copiedFilePaths, deferredSidecars) && completed + ) +} + +export function migrateLegacyOmpOverlayState(sourceAgentDir: string, overlayDir: string): void { + // Why: temporary rescue shim for OMP builds from the legacy overlay window. + // Remove after 2026-08-07 once affected users have had a full upgrade window. + const overlayStats = getPathStats(overlayDir) + if (!overlayStats || overlayStats.isSymbolicLink() || !overlayStats.isDirectory()) { + return + } + const markerPath = join(overlayDir, LEGACY_OMP_OVERLAY_MIGRATION_MARKER_FILE) + if (getPathStats(markerPath)) { + return + } + try { + mkdirSync(sourceAgentDir, { recursive: true }) + // Why: some pre-managed-extension builds pointed OMP at this overlay, so + // first-login auth/session files can exist only there after an update. + if (copyMissingLegacyOmpOverlayEntries(overlayDir, sourceAgentDir)) { + // Why: legacy source overlays can be large and are intentionally kept + // for recovery; mark clean migrations so future OMP spawns stay cheap. + writeFileSync(markerPath, 'complete\n') + } + } catch (error) { + console.warn('[pi-titlebar-extension] failed to migrate legacy OMP overlay state:', error) + } +} diff --git a/src/main/pi/titlebar-extension-service.test.ts b/src/main/pi/titlebar-extension-service.test.ts index 75f01583154b..7516f04dad95 100644 --- a/src/main/pi/titlebar-extension-service.test.ts +++ b/src/main/pi/titlebar-extension-service.test.ts @@ -1,6 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { + chmodSync, existsSync, + lstatSync, mkdirSync, mkdtempSync, readFileSync, @@ -11,6 +15,7 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import type * as osModule from 'node:os' +import type * as fsModule from 'node:fs' import { join } from 'node:path' // The service calls app.getPath('userData') for its overlay root. Point that @@ -50,6 +55,12 @@ function legacyOverlayPath(kind: 'pi' | 'omp', ptyId: string): string { return join(userDataDir, rootDir, ptyId) } +function legacySourceOverlayPath(kind: 'pi' | 'omp', sourceAgentDir: string): string { + const rootDir = kind === 'pi' ? 'pi-agent-overlays' : 'omp-agent-overlays' + const hashed = createHash('sha256').update(`source:${sourceAgentDir}`).digest('hex').slice(0, 32) + return join(userDataDir, rootDir, hashed) +} + describe('PiTitlebarExtensionService', () => { let piHome: string @@ -185,6 +196,242 @@ describe('PiTitlebarExtensionService', () => { expect(readFileSync(sourcePath, 'utf-8')).toBe(content) }) + it('migrates missing OMP state from the old source overlay without overwriting source files', () => { + rmSync(join(piHome, 'sessions'), { recursive: true, force: true }) + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(join(overlayDir, 'sessions'), { recursive: true }) + mkdirSync(join(overlayDir, 'extensions'), { recursive: true }) + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + writeFileSync(join(overlayDir, 'agent.db-wal'), 'legacy sqlite wal') + writeFileSync(join(overlayDir, 'sessions', 'legacy-session.jsonl'), 'legacy transcript') + writeFileSync(join(overlayDir, 'auth.json'), 'legacy token should not overwrite') + writeFileSync(join(overlayDir, 'settings.json'), '{"overlayOnly":true}') + writeFileSync(join(overlayDir, '.orca-pi-overlay-manifest.json'), '{}') + writeFileSync(join(overlayDir, 'extensions', 'orca-agent-status.ts'), 'stale managed extension') + writeFileSync(join(overlayDir, 'extensions', 'legacy-user-ext.ts'), 'legacy user extension') + mkdirSync(join(overlayDir, 'extensions', 'legacy-package'), { recursive: true }) + writeFileSync( + join(overlayDir, 'extensions', 'legacy-package', 'orca-prefill.ts'), + 'user package file' + ) + + const svc = new PiTitlebarExtensionService() + const env = svc.buildPtyEnv('pty-omp-migrate', piHome, 'omp') + + expect(env.PI_CODING_AGENT_DIR).toBeUndefined() + expect(readFileSync(join(piHome, 'agent.db'), 'utf-8')).toBe('legacy sqlite credentials') + expect(readFileSync(join(piHome, 'agent.db-wal'), 'utf-8')).toBe('legacy sqlite wal') + expect(readFileSync(join(piHome, 'sessions', 'legacy-session.jsonl'), 'utf-8')).toBe( + 'legacy transcript' + ) + expect(readFileSync(join(piHome, 'auth.json'), 'utf-8')).toBe('secret token') + expect(JSON.parse(readFileSync(join(piHome, 'settings.json'), 'utf-8'))).toEqual({ + defaultProvider: 'amazon-bedrock', + hideThinkingBlock: false, + packages: ['npm:pi-web-access'], + terminal: { + showImages: false, + clearOnShrink: false + } + }) + expect(readFileSync(join(piHome, 'extensions', 'legacy-user-ext.ts'), 'utf-8')).toBe( + 'legacy user extension' + ) + expect( + readFileSync(join(piHome, 'extensions', 'legacy-package', 'orca-prefill.ts'), 'utf-8') + ).toBe('user package file') + expect(readFileSync(join(piHome, 'extensions', 'orca-agent-status.ts'), 'utf-8')).toContain( + '/hook/omp' + ) + expect(readFileSync(join(overlayDir, '.orca-omp-overlay-migration-complete'), 'utf-8')).toBe( + 'complete\n' + ) + }) + + it('does not copy stale SQLite sidecars when the target database already exists', () => { + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(overlayDir, { recursive: true }) + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + writeFileSync(join(overlayDir, 'agent.db-wal'), 'legacy sqlite wal') + writeFileSync(join(overlayDir, 'agent.db-shm'), 'legacy sqlite shm') + writeFileSync(join(piHome, 'agent.db'), 'fresh sqlite credentials') + + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-stale-sidecars', piHome, 'omp') + + expect(readFileSync(join(piHome, 'agent.db'), 'utf-8')).toBe('fresh sqlite credentials') + expect(existsSync(join(piHome, 'agent.db-wal'))).toBe(false) + expect(existsSync(join(piHome, 'agent.db-shm'))).toBe(false) + expect(readFileSync(join(overlayDir, '.orca-omp-overlay-migration-complete'), 'utf-8')).toBe( + 'complete\n' + ) + }) + + it.skipIf(process.platform === 'win32')( + 'retries a legacy SQLite migration as a whole set after sidecar copy failure', + () => { + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(overlayDir, { recursive: true }) + const walPath = join(overlayDir, 'agent.db-wal') + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + writeFileSync(walPath, 'legacy sqlite wal') + chmodSync(walPath, 0o000) + + try { + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-sidecar-fail-1', piHome, 'omp') + + expect(existsSync(join(piHome, 'agent.db'))).toBe(false) + expect(existsSync(join(piHome, 'agent.db-wal'))).toBe(false) + expect(existsSync(join(overlayDir, '.orca-omp-overlay-migration-complete'))).toBe(false) + + chmodSync(walPath, 0o600) + svc.buildPtyEnv('pty-omp-sidecar-fail-2', piHome, 'omp') + + expect(readFileSync(join(piHome, 'agent.db'), 'utf-8')).toBe('legacy sqlite credentials') + expect(readFileSync(join(piHome, 'agent.db-wal'), 'utf-8')).toBe('legacy sqlite wal') + expect( + readFileSync(join(overlayDir, '.orca-omp-overlay-migration-complete'), 'utf-8') + ).toBe('complete\n') + } finally { + chmodSync(walPath, 0o600) + } + } + ) + + it('retries a legacy SQLite migration as a whole set after sidecar stat failure', async () => { + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(overlayDir, { recursive: true }) + const walPath = join(overlayDir, 'agent.db-wal') + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + writeFileSync(walPath, 'legacy sqlite wal') + + let failNextWalStat = true + vi.resetModules() + vi.doMock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + lstatSync: (path: Parameters[0]) => { + if (String(path) === walPath && failNextWalStat) { + failNextWalStat = false + throw new Error('transient lstat failure') + } + return actual.lstatSync(path) + } + } + }) + + try { + const { migrateLegacyOmpOverlayState } = await import('./legacy-omp-overlay-migration') + migrateLegacyOmpOverlayState(piHome, overlayDir) + + expect(existsSync(join(piHome, 'agent.db'))).toBe(false) + expect(existsSync(join(piHome, 'agent.db-wal'))).toBe(false) + expect(existsSync(join(overlayDir, '.orca-omp-overlay-migration-complete'))).toBe(false) + + migrateLegacyOmpOverlayState(piHome, overlayDir) + + expect(readFileSync(join(piHome, 'agent.db'), 'utf-8')).toBe('legacy sqlite credentials') + expect(readFileSync(join(piHome, 'agent.db-wal'), 'utf-8')).toBe('legacy sqlite wal') + expect(readFileSync(join(overlayDir, '.orca-omp-overlay-migration-complete'), 'utf-8')).toBe( + 'complete\n' + ) + } finally { + vi.doUnmock('node:fs') + vi.resetModules() + } + }) + + it('marks successful legacy OMP migrations so old overlays are not re-scanned', () => { + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(overlayDir, { recursive: true }) + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-migrate-once-1', piHome, 'omp') + + expect(readFileSync(join(piHome, 'agent.db'), 'utf-8')).toBe('legacy sqlite credentials') + expect(readFileSync(join(overlayDir, '.orca-omp-overlay-migration-complete'), 'utf-8')).toBe( + 'complete\n' + ) + + writeFileSync(join(overlayDir, 'later-overlay-only-file'), 'should not migrate') + svc.buildPtyEnv('pty-omp-migrate-once-2', piHome, 'omp') + + expect(existsSync(join(piHome, 'later-overlay-only-file'))).toBe(false) + }) + + it.skipIf(process.platform === 'win32')( + 'skips special legacy overlay entries while continuing the OMP migration', + () => { + rmSync(join(piHome, 'sessions'), { recursive: true, force: true }) + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(join(overlayDir, 'sessions'), { recursive: true }) + execFileSync('mkfifo', [join(overlayDir, 'stray-fifo')]) + writeFileSync(join(overlayDir, 'sessions', 'legacy-session.jsonl'), 'legacy transcript') + + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-special-entry', piHome, 'omp') + + expect(existsSync(join(piHome, 'stray-fifo'))).toBe(false) + expect(readFileSync(join(piHome, 'sessions', 'legacy-session.jsonl'), 'utf-8')).toBe( + 'legacy transcript' + ) + } + ) + + it.skipIf(process.platform === 'win32')( + 'does not descend through existing target directory symlinks while migrating OMP state', + () => { + rmSync(join(piHome, 'sessions'), { recursive: true, force: true }) + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(join(overlayDir, 'sessions'), { recursive: true }) + writeFileSync(join(overlayDir, 'sessions', 'legacy-session.jsonl'), 'legacy transcript') + const outsideDir = mkdtempSync(join(tmpdir(), 'orca-omp-target-junction-')) + const sessionsPath = join(piHome, 'sessions') + + try { + symlinkSync(outsideDir, sessionsPath, 'dir') + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-target-dir-symlink', piHome, 'omp') + + expect(lstatSync(sessionsPath).isSymbolicLink()).toBe(true) + expect(existsSync(join(outsideDir, 'legacy-session.jsonl'))).toBe(false) + } finally { + rmSync(outsideDir, { recursive: true, force: true }) + } + } + ) + + it.skipIf(process.platform === 'win32')( + 'does not follow existing target symlinks while migrating OMP state', + () => { + rmSync(join(piHome, 'sessions'), { recursive: true, force: true }) + const overlayDir = legacySourceOverlayPath('omp', piHome) + mkdirSync(join(overlayDir, 'sessions'), { recursive: true }) + writeFileSync(join(overlayDir, 'agent.db'), 'legacy sqlite credentials') + writeFileSync(join(overlayDir, 'sessions', 'legacy-session.jsonl'), 'legacy transcript') + const outsideDir = mkdtempSync(join(tmpdir(), 'orca-omp-dangling-target-')) + + try { + const outsideTarget = join(outsideDir, 'agent.db') + symlinkSync(outsideTarget, join(piHome, 'agent.db'), 'file') + + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-omp-target-symlink', piHome, 'omp') + + expect(existsSync(outsideTarget)).toBe(false) + expect(lstatSync(join(piHome, 'agent.db')).isSymbolicLink()).toBe(true) + expect(readFileSync(join(piHome, 'sessions', 'legacy-session.jsonl'), 'utf-8')).toBe( + 'legacy transcript' + ) + } finally { + rmSync(outsideDir, { recursive: true, force: true }) + } + } + ) + it('rebuilding managed extensions for the same ptyId does not corrupt the user Pi dir', () => { const svc = new PiTitlebarExtensionService() svc.buildPtyEnv('pty-3', piHome, 'pi') diff --git a/src/main/pi/titlebar-extension-service.ts b/src/main/pi/titlebar-extension-service.ts index d5b3c0a87c5f..37d030b5e31c 100644 --- a/src/main/pi/titlebar-extension-service.ts +++ b/src/main/pi/titlebar-extension-service.ts @@ -17,6 +17,7 @@ import { isSafeDescendCandidate as sharedIsSafeDescendCandidate, safeRemoveOverlay } from '../pty/overlay-mirror' +import { migrateLegacyOmpOverlayState } from './legacy-omp-overlay-migration' import type { PiAgentKind } from '../../shared/pi-agent-kind' // Why: the Pi test suite imports `isSafeDescendCandidate` from this module's @@ -74,6 +75,12 @@ export class PiTitlebarExtensionService { return join(app.getPath('userData'), OVERLAY_ROOT_DIR_NAME[kind]) } + private getSourceOverlayDir(sourceAgentDir: string, kind: PiAgentKind): string { + // Why: builds before managed extensions stored Pi/OMP state in source-scoped + // overlays. Resolve the old path so OMP upgrades can rescue stranded state. + return join(this.getOverlayRoot(kind), toSafeOverlayDirName(`source:${sourceAgentDir}`)) + } + private getPtyOverlayDir(ptyId: string, kind: PiAgentKind): string { // Why: old Orca versions used PTY-scoped hashed overlays. Keep resolving // that path so new spawns/teardowns can clean stale pre-migration dirs. @@ -173,6 +180,10 @@ export class PiTitlebarExtensionService { // directory should not prevent the terminal from starting. } + if (kind === 'omp') { + migrateLegacyOmpOverlayState(sourceAgentDir, this.getSourceOverlayDir(sourceAgentDir, 'omp')) + } + const installed = this.installManagedExtensions(sourceAgentDir, kind) const env: Record = {} if (kind === 'omp') { diff --git a/src/main/providers/agent-foreground-process.test.ts b/src/main/providers/agent-foreground-process.test.ts index c21d501b49ae..a93735a0287e 100644 --- a/src/main/providers/agent-foreground-process.test.ts +++ b/src/main/providers/agent-foreground-process.test.ts @@ -9,7 +9,10 @@ vi.mock('child_process', () => ({ })) import { resetProcessTableSnapshotForTests } from '../../shared/process-table-snapshot' -import { resolveAgentForegroundProcess } from './agent-foreground-process' +import { + resolveAgentForegroundProcess, + resolveAgentForegroundProcessWithAvailability +} from './agent-foreground-process' import { resetWindowsProcessRowsSnapshotForTests } from './windows-foreground-process-rows' // Why: the module wraps execFile with promisify, so the mock must honor the @@ -106,6 +109,28 @@ describe('resolveAgentForegroundProcess', () => { await expect(resolveAgentForegroundProcess(100, 'node')).resolves.toBe('codex') }) + it('treats a fresh POSIX snapshot missing the PTY root as unavailable', async () => { + mockPs('101 999 S+ node /Users/dev/.nvm/versions/node/bin/codex') + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'zsh', { fresh: true }) + ).resolves.toEqual({ available: false, processName: 'zsh' }) + }) + + it('treats a failed fresh POSIX scan as unavailable', async () => { + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(new Error('ps unavailable'), { stdout: '', stderr: '' }) + } + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'zsh', { fresh: true }) + ).resolves.toEqual({ available: false, processName: 'zsh' }) + await expect(resolveAgentForegroundProcess(100, 'zsh')).resolves.toBe('zsh') + }) + it('does not report Claude print-mode hook descendants as foreground agents', async () => { mockPs( [ @@ -270,6 +295,117 @@ describe('resolveAgentForegroundProcess', () => { ) }) + it('distinguishes unavailable Windows enumeration from a confirmed shell', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(new Error('enumeration unavailable'), { stdout: '', stderr: '' }) + } + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe') + ).resolves.toEqual({ available: false, processName: 'powershell.exe' }) + await expect(resolveAgentForegroundProcess(100, 'powershell.exe')).resolves.toBe( + 'powershell.exe' + ) + }) + + it.each([ + ['blank', ' \r\n'], + ['unparseable', 'wmic returned no structured process values'] + ])('treats successful but %s WMIC output as unavailable', async (_label, wmicOutput) => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation((cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + if (cmd === 'powershell.exe') { + callback(new Error('powershell unavailable'), { stdout: '', stderr: '' }) + return + } + callback(null, { stdout: wmicOutput, stderr: '' }) + }) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe') + ).resolves.toEqual({ available: false, processName: 'powershell.exe' }) + await expect(resolveAgentForegroundProcess(100, 'powershell.exe')).resolves.toBe( + 'powershell.exe' + ) + }) + + it('treats an observed Windows shell with no children as authoritative', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { + stdout: windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + } + ]), + stderr: '' + }) + } + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe') + ).resolves.toEqual({ available: true, processName: 'powershell.exe' }) + }) + + it('does not restore a recognized fallback that disappeared before confirmation', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + mockPs( + windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + } + ]) + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'droid', { + fresh: true, + forceProcessScan: true + }) + ).resolves.toEqual({ available: true, processName: null }) + }) + + it('treats a Windows snapshot missing the requested shell as unavailable', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { + stdout: windowsProcessJsonRows([ + { + CommandLine: 'unrelated.exe', + Name: 'unrelated.exe', + ParentProcessId: 99, + ProcessId: 200 + } + ]), + stderr: '' + }) + } + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe') + ).resolves.toEqual({ available: false, processName: 'powershell.exe' }) + await expect(resolveAgentForegroundProcess(100, 'powershell.exe')).resolves.toBe( + 'powershell.exe' + ) + }) + it('does not use unrelated Windows agent descendants for wrapper fallbacks', async () => { Object.defineProperty(process, 'platform', { value: 'win32' }) execFileMock.mockImplementation( @@ -334,6 +470,39 @@ describe('resolveAgentForegroundProcess', () => { ) }) + it('filters detached agents before resolving an otherwise ambiguous ConPTY tree', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + mockPs( + windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + }, + { + CommandLine: 'droid', + Name: 'droid.exe', + ParentProcessId: 100, + ProcessId: 101 + }, + { + CommandLine: 'agy', + Name: 'agy.exe', + ParentProcessId: 100, + ProcessId: 102 + } + ]) + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { + fresh: true, + readWindowsConptyProcessIds: async () => new Set([100, 101]) + }) + ).resolves.toEqual({ available: true, processName: 'droid' }) + }) + it('recognizes a Windows shell-rooted agent when only one candidate matches the worktree path', async () => { Object.defineProperty(process, 'platform', { value: 'win32' }) execFileMock.mockImplementation( @@ -494,4 +663,83 @@ describe('resolveAgentForegroundProcess', () => { await expect(resolveAgentForegroundProcess(100, 'vim.exe')).resolves.toBe('vim.exe') expect(execFileMock).not.toHaveBeenCalled() }) + + it('authorizes a fresh Windows agent only when it still belongs to the ConPTY', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + mockPs( + windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + }, + { + CommandLine: 'droid', + Name: 'droid.exe', + ParentProcessId: 100, + ProcessId: 101 + } + ]) + ) + const readWindowsConptyProcessIds = vi.fn(async () => new Set([100, 101, 999])) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { + fresh: true, + readWindowsConptyProcessIds + }) + ).resolves.toEqual({ available: true, processName: 'droid' }) + expect(readWindowsConptyProcessIds).toHaveBeenCalledTimes(1) + }) + + it('excludes a detached Windows Droid descendant from byte authority', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + mockPs( + windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + }, + { + CommandLine: 'droid', + Name: 'droid.exe', + ParentProcessId: 100, + ProcessId: 101 + } + ]) + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { + fresh: true, + readWindowsConptyProcessIds: async () => new Set([100, 999]) + }) + ).resolves.toEqual({ available: true, processName: 'powershell.exe' }) + }) + + it('does not fork the ConPTY membership helper when no Windows agent is inferred', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + mockPs( + windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + } + ]) + ) + const readWindowsConptyProcessIds = vi.fn(async () => new Set([100, 999])) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { + fresh: true, + readWindowsConptyProcessIds + }) + ).resolves.toEqual({ available: true, processName: 'powershell.exe' }) + expect(readWindowsConptyProcessIds).not.toHaveBeenCalled() + }) }) diff --git a/src/main/providers/agent-foreground-process.ts b/src/main/providers/agent-foreground-process.ts index d60582964bd9..6224b8049539 100644 --- a/src/main/providers/agent-foreground-process.ts +++ b/src/main/providers/agent-foreground-process.ts @@ -1,13 +1,22 @@ import { recognizeAgentProcessFromCommandLine } from '../../shared/agent-process-recognition' -import { getProcessTableSnapshot, type ProcessTableRow } from '../../shared/process-table-snapshot' import { - resolveWindowsAgentForegroundProcess, + getFreshProcessTableSnapshot, + getProcessTableSnapshot, + type ProcessTableRow +} from '../../shared/process-table-snapshot' +import { + resolveWindowsAgentForegroundProcessWithAvailability, shouldInspectWindowsAgentForeground, type AgentForegroundResolutionOptions } from './windows-agent-foreground-process' export type { AgentForegroundResolutionOptions } from './windows-agent-foreground-process' +export type AgentForegroundProcessResolution = { + available: boolean + processName: string | null +} + function collectDescendants( rows: Row[], rootPid: number @@ -43,29 +52,57 @@ export async function resolveAgentForegroundProcess( fallbackProcess: string | null, options: AgentForegroundResolutionOptions = {} ): Promise { + return (await resolveAgentForegroundProcessWithAvailability(shellPid, fallbackProcess, options)) + .processName +} + +export async function resolveAgentForegroundProcessWithAvailability( + shellPid: number | null | undefined, + fallbackProcess: string | null, + options: AgentForegroundResolutionOptions = {} +): Promise { if (!shellPid) { - return fallbackProcess + return { available: false, processName: fallbackProcess } } if (process.platform === 'win32') { - if (!fallbackProcess || !shouldInspectWindowsAgentForeground(fallbackProcess)) { - return fallbackProcess + if ( + !fallbackProcess || + (!shouldInspectWindowsAgentForeground(fallbackProcess) && !options.forceProcessScan) + ) { + return { available: true, processName: fallbackProcess } } - return ( - (await resolveWindowsAgentForegroundProcess(shellPid, fallbackProcess, options)) ?? - fallbackProcess + const resolution = await resolveWindowsAgentForegroundProcessWithAvailability( + shellPid, + fallbackProcess, + options ) + return { + available: resolution.available, + // Why: a forced confirmation scan that no longer sees the recognized + // fallback is authoritative evidence that the agent exited meanwhile. + processName: + resolution.processName ?? + (options.forceProcessScan && recognizeAgentProcessFromCommandLine(fallbackProcess) + ? null + : fallbackProcess) + } } try { - const rows = await getProcessTableSnapshot() - return resolveAgentForegroundProcessFromPs(rows, shellPid) ?? fallbackProcess + const rows = options.fresh + ? await getFreshProcessTableSnapshot() + : await getProcessTableSnapshot() + if (options.fresh && !rows.some((row) => row.pid === shellPid)) { + return { available: false, processName: fallbackProcess } + } + return { + available: true, + processName: resolveAgentForegroundProcessFromPs(rows, shellPid) ?? fallbackProcess + } } catch { - // Fall through to node-pty's process name. Foreground process inspection is - // best-effort because terminal identity should never break PTY operation. + return { available: !options.fresh, processName: fallbackProcess } } - - return fallbackProcess } function resolveAgentForegroundProcessFromPs( diff --git a/src/main/providers/local-pty-provider.test.ts b/src/main/providers/local-pty-provider.test.ts index 3fc96c897bf2..57748417caca 100644 --- a/src/main/providers/local-pty-provider.test.ts +++ b/src/main/providers/local-pty-provider.test.ts @@ -58,7 +58,10 @@ vi.mock('./windows-powershell-executable', () => ({ })) vi.mock('./agent-foreground-process', () => ({ - resolveAgentForegroundProcess: resolveAgentForegroundProcessMock + resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => ({ + available: true, + processName: await resolveAgentForegroundProcessMock(...args) + }) })) vi.mock('../wsl', () => ({ @@ -92,6 +95,8 @@ describe('LocalPtyProvider', () => { onExit: ReturnType write: ReturnType resize: ReturnType + pause: ReturnType + resume: ReturnType kill: ReturnType process: string pid: number @@ -138,6 +143,8 @@ describe('LocalPtyProvider', () => { }), write: vi.fn(), resize: vi.fn(), + pause: vi.fn(), + resume: vi.fn(), kill: vi.fn(() => { exitCb?.({ exitCode: -1 }) }), @@ -896,6 +903,39 @@ describe('LocalPtyProvider', () => { }) }) + describe('producer flow control', () => { + it('pauses and resumes the node-pty process directly', async () => { + const { id } = await provider.spawn({ cols: 80, rows: 24 }) + provider.pauseProducer(id) + expect(mockProc.pause).toHaveBeenCalledTimes(1) + provider.resumeProducer(id) + expect(mockProc.resume).toHaveBeenCalledTimes(1) + }) + + it('is a no-op for unknown PTY ids', () => { + expect(() => { + provider.pauseProducer('nonexistent') + provider.resumeProducer('nonexistent') + }).not.toThrow() + expect(mockProc.pause).not.toHaveBeenCalled() + expect(mockProc.resume).not.toHaveBeenCalled() + }) + + it('swallows node-pty throws from a torn-down PTY', async () => { + const { id } = await provider.spawn({ cols: 80, rows: 24 }) + mockProc.pause.mockImplementation(() => { + throw new Error('read EIO') + }) + mockProc.resume.mockImplementation(() => { + throw new Error('read EIO') + }) + expect(() => { + provider.pauseProducer(id) + provider.resumeProducer(id) + }).not.toThrow() + }) + }) + describe('shutdown', () => { it('kills the PTY process', async () => { // Why: capture the spy reference before shutdown triggers onExit → @@ -1002,6 +1042,24 @@ describe('LocalPtyProvider', () => { }) }) + describe('confirmForegroundProcess', () => { + it('drops a delayed result after the PTY exits', async () => { + let resolveScan!: (processName: string) => void + resolveAgentForegroundProcessMock.mockReturnValue( + new Promise((resolve) => { + resolveScan = resolve + }) + ) + const { id } = await provider.spawn({ cols: 80, rows: 24 }) + + const confirmation = provider.confirmForegroundProcess(id) + exitCb?.({ exitCode: 0 }) + resolveScan('droid') + + await expect(confirmation).resolves.toBeNull() + }) + }) + describe('event listeners', () => { it('notifies data listeners when PTY produces output', async () => { const dataHandler = vi.fn() diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts index 5b0e5ea84dae..806dfdd5d24a 100644 --- a/src/main/providers/local-pty-provider.ts +++ b/src/main/providers/local-pty-provider.ts @@ -51,9 +51,10 @@ import { resolveWindowsGitBashShellPath } from '../git-bash' import { WINDOWS_GIT_BASH_SHELL } from '../../shared/windows-terminal-shell' -import { resolveAgentForegroundProcess } from './agent-foreground-process' +import { resolveAgentForegroundProcessWithAvailability } from './agent-foreground-process' import { getAgentForegroundContextPaths } from './agent-foreground-context-paths' import { recognizeAgentProcessFromCommandLine } from '../../shared/agent-process-recognition' +import { readWindowsConptyProcessIds } from './windows-conpty-process-membership' import { shouldUseShellReadyStartupDelivery } from '../../shared/codex-startup-delivery' import { assertSafeAgentStartupCwd, resolveSafePtyDefaultCwd } from './pty-default-cwd' @@ -842,6 +843,26 @@ export class LocalPtyProvider implements IPtyProvider { ptyProcesses.get(id)?.resize(cols, rows) } + // Why: node-pty pause() stops reading the pty master fd, so the kernel + // buffer fills and a flooding child blocks on write — true producer + // backpressure. Best-effort: a PTY torn down mid-call must never throw + // into the flow-control path. + pauseProducer(id: string): void { + try { + ptyProcesses.get(id)?.pause() + } catch { + /* PTY already destroyed */ + } + } + + resumeProducer(id: string): void { + try { + ptyProcesses.get(id)?.resume() + } catch { + /* PTY already destroyed */ + } + } + // Why: node-pty caches the last winsize it applied on the IPty handle, so its // cols/rows are the authoritative applied size (node-pty clamps invalid dims // and a resize on a dead handle is a no-op, neither of which the requested @@ -951,13 +972,45 @@ export class LocalPtyProvider implements IPtyProvider { return null } try { - return await resolveAgentForegroundProcess( + const resolution = await resolveAgentForegroundProcessWithAvailability( proc.pid, resolveForegroundFallbackProcess(proc.process || null, ptyShellName.get(id)), { contextPaths: ptyAgentForegroundContextPaths.get(id) } ) + return resolution.processName + } catch { + return null + } + } + + async confirmForegroundProcess(id: string): Promise { + const proc = ptyProcesses.get(id) + if (!proc) { + return null + } + try { + const resolution = await resolveAgentForegroundProcessWithAvailability( + proc.pid, + resolveForegroundFallbackProcess(proc.process || null, ptyShellName.get(id)), + { + contextPaths: ptyAgentForegroundContextPaths.get(id), + fresh: true, + ...(process.platform === 'win32' + ? { + forceProcessScan: true, + readWindowsConptyProcessIds: () => readWindowsConptyProcessIds(proc.pid) + } + : {}) + } + ) + // Why: a fresh scan can outlive this PTY id; never publish identity from + // an exited process or a replacement session that reused the same id. + if (ptyProcesses.get(id) !== proc) { + return null + } + return resolution.available ? resolution.processName : null } catch { return null } @@ -1044,7 +1097,7 @@ export class LocalPtyProvider implements IPtyProvider { return ptyProcesses.get(id) } - /** Kill all PTYs. Call on app quit. */ + /** Kill all in-process local PTYs. Call on app quit. */ killAll(): void { for (const [id, proc] of ptyProcesses) { safeKillAndClean(id, proc) diff --git a/src/main/providers/local-pty-shell-ready.test.ts b/src/main/providers/local-pty-shell-ready.test.ts index e736e236c9af..677c2c659464 100644 --- a/src/main/providers/local-pty-shell-ready.test.ts +++ b/src/main/providers/local-pty-shell-ready.test.ts @@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { spawnSync } from 'node:child_process' import { tmpdir } from 'node:os' import { join, dirname } from 'node:path' -import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs' +import { mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync, mkdirSync } from 'node:fs' import type * as pty from 'node-pty' import type * as LocalPtyShellReadyModule from './local-pty-shell-ready' import { @@ -14,20 +14,24 @@ import { writeStartupCommandWhenShellReady } from './local-pty-shell-ready' -const { getUserDataPathMock } = vi.hoisted(() => ({ - getUserDataPathMock: vi.fn<() => string>() -})) +// Why: the wrapper root is resolved from ORCA_USER_DATA_PATH (main +// canonicalizes it at startup; the daemon fork sets it explicitly). This +// module must not import electron because it is bundled into the plain-node +// daemon-entry fork, so tests point the root through the env var rather than +// mocking electron's app. +function setTestUserDataPath(path: string): void { + process.env.ORCA_USER_DATA_PATH = path +} -vi.mock('electron', () => ({ - app: { - getPath: (name: string) => { - if (name === 'userData') { - return getUserDataPathMock() - } - throw new Error(`unexpected app.getPath(${name})`) - } +const ORIGINAL_ORCA_USER_DATA_PATH = process.env.ORCA_USER_DATA_PATH + +afterEach(() => { + if (ORIGINAL_ORCA_USER_DATA_PATH === undefined) { + delete process.env.ORCA_USER_DATA_PATH + } else { + process.env.ORCA_USER_DATA_PATH = ORIGINAL_ORCA_USER_DATA_PATH } -})) +}) async function importFreshLocalPtyShellReady(): Promise { vi.resetModules() @@ -279,6 +283,23 @@ describe('scanForShellReady', () => { }) }) +describe('shell-ready wrapper root resolution', () => { + // Why: regression guard — the daemon-entry fork runs as plain Node and cannot + // import electron, so the wrapper root must resolve from ORCA_USER_DATA_PATH + // (set by main at startup and by the daemon fork) rather than app.getPath. + it('resolves the wrapper root from ORCA_USER_DATA_PATH', async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-userdata-env-')) + try { + setTestUserDataPath(root) + const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady() + const config = getShellReadyLaunchConfig('/bin/zsh') + expect(config.env.ZDOTDIR).toBe(`${root}/shell-ready/zsh`) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) +}) + const describePosix = process.platform === 'win32' ? describe.skip : describe const hasBash = process.platform !== 'win32' && spawnSync('bash', ['--version']).status === 0 const itWithBash = hasBash ? it : it.skip @@ -342,7 +363,7 @@ describePosix('local PTY shell-ready launch config', () => { previousOrcaOrigZdotdir = process.env.ORCA_ORIG_ZDOTDIR delete process.env.ORCA_ORIG_ZDOTDIR userDataPath = mkdtempSync(join(tmpdir(), 'local-pty-shell-ready-test-')) - getUserDataPathMock.mockReturnValue(userDataPath) + setTestUserDataPath(userDataPath) }) afterEach(() => { @@ -703,6 +724,31 @@ describePosix('local PTY shell-ready launch config', () => { // Fallback chain: discovered → normalized spawn-env path → HOME expect(zshenv).toContain('${_orca_discovered_zdotdir:-${_orca_user_zdotdir:-$HOME}}') }) + + it('restores wrapper ZDOTDIR from the runtime sourced path, not the baked literal', async () => { + // Why: issue #8003 — WSL sources Windows-generated wrappers via /mnt/c, + // so the generation-time path baked into .zshenv does not exist there. + const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady() + + getShellReadyLaunchConfig('/bin/zsh') + + const zshenv = readFileSync(join(userDataPath, 'shell-ready', 'zsh', '.zshenv'), 'utf8') + + expect(zshenv).toContain('_orca_wrapper_zdotdir_self="${ZDOTDIR:-}"') + // The runtime path is only trusted when it still holds a wrapper .zshenv; + // otherwise the generation-time literal remains as the fallback. + expect(zshenv).toContain( + 'if [[ -n "${_orca_wrapper_zdotdir_self:-}" && -f "${_orca_wrapper_zdotdir_self:-}/.zshenv" ]]; then\n' + + ' export ZDOTDIR="${_orca_wrapper_zdotdir_self:-}"\n' + + 'else\n' + + ` export ZDOTDIR='${join(userDataPath, 'shell-ready', 'zsh')}'\n` + + 'fi' + ) + // Capture must happen before the wrapper unsets ZDOTDIR to source user files. + expect(zshenv.indexOf('_orca_wrapper_zdotdir_self="${ZDOTDIR:-}"')).toBeLessThan( + zshenv.indexOf('unset ZDOTDIR') + ) + }) }) // Why: end-to-end validation that wrapper ZDOTDIR discovery preserves top-level @@ -723,7 +769,7 @@ describePosix('live zsh subprocess tests', () => { beforeEach(async () => { testHome = mkdtempSync(join(tmpdir(), 'orca-zsh-test-home-')) userDataPath = mkdtempSync(join(tmpdir(), 'orca-zsh-test-userdata-')) - getUserDataPathMock.mockReturnValue(userDataPath) + setTestUserDataPath(userDataPath) }) afterEach(() => { @@ -791,6 +837,61 @@ path=(/custom/bin $path) expect(output).toContain('PATH_HAS_CUSTOM=/custom/bin') }) + it('loads user .zshrc when wrappers are sourced from a different runtime path (WSL simulation)', async () => { + // Why: issue #8003 — on Windows the wrappers are generated under the + // native userData path but WSL sources them via /mnt/c, where the baked + // generation-time path does not exist. Renaming the userData dir after + // generation reproduces that split: runtime ZDOTDIR resolves, the baked + // literal does not. + writeFileSync(join(testHome, '.zshrc'), 'export USER_ZSHRC_LOADED=yes\n') + + const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady() + getShellReadyLaunchConfig('/bin/zsh') + + const movedUserData = `${userDataPath}-wsl-view` + renameSync(userDataPath, movedUserData) + try { + const cleanEnv: Record = { + ...process.env, + HOME: testHome, + PATH: '/usr/bin:/bin' + } + delete cleanEnv.ZDOTDIR + delete cleanEnv.ORCA_ORIG_ZDOTDIR + delete cleanEnv.ORCA_ATTRIBUTION_SHIM_DIR + delete cleanEnv.USER_ZSHRC_LOADED + cleanEnv.ZDOTDIR = join(movedUserData, 'shell-ready', 'zsh') + + // Production WSL launches a login shell (`exec zsh -l`); also cover the + // non-login flow used by local panes so both restore paths stay pinned. + // Login must still load user .zshrc (via wrapper .zshrc after .zprofile) + // and leave final ZDOTDIR at the user home after .zlogin restore. + for (const args of [['-i'], ['-l', '-i']] as const) { + const result = spawnSync( + 'zsh', + [ + ...args, + '-c', + 'echo "USER_ZSHRC_LOADED=${USER_ZSHRC_LOADED:-no}" && echo "FINAL_ZDOTDIR=${ZDOTDIR:-unset}" && echo "IS_LOGIN=$([[ -o login ]] && echo yes || echo no)"' + ], + { + env: cleanEnv as NodeJS.ProcessEnv, + encoding: 'utf8' + } + ) + + expect(result.status, `zsh ${args.join(' ')} failed: ${result.stderr}`).toBe(0) + expect(result.stdout).toContain('USER_ZSHRC_LOADED=yes') + expect(result.stdout).toContain(`FINAL_ZDOTDIR=${testHome}`) + // Why: `as const` makes .includes('-l') reject the union of tuple + // element types; check the login flag by position instead. + expect(result.stdout).toContain(args[0] === '-l' ? 'IS_LOGIN=yes' : 'IS_LOGIN=no') + } + } finally { + rmSync(movedUserData, { recursive: true, force: true }) + } + }) + it('preserves top-level .zshenv path and function side effects', async () => { // Why: .zshenv is the normal place for always-on zsh env/path setup. // Dropping those side effects regresses non-Orca zsh startup semantics. @@ -957,7 +1058,7 @@ export MY_VAR=foo beforeEach(async () => { testHome = mkdtempSync(join(tmpdir(), 'orca-zsh-edge-')) userDataPath = mkdtempSync(join(tmpdir(), 'orca-zsh-userdata-')) - getUserDataPathMock.mockReturnValue(userDataPath) + setTestUserDataPath(userDataPath) }) afterEach(() => { @@ -1283,7 +1384,7 @@ export MY_VAR=foo beforeEach(async () => { testHome = mkdtempSync(join(tmpdir(), 'orca-term-')) userDataPath = mkdtempSync(join(tmpdir(), 'orca-term-userdata-')) - getUserDataPathMock.mockReturnValue(userDataPath) + setTestUserDataPath(userDataPath) }) afterEach(() => { @@ -1516,7 +1617,7 @@ export MY_VAR=foo beforeEach(async () => { testHome = mkdtempSync(join(tmpdir(), 'orca-auto-')) userDataPath = mkdtempSync(join(tmpdir(), 'orca-auto-userdata-')) - getUserDataPathMock.mockReturnValue(userDataPath) + setTestUserDataPath(userDataPath) }) afterEach(() => { diff --git a/src/main/providers/local-pty-shell-ready.ts b/src/main/providers/local-pty-shell-ready.ts index 978d3e94b2a2..e7b5c618f4da 100644 --- a/src/main/providers/local-pty-shell-ready.ts +++ b/src/main/providers/local-pty-shell-ready.ts @@ -13,7 +13,6 @@ import { tmpdir } from 'node:os' import { basename, win32 as pathWin32 } from 'node:path' import { mkdirSync, writeFileSync, chmodSync, existsSync } from 'node:fs' -import { app } from 'electron' import type * as pty from 'node-pty' import { encodePowerShellCommand, @@ -50,7 +49,11 @@ export type ShellReadySignal = { // ── Shell wrapper files ───────────────────────────────────────────── function getShellReadyWrapperRoot(): string { - const userDataPath = app?.getPath?.('userData') ?? process.env.ORCA_USER_DATA_PATH ?? tmpdir() + // Why: bundled into daemon-entry.js (a plain-node fork with no electron + // require), so this must not import electron. Main canonicalizes + // ORCA_USER_DATA_PATH to its own userData at startup (configureOrcaUserDataPathEnv) + // and the daemon fork sets it explicitly, so the env value matches this root. + const userDataPath = process.env.ORCA_USER_DATA_PATH ?? tmpdir() return `${userDataPath}/shell-ready` } @@ -64,8 +67,8 @@ function getRequiredShellReadyWrapperPaths(root = getShellReadyWrapperRoot()): s ] } -function shellReadyWrappersExist(): boolean { - return getRequiredShellReadyWrapperPaths().every((path) => existsSync(path)) +function shellReadyWrappersExist(root = getShellReadyWrapperRoot()): boolean { + return getRequiredShellReadyWrapperPaths(root).every((path) => existsSync(path)) } // Why: if our own process inherited ZDOTDIR from a parent shell that was @@ -288,16 +291,12 @@ fi ` } -function ensureShellReadyWrappers(): void { - if (process.platform === 'win32') { - return - } - if (didEnsureShellReadyWrappers && shellReadyWrappersExist()) { +export function ensureShellReadyWrappersAt(root = getShellReadyWrapperRoot()): void { + if (didEnsureShellReadyWrappers && shellReadyWrappersExist(root)) { return } didEnsureShellReadyWrappers = true - const root = getShellReadyWrapperRoot() const zshDir = `${root}/zsh` const bashDir = `${root}/bash` @@ -365,6 +364,13 @@ ${getZshFinalZdotdirRestoreBlock()} } } +function ensureShellReadyWrappers(): void { + if (process.platform === 'win32') { + return + } + ensureShellReadyWrappersAt() +} + // ── Shell launch config ───────────────────────────────────────────── export type ShellReadyLaunchConfig = { diff --git a/src/main/providers/provider-dispatch.test.ts b/src/main/providers/provider-dispatch.test.ts index 367179338c20..be45aa04ff39 100644 --- a/src/main/providers/provider-dispatch.test.ts +++ b/src/main/providers/provider-dispatch.test.ts @@ -17,6 +17,9 @@ vi.mock('electron', () => ({ on: onMock, removeHandler: removeHandlerMock, removeAllListeners: removeAllListenersMock + }, + powerMonitor: { + on: vi.fn() } })) diff --git a/src/main/providers/ssh-filesystem-provider.test.ts b/src/main/providers/ssh-filesystem-provider.test.ts index 6d4170209e7f..d35460bd489b 100644 --- a/src/main/providers/ssh-filesystem-provider.test.ts +++ b/src/main/providers/ssh-filesystem-provider.test.ts @@ -417,7 +417,11 @@ describe('SshFilesystemProvider', () => { it('listFiles sends fs.listFiles request', async () => { mux.request.mockResolvedValue(['src/index.ts', 'package.json']) const result = await provider.listFiles('/home/user/project') - expect(mux.request).toHaveBeenCalledWith('fs.listFiles', { rootPath: '/home/user/project' }) + expect(mux.request).toHaveBeenCalledWith( + 'fs.listFiles', + { rootPath: '/home/user/project' }, + { signal: undefined } + ) expect(result).toEqual(['src/index.ts', 'package.json']) }) @@ -426,16 +430,35 @@ describe('SshFilesystemProvider', () => { await provider.listFiles('/home/user/project', { excludePaths: ['/home/user/project/worktrees/b'] }) - expect(mux.request).toHaveBeenCalledWith('fs.listFiles', { - rootPath: '/home/user/project', - excludePaths: ['/home/user/project/worktrees/b'] - }) + expect(mux.request).toHaveBeenCalledWith( + 'fs.listFiles', + { + rootPath: '/home/user/project', + excludePaths: ['/home/user/project/worktrees/b'] + }, + { signal: undefined } + ) }) it('listFiles omits excludePaths when empty', async () => { mux.request.mockResolvedValue([]) await provider.listFiles('/home/user/project', { excludePaths: [] }) - expect(mux.request).toHaveBeenCalledWith('fs.listFiles', { rootPath: '/home/user/project' }) + expect(mux.request).toHaveBeenCalledWith( + 'fs.listFiles', + { rootPath: '/home/user/project' }, + { signal: undefined } + ) + }) + + it('listFiles forwards the cancellation signal to the mux request (#7721)', async () => { + mux.request.mockResolvedValue([]) + const controller = new AbortController() + await provider.listFiles('/home/user/project', { signal: controller.signal }) + expect(mux.request).toHaveBeenCalledWith( + 'fs.listFiles', + { rootPath: '/home/user/project' }, + { signal: controller.signal } + ) }) describe('watch', () => { diff --git a/src/main/providers/ssh-filesystem-provider.ts b/src/main/providers/ssh-filesystem-provider.ts index 3adeeec6cb88..ce5256d2744f 100644 --- a/src/main/providers/ssh-filesystem-provider.ts +++ b/src/main/providers/ssh-filesystem-provider.ts @@ -283,12 +283,20 @@ export class SshFilesystemProvider implements IFilesystemProvider { return (await this.mux.request('fs.search', opts)) as SearchResult } - async listFiles(rootPath: string, options?: { excludePaths?: string[] }): Promise { + async listFiles( + rootPath: string, + options?: { excludePaths?: string[]; signal?: AbortSignal } + ): Promise { const params: Record = { rootPath } if (options?.excludePaths && options.excludePaths.length > 0) { params.excludePaths = options.excludePaths } - return (await this.mux.request('fs.listFiles', params)) as string[] + // Why #7721: the signal lets a workspace switch send rpc.cancel so the + // relay aborts the full-tree scan instead of stacking abandoned scans + // that starve interactive fs.readDir/fs.stat on the shared SSH channel. + return (await this.mux.request('fs.listFiles', params, { + signal: options?.signal + })) as string[] } async watch(rootPath: string, callback: (events: FsChangeEvent[]) => void): Promise<() => void> { diff --git a/src/main/providers/ssh-git-provider.test.ts b/src/main/providers/ssh-git-provider.test.ts index acfaefaed122..91c781bf452c 100644 --- a/src/main/providers/ssh-git-provider.test.ts +++ b/src/main/providers/ssh-git-provider.test.ts @@ -7,6 +7,7 @@ type MockMultiplexer = { notify: ReturnType onNotification: ReturnType onNotificationByMethod: ReturnType + onDispose: ReturnType dispose: ReturnType isDisposed: ReturnType } @@ -17,6 +18,9 @@ function createMockMux(): MockMultiplexer { notify: vi.fn(), onNotification: vi.fn(), onNotificationByMethod: vi.fn().mockReturnValue(vi.fn()), + // Why: requestGitStreamable subscribes to onDispose before awaiting the + // response so it can reject in-flight reassembly if the link drops. + onDispose: vi.fn().mockReturnValue(vi.fn()), dispose: vi.fn(), isDisposed: vi.fn().mockReturnValue(false) } @@ -320,7 +324,10 @@ describe('SshGitProvider', () => { 'git.exec', { args: ['clone', '--progress', '--', 'git@example.com:repo.git', 'repo'], - cwd: '/home/user' + cwd: '/home/user', + // Why: exec opts into response streaming so a large stdout is chunked + // onto the bulk lane; old relays ignore the flag. + __streamResponse: true }, { signal: controller.signal, @@ -353,7 +360,8 @@ describe('SshGitProvider', () => { }) expect(mux.request).toHaveBeenCalledWith('git.exec', { args: ['diff', '--cached', '--patch', '--minimal', '--no-color', '--no-ext-diff'], - cwd: '/home/user/repo' + cwd: '/home/user/repo', + __streamResponse: true }) }) @@ -636,7 +644,10 @@ describe('SshGitProvider', () => { expect(mux.request).toHaveBeenCalledWith('git.diff', { worktreePath: '/home/user/repo', filePath: 'src/index.ts', - staged: true + staged: true, + // Why: opts into response streaming; a small result still comes back as a + // single frame (relay decides), and old relays ignore the flag. + __streamResponse: true }) expect(result).toEqual(diffResult) }) @@ -850,14 +861,16 @@ describe('SshGitProvider', () => { '/home/user/repo', 'origin', 'main', - 'refs/remotes/origin/main' + 'refs/remotes/origin/main', + { skipAutoMaintenance: true } ) expect(mux.request).toHaveBeenCalledWith('git.fetchRemoteTrackingRef', { worktreePath: '/home/user/repo', remote: 'origin', branch: 'main', - ref: 'refs/remotes/origin/main' + ref: 'refs/remotes/origin/main', + skipAutoMaintenance: true }) }) @@ -878,7 +891,8 @@ describe('SshGitProvider', () => { const result = await provider.getBranchDiff('/home/user/repo', 'main') expect(mux.request).toHaveBeenCalledWith('git.branchDiff', { worktreePath: '/home/user/repo', - baseRef: 'main' + baseRef: 'main', + __streamResponse: true }) expect(result).toEqual(diffs) }) diff --git a/src/main/providers/ssh-git-provider.ts b/src/main/providers/ssh-git-provider.ts index 5ba6a29e380c..76fb163909b4 100644 --- a/src/main/providers/ssh-git-provider.ts +++ b/src/main/providers/ssh-git-provider.ts @@ -21,6 +21,7 @@ import type { import type { GitHistoryOptions, GitHistoryResult } from '../../shared/git-history' import { buildHostedRemoteCommitUrl, buildHostedRemoteFileUrl } from '../git/hosted-remote-url' import { JsonRpcErrorCode } from '../ssh/relay-protocol' +import { requestGitStreamable } from '../ssh/ssh-git-response-stream-reader' import type { CommitMessageDraftContext } from '../../shared/commit-message-generation' import type { CommitMessagePlan } from '../../shared/commit-message-plan' import type { RemoteCommitMessageExecResult } from '../text-generation/commit-message-text-generation' @@ -373,7 +374,7 @@ export class SshGitProvider implements IGitProvider { return this.gitDiffReadDedupe.run( stableInFlightKey(['diff', worktreePath, filePath, staged, compareAgainstHead]), async () => - (await this.mux.request('git.diff', { + (await requestGitStreamable(this.mux, 'git.diff', { worktreePath, filePath, staged, @@ -553,14 +554,16 @@ export class SshGitProvider implements IGitProvider { worktreePath: string, remote: string, branch: string, - ref: string + ref: string, + options?: { skipAutoMaintenance?: boolean } ): Promise { await this.runWithDiffDedupeClear(async () => { await this.mux.request('git.fetchRemoteTrackingRef', { worktreePath, remote, branch, - ref + ref, + ...(options?.skipAutoMaintenance ? { skipAutoMaintenance: true } : {}) }) }) } @@ -595,7 +598,7 @@ export class SshGitProvider implements IGitProvider { keyOptions.oldPath ?? null ]), async () => - (await this.mux.request('git.branchDiff', { + (await requestGitStreamable(this.mux, 'git.branchDiff', { worktreePath, baseRef, ...options @@ -617,7 +620,7 @@ export class SshGitProvider implements IGitProvider { args.oldPath ?? null ]), async () => - (await this.mux.request('git.commitDiff', { + (await requestGitStreamable(this.mux, 'git.commitDiff', { worktreePath, ...args })) as GitDiffResult @@ -759,8 +762,8 @@ export class SshGitProvider implements IGitProvider { options?: { signal?: AbortSignal; timeoutMs?: number } ): Promise<{ stdout: string; stderr: string }> { const result = options - ? await this.mux.request('git.exec', { args, cwd }, options) - : await this.mux.request('git.exec', { args, cwd }) + ? await requestGitStreamable(this.mux, 'git.exec', { args, cwd }, options) + : await requestGitStreamable(this.mux, 'git.exec', { args, cwd }) return result as { stdout: string stderr: string diff --git a/src/main/providers/ssh-pty-provider.test.ts b/src/main/providers/ssh-pty-provider.test.ts index 27a279cdd557..ca0a9fd82614 100644 --- a/src/main/providers/ssh-pty-provider.test.ts +++ b/src/main/providers/ssh-pty-provider.test.ts @@ -138,8 +138,39 @@ describe('SshPtyProvider', () => { cols: 120, rows: 40, cwd: undefined, - env: {} + env: {}, + envToDelete: [POWERLEVEL10K_WIZARD_DISABLE_ENV] + }) + }) + + it('preserves explicit TERM and forwards final env deletions to the relay', async () => { + mux.request.mockResolvedValue({ id: 'pty-env-precedence' }) + const envToDelete = ['TERM_PROGRAM', 'ORCA_ATTRIBUTION_SHIM_DIR'] + + await provider.spawn({ + cols: 120, + rows: 40, + env: { + TERM: 'screen-256color', + TERM_PROGRAM: 'stale-terminal', + ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/stale-attribution' + }, + envToDelete + }) + + expect(mux.request).toHaveBeenCalledWith('pty.spawn', { + cols: 120, + rows: 40, + cwd: undefined, + env: { + TERM: 'screen-256color', + [POWERLEVEL10K_WIZARD_DISABLE_ENV]: 'true' + }, + envToDelete }) + const spawnCall = mux.request.mock.calls.find((call) => call[0] === 'pty.spawn') + expect(spawnCall?.[1]?.env).not.toHaveProperty('TERM_PROGRAM') + expect(spawnCall?.[1]?.env).not.toHaveProperty('ORCA_ATTRIBUTION_SHIM_DIR') }) it('forwards provider command delivery to the relay', async () => { diff --git a/src/main/providers/ssh-pty-provider.ts b/src/main/providers/ssh-pty-provider.ts index be84c2a6267f..e386e89dbbac 100644 --- a/src/main/providers/ssh-pty-provider.ts +++ b/src/main/providers/ssh-pty-provider.ts @@ -149,6 +149,7 @@ export class SshPtyProvider implements IPtyProvider { rows: opts.rows, cwd: opts.cwd, env: this.withRemoteCliBridgeEnv(opts.env, opts.envToDelete), + ...(opts.envToDelete?.length ? { envToDelete: opts.envToDelete } : {}), // Why: the relay's plugin-overlay env augmenter needs to know which // Pi-compatible agent is being launched, while commandDelivery tells it // whether to submit the command itself for runtime-owned background PTYs. @@ -179,27 +180,28 @@ export class SshPtyProvider implements IPtyProvider { envToDelete?: readonly string[] ): Record { const merged = { ...env } + if (this.remoteCliBridgeEnv) { + const pathDelimiter = this.remoteCliBridgeEnv.pathDelimiter ?? ':' + const pathKey = merged.PATH !== undefined ? 'PATH' : merged.Path !== undefined ? 'Path' : null + if (pathKey) { + const pathValue = merged[pathKey] ?? '' + merged[pathKey] = pathValue.split(pathDelimiter).includes(this.remoteCliBridgeEnv.binDir) + ? pathValue + : pathValue + ? `${this.remoteCliBridgeEnv.binDir}${pathDelimiter}${pathValue}` + : this.remoteCliBridgeEnv.binDir + } + merged.ORCA_REMOTE_CLI_BIN_DIR = this.remoteCliBridgeEnv.binDir + merged.ORCA_RELAY_DIR = this.remoteCliBridgeEnv.relayDir + merged.ORCA_RELAY_NODE_PATH = this.remoteCliBridgeEnv.nodePath + merged.ORCA_RELAY_SOCKET_PATH = this.remoteCliBridgeEnv.sockPath + } + // Why: match local/daemon precedence—managed defaults and augmentations + // cannot resurrect values the caller explicitly removed. for (const key of envToDelete ?? []) { delete merged[key] } seedPowerlevel10kWizardEnv(merged, { envToDelete }) - if (!this.remoteCliBridgeEnv) { - return merged - } - const pathDelimiter = this.remoteCliBridgeEnv.pathDelimiter ?? ':' - const pathKey = merged.PATH !== undefined ? 'PATH' : merged.Path !== undefined ? 'Path' : null - if (pathKey) { - const pathValue = merged[pathKey] ?? '' - merged[pathKey] = pathValue.split(pathDelimiter).includes(this.remoteCliBridgeEnv.binDir) - ? pathValue - : pathValue - ? `${this.remoteCliBridgeEnv.binDir}${pathDelimiter}${pathValue}` - : this.remoteCliBridgeEnv.binDir - } - merged.ORCA_REMOTE_CLI_BIN_DIR = this.remoteCliBridgeEnv.binDir - merged.ORCA_RELAY_DIR = this.remoteCliBridgeEnv.relayDir - merged.ORCA_RELAY_NODE_PATH = this.remoteCliBridgeEnv.nodePath - merged.ORCA_RELAY_SOCKET_PATH = this.remoteCliBridgeEnv.sockPath return merged } diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts index 28d5d1d94475..d5873c948ea7 100644 --- a/src/main/providers/types.ts +++ b/src/main/providers/types.ts @@ -12,6 +12,7 @@ import type { GitStagingArea, GitUpstreamStatus, GitWorktreeInfo, + TuiAgent, RemoveWorktreeResult, SearchOptions, SearchResult @@ -21,9 +22,38 @@ import type { CommitMessageDraftContext } from '../../shared/commit-message-gene import type { WorkspaceSpaceDirectoryScanResult } from '../../shared/workspace-space-types' import type { StartupCommandDelivery } from '../../shared/codex-startup-delivery' import type { TerminalOscLinkRange } from '../../shared/terminal-osc-link-ranges' +import type { TerminalGitHubPRLink } from '../../shared/terminal-github-pr-link-detector' // ─── PTY Provider ─────────────────────────────────────────────────── +/** Notification-bearing fact a thinning transport detected while it held + * scan authority for a backgrounded PTY (see onBackgroundStreamEvent). */ +export type PtyTransientFact = + | { kind: 'bell' } + | { kind: 'command-finished'; exitCode: number | null } + | { kind: 'pr-link'; link: TerminalGitHubPRLink } + | { kind: '2031-subscribe' } + +export type PtyBackgroundStreamEvent = + | { id: string; kind: 'backgroundMarker'; background: boolean; scanSeedAnsi?: string } + | { id: string; kind: 'dataGap'; droppedChars: number; sequenceChars?: number } + | { id: string; kind: 'transientFact'; fact: PtyTransientFact } + +export type PtyProviderBufferSnapshot = { + data: string + /** Authoritative normal buffer captured beside an alternate-screen frame. */ + scrollbackAnsi?: string + cols: number + rows: number + cwd?: string | null + lastTitle?: string + seq: number + source: 'headless' + oscLinks?: TerminalOscLinkRange[] + alternateScreen?: boolean + pendingEscapeTailAnsi?: string +} + export type PtySpawnOptions = { cols: number rows: number @@ -33,6 +63,8 @@ export type PtySpawnOptions = { command?: string commandDelivery?: 'renderer' | 'provider' startupCommandDelivery?: StartupCommandDelivery + /** Minimal allowlisted launch ownership preserved by daemon reattach. */ + launchAgent?: TuiAgent /** Orca worktree identity. When present, the local provider scopes shell * history to this worktree so ArrowUp only surfaces local commands. */ worktreeId?: string @@ -76,6 +108,8 @@ export type PtySpawnResult = { * local providers read it from node-pty. Null when the underlying * provider could not publish a pid (e.g., race during spawn). */ pid?: number | null + /** Minimal allowlisted launch ownership returned by daemon reattach. */ + launchAgent?: TuiAgent /** ANSI snapshot of the terminal screen, present when reattaching to an * existing daemon session. Write this to xterm.js to restore visual state. */ snapshot?: string @@ -83,6 +117,11 @@ export type PtySpawnResult = { * writing the snapshot so ANSI cursor positions land correctly. */ snapshotCols?: number snapshotRows?: number + /** Kitty keyboard flags persisted in the daemon snapshot, threaded so the + * re-seeded runtime emulator answers hidden `CSI ? u` with the real flags + * (terminal-query-authority.md §kitty). Never replayed into a renderer + * xterm — POST_REPLAY_REATTACH_RESET's kitty reset stays authoritative. */ + snapshotKittyKeyboardFlags?: number /** True when the spawn reattached to an existing daemon session. */ isReattach?: boolean /** True when the reattached session uses the alternate screen buffer @@ -119,6 +158,36 @@ export type IPtyProvider = { hasPty?: (id: string) => boolean write(id: string, data: string): void resize(id: string, cols: number, rows: number): void + /** + * Producer-side flow control: stop/restart reading the underlying PTY so a + * flooding child blocks on write (kernel backpressure) instead of growing + * main-process buffers. Best-effort and optional — providers that cannot + * pause (SSH relay, legacy daemon protocols) omit these or no-op silently, + * and callers must keep functioning without them (the pending-output cap + * still bounds memory when pause is unavailable). + */ + pauseProducer?: (id: string) => void + resumeProducer?: (id: string) => void + /** + * Hidden-delivery hint: the renderer has no visible view for this PTY, so + * the provider's transport may keep-tail thin this PTY's monitoring stream + * under backlog (bytes nobody is watching must not bury a visible pane's + * echo). Best-effort and optional, like pauseProducer. + */ + setPtyBackgrounded?: (id: string, background: boolean) => void + /** + * Facts a thinning transport interleaves with onData, in byte order: + * scan-authority handoff markers, keep-tail gaps, and the transient facts + * (bell/command-finished/pr-link/2031) it detected in bytes it was allowed + * to drop. Only transports that thin implement it. + */ + onBackgroundStreamEvent?: (callback: (payload: PtyBackgroundStreamEvent) => void) => () => void + /** Authoritative provider-owned model snapshot. Daemon providers expose this + * after their monitoring stream gaps; other providers may omit it. */ + getBufferSnapshot?: ( + id: string, + opts?: { scrollbackRows?: number } + ) => Promise /** * The size the PTY has ACTUALLY applied, not the last size requested. * resize() is fire-and-forget for remote providers (daemon/SSH `notify`), @@ -140,12 +209,16 @@ export type IPtyProvider = { acknowledgeDataEvent(id: string, charCount: number): void hasChildProcesses(id: string): Promise getForegroundProcess(id: string): Promise + /** Strong process evidence captured after the caller's command boundary. */ + confirmForegroundProcess?: (id: string) => Promise serialize(ids: string[]): Promise revive(state: string): Promise listProcesses(): Promise getDefaultShell(): Promise getProfiles(): Promise<{ name: string; path: string }[]> - onData(callback: (payload: { id: string; data: string }) => void): () => void + onData( + callback: (payload: { id: string; data: string; sequenceChars?: number }) => void + ): () => void onReplay(callback: (payload: { id: string; data: string }) => void): () => void onExit(callback: (payload: { id: string; code: number }) => void): () => void } @@ -197,7 +270,10 @@ export type IFilesystemProvider = { copy(source: string, destination: string): Promise realpath(filePath: string): Promise search(opts: SearchOptions): Promise - listFiles(rootPath: string, options?: { excludePaths?: string[] }): Promise + listFiles( + rootPath: string, + options?: { excludePaths?: string[]; signal?: AbortSignal } + ): Promise scanWorkspaceSpace?( rootPath: string, options?: { signal?: AbortSignal } diff --git a/src/main/providers/windows-agent-foreground-process.ts b/src/main/providers/windows-agent-foreground-process.ts index 39447432a915..556d6763e628 100644 --- a/src/main/providers/windows-agent-foreground-process.ts +++ b/src/main/providers/windows-agent-foreground-process.ts @@ -12,6 +12,17 @@ import { export type AgentForegroundResolutionOptions = { contextPaths?: readonly string[] + /** Require a Windows process-table scan started after this request. */ + fresh?: boolean + /** Force confirmation scans even when node-pty reports a recognized name. */ + forceProcessScan?: boolean + /** Lazily proves which global descendants still belong to this ConPTY. */ + readWindowsConptyProcessIds?: () => Promise | null> +} + +export type WindowsAgentForegroundResolution = { + available: boolean + processName: string | null } export function shouldInspectWindowsAgentForeground(fallbackProcess: string): boolean { @@ -23,21 +34,79 @@ export async function resolveWindowsAgentForegroundProcess( fallbackProcess: string, options: AgentForegroundResolutionOptions ): Promise { - const candidates = await queryWindowsProcessDescendants(shellPid) + return ( + await resolveWindowsAgentForegroundProcessWithAvailability(shellPid, fallbackProcess, options) + ).processName +} + +export async function resolveWindowsAgentForegroundProcessWithAvailability( + shellPid: number, + fallbackProcess: string, + options: AgentForegroundResolutionOptions +): Promise { + const candidates = await queryWindowsProcessDescendants( + shellPid, + options.fresh === true ? { fresh: true } : {} + ) if (!candidates) { - return null + return { available: false, processName: null } + } + // Resolve membership before applying the global ambiguity rule. A detached + // agent can otherwise make an attached Droid look ambiguous and suppress + // the only identity that is actually able to receive this PTY's input. + const hasRecognizedCandidate = windowsCandidatesContainRecognizedAgent( + candidates, + fallbackProcess, + options.contextPaths + ) + let filteredCandidates = candidates + if (hasRecognizedCandidate && options.readWindowsConptyProcessIds) { + const conptyProcessIds = await options.readWindowsConptyProcessIds() + if (!conptyProcessIds) { + return { available: false, processName: null } + } + filteredCandidates = candidates.filter((candidate) => conptyProcessIds.has(candidate.pid)) + } + return { + available: true, + processName: resolveWindowsProcessName( + filteredCandidates, + fallbackProcess, + options.contextPaths + ) } +} + +function windowsCandidatesContainRecognizedAgent( + candidates: readonly WindowsProcessCandidate[], + fallbackProcess: string, + contextPaths: readonly string[] | undefined +): boolean { if (isShellProcess(fallbackProcess)) { - return resolveShellForegroundProcessFromWindowsCandidates(candidates, options.contextPaths) + return createRecognizedWindowsProcessCandidates(candidates, contextPaths).length > 0 + } + return candidates + .filter((candidate) => windowsCandidateMatchesFallbackWrapper(candidate, fallbackProcess)) + .some( + (candidate) => + recognizeAgentProcessFromCommandLine(candidate.command) !== null || + recognizeAgentProcessFromCommandLine(candidate.name) !== null + ) +} + +function resolveWindowsProcessName( + candidates: readonly WindowsProcessCandidate[], + fallbackProcess: string, + contextPaths: readonly string[] | undefined +): string | null { + if (isShellProcess(fallbackProcess)) { + return resolveShellForegroundProcessFromWindowsCandidates(candidates, contextPaths) } const wrapperCandidates = candidates.filter((candidate) => windowsCandidateMatchesFallbackWrapper(candidate, fallbackProcess) ) if (wrapperCandidates.length !== 1) { - return resolveWrapperForegroundProcessFromWindowsCandidates( - wrapperCandidates, - options.contextPaths - ) + return resolveWrapperForegroundProcessFromWindowsCandidates(wrapperCandidates, contextPaths) } const [candidate] = wrapperCandidates const recognized = diff --git a/src/main/providers/windows-conpty-process-membership.test.ts b/src/main/providers/windows-conpty-process-membership.test.ts new file mode 100644 index 000000000000..e9e2ef09fdd0 --- /dev/null +++ b/src/main/providers/windows-conpty-process-membership.test.ts @@ -0,0 +1,64 @@ +import { EventEmitter } from 'node:events' +import { describe, expect, it, vi } from 'vitest' +import { readWindowsConptyProcessIds } from './windows-conpty-process-membership' + +function forkWith(event: 'message' | 'error' | 'none', value?: unknown) { + const child = new EventEmitter() as EventEmitter & { kill: ReturnType } + child.kill = vi.fn() + const forkProcess = vi.fn(() => { + queueMicrotask(() => { + if (event === 'message') { + child.emit('message', { consoleProcessList: value }) + } else if (event === 'error') { + child.emit('error', new Error('spawn failed')) + } + }) + return child + }) + return { child, forkProcess: forkProcess as never } +} + +describe('readWindowsConptyProcessIds', () => { + it('returns exact console membership from the fixed node-pty helper', async () => { + const { forkProcess } = forkWith('message', [101, 202, 303]) + + await expect( + readWindowsConptyProcessIds(101, { + forkProcess, + resolveAgentPath: () => '/fixed/node-pty/conpty_console_list_agent.js' + }) + ).resolves.toEqual(new Set([101, 202, 303])) + expect(forkProcess).toHaveBeenCalledWith( + '/fixed/node-pty/conpty_console_list_agent.js', + ['101'], + { silent: true } + ) + }) + + it.each([ + ['root-only failure fallback', [101]], + ['malformed response', [101, '202']], + ['missing PTY root', [202, 303]] + ])('fails closed for %s', async (_label, processIds) => { + const { forkProcess } = forkWith('message', processIds) + await expect(readWindowsConptyProcessIds(101, { forkProcess })).resolves.toBeNull() + }) + + it('handles helper spawn errors without an unhandled child error', async () => { + const { forkProcess } = forkWith('error') + await expect(readWindowsConptyProcessIds(101, { forkProcess })).resolves.toBeNull() + }) + + it('kills a silent helper at the bounded timeout', async () => { + vi.useFakeTimers() + try { + const { child, forkProcess } = forkWith('none') + const result = readWindowsConptyProcessIds(101, { forkProcess, timeoutMs: 10 }) + await vi.advanceTimersByTimeAsync(10) + await expect(result).resolves.toBeNull() + expect(child.kill).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/main/providers/windows-conpty-process-membership.ts b/src/main/providers/windows-conpty-process-membership.ts new file mode 100644 index 000000000000..759a234c63fc --- /dev/null +++ b/src/main/providers/windows-conpty-process-membership.ts @@ -0,0 +1,74 @@ +import { fork, type ChildProcess } from 'node:child_process' + +const CONPTY_PROCESS_LIST_TIMEOUT_MS = 3_000 + +type ProcessListMessage = { consoleProcessList?: unknown } + +type WindowsConptyMembershipDeps = { + forkProcess?: typeof fork + resolveAgentPath?: () => string + timeoutMs?: number +} + +function resolveNodePtyConsoleListAgent(): string { + return require.resolve('node-pty/lib/conpty_console_list_agent.js') +} + +/** + * Runs node-pty's fixed native console-list helper with bounded error/exit + * handling. A root-only result is its failure fallback, not shell proof. + */ +export function readWindowsConptyProcessIds( + rootPid: number, + deps: WindowsConptyMembershipDeps = {} +): Promise | null> { + if (!Number.isSafeInteger(rootPid) || rootPid <= 0) { + return Promise.resolve(null) + } + let child: ChildProcess + try { + child = (deps.forkProcess ?? fork)( + (deps.resolveAgentPath ?? resolveNodePtyConsoleListAgent)(), + [String(rootPid)], + { silent: true } + ) + } catch { + return Promise.resolve(null) + } + + return new Promise((resolve) => { + let settled = false + const finish = (value: ReadonlySet | null): void => { + if (settled) { + return + } + settled = true + clearTimeout(timeout) + child.removeListener('message', onMessage) + child.removeListener('error', onFailure) + child.removeListener('exit', onFailure) + resolve(value) + } + const onFailure = (): void => finish(null) + const onMessage = (message: ProcessListMessage): void => { + const value = message?.consoleProcessList + if ( + !Array.isArray(value) || + value.length <= 1 || + !value.includes(rootPid) || + value.some((pid) => !Number.isSafeInteger(pid) || pid <= 0) + ) { + finish(null) + return + } + finish(new Set(value)) + } + const timeout = setTimeout(() => { + child.kill() + finish(null) + }, deps.timeoutMs ?? CONPTY_PROCESS_LIST_TIMEOUT_MS) + child.once('message', onMessage) + child.once('error', onFailure) + child.once('exit', onFailure) + }) +} diff --git a/src/main/providers/windows-foreground-process-rows.ts b/src/main/providers/windows-foreground-process-rows.ts index d26067122a58..6fea54165c8d 100644 --- a/src/main/providers/windows-foreground-process-rows.ts +++ b/src/main/providers/windows-foreground-process-rows.ts @@ -48,14 +48,23 @@ const windowsProcessRowsReader = createProcessTableSnapshotReader { let rows: WindowsProcessRow[] try { - rows = await windowsProcessRowsReader.getSnapshot() + rows = + options.fresh === true + ? await windowsProcessRowsReader.getFreshSnapshot() + : await windowsProcessRowsReader.getSnapshot() } catch { return null } + // Why: a snapshot that omitted the PTY root may be stale or permission- + // filtered; only an observed root can authoritatively have no descendants. + if (!rows.some((row) => row.pid === rootPid)) { + return null + } return collectDescendants(rows, rootPid).sort((a, b) => b.depth - a.depth) } @@ -234,7 +243,8 @@ async function queryWindowsProcessesWithWmic(): Promise 0 ? rows : null } catch { // Best-effort: Windows process enumeration may be disabled, so callers // still fall back to node-pty's process name when both probes fail. diff --git a/src/main/providers/windows-shell-args.test.ts b/src/main/providers/windows-shell-args.test.ts index d68f4014b232..7d0eeb5b4e32 100644 --- a/src/main/providers/windows-shell-args.test.ts +++ b/src/main/providers/windows-shell-args.test.ts @@ -1,4 +1,7 @@ -import { describe, expect, it } from 'vitest' +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { encodePowerShellCommand, getPowerShellOsc133Bootstrap @@ -17,6 +20,24 @@ function expectedWslArgs(linuxCwd: string, distro?: string): string[] { } describe('resolveWindowsShellLaunchArgs', () => { + let previousUserDataPath: string | undefined + let userDataPath: string + + beforeEach(() => { + previousUserDataPath = process.env.ORCA_USER_DATA_PATH + userDataPath = mkdtempSync(join(tmpdir(), 'windows-shell-args-test-')) + process.env.ORCA_USER_DATA_PATH = userDataPath + }) + + afterEach(() => { + if (previousUserDataPath === undefined) { + delete process.env.ORCA_USER_DATA_PATH + } else { + process.env.ORCA_USER_DATA_PATH = previousUserDataPath + } + rmSync(userDataPath, { recursive: true, force: true }) + }) + it('returns cmd.exe args with chcp 65001 for UTF-8 output', () => { const result = resolveWindowsShellLaunchArgs('cmd.exe', 'C:\\Users\\alice', 'C:\\Users\\alice') expect(result.shellArgs).toEqual(['/K', 'chcp 65001 > nul']) @@ -201,6 +222,27 @@ describe('resolveWindowsShellLaunchArgs', () => { expect(result.validationCwd).toBe('C:\\Users\\alice\\code') }) + it('materializes shell-ready wrappers before building WSL shell args', () => { + const result = resolveWindowsShellLaunchArgs( + 'wsl.exe', + 'C:\\Users\\alice\\code', + 'C:\\Users\\alice' + ) + + expect(result.shellArgs).toEqual(expectedWslArgs('/mnt/c/Users/alice/code')) + expect(existsSync(join(userDataPath, 'shell-ready', 'bash', 'rcfile'))).toBe(true) + expect(existsSync(join(userDataPath, 'shell-ready', 'zsh', '.zshenv'))).toBe(true) + + // Why: the point of materializing wrappers for WSL is that a typed `omp` + // picks up Orca's status extension; pin that shim end to end. + const bashRcfile = readFileSync(join(userDataPath, 'shell-ready', 'bash', 'rcfile'), 'utf8') + const zshLogin = readFileSync(join(userDataPath, 'shell-ready', 'zsh', '.zlogin'), 'utf8') + for (const wrapperFile of [bashRcfile, zshLogin]) { + expect(wrapperFile).toContain('command omp --extension "${ORCA_OMP_STATUS_EXTENSION}" "$@"') + expect(wrapperFile).toContain('omp() { __orca_omp "$@"; }') + } + }) + it('translates MSYS drive cwd to /mnt//... for wsl.exe', () => { const result = resolveWindowsShellLaunchArgs( 'wsl.exe', diff --git a/src/main/providers/windows-shell-args.ts b/src/main/providers/windows-shell-args.ts index 98b119d85978..3889edfc5c19 100644 --- a/src/main/providers/windows-shell-args.ts +++ b/src/main/providers/windows-shell-args.ts @@ -6,6 +6,7 @@ import { escapeWslShCommandForWindows, quotePosixShell } from '../../shared/wsl-login-shell-command' +import { ensureShellReadyWrappersAt } from './local-pty-shell-ready' import { encodePowerShellCommand, getPowerShellOsc133Bootstrap @@ -94,6 +95,7 @@ function getPowerShellEncodedCommand(startupCommand?: string): { * Builds wsl.exe arguments that enter the target directory through the distro shell. */ function buildWslShellArgs(linuxCwd: string, distro?: string): string[] { + ensureShellReadyWrappersAt() const setupCommand = [ `cd ${quotePosixShell(linuxCwd)}`, 'export PATH="$HOME/.local/bin:$PATH"', diff --git a/src/main/pty/codex-home-wsl-env.ts b/src/main/pty/codex-home-wsl-env.ts index b642e7661f64..f61272de8c34 100644 --- a/src/main/pty/codex-home-wsl-env.ts +++ b/src/main/pty/codex-home-wsl-env.ts @@ -1,3 +1,19 @@ +/** Guest-relative layout of Orca's managed WSL CODEX_HOME. Must stay in sync + * with getWslRuntimeHomePath (codex-accounts/runtime-home-service.ts), which + * builds the UNC twin of this path. */ +export const WSL_CODEX_RUNTIME_HOME_SEGMENTS = [ + '.local', + 'share', + 'orca', + 'codex-runtime-home', + 'home' +] as const + +export function wslCodexRuntimeHomeForGuestHome(guestHome: string): string { + const home = guestHome.endsWith('/') ? guestHome.slice(0, -1) : guestHome + return `${home}/${WSL_CODEX_RUNTIME_HOME_SEGMENTS.join('/')}` +} + export function isHostCodexHomeForWsl(value: string | undefined): boolean { const trimmed = value?.trim() if (!trimmed) { diff --git a/src/main/pty/terminal-cwd-realpath.test.ts b/src/main/pty/terminal-cwd-realpath.test.ts deleted file mode 100644 index 47110648b199..000000000000 --- a/src/main/pty/terminal-cwd-realpath.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { mkdtempSync, mkdirSync, rmSync, symlinkSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterAll, describe, expect, it } from 'vitest' -import { - canonicalizeLocalTerminalPath, - localTerminalCwdCanonicalizer -} from './terminal-cwd-realpath' - -describe('canonicalizeLocalTerminalPath', () => { - const root = mkdtempSync(join(tmpdir(), 'orca-cwd-realpath-')) - - afterAll(() => { - rmSync(root, { recursive: true, force: true }) - }) - - it('resolves symlinks to their target', () => { - const outside = join(root, 'outside') - const worktree = join(root, 'worktree') - mkdirSync(outside) - mkdirSync(worktree) - const link = join(worktree, 'escape') - symlinkSync(outside, link, 'dir') - expect(canonicalizeLocalTerminalPath(link)).toBe(canonicalizeLocalTerminalPath(outside)) - }) - - it('returns null for nonexistent paths', () => { - expect(canonicalizeLocalTerminalPath(join(root, 'does-not-exist'))).toBeNull() - }) - - it('skips WSL UNC paths instead of touching the 9P share', () => { - expect(canonicalizeLocalTerminalPath('\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo')).toBeNull() - expect(canonicalizeLocalTerminalPath('//wsl$/Ubuntu/home/jin/repo')).toBeNull() - }) -}) - -describe('localTerminalCwdCanonicalizer', () => { - it('is disabled for SSH connections and enabled locally', () => { - expect(localTerminalCwdCanonicalizer('ssh-1')).toBeUndefined() - expect(localTerminalCwdCanonicalizer(null)).toBe(canonicalizeLocalTerminalPath) - expect(localTerminalCwdCanonicalizer(undefined)).toBe(canonicalizeLocalTerminalPath) - }) -}) diff --git a/src/main/pty/terminal-cwd-realpath.ts b/src/main/pty/terminal-cwd-realpath.ts deleted file mode 100644 index f9131d9f01ad..000000000000 --- a/src/main/pty/terminal-cwd-realpath.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { realpathSync } from 'node:fs' -import { isWslUncPath } from '../../shared/wsl-paths' - -// Why: terminal startup cwd containment is string-based; realpath closes the -// symlink escape for local paths. Only for local worktrees — SSH/remote paths -// are not resolvable on this filesystem. -export function canonicalizeLocalTerminalPath(targetPath: string): string | null { - // Why: realpath over the WSL 9P share is unreliable and can block the main - // process while the distro boots; keep the string containment check only. - if (isWslUncPath(targetPath)) { - return null - } - try { - return realpathSync.native(targetPath) - } catch { - try { - // Why: realpathSync.native can fail on network/UNC mounts where the - // JS implementation still succeeds (same fallback as git repo scanning). - return realpathSync(targetPath) - } catch { - return null - } - } -} - -export function localTerminalCwdCanonicalizer( - connectionId: string | null | undefined -): ((path: string) => string | null) | undefined { - return connectionId ? undefined : canonicalizeLocalTerminalPath -} diff --git a/src/main/pty/wsl-orca-env.test.ts b/src/main/pty/wsl-orca-env.test.ts index ec210e5db3b3..550295460ad1 100644 --- a/src/main/pty/wsl-orca-env.test.ts +++ b/src/main/pty/wsl-orca-env.test.ts @@ -23,6 +23,7 @@ describe('addOrcaWslInteropEnv', () => { it('marks OMP status and hook env for Windows to WSL import', () => { const env: Record = { ORCA_TERMINAL_HANDLE: 'term_wsl', + ORCA_USER_DATA_PATH: 'C:\\Users\\jin\\AppData\\Roaming\\Orca', ORCA_OMP_STATUS_EXTENSION: 'C:\\Users\\jin\\.omp\\agent\\extensions\\orca-agent-status.ts', ORCA_PANE_KEY: 'tab-1:leaf-1', ORCA_TAB_ID: 'tab-1', @@ -36,6 +37,7 @@ describe('addOrcaWslInteropEnv', () => { addOrcaWslInteropEnv(env) expect(env.WSLENV).toContain('ORCA_TERMINAL_HANDLE/u') + expect(env.WSLENV).toContain('ORCA_USER_DATA_PATH/p') expect(env.WSLENV).toContain('ORCA_OMP_STATUS_EXTENSION/p') expect(env.WSLENV).toContain('ORCA_PANE_KEY/u') expect(env.WSLENV).toContain('ORCA_TAB_ID/u') @@ -45,4 +47,25 @@ describe('addOrcaWslInteropEnv', () => { expect(env.WSLENV).toContain('ORCA_AGENT_HOOK_ENV/u') expect(env.WSLENV).toContain('ORCA_AGENT_HOOK_VERSION/u') }) + + it('path-translates a Windows hook endpoint but passes a guest-side one untouched', () => { + const windowsEnv: Record = { + ORCA_AGENT_HOOK_ENDPOINT: 'C:\\Users\\jin\\AppData\\Roaming\\Orca\\agent-hooks\\endpoint.cmd' + } + addOrcaWslInteropEnv(windowsEnv) + expect(windowsEnv.WSLENV).toContain('ORCA_AGENT_HOOK_ENDPOINT/p') + + const guestEnv: Record = { + ORCA_AGENT_HOOK_ENDPOINT: '/home/jin/.orca-wsl/agent-hooks/port-4567/endpoint.env' + } + addOrcaWslInteropEnv(guestEnv) + expect(guestEnv.WSLENV).toContain('ORCA_AGENT_HOOK_ENDPOINT/u') + expect(guestEnv.WSLENV).not.toContain('ORCA_AGENT_HOOK_ENDPOINT/p') + }) + + it('marks the WSL hook relay version for import on relay spawn envs', () => { + const env: Record = { ORCA_WSL_HOOK_RELAY_VERSION: '0.1.0+abc' } + addOrcaWslInteropEnv(env) + expect(env.WSLENV).toBe('ORCA_WSL_HOOK_RELAY_VERSION/u') + }) }) diff --git a/src/main/pty/wsl-orca-env.ts b/src/main/pty/wsl-orca-env.ts index 2e4a878f52bb..161621e8c0fd 100644 --- a/src/main/pty/wsl-orca-env.ts +++ b/src/main/pty/wsl-orca-env.ts @@ -16,10 +16,14 @@ function upsertWslenvEntry(entries: string[], entry: string): void { export function addOrcaWslInteropEnv(env: Record): void { const entries = parseWslenvEntries(env.WSLENV) - // Why: wsl.exe only imports selected Windows env vars. Agent status in WSL - // needs both the pane identity and the hook/OMP coordinates at process start. + // Why: the endpoint is a Windows path (/p-translated so the guest reads it + // via /mnt/c) until the WSL hook relay reports the guest home — then it is + // already a guest-side POSIX path and must cross untranslated. + const endpointFlag = env.ORCA_AGENT_HOOK_ENDPOINT?.startsWith('/') ? 'u' : 'p' + // Why: wsl.exe only imports selected Windows env vars, so WSL needs the wrapper root, pane identity, and hook/OMP coordinates at start. const passthroughEntries = [ 'ORCA_TERMINAL_HANDLE/u', + 'ORCA_USER_DATA_PATH/p', 'ORCA_PANE_KEY/u', 'ORCA_TAB_ID/u', 'ORCA_WORKTREE_ID/u', @@ -28,7 +32,9 @@ export function addOrcaWslInteropEnv(env: Record): void { 'ORCA_AGENT_HOOK_TOKEN/u', 'ORCA_AGENT_HOOK_ENV/u', 'ORCA_AGENT_HOOK_VERSION/u', - 'ORCA_AGENT_HOOK_ENDPOINT/p', + `ORCA_AGENT_HOOK_ENDPOINT/${endpointFlag}`, + 'ORCA_WSL_HOOK_RELAY_VERSION/u', + 'ORCA_WSL_HOOK_INSTANCE/u', 'ORCA_OMP_SOURCE_AGENT_DIR/p', 'ORCA_OMP_STATUS_EXTENSION/p' ] diff --git a/src/main/rate-limits/auth-filesystem-operation.test.ts b/src/main/rate-limits/auth-filesystem-operation.test.ts new file mode 100644 index 000000000000..92099fa2dccb --- /dev/null +++ b/src/main/rate-limits/auth-filesystem-operation.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it, vi } from 'vitest' +import { createAuthFilesystemOperation } from './auth-filesystem-operation' + +describe('createAuthFilesystemOperation', () => { + it('serializes WSL aliases by distro and drops an abandoned queued read', async () => { + let resolveFirst!: (value: string) => void + const firstRaw = vi.fn( + () => + new Promise((resolve) => { + resolveFirst = resolve + }) + ) + const secondRaw = vi.fn(async () => 'second') + const first = createAuthFilesystemOperation( + '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex\\auth.json', + firstRaw + ) + const second = createAuthFilesystemOperation( + '\\\\WSL$\\ubuntu\\home\\alice\\managed\\auth.json', + secondRaw + ) + const firstController = new AbortController() + const secondController = new AbortController() + + const firstWait = first.wait(firstController.signal) + const secondWait = second.wait(secondController.signal) + await Promise.resolve() + await Promise.resolve() + expect(firstRaw).toHaveBeenCalledOnce() + expect(secondRaw).not.toHaveBeenCalled() + + const queuedAbort = new Error('queued caller expired') + secondController.abort(queuedAbort) + await expect(secondWait).rejects.toBe(queuedAbort) + + resolveFirst('first') + await expect(firstWait).resolves.toBe('first') + await expect(second.result).rejects.toBe(queuedAbort) + expect(secondRaw).not.toHaveBeenCalled() + }) + + it('allows different WSL distros to probe concurrently', async () => { + const ubuntuRaw = vi.fn(async () => 'ubuntu') + const debianRaw = vi.fn(async () => 'debian') + const ubuntu = createAuthFilesystemOperation( + '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex\\auth.json', + ubuntuRaw + ) + const debian = createAuthFilesystemOperation( + '\\\\wsl.localhost\\Debian\\home\\alice\\.codex\\auth.json', + debianRaw + ) + const controller = new AbortController() + + await expect( + Promise.all([ubuntu.wait(controller.signal), debian.wait(controller.signal)]) + ).resolves.toEqual(['ubuntu', 'debian']) + expect(ubuntuRaw).toHaveBeenCalledOnce() + expect(debianRaw).toHaveBeenCalledOnce() + }) + + it('does not start an operation for an already-aborted waiter', async () => { + const raw = vi.fn(async () => 'unexpected') + const operation = createAuthFilesystemOperation( + '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex\\auth.json', + raw + ) + const controller = new AbortController() + const abortError = new Error('already expired') + controller.abort(abortError) + + await expect(operation.wait(controller.signal)).rejects.toBe(abortError) + await expect(operation.result).rejects.toBe(abortError) + expect(raw).not.toHaveBeenCalled() + }) + + it('caps cross-distro operations and never starts an expired queued probe', async () => { + let resolveUbuntu!: (value: string) => void + let resolveDebian!: (value: string) => void + const ubuntuRaw = vi.fn( + () => + new Promise((resolve) => { + resolveUbuntu = resolve + }) + ) + const debianRaw = vi.fn( + () => + new Promise((resolve) => { + resolveDebian = resolve + }) + ) + const fedoraRaw = vi.fn(async () => 'fedora') + const ubuntu = createAuthFilesystemOperation('\\\\wsl$\\Ubuntu\\a\\auth.json', ubuntuRaw) + const debian = createAuthFilesystemOperation('\\\\wsl$\\Debian\\b\\auth.json', debianRaw) + const fedora = createAuthFilesystemOperation('\\\\wsl$\\Fedora\\c\\auth.json', fedoraRaw) + const ubuntuController = new AbortController() + const debianController = new AbortController() + const fedoraController = new AbortController() + + const ubuntuWait = ubuntu.wait(ubuntuController.signal) + const debianWait = debian.wait(debianController.signal) + const fedoraWait = fedora.wait(fedoraController.signal) + await Promise.resolve() + await Promise.resolve() + expect(ubuntuRaw).toHaveBeenCalledOnce() + expect(debianRaw).toHaveBeenCalledOnce() + expect(fedoraRaw).not.toHaveBeenCalled() + + const queuedAbort = new Error('global queue expired') + fedoraController.abort(queuedAbort) + await expect(fedoraWait).rejects.toBe(queuedAbort) + await expect(fedora.result).rejects.toBe(queuedAbort) + + resolveUbuntu('ubuntu') + resolveDebian('debian') + await expect(Promise.all([ubuntuWait, debianWait])).resolves.toEqual(['ubuntu', 'debian']) + expect(fedoraRaw).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/rate-limits/auth-filesystem-operation.ts b/src/main/rate-limits/auth-filesystem-operation.ts new file mode 100644 index 000000000000..228234e92c0d --- /dev/null +++ b/src/main/rate-limits/auth-filesystem-operation.ts @@ -0,0 +1,175 @@ +import { parseWslUncPath } from '../../shared/wsl-paths' + +const MAX_CONCURRENT_WSL_AUTH_OPERATIONS = 2 +const activeWslOperationDistros = new Set() +const queuedWslOperations: QueuedWslOperation[] = [] +let activeWslOperationCount = 0 + +type QueuedWslOperation = { + distroKey: string + neededSignal: AbortSignal + operation: () => Promise + resolve: (value: T) => void + reject: (error: unknown) => void + onAbort: () => void + state: 'queued' | 'running' | 'settled' +} + +function getAbortReason(signal: AbortSignal): unknown { + return signal.reason ?? new Error('Auth filesystem operation aborted') +} + +function finishWslOperation(task: QueuedWslOperation, settle: () => void): void { + if (task.state !== 'running') { + return + } + task.state = 'settled' + activeWslOperationCount -= 1 + activeWslOperationDistros.delete(task.distroKey) + settle() + pumpWslOperations() +} + +function pumpWslOperations(): void { + while (activeWslOperationCount < MAX_CONCURRENT_WSL_AUTH_OPERATIONS) { + const nextIndex = queuedWslOperations.findIndex( + (task) => !activeWslOperationDistros.has(task.distroKey) + ) + if (nextIndex === -1) { + return + } + const task = queuedWslOperations.splice(nextIndex, 1)[0] + if (!task || task.state !== 'queued') { + continue + } + task.neededSignal.removeEventListener('abort', task.onAbort) + if (task.neededSignal.aborted) { + task.state = 'settled' + task.reject(getAbortReason(task.neededSignal)) + continue + } + task.state = 'running' + activeWslOperationCount += 1 + activeWslOperationDistros.add(task.distroKey) + void Promise.resolve() + .then(() => { + if (task.neededSignal.aborted) { + throw getAbortReason(task.neededSignal) + } + return task.operation() + }) + .then( + (value) => finishWslOperation(task, () => task.resolve(value)), + (error: unknown) => finishWslOperation(task, () => task.reject(error)) + ) + } +} + +function scheduleWslAuthFilesystemOperation( + distroKey: string, + neededSignal: AbortSignal, + operation: () => Promise +): Promise { + return new Promise((resolve, reject) => { + const task: QueuedWslOperation = { + distroKey, + neededSignal, + operation, + resolve, + reject, + state: 'queued', + onAbort: () => { + if (task.state !== 'queued') { + return + } + task.state = 'settled' + const index = queuedWslOperations.indexOf(task as QueuedWslOperation) + if (index !== -1) { + queuedWslOperations.splice(index, 1) + } + reject(getAbortReason(neededSignal)) + pumpWslOperations() + } + } + neededSignal.addEventListener('abort', task.onAbort, { once: true }) + queuedWslOperations.push(task as QueuedWslOperation) + queueMicrotask(pumpWslOperations) + }) +} + +function scheduleAuthFilesystemOperation( + authPath: string, + neededSignal: AbortSignal, + operation: () => Promise +): Promise { + const wslInfo = parseWslUncPath(authPath) + if (!wslInfo) { + return Promise.resolve().then(() => { + if (neededSignal.aborted) { + throw getAbortReason(neededSignal) + } + return operation() + }) + } + // Why: a few disconnected distros must not occupy libuv's entire default + // filesystem pool. Distro serialization also folds wsl$/wsl.localhost and + // case aliases without forcing healthy local auth reads through the queue. + return scheduleWslAuthFilesystemOperation( + wslInfo.distro.trim().toLowerCase(), + neededSignal, + operation + ) +} + +export type SharedAuthFilesystemOperation = { + result: Promise + wait: (signal: AbortSignal) => Promise +} + +/** + * Shares one raw operation with all callers for an auth path. WSL paths also + * serialize by normalized distro because one stuck UNC request per account can + * otherwise exhaust libuv's filesystem threadpool. + */ +export function createAuthFilesystemOperation( + authPath: string, + operation: () => Promise +): SharedAuthFilesystemOperation { + const neededController = new AbortController() + const waiters = new Set() + let settled = false + const result = scheduleAuthFilesystemOperation(authPath, neededController.signal, operation) + const markSettled = (): void => { + settled = true + } + void result.then(markSettled, markSettled) + + return { + result, + wait(signal) { + if (signal.aborted) { + if (!settled && waiters.size === 0) { + neededController.abort(getAbortReason(signal)) + } + return Promise.reject(getAbortReason(signal)) + } + + const waiter = Symbol('auth-filesystem-waiter') + waiters.add(waiter) + let onAbort: (() => void) | null = null + const aborted = new Promise((_resolve, reject) => { + onAbort = () => reject(getAbortReason(signal)) + signal.addEventListener('abort', onAbort, { once: true }) + }) + return Promise.race([result, aborted]).finally(() => { + if (onAbort) { + signal.removeEventListener('abort', onAbort) + } + waiters.delete(waiter) + if (!settled && waiters.size === 0) { + neededController.abort(getAbortReason(signal)) + } + }) + } + } +} diff --git a/src/main/rate-limits/codex-auth-presence.test.ts b/src/main/rate-limits/codex-auth-presence.test.ts index f4e10fa86937..6f49f27bfb44 100644 --- a/src/main/rate-limits/codex-auth-presence.test.ts +++ b/src/main/rate-limits/codex-auth-presence.test.ts @@ -1,22 +1,26 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const { existsSyncMock, homedirMock } = vi.hoisted(() => ({ - existsSyncMock: vi.fn(), +const { accessMock, homedirMock } = vi.hoisted(() => ({ + accessMock: vi.fn(), homedirMock: vi.fn() })) -vi.mock('node:fs', () => ({ - existsSync: existsSyncMock +vi.mock('node:fs/promises', () => ({ + access: accessMock })) vi.mock('node:os', () => ({ homedir: homedirMock })) -import { codexAuthExists } from './codex-auth-presence' +import { probeCodexAuthPresence } from './codex-auth-presence' -describe('codexAuthExists', () => { +function fsError(code: string): NodeJS.ErrnoException { + return Object.assign(new Error(code), { code }) +} + +describe('probeCodexAuthPresence', () => { const originalCodexHome = process.env.CODEX_HOME beforeEach(() => { @@ -33,33 +37,119 @@ describe('codexAuthExists', () => { } }) - it('checks an explicit managed-account home first', () => { - existsSyncMock.mockReturnValue(true) + it('checks an explicit managed-account home first', async () => { + accessMock.mockResolvedValue(undefined) - expect(codexAuthExists('/managed/home')).toBe(true) - expect(existsSyncMock).toHaveBeenCalledWith(join('/managed/home', 'auth.json')) + await expect(probeCodexAuthPresence('/managed/home')).resolves.toBe('present') + expect(accessMock).toHaveBeenCalledWith(join('/managed/home', 'auth.json')) }) - it('falls back to CODEX_HOME when no home is provided', () => { + it('falls back to CODEX_HOME when no home is provided', async () => { process.env.CODEX_HOME = '/custom/codex' - existsSyncMock.mockReturnValue(true) + accessMock.mockResolvedValue(undefined) + + await expect(probeCodexAuthPresence()).resolves.toBe('present') + expect(accessMock).toHaveBeenCalledWith(join('/custom/codex', 'auth.json')) + }) - expect(codexAuthExists()).toBe(true) - expect(existsSyncMock).toHaveBeenCalledWith(join('/custom/codex', 'auth.json')) + it('falls back to ~/.codex when neither home nor CODEX_HOME is set', async () => { + accessMock.mockRejectedValue(fsError('ENOENT')) + + await expect(probeCodexAuthPresence()).resolves.toBe('absent') + expect(accessMock).toHaveBeenCalledWith(join('/home/alice', '.codex', 'auth.json')) }) - it('falls back to ~/.codex when neither home nor CODEX_HOME is set', () => { - existsSyncMock.mockReturnValue(false) + it('keeps an inaccessible auth path distinct from confirmed absence', async () => { + accessMock.mockRejectedValue(fsError('EACCES')) - expect(codexAuthExists()).toBe(false) - expect(existsSyncMock).toHaveBeenCalledWith(join('/home/alice', '.codex', 'auth.json')) + await expect(probeCodexAuthPresence('/managed/home')).resolves.toBe('unavailable') }) - it('returns false instead of throwing when the fs check fails', () => { - existsSyncMock.mockImplementation(() => { - throw new Error('EACCES') + it('confirms WSL auth absence only when the Codex home is reachable', async () => { + accessMock.mockRejectedValueOnce(fsError('ENOENT')).mockResolvedValueOnce(undefined) + + await expect( + probeCodexAuthPresence('\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex') + ).resolves.toBe('absent') + expect(accessMock).toHaveBeenCalledTimes(2) + }) + + it('reports unavailable when WSL cannot resolve either the auth file or its home', async () => { + accessMock.mockRejectedValue(fsError('ENOENT')) + + await expect( + probeCodexAuthPresence('\\\\wsl.localhost\\Missing\\home\\alice\\.codex') + ).resolves.toBe('unavailable') + expect(accessMock).toHaveBeenCalledTimes(2) + }) + + it('stops waiting for a stalled filesystem check when the caller aborts', async () => { + let resolveAccess!: () => void + accessMock.mockReturnValue( + new Promise((resolve) => { + resolveAccess = resolve + }) + ) + const controller = new AbortController() + + const result = probeCodexAuthPresence('/managed/home', { signal: controller.signal }) + await Promise.resolve() + await Promise.resolve() + controller.abort() + + await expect(result).resolves.toBe('unavailable') + resolveAccess() + await Promise.resolve() + }) + + it('bounds a stalled filesystem check even without a caller signal', async () => { + let resolveAccess!: () => void + accessMock.mockReturnValue( + new Promise((resolve) => { + resolveAccess = resolve + }) + ) + const timeoutController = new AbortController() + const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(timeoutController.signal) + + const result = probeCodexAuthPresence('/managed/home') + expect(timeout).toHaveBeenCalledWith(5_000) + await Promise.resolve() + await Promise.resolve() + timeoutController.abort() + + await expect(result).resolves.toBe('timeout') + resolveAccess() + await Promise.resolve() + timeout.mockRestore() + }) + + it('shares one stalled UNC probe across concurrent callers', async () => { + let resolveAccess!: () => void + accessMock.mockReturnValue( + new Promise((resolve) => { + resolveAccess = resolve + }) + ) + const firstController = new AbortController() + const secondController = new AbortController() + + const first = probeCodexAuthPresence('\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex', { + signal: firstController.signal }) + const second = probeCodexAuthPresence('\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex', { + signal: secondController.signal + }) + + await Promise.resolve() + await Promise.resolve() + expect(accessMock).toHaveBeenCalledTimes(1) + firstController.abort() + secondController.abort() + await expect(first).resolves.toBe('unavailable') + await expect(second).resolves.toBe('unavailable') - expect(codexAuthExists('/managed/home')).toBe(false) + resolveAccess() + await Promise.resolve() }) }) diff --git a/src/main/rate-limits/codex-auth-presence.ts b/src/main/rate-limits/codex-auth-presence.ts index f972fcecbc0f..833f46a1b6fe 100644 --- a/src/main/rate-limits/codex-auth-presence.ts +++ b/src/main/rate-limits/codex-auth-presence.ts @@ -1,6 +1,52 @@ -import { existsSync } from 'node:fs' +import { access } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'node:path' +import { parseWslUncPath } from '../../shared/wsl-paths' +import { + createAuthFilesystemOperation, + type SharedAuthFilesystemOperation +} from './auth-filesystem-operation' + +const AUTH_PRESENCE_TIMEOUT_MS = 5_000 +const authPresenceProbeByPath = new Map>() + +export type CodexAuthPresence = 'present' | 'absent' | 'timeout' | 'unavailable' + +type CodexAuthPresenceOptions = { + signal?: AbortSignal + timeoutMs?: number +} + +function isMissingPathError(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | null)?.code + return code === 'ENOENT' || code === 'ENOTDIR' +} + +function getAuthPresenceProbe(authPath: string): SharedAuthFilesystemOperation { + const existing = authPresenceProbeByPath.get(authPath) + if (existing) { + return existing + } + // Why: aborting a Node fs promise does not necessarily cancel an already + // issued UNC operation. Share the raw probe until it really settles so a + // disconnected WSL home cannot accumulate native requests across polls. + const probe = createAuthFilesystemOperation(authPath, async () => { + try { + await access(authPath) + return 'present' + } catch (error) { + return isMissingPathError(error) ? 'absent' : 'unavailable' + } + }) + authPresenceProbeByPath.set(authPath, probe) + const clearProbe = (): void => { + if (authPresenceProbeByPath.get(authPath) === probe) { + authPresenceProbeByPath.delete(authPath) + } + } + void probe.result.then(clearProbe, clearProbe) + return probe +} // Why: the background quota poller spawns the real `codex` binary to read rate // limits. For users who installed Codex but never signed in, that spawn can @@ -8,13 +54,30 @@ import { join } from 'node:path' // the background. A signed-in Codex always writes an auth.json under its // CODEX_HOME, so gating the fetch on that file keeps the poller silent until // the user actually uses Codex. -export function codexAuthExists(codexHomePath?: string | null): boolean { +export async function probeCodexAuthPresence( + codexHomePath?: string | null, + options: CodexAuthPresenceOptions = {} +): Promise { // Mirror Codex's own home resolution: an explicit managed-account home wins, // then CODEX_HOME, then the default ~/.codex. const home = codexHomePath ?? process.env.CODEX_HOME ?? join(homedir(), '.codex') + const authPath = join(home, 'auth.json') + const timeoutSignal = AbortSignal.timeout(options.timeoutMs ?? AUTH_PRESENCE_TIMEOUT_MS) + const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal try { - return existsSync(join(home, 'auth.json')) + // Why: managed WSL homes are UNC paths. A synchronous stat can park + // Electron main while Windows wakes or reconnects the distro; the race + // also keeps a disconnected distro from serializing all later refreshes. + const authPresence = await getAuthPresenceProbe(authPath).wait(signal) + if (authPresence !== 'absent' || !parseWslUncPath(home)) { + return authPresence + } + + // Why: ENOENT on a WSL UNC auth path can mean either a missing auth file or + // an unavailable distro. Only an accessible Codex home proves signed-out. + const homePresence = await getAuthPresenceProbe(home).wait(signal) + return homePresence === 'present' ? 'absent' : 'unavailable' } catch { - return false + return timeoutSignal.aborted && !options.signal?.aborted ? 'timeout' : 'unavailable' } } diff --git a/src/main/rate-limits/codex-fetcher-auth-errors.test.ts b/src/main/rate-limits/codex-fetcher-auth-errors.test.ts index 3342b5c608e9..43b3bc44e5da 100644 --- a/src/main/rate-limits/codex-fetcher-auth-errors.test.ts +++ b/src/main/rate-limits/codex-fetcher-auth-errors.test.ts @@ -21,7 +21,7 @@ vi.mock('node-pty', () => ({ // Auth gate is covered separately; these tests assume a signed-in Codex. vi.mock('./codex-auth-presence', () => ({ - codexAuthExists: vi.fn(() => true) + probeCodexAuthPresence: vi.fn(() => 'present') })) import { fetchCodexRateLimits } from './codex-fetcher' diff --git a/src/main/rate-limits/codex-fetcher-backend.test.ts b/src/main/rate-limits/codex-fetcher-backend.test.ts new file mode 100644 index 000000000000..3028bee551ea --- /dev/null +++ b/src/main/rate-limits/codex-fetcher-backend.test.ts @@ -0,0 +1,196 @@ +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { childSpawnMock, readFileMock, ptySpawnMock } = vi.hoisted(() => ({ + childSpawnMock: vi.fn(), + readFileMock: vi.fn(), + ptySpawnMock: vi.fn() +})) + +vi.mock('node:child_process', () => ({ spawn: childSpawnMock })) +vi.mock('node:fs/promises', () => ({ readFile: readFileMock })) +vi.mock('node-pty', () => ({ spawn: ptySpawnMock })) +vi.mock('./codex-auth-presence', () => ({ + probeCodexAuthPresence: vi.fn(async () => 'present') +})) + +import { consumeCodexRateLimitResetCredit, fetchCodexRateLimits } from './codex-fetcher' + +describe('Codex backend rate-limit requests', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.clearAllMocks() + vi.stubGlobal('fetch', vi.fn()) + }) + + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('uses the official backend usage contract without spawning Codex', async () => { + readFileMock.mockResolvedValue( + JSON.stringify({ + tokens: { access_token: 'access-token', account_id: 'account-id' } + }) + ) + vi.mocked(fetch) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ + plan_type: 'plus', + rate_limit: { + primary_window: { + used_percent: 12, + limit_window_seconds: 3_600, + reset_at: 1_800_000_000 + }, + secondary_window: { + used_percent: 34, + limit_window_seconds: 86_400, + reset_at: 1_800_100_000 + } + }, + rate_limit_reset_credits: { available_count: 1 } + }) + } as Response) + .mockResolvedValueOnce({ + ok: true, + json: async () => ({ + available_count: 1, + credits: [ + { + status: 'available', + expires_at: '2027-01-15T12:00:00Z', + granted_at: '2027-01-08T12:00:00Z' + } + ] + }) + } as Response) + + await expect( + fetchCodexRateLimits({ + codexHomePath: '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.local\\share\\orca\\account\\home' + }) + ).resolves.toMatchObject({ + session: { usedPercent: 12, windowMinutes: 60, resetsAt: 1_800_000_000_000 }, + weekly: { usedPercent: 34, windowMinutes: 1440, resetsAt: 1_800_100_000_000 }, + rateLimitResetCredits: { + availableCount: 1, + nextExpiresAt: Date.parse('2027-01-15T12:00:00Z') + }, + status: 'ok' + }) + + expect(childSpawnMock).not.toHaveBeenCalled() + expect(ptySpawnMock).not.toHaveBeenCalled() + expect(fetch).toHaveBeenNthCalledWith( + 1, + 'https://chatgpt.com/backend-api/wham/usage', + expect.objectContaining({ + headers: expect.objectContaining({ Authorization: 'Bearer access-token' }), + signal: expect.any(AbortSignal) + }) + ) + }) + + it('aborts callers while sharing one stalled backend auth read', async () => { + let resolveRead!: (content: string) => void + readFileMock.mockImplementation( + () => + new Promise((resolve) => { + resolveRead = resolve + }) + ) + const firstController = new AbortController() + const secondController = new AbortController() + const codexHomePath = '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex' + + const first = fetchCodexRateLimits({ codexHomePath, signal: firstController.signal }) + const second = fetchCodexRateLimits({ codexHomePath, signal: secondController.signal }) + await vi.advanceTimersByTimeAsync(0) + expect(readFileMock).toHaveBeenCalledTimes(1) + expect(readFileMock).toHaveBeenCalledWith(expect.stringContaining('auth.json'), 'utf8') + + firstController.abort() + secondController.abort() + + await expect(first).resolves.toMatchObject({ + provider: 'codex', + status: 'error', + error: 'Rate-limit fetch aborted' + }) + await expect(second).resolves.toMatchObject({ + provider: 'codex', + status: 'error', + error: 'Rate-limit fetch aborted' + }) + expect(fetch).not.toHaveBeenCalled() + expect(childSpawnMock).not.toHaveBeenCalled() + expect(ptySpawnMock).not.toHaveBeenCalled() + resolveRead('{}') + await vi.advanceTimersByTimeAsync(0) + }) + + it('applies the backend deadline while auth reading is still pending', async () => { + let resolveRead!: (content: string) => void + readFileMock.mockImplementation( + () => + new Promise((resolve) => { + resolveRead = resolve + }) + ) + const timeoutController = new AbortController() + const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValueOnce(timeoutController.signal) + const deadlineError = new Error('backend deadline') + + const result = consumeCodexRateLimitResetCredit({ + codexHomePath: '/managed/deadline-home', + idempotencyKey: 'redeem-timeout' + }) + await vi.advanceTimersByTimeAsync(0) + // Why: redeem is user-triggered, so it gets the longer redeem deadline. + expect(timeout).toHaveBeenCalledWith(30_000) + expect(readFileMock).toHaveBeenCalledWith(join('/managed/deadline-home', 'auth.json'), 'utf8') + + timeoutController.abort(deadlineError) + + await expect(result).rejects.toBe(deadlineError) + resolveRead('{}') + await vi.advanceTimersByTimeAsync(0) + }) + + it('consumes a reset credit with the official payload and bounded request signal', async () => { + readFileMock.mockResolvedValue( + JSON.stringify({ + tokens: { access_token: 'access-token', account_id: 'account-id' } + }) + ) + vi.mocked(fetch).mockResolvedValue({ + ok: true, + json: async () => ({ code: 'already_redeemed' }) + } as Response) + + await expect( + consumeCodexRateLimitResetCredit({ + codexHomePath: '/managed/codex-home', + idempotencyKey: 'redeem-123' + }) + ).resolves.toBe('alreadyRedeemed') + + expect(fetch).toHaveBeenCalledWith( + 'https://chatgpt.com/backend-api/wham/rate-limit-reset-credits/consume', + expect.objectContaining({ + method: 'POST', + body: JSON.stringify({ redeem_request_id: 'redeem-123' }), + signal: expect.any(AbortSignal), + headers: expect.objectContaining({ + Authorization: 'Bearer access-token', + 'ChatGPT-Account-Id': 'account-id', + 'Content-Type': 'application/json' + }) + }) + ) + }) +}) diff --git a/src/main/rate-limits/codex-fetcher-pty-settle.test.ts b/src/main/rate-limits/codex-fetcher-pty-settle.test.ts index 969ba02ce75d..c5088a2ae776 100644 --- a/src/main/rate-limits/codex-fetcher-pty-settle.test.ts +++ b/src/main/rate-limits/codex-fetcher-pty-settle.test.ts @@ -20,7 +20,7 @@ vi.mock('node-pty', () => ({ // Auth gate is covered separately; these tests assume a signed-in Codex. vi.mock('./codex-auth-presence', () => ({ - codexAuthExists: vi.fn(() => true) + probeCodexAuthPresence: vi.fn(() => 'present') })) import { fetchCodexRateLimits } from './codex-fetcher' diff --git a/src/main/rate-limits/codex-fetcher.test.ts b/src/main/rate-limits/codex-fetcher.test.ts index daaec0ce7fd1..571229188c63 100644 --- a/src/main/rate-limits/codex-fetcher.test.ts +++ b/src/main/rate-limits/codex-fetcher.test.ts @@ -28,11 +28,11 @@ vi.mock('node-pty', () => ({ // Default to signed-in so the spawn paths under test still run; the auth gate // itself is covered by codex-auth-presence.test.ts and the no-auth case below. vi.mock('./codex-auth-presence', () => ({ - codexAuthExists: vi.fn(() => true) + probeCodexAuthPresence: vi.fn(() => 'present') })) import { fetchCodexRateLimits } from './codex-fetcher' -import { codexAuthExists } from './codex-auth-presence' +import { probeCodexAuthPresence } from './codex-auth-presence' import { getActiveHiddenRateLimitPtyCount } from './hidden-pty-cleanup' function makeDisposable() { @@ -77,7 +77,7 @@ describe('fetchCodexRateLimits', () => { vi.useFakeTimers() vi.clearAllMocks() resolveCodexCommandMock.mockReturnValue('codex') - vi.mocked(codexAuthExists).mockReturnValue(true) + vi.mocked(probeCodexAuthPresence).mockResolvedValue('present') readFileMock.mockRejectedValue(new Error('no auth fixture')) vi.stubGlobal('fetch', vi.fn()) }) @@ -87,7 +87,7 @@ describe('fetchCodexRateLimits', () => { }) it('does not spawn Codex when the user is not signed in', async () => { - vi.mocked(codexAuthExists).mockReturnValue(false) + vi.mocked(probeCodexAuthPresence).mockResolvedValue('absent') await expect(fetchCodexRateLimits()).resolves.toMatchObject({ provider: 'codex', @@ -101,6 +101,46 @@ describe('fetchCodexRateLimits', () => { expect(ptySpawnMock).not.toHaveBeenCalled() }) + it('preserves the aborted result when cancellation lands during the auth check', async () => { + let resolveAuth!: (presence: 'absent') => void + vi.mocked(probeCodexAuthPresence).mockReturnValueOnce( + new Promise<'absent'>((resolve) => { + resolveAuth = resolve + }) + ) + const controller = new AbortController() + + const result = fetchCodexRateLimits({ signal: controller.signal }) + controller.abort() + resolveAuth('absent') + + await expect(result).resolves.toMatchObject({ + provider: 'codex', + status: 'error', + error: 'Rate-limit fetch aborted' + }) + expect(childSpawnMock).not.toHaveBeenCalled() + expect(ptySpawnMock).not.toHaveBeenCalled() + }) + + it.each([ + ['timeout', 'Timed out while checking Codex sign-in status'], + ['unavailable', 'Codex sign-in status is unavailable'] + ] as const)( + 'does not report an indeterminate %s probe as signed out', + async (presence, error) => { + vi.mocked(probeCodexAuthPresence).mockResolvedValue(presence) + + await expect(fetchCodexRateLimits()).resolves.toMatchObject({ + provider: 'codex', + status: 'error', + error + }) + expect(childSpawnMock).not.toHaveBeenCalled() + expect(ptySpawnMock).not.toHaveBeenCalled() + } + ) + it('disposes node-pty listeners before killing the PTY fallback on timeout', async () => { const onDataDisposable = makeDisposable() const onExitDisposable = makeDisposable() @@ -133,6 +173,7 @@ describe('fetchCodexRateLimits', () => { childSpawnMock.mockReturnValue(rpcChild) const resultPromise = fetchCodexRateLimits({ allowPtyFallback: false }) + await vi.advanceTimersByTimeAsync(0) const spawnCwd = childSpawnMock.mock.calls[0]?.[2]?.cwd as string expect(spawnCwd).toContain('rate-limit-pty-cwd') @@ -168,6 +209,7 @@ describe('fetchCodexRateLimits', () => { const controller = new AbortController() const resultPromise = fetchCodexRateLimits({ signal: controller.signal }) + await vi.advanceTimersByTimeAsync(0) controller.abort() @@ -221,6 +263,7 @@ describe('fetchCodexRateLimits', () => { }) const resultPromise = fetchCodexRateLimits() + await vi.advanceTimersByTimeAsync(0) rpcChild.emit('close') await vi.advanceTimersByTimeAsync(0) @@ -247,6 +290,7 @@ describe('fetchCodexRateLimits', () => { childSpawnMock.mockReturnValue(rpcChild) const resultPromise = fetchCodexRateLimits({ allowPtyFallback: false }) + await vi.advanceTimersByTimeAsync(0) rpcChild.emit('close') await vi.advanceTimersByTimeAsync(0) @@ -421,6 +465,7 @@ describe('fetchCodexRateLimits', () => { expect(fetch).toHaveBeenCalledWith( 'https://chatgpt.com/backend-api/wham/rate-limit-reset-credits', expect.objectContaining({ + signal: expect.any(AbortSignal), headers: expect.objectContaining({ Authorization: 'Bearer access-token', 'ChatGPT-Account-Id': 'account-id', @@ -536,13 +581,25 @@ describe('fetchCodexRateLimits', () => { const [spawnFile, spawnArgs, spawnOptions] = childSpawnMock.mock.calls[0] expect(spawnFile).toBe('wsl.exe') - const bashCommand = spawnArgs.at(-1) as string - expect(bashCommand).toContain('mkdir -p "$orca_rate_limit_cwd"') - expect(bashCommand).toContain('cd "$orca_rate_limit_cwd"') - expect(bashCommand).toContain( - "export CODEX_HOME='/home/alice/.local/share/orca/account/home'" + expect(spawnArgs.slice(0, 5)).toEqual(['-d', 'Ubuntu', '--', 'sh', '-c']) + const shellCommand = spawnArgs.at(-1) as string + expect(shellCommand).toContain('_orca_wsl_shell=\\$(getent passwd') + expect(shellCommand).toContain('bash|zsh|ksh|mksh|ash) exec "\\$_orca_wsl_shell" -ilc') + expect(shellCommand).toContain( + 'exec 3<&0\nexec 4>&1\nexec /dev/null\n_orca_wsl_shell=' + ) + expect(shellCommand).toContain('mkdir -p "\\$orca_rate_limit_cwd"') + expect(shellCommand).toContain('cd "\\$orca_rate_limit_cwd"') + expect(shellCommand).toContain( + "export CODEX_HOME='\\''/home/alice/.local/share/orca/account/home'\\''" ) - expect(bashCommand).toContain("exec codex '-s' 'read-only' '-a' 'untrusted' 'app-server'") + expect(shellCommand).toContain( + "exec codex '\\''-s'\\'' '\\''read-only'\\'' '\\''-a'\\'' '\\''untrusted'\\'' '\\''app-server'\\'' <&3 >&4 3<&- 4>&-" + ) + expect(shellCommand.match(/<&3 >&4 3<&- 4>&-/g)).toHaveLength(3) + expect(shellCommand.match(/exec codex [^\n]+<&3 >&4 3<&- 4>&-/g)).toHaveLength(3) + expect(shellCommand).not.toContain('_orca_codex') + expect(shellCommand).not.toContain('wsl-codex-path') expect(spawnOptions).toEqual( expect.objectContaining({ cwd: expect.stringContaining('rate-limit-pty-cwd'), @@ -557,6 +614,62 @@ describe('fetchCodexRateLimits', () => { } }) + it('routes Windows host Codex homes through the host RPC path', async () => { + const originalPlatform = process.platform + Object.defineProperty(process, 'platform', { + configurable: true, + value: 'win32' + }) + const rpcChild = makeRpcChild() + childSpawnMock.mockReturnValue(rpcChild) + rpcChild.stdin.write.mockImplementation((line: string) => { + const msg = JSON.parse(line) as { id?: number; method?: string } + if (msg.method === 'initialize') { + setTimeout(() => { + rpcChild.stdout.emit( + 'data', + Buffer.from(`${JSON.stringify({ jsonrpc: '2.0', id: msg.id, result: {} })}\n`) + ) + }, 0) + } + if (msg.method === 'account/rateLimits/read') { + setTimeout(() => { + rpcChild.stdout.emit( + 'data', + Buffer.from( + `${JSON.stringify({ + jsonrpc: '2.0', + id: msg.id, + result: { rateLimits: { primary: { usedPercent: 13 } } } + })}\n` + ) + ) + }, 0) + } + }) + + try { + const resultPromise = fetchCodexRateLimits({ codexHomePath: 'C:\\Users\\alice\\.codex' }) + await vi.advanceTimersByTimeAsync(1) + await vi.advanceTimersByTimeAsync(1) + await resultPromise + + const [spawnFile, spawnArgs, spawnOptions] = childSpawnMock.mock.calls[0] + expect(spawnFile).toBe('codex') + expect(spawnArgs).toEqual(['-s', 'read-only', '-a', 'untrusted', 'app-server']) + expect(spawnOptions).toEqual( + expect.objectContaining({ + env: expect.objectContaining({ CODEX_HOME: 'C:\\Users\\alice\\.codex' }) + }) + ) + } finally { + Object.defineProperty(process, 'platform', { + configurable: true, + value: originalPlatform + }) + } + }) + it('runs rate-limit PTY fallback through WSL when RPC cannot read usage', async () => { const originalPlatform = process.platform const originalCodexHome = process.env.CODEX_HOME @@ -583,18 +696,28 @@ describe('fetchCodexRateLimits', () => { const resultPromise = fetchCodexRateLimits({ codexHomePath: '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.local\\share\\orca\\account\\home' }) + await vi.advanceTimersByTimeAsync(0) rpcChild.emit('close') await vi.advanceTimersByTimeAsync(0) const [spawnFile, spawnArgs, spawnOptions] = ptySpawnMock.mock.calls[0] expect(spawnFile).toBe('wsl.exe') - const bashCommand = spawnArgs.at(-1) as string - expect(bashCommand).toContain('mkdir -p "$orca_rate_limit_cwd"') - expect(bashCommand).toContain('cd "$orca_rate_limit_cwd"') - expect(bashCommand).toContain( - "export CODEX_HOME='/home/alice/.local/share/orca/account/home'" + expect(spawnArgs.slice(0, 5)).toEqual(['-d', 'Ubuntu', '--', 'sh', '-c']) + const shellCommand = spawnArgs.at(-1) as string + expect(shellCommand).toContain('_orca_wsl_shell=\\$(getent passwd') + expect(shellCommand).toContain('bash|zsh|ksh|mksh|ash) exec "\\$_orca_wsl_shell" -ilc') + expect(shellCommand).not.toContain('exec 3<&0') + expect(shellCommand).not.toContain('exec /dev/null') + expect(shellCommand).not.toContain('<&3 >&4 3<&- 4>&-') + expect(shellCommand).toContain('mkdir -p "\\$orca_rate_limit_cwd"') + expect(shellCommand).toContain('cd "\\$orca_rate_limit_cwd"') + expect(shellCommand).toContain( + "export CODEX_HOME='\\''/home/alice/.local/share/orca/account/home'\\''" ) - expect(bashCommand).toContain('exec codex ') + expect(shellCommand).toContain('exec codex ') + expect(shellCommand).not.toContain('_orca_codex') + expect(shellCommand).not.toContain('wsl-codex-path') expect(spawnOptions).toEqual( expect.objectContaining({ cwd: expect.stringContaining('rate-limit-pty-cwd'), diff --git a/src/main/rate-limits/codex-fetcher.ts b/src/main/rate-limits/codex-fetcher.ts index 28ef1b710fdc..d606a12e850f 100644 --- a/src/main/rate-limits/codex-fetcher.ts +++ b/src/main/rate-limits/codex-fetcher.ts @@ -10,21 +10,33 @@ import { spawn } from 'node:child_process' import { readFile } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'node:path' -import { codexAuthExists } from './codex-auth-presence' +import { probeCodexAuthPresence } from './codex-auth-presence' import { resolveCodexCommand } from '../codex-cli/command' import { withMacTailscaleDnsHint } from '../network/macos-tailscale-dns-diagnostic' import { getCmdExePath, getSpawnArgsForWindows } from '../win32-utils' import { cleanupHiddenRateLimitPty, registerHiddenRateLimitPty } from './hidden-pty-cleanup' import { parseWslUncPath } from '../../shared/wsl-paths' import { extractCodexAuthError, isCodexAuthError } from '../../shared/codex-auth-errors' +import { + buildWslLoginShellCommand, + escapeWslShCommandForWindows +} from '../../shared/wsl-login-shell-command' import { getHiddenRateLimitWslCwdSetupCommands, resolveHiddenRateLimitPtyCwd } from './hidden-rate-limit-pty-cwd' +import { + createAuthFilesystemOperation, + type SharedAuthFilesystemOperation +} from './auth-filesystem-operation' const RPC_TIMEOUT_MS = 10_000 const WSL_RPC_TIMEOUT_MS = 25_000 const PTY_TIMEOUT_MS = 15_000 +const BACKEND_TIMEOUT_MS = 10_000 +// Why: redeeming a reset credit is an explicit user action, not a background +// poll — give it more room before failing so a slow backend can still finish. +const REDEEM_BACKEND_TIMEOUT_MS = 30_000 const MAX_DIAGNOSTIC_OUTPUT_LENGTH = 100_000 export type FetchCodexRateLimitsOptions = { @@ -98,6 +110,21 @@ type BackendRateLimitResetCreditsResponse = { }[] } +type BackendRateLimitWindow = { + used_percent?: number + limit_window_seconds?: number + reset_at?: number +} + +type BackendUsageResponse = { + plan_type?: string + rate_limit?: { + primary_window?: BackendRateLimitWindow | null + secondary_window?: BackendRateLimitWindow | null + } | null + rate_limit_reset_credits?: BackendRateLimitResetCreditsResponse | null +} + type BackendConsumeRateLimitResetCreditResponse = { code?: string } @@ -106,13 +133,23 @@ type CodexBackendAuthHeaders = { headers: Record } +type BackendAuthReadResult = + | { content: string; error?: never } + | { content?: never; error: unknown } + +const backendAuthReadByPath = new Map< + string, + SharedAuthFilesystemOperation +>() + function shellQuote(value: string): string { return `'${value.replace(/'/g, "'\\''")}'` } function buildWslCodexCommand( codexHomePath: string, - args: string[] + args: string[], + options?: { isolateRpcStdio?: boolean } ): { command: string args: string[] @@ -121,14 +158,27 @@ function buildWslCodexCommand( if (process.platform !== 'win32' || !wslInfo) { return null } - const script = [ + const setupCommands = [ ...getHiddenRateLimitWslCwdSetupCommands(), - `export CODEX_HOME=${shellQuote(wslInfo.linuxPath)}`, - `exec codex ${args.map(shellQuote).join(' ')}` + `export CODEX_HOME=${shellQuote(wslInfo.linuxPath)}` ].join(' && ') + const execSuffix = `${args.map(shellQuote).join(' ')}${ + options?.isolateRpcStdio ? ' <&3 >&4 3<&- 4>&-' : '' + }` + // Why: npm/nvm Codex launchers use `#!/usr/bin/env node`. Resolving an + // absolute launcher in a login shell and later execing it from plain `sh` + // loses the PATH that supplies Node and also pins obsolete installations. + const loginShellCommand = buildWslLoginShellCommand( + [setupCommands, `exec codex ${execSuffix}`].join(' && ') + ) + // Why: keep the outer sh non-login and hide RPC pipes before the configured + // shell startup can read input or print banners. + const command = options?.isolateRpcStdio + ? ['exec 3<&0', 'exec 4>&1', 'exec /dev/null', loginShellCommand].join('\n') + : loginShellCommand return { command: 'wsl.exe', - args: ['-d', wslInfo.distro, '--', 'bash', '-lc', script] + args: ['-d', wslInfo.distro, '--', 'sh', '-c', escapeWslShCommandForWindows(command)] } } @@ -242,14 +292,57 @@ function mapBackendRateLimitResetCredits( } } +function createBackendRequestSignal( + callerSignal?: AbortSignal, + timeoutMs = BACKEND_TIMEOUT_MS +): AbortSignal { + const timeoutSignal = AbortSignal.timeout(timeoutMs) + return callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal +} + +function getBackendAuthRead( + authPath: string +): SharedAuthFilesystemOperation { + const existing = backendAuthReadByPath.get(authPath) + if (existing) { + return existing + } + // Why: the caller deadline must settle promptly, but Node cannot guarantee + // cancellation of an already-issued UNC read. Keep one raw read per auth + // path until the OS finishes so repeated quota refreshes cannot stack them. + const read = createAuthFilesystemOperation(authPath, () => + readFile(authPath, 'utf8').then( + (content) => ({ content }), + (error: unknown) => ({ error }) + ) + ) + backendAuthReadByPath.set(authPath, read) + const clearRead = (): void => { + if (backendAuthReadByPath.get(authPath) === read) { + backendAuthReadByPath.delete(authPath) + } + } + void read.result.then(clearRead, clearRead) + return read +} + +async function readBackendAuth(authPath: string, signal: AbortSignal): Promise { + const result = await getBackendAuthRead(authPath).wait(signal) + if ('error' in result) { + throw result.error + } + return result.content +} + async function getCodexBackendAuthHeaders( - options?: FetchCodexRateLimitsOptions + options: FetchCodexRateLimitsOptions | undefined, + signal: AbortSignal ): Promise { - if (options?.signal?.aborted) { + if (signal.aborted) { return null } const authPath = join(getCodexHomePath(options?.codexHomePath), 'auth.json') - const auth = JSON.parse(await readFile(authPath, 'utf8')) as CodexAuthFile + const auth = JSON.parse(await readBackendAuth(authPath, signal)) as CodexAuthFile const accessToken = auth.tokens?.access_token if (!accessToken) { return null @@ -273,18 +366,19 @@ async function fetchBackendRateLimitResetCredits( if (options?.signal?.aborted) { return null } - const auth = await getCodexBackendAuthHeaders(options) + const signal = createBackendRequestSignal(options?.signal) + const auth = await getCodexBackendAuthHeaders(options, signal) if (!auth) { return null } - if (options?.signal?.aborted) { + if (signal.aborted) { return null } // Why: published Codex 0.140 can read windows through app-server but strips // reset-credit metadata that the backend already returns. const response = await fetch('https://chatgpt.com/backend-api/wham/rate-limit-reset-credits', { ...auth, - signal: options?.signal + signal }) if (!response.ok) { return null @@ -336,7 +430,8 @@ export async function consumeCodexRateLimitResetCredit(options: { if (!options.idempotencyKey.trim()) { throw new Error('Codex reset idempotency key is required') } - const auth = await getCodexBackendAuthHeaders(options) + const signal = createBackendRequestSignal(undefined, REDEEM_BACKEND_TIMEOUT_MS) + const auth = await getCodexBackendAuthHeaders(options, signal) if (!auth) { throw new Error('Codex not signed in') } @@ -348,7 +443,8 @@ export async function consumeCodexRateLimitResetCredit(options: { ...auth.headers, 'Content-Type': 'application/json' }, - body: JSON.stringify({ redeem_request_id: options.idempotencyKey }) + body: JSON.stringify({ redeem_request_id: options.idempotencyKey }), + signal } ) if (!response.ok) { @@ -362,13 +458,13 @@ function mapRpcWindow( raw: RpcRateWindow | undefined, expectedWindowMinutes: number ): RateLimitWindow | null { - if (!raw || typeof raw.usedPercent !== 'number') { + if (!raw || typeof raw.usedPercent !== 'number' || !Number.isFinite(raw.usedPercent)) { return null } let resetDescription: string | null = null let resetsAt: number | null = null - if (raw.resetsAt) { + if (typeof raw.resetsAt === 'number' && Number.isFinite(raw.resetsAt) && raw.resetsAt > 0) { // Why: Codex returns resetsAt as Unix seconds, not milliseconds. const date = new Date(raw.resetsAt * 1000) if (!Number.isNaN(date.getTime())) { @@ -395,6 +491,71 @@ function mapRpcWindow( } } +function mapBackendUsageWindow( + raw: BackendRateLimitWindow | null | undefined, + fallbackWindowMinutes: number +): RateLimitWindow | null { + const limitWindowSeconds = raw?.limit_window_seconds + // Match Codex backend-client's `window_minutes_from_seconds`: the backend + // field is the actual bucket duration and rounds partial minutes upward. + const windowMinutes = + typeof limitWindowSeconds === 'number' && + Number.isFinite(limitWindowSeconds) && + limitWindowSeconds > 0 + ? Math.ceil(limitWindowSeconds / 60) + : fallbackWindowMinutes + return mapRpcWindow( + raw + ? { + usedPercent: raw.used_percent, + resetsAt: raw.reset_at + } + : undefined, + windowMinutes + ) +} + +async function fetchViaBackend( + options?: FetchCodexRateLimitsOptions +): Promise { + const signal = createBackendRequestSignal(options?.signal) + const auth = await getCodexBackendAuthHeaders(options, signal) + if (!auth || signal.aborted) { + return null + } + // Why: Codex itself reads this endpoint in backend-client's + // `get_rate_limit_status`; using the same contract avoids launching a hidden + // app-server (and a WSL login shell) for every routine quota refresh. + const response = await fetch('https://chatgpt.com/backend-api/wham/usage', { + ...auth, + signal + }) + if (!response.ok) { + return null + } + const payload = (await response.json()) as BackendUsageResponse + // `plan_type` is required by Codex's RateLimitStatusPayload. Reject a + // superficially successful but unrelated/malformed JSON response so the + // established app-server fallback still gets a chance. + if (typeof payload.plan_type !== 'string') { + return null + } + return { + provider: 'codex', + session: mapBackendUsageWindow(payload.rate_limit?.primary_window, 300), + weekly: mapBackendUsageWindow(payload.rate_limit?.secondary_window, 10080), + ...(payload.rate_limit_reset_credits !== undefined + ? { + rateLimitResetCredits: + mapBackendRateLimitResetCredits(payload.rate_limit_reset_credits) ?? null + } + : {}), + updatedAt: Date.now(), + error: null, + status: 'ok' + } +} + // --------------------------------------------------------------------------- // RPC fetch — spawn `codex -s read-only -a untrusted app-server` // --------------------------------------------------------------------------- @@ -411,7 +572,7 @@ async function fetchViaRpc(options?: FetchCodexRateLimitsOptions): Promise { + afterEach(() => { + vi.resetModules() + vi.doUnmock('node:fs') + }) + + it('redacts filesystem paths from auth read failures', async () => { + vi.doMock('node:fs', () => ({ + existsSync: vi.fn(() => true), + readFileSync: vi.fn(() => { + throw new Error( + 'EACCES: permission denied, open /Users/brennanbenson/private/.grok/auth.json' + ) + }) + })) + const { readGrokAuthSession } = await import('./grok-auth') + + expect(readGrokAuthSession()).toEqual({ + status: 'error', + error: 'Unable to read Grok auth file' + }) + }) + + it('treats a token-less auth file as signed out, not an error', async () => { + vi.doMock('node:fs', () => ({ + existsSync: vi.fn(() => true), + readFileSync: vi.fn(() => JSON.stringify({ 'https://auth.x.ai::client': { user_id: 'u1' } })) + })) + const { readGrokAuthSession } = await import('./grok-auth') + + expect(readGrokAuthSession()).toEqual({ status: 'missing' }) + }) + + it('reports malformed auth JSON without parser details', async () => { + vi.doMock('node:fs', () => ({ + existsSync: vi.fn(() => true), + readFileSync: vi.fn(() => '{') + })) + const { readGrokAuthSession } = await import('./grok-auth') + + expect(readGrokAuthSession()).toEqual({ + status: 'error', + error: 'Grok auth file is invalid' + }) + }) +}) diff --git a/src/main/rate-limits/grok-auth.ts b/src/main/rate-limits/grok-auth.ts new file mode 100644 index 000000000000..10ba629ff340 --- /dev/null +++ b/src/main/rate-limits/grok-auth.ts @@ -0,0 +1,116 @@ +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { resolveGrokHomeDir } from '../../shared/grok-session-paths' + +// Why: when GROK_HOME is set, auth.json must be the same path Grok CLI uses. +export function getGrokHome(): string { + return resolveGrokHomeDir() +} + +export function getGrokAuthPath(): string { + return join(getGrokHome(), 'auth.json') +} + +export type GrokAuthSession = { + accessToken: string + userId: string | null + email: string | null + teamId: string | null + expiresAtMs: number | null + oidcClientId: string | null +} + +type GrokAuthEntry = { + key?: string + user_id?: string + email?: string + team_id?: string + expires_at?: string + oidc_client_id?: string +} + +export type GrokAuthReadResult = + | { status: 'missing' } + | { status: 'error'; error: string } + | { status: 'ok'; session: GrokAuthSession } + +function getGrokAuthReadError(err: unknown): string { + if (err instanceof SyntaxError) { + return 'Grok auth file is invalid' + } + // Why: filesystem errors often include the full auth path; renderer/mobile + // account state should not expose local usernames or custom GROK_HOME values. + return 'Unable to read Grok auth file' +} + +function parseAuthEntry(value: unknown): GrokAuthEntry | null { + if (typeof value !== 'object' || value === null) { + return null + } + const entry = value as GrokAuthEntry + if (typeof entry.key !== 'string' || entry.key.length === 0) { + return null + } + return entry +} + +function parseExpiresAtMs(iso: string | undefined): number | null { + if (!iso) { + return null + } + const ms = Date.parse(iso) + return Number.isFinite(ms) ? ms : null +} + +export function readGrokAuthSession(): GrokAuthReadResult { + const path = getGrokAuthPath() + if (!existsSync(path)) { + return { status: 'missing' } + } + try { + const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8')) + if (typeof parsed !== 'object' || parsed === null) { + return { status: 'error', error: 'Grok auth file is invalid' } + } + for (const entry of Object.values(parsed)) { + const authEntry = parseAuthEntry(entry) + if (!authEntry?.key) { + continue + } + return { + status: 'ok', + session: { + accessToken: authEntry.key, + userId: typeof authEntry.user_id === 'string' ? authEntry.user_id : null, + email: typeof authEntry.email === 'string' ? authEntry.email : null, + teamId: typeof authEntry.team_id === 'string' ? authEntry.team_id : null, + expiresAtMs: parseExpiresAtMs(authEntry.expires_at), + oidcClientId: + typeof authEntry.oidc_client_id === 'string' ? authEntry.oidc_client_id : null + } + } + } + // Why: a token-less file (e.g. after grok logout) means signed out, not a + // failure — 'error' would keep a status-bar alert visible for that user. + return { status: 'missing' } + } catch (err) { + return { + status: 'error', + error: getGrokAuthReadError(err) + } + } +} + +export function hasGrokAuthSession(): boolean { + return readGrokAuthSession().status === 'ok' +} + +const TOKEN_SKEW_MS = 5 * 60 * 1000 + +export function isGrokAccessTokenFresh(session: GrokAuthSession): boolean { + if (session.expiresAtMs === null) { + // Why: auth.json may lack expiry; a bad token still surfaces as billing HTTP 401. + return true + } + return session.expiresAtMs - Date.now() > TOKEN_SKEW_MS +} diff --git a/src/main/rate-limits/grok-fetcher.test.ts b/src/main/rate-limits/grok-fetcher.test.ts new file mode 100644 index 000000000000..f816d5c552fc --- /dev/null +++ b/src/main/rate-limits/grok-fetcher.test.ts @@ -0,0 +1,164 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const netFetchMock = vi.hoisted(() => vi.fn()) +const authState = vi.hoisted<{ + file: string | null + readError: Error | null +}>(() => ({ file: null, readError: null })) + +vi.mock('electron', () => ({ + net: { fetch: netFetchMock } +})) + +vi.mock('node:fs', () => ({ + existsSync: () => authState.file !== null, + readFileSync: () => { + if (authState.readError) { + throw authState.readError + } + if (authState.file === null) { + throw new Error('ENOENT') + } + return authState.file + } +})) + +vi.mock('node:os', () => ({ homedir: () => '/home/test' })) + +import { fetchGrokRateLimits } from './grok-fetcher' + +function jsonResponse(body: unknown, status = 200): Response { + return { + ok: status >= 200 && status < 300, + status, + json: async () => body + } as Response +} + +const BILLING_RESPONSE = { + config: { + creditUsagePercent: 42, + currentPeriod: { + type: 'USAGE_PERIOD_TYPE_WEEKLY', + start: '2026-06-30T18:36:14.268512+00:00', + end: '2026-07-07T18:36:14.268512+00:00' + }, + subscriptionTier: 'SuperGrok', + isUnifiedBillingUser: true + } +} + +function freshAuthJson(): string { + return JSON.stringify({ + 'https://auth.x.ai::client': { + key: 'access-token', + user_id: 'user-1', + email: 'dev@example.com', + expires_at: '2099-01-01T00:00:00.000Z' + } + }) +} + +describe('fetchGrokRateLimits', () => { + beforeEach(() => { + netFetchMock.mockReset() + authState.file = null + authState.readError = null + }) + + afterEach(() => { + vi.unstubAllEnvs() + }) + + it('returns unavailable when not signed in', async () => { + const result = await fetchGrokRateLimits() + expect(result.provider).toBe('grok') + expect(result.status).toBe('unavailable') + expect(netFetchMock).not.toHaveBeenCalled() + }) + + it('maps weekly credit usage from billing config', async () => { + authState.file = freshAuthJson() + netFetchMock.mockResolvedValueOnce(jsonResponse(BILLING_RESPONSE)) + + const result = await fetchGrokRateLimits() + expect(result.status).toBe('ok') + expect(result.weekly?.usedPercent).toBe(42) + expect(result.weekly?.windowMinutes).toBe(10_080) + expect(result.usageMetadata?.source).toBe('oauth') + expect(result.usageMetadata?.authProvenance).toContain('SuperGrok') + + expect(netFetchMock).toHaveBeenCalledWith( + 'https://cli-chat-proxy.grok.com/v1/billing?format=credits', + expect.objectContaining({ + headers: expect.objectContaining({ + Authorization: 'Bearer access-token', + 'X-XAI-Token-Auth': 'xai-grok-cli', + 'x-userid': 'user-1' + }) + }) + ) + }) + + it('returns unavailable when not signed in even if a token-less auth file exists', async () => { + authState.file = JSON.stringify({}) + const result = await fetchGrokRateLimits() + expect(result.status).toBe('unavailable') + expect(netFetchMock).not.toHaveBeenCalled() + }) + + it('returns unavailable when billing has no credit usage', async () => { + authState.file = freshAuthJson() + netFetchMock.mockResolvedValueOnce(jsonResponse({ config: { subscriptionTier: 'Enterprise' } })) + + const result = await fetchGrokRateLimits() + expect(result.status).toBe('unavailable') + expect(result.weekly).toBeNull() + }) + + it('returns unavailable when billing response has no config', async () => { + authState.file = freshAuthJson() + netFetchMock.mockResolvedValueOnce(jsonResponse({})) + + const result = await fetchGrokRateLimits() + expect(result.status).toBe('unavailable') + }) + + it('aborts the billing request when the caller aborts', async () => { + authState.file = freshAuthJson() + const controller = new AbortController() + let requestSignal: AbortSignal | undefined + netFetchMock.mockImplementationOnce((_url, init: RequestInit) => { + requestSignal = init.signal as AbortSignal + return new Promise((_resolve, reject) => { + requestSignal?.addEventListener('abort', () => reject(new Error('aborted')), { + once: true + }) + }) + }) + + const resultPromise = fetchGrokRateLimits({ signal: controller.signal }) + await Promise.resolve() + + expect(requestSignal?.aborted).toBe(false) + controller.abort() + expect(requestSignal?.aborted).toBe(true) + + const result = await resultPromise + expect(result.status).toBe('error') + expect(result.error).toBe('aborted') + }) + + it('returns error when the session token is expired', async () => { + authState.file = JSON.stringify({ + 'https://auth.x.ai::client': { + key: 'stale', + expires_at: '2000-01-01T00:00:00.000Z' + } + }) + const result = await fetchGrokRateLimits() + expect(result.status).toBe('error') + expect(result.error).toMatch(/expired/i) + expect(netFetchMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/rate-limits/grok-fetcher.ts b/src/main/rate-limits/grok-fetcher.ts new file mode 100644 index 000000000000..963a2fb13505 --- /dev/null +++ b/src/main/rate-limits/grok-fetcher.ts @@ -0,0 +1,173 @@ +import { net } from 'electron' +import type { ProviderRateLimits, RateLimitWindow } from '../../shared/rate-limit-types' +import { + isGrokAccessTokenFresh, + readGrokAuthSession, + type GrokAuthReadResult, + type GrokAuthSession +} from './grok-auth' + +// Why: billing URL and headers must match Grok CLI or xAI rejects the request. +const GROK_CLI_PROXY_BASE = + process.env.GROK_CLI_CHAT_PROXY_BASE_URL?.trim().replace(/\/$/, '') || + 'https://cli-chat-proxy.grok.com/v1' +const BILLING_CREDITS_URL = `${GROK_CLI_PROXY_BASE}/billing?format=credits` +const API_TIMEOUT_MS = 10_000 +const WEEKLY_WINDOW_MINUTES = 10_080 + +const GROK_CLI_AUTH_HEADER = 'xai-grok-cli' + +type GrokMoneyVal = { val?: string | number } + +type GrokUsagePeriod = { + type?: string + start?: string + end?: string +} + +type GrokBillingConfig = { + creditUsagePercent?: number + currentPeriod?: GrokUsagePeriod + billingPeriodStart?: string + billingPeriodEnd?: string + subscriptionTier?: string + onDemandCap?: GrokMoneyVal + onDemandUsed?: GrokMoneyVal + prepaidBalance?: GrokMoneyVal + isUnifiedBillingUser?: boolean +} + +type GrokBillingResponse = GrokBillingConfig & { + config?: GrokBillingConfig +} + +function result(status: ProviderRateLimits['status'], error: string | null): ProviderRateLimits { + return { + provider: 'grok', + session: null, + weekly: null, + updatedAt: Date.now(), + error, + status + } +} + +function parseResetDescription(isoString: string | undefined): string | null { + if (!isoString) { + return null + } + const date = new Date(isoString) + if (Number.isNaN(date.getTime())) { + return null + } + const isToday = date.toDateString() === new Date().toDateString() + return isToday + ? date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' }) + : date.toLocaleDateString(undefined, { weekday: 'short', hour: 'numeric', minute: '2-digit' }) +} + +function mapWeeklyCredits(config: GrokBillingConfig): RateLimitWindow | null { + const usedPercent = config.creditUsagePercent + if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent)) { + return null + } + const periodEnd = config.currentPeriod?.end ?? config.billingPeriodEnd + const resetsAt = periodEnd ? Date.parse(periodEnd) : null + return { + usedPercent: Math.min(100, Math.max(0, usedPercent)), + windowMinutes: WEEKLY_WINDOW_MINUTES, + resetsAt: resetsAt !== null && Number.isFinite(resetsAt) ? resetsAt : null, + resetDescription: parseResetDescription(periodEnd) + } +} + +function grokRequestHeaders(session: GrokAuthSession): Record { + const headers: Record = { + Authorization: `Bearer ${session.accessToken}`, + 'X-XAI-Token-Auth': GROK_CLI_AUTH_HEADER, + Accept: 'application/json' + } + if (session.userId) { + headers['x-userid'] = session.userId + } + return headers +} + +function resolveBillingConfig(data: GrokBillingResponse): GrokBillingConfig | null { + if (data.config) { + return data.config + } + if (typeof data.creditUsagePercent === 'number') { + return data + } + return null +} + +function mapBillingResponse( + data: GrokBillingResponse, + session: GrokAuthSession +): ProviderRateLimits { + const config = resolveBillingConfig(data) + // Why: a 200 without credit usage means the plan has no weekly credits — + // 'unavailable' hides the bar (like Claude on API-key billing); 'error' + // would paint a permanent alert for a signed-in account that has no quota. + if (!config) { + return result('unavailable', 'Grok billing response did not include config') + } + const weekly = mapWeeklyCredits(config) + const tier = config.subscriptionTier?.trim() + const authLabel = session.email?.trim() || session.userId || 'Grok account' + const provenance = tier ? `${authLabel} (${tier})` : authLabel + return { + provider: 'grok', + session: null, + weekly, + updatedAt: Date.now(), + error: weekly ? null : 'Grok billing response did not include credit usage', + status: weekly ? 'ok' : 'unavailable', + usageMetadata: { + source: 'oauth', + authProvenance: provenance + } + } +} + +// Why: Orca never runs grok login; it only reads the session file the CLI updates. +export async function fetchGrokRateLimits( + options: { signal?: AbortSignal; authReadResult?: GrokAuthReadResult } = {} +): Promise { + const readResult = options.authReadResult ?? readGrokAuthSession() + if (readResult.status === 'missing') { + return result('unavailable', 'Not signed in to Grok — run grok login') + } + if (readResult.status === 'error') { + return result('error', readResult.error) + } + const session = readResult.session + if (!isGrokAccessTokenFresh(session)) { + return result('error', 'Grok session expired — run grok login to refresh') + } + + try { + const signal = options.signal + ? AbortSignal.any([options.signal, AbortSignal.timeout(API_TIMEOUT_MS)]) + : AbortSignal.timeout(API_TIMEOUT_MS) + const res = await net.fetch(BILLING_CREDITS_URL, { + headers: grokRequestHeaders(session), + signal + }) + if (res.status === 401 || res.status === 403) { + return result('error', `Grok usage request unauthorized (HTTP ${res.status})`) + } + if (!res.ok) { + return result('error', `Grok usage request failed (HTTP ${res.status})`) + } + const data: unknown = await res.json() + return mapBillingResponse( + typeof data === 'object' && data !== null ? (data as GrokBillingResponse) : {}, + session + ) + } catch (err) { + return result('error', err instanceof Error ? err.message : 'Grok usage request failed') + } +} diff --git a/src/main/rate-limits/service.test.ts b/src/main/rate-limits/service.test.ts index 082dcf282a91..166442ee0aea 100644 --- a/src/main/rate-limits/service.test.ts +++ b/src/main/rate-limits/service.test.ts @@ -9,7 +9,10 @@ import { RateLimitService } from './service' import { fetchClaudeRateLimits, fetchManagedAccountUsage } from './claude-fetcher' import { fetchCodexRateLimits } from './codex-fetcher' import { fetchGeminiRateLimits } from './gemini-usage-fetcher' +import { fetchKimiRateLimits } from './kimi-fetcher' import { fetchMiniMaxRateLimits } from './minimax-fetcher' +import { fetchGrokRateLimits } from './grok-fetcher' +import { readGrokAuthSession } from './grok-auth' import { fetchOpenCodeGoRateLimits } from './opencode-go-usage-fetcher' import { hasMiniMaxSessionCookie } from '../minimax/minimax-cookie-store' @@ -30,10 +33,22 @@ vi.mock('./opencode-go-usage-fetcher', () => ({ fetchOpenCodeGoRateLimits: vi.fn() })) +vi.mock('./kimi-fetcher', () => ({ + fetchKimiRateLimits: vi.fn() +})) + vi.mock('./minimax-fetcher', () => ({ fetchMiniMaxRateLimits: vi.fn() })) +vi.mock('./grok-fetcher', () => ({ + fetchGrokRateLimits: vi.fn() +})) + +vi.mock('./grok-auth', () => ({ + readGrokAuthSession: vi.fn(() => ({ status: 'missing' })) +})) + vi.mock('../minimax/minimax-cookie-store', () => ({ hasMiniMaxSessionCookie: vi.fn(() => false) })) @@ -51,8 +66,14 @@ function deferred(): Deferred { return { promise, resolve } } +async function flushMicrotasks(times = 4): Promise { + for (let i = 0; i < times; i += 1) { + await Promise.resolve() + } +} + function okProvider( - provider: 'claude' | 'codex' | 'gemini' | 'opencode-go' | 'minimax', + provider: 'claude' | 'codex' | 'gemini' | 'opencode-go' | 'kimi' | 'minimax' | 'grok', usedPercent: number, updatedAt = Date.now() ): ProviderRateLimits { @@ -72,7 +93,7 @@ function okProvider( } function errorProvider( - provider: 'claude' | 'codex' | 'gemini' | 'opencode-go' | 'minimax', + provider: 'claude' | 'codex' | 'gemini' | 'opencode-go' | 'kimi' | 'minimax' | 'grok', message: string ): ProviderRateLimits { return { @@ -126,8 +147,72 @@ describe('RateLimitService', () => { vi.clearAllMocks() vi.mocked(fetchGeminiRateLimits).mockResolvedValue(okProvider('gemini', 0, Date.now())) vi.mocked(fetchOpenCodeGoRateLimits).mockResolvedValue(okProvider('opencode-go', 0, Date.now())) + vi.mocked(fetchKimiRateLimits).mockResolvedValue(okProvider('kimi', 0, Date.now())) vi.mocked(fetchMiniMaxRateLimits).mockResolvedValue(okProvider('minimax', 0, Date.now())) + vi.mocked(fetchGrokRateLimits).mockResolvedValue({ + provider: 'grok', + session: null, + weekly: null, + updatedAt: Date.now(), + error: null, + status: 'unavailable' + }) vi.mocked(hasMiniMaxSessionCookie).mockReturnValue(false) + vi.mocked(readGrokAuthSession).mockReturnValue({ status: 'missing' }) + }) + + it('does not reread Grok auth when callers read state snapshots', () => { + vi.mocked(readGrokAuthSession).mockReturnValue({ + status: 'ok', + session: { + accessToken: 'token', + userId: null, + email: null, + teamId: null, + expiresAtMs: null, + oidcClientId: null + } + }) + const service = new RateLimitService() + vi.mocked(readGrokAuthSession).mockClear() + + expect(service.getState().grokAuthConfigured).toBe(true) + service.getState() + + expect(readGrokAuthSession).not.toHaveBeenCalled() + }) + + it('refreshes Grok without refreshing other providers', async () => { + const authReadResult = { + status: 'ok' as const, + session: { + accessToken: 'token', + userId: null, + email: 'dev@example.com', + teamId: null, + expiresAtMs: null, + oidcClientId: null + } + } + vi.mocked(readGrokAuthSession).mockReturnValue(authReadResult) + vi.mocked(fetchGrokRateLimits).mockResolvedValueOnce(okProvider('grok', 42)) + const service = new RateLimitService() + + await service.refreshGrok() + + expect(fetchGrokRateLimits).toHaveBeenCalledTimes(1) + expect(fetchGrokRateLimits).toHaveBeenCalledWith({ + authReadResult, + signal: expect.any(AbortSignal) + }) + expect(fetchClaudeRateLimits).not.toHaveBeenCalled() + expect(fetchCodexRateLimits).not.toHaveBeenCalled() + expect(fetchGeminiRateLimits).not.toHaveBeenCalled() + expect(fetchOpenCodeGoRateLimits).not.toHaveBeenCalled() + expect(fetchKimiRateLimits).not.toHaveBeenCalled() + expect(fetchMiniMaxRateLimits).not.toHaveBeenCalled() + expect(service.getState().grokAuthConfigured).toBe(true) + expect(service.getState().grok?.status).toBe('ok') }) it('does not refetch Claude when a Codex account switch is queued during fetchAll', async () => { @@ -345,9 +430,47 @@ describe('RateLimitService', () => { expect(fetchCodexRateLimits).toHaveBeenCalledTimes(2) }) + it('publishes non-Grok provider results before a slow Grok fetch completes', async () => { + const service = new RateLimitService() + const grok = deferred() + let refreshResolved = false + + vi.mocked(fetchClaudeRateLimits).mockResolvedValueOnce(okProvider('claude', 10, Date.now())) + vi.mocked(fetchCodexRateLimits).mockResolvedValueOnce(okProvider('codex', 20, Date.now())) + vi.mocked(fetchGeminiRateLimits).mockResolvedValueOnce(okProvider('gemini', 30, Date.now())) + vi.mocked(fetchOpenCodeGoRateLimits).mockResolvedValueOnce( + okProvider('opencode-go', 40, Date.now()) + ) + vi.mocked(fetchKimiRateLimits).mockResolvedValueOnce(okProvider('kimi', 50, Date.now())) + vi.mocked(fetchMiniMaxRateLimits).mockResolvedValueOnce(okProvider('minimax', 60, Date.now())) + vi.mocked(fetchGrokRateLimits).mockReturnValueOnce(grok.promise) + + const refresh = service.refresh().then(() => { + refreshResolved = true + }) + await flushMicrotasks() + + const pendingGrokState = service.getState() + expect(pendingGrokState.claude?.status).toBe('ok') + expect(pendingGrokState.codex?.status).toBe('ok') + expect(pendingGrokState.gemini?.status).toBe('ok') + expect(pendingGrokState.opencodeGo?.status).toBe('ok') + expect(pendingGrokState.kimi?.status).toBe('ok') + expect(pendingGrokState.minimax?.status).toBe('ok') + expect(pendingGrokState.grok?.status).toBe('fetching') + expect(refreshResolved).toBe(false) + + grok.resolve(okProvider('grok', 70, Date.now())) + await refresh + + const completedState = service.getState() + expect(completedState.grok?.status).toBe('ok') + expect(refreshResolved).toBe(true) + }) + it('aborts the active fetch cycle and clears queued refreshes on stop', async () => { const service = new RateLimitService() - const capturedSignals: { claude?: AbortSignal; codex?: AbortSignal } = {} + const capturedSignals: { claude?: AbortSignal; codex?: AbortSignal; grok?: AbortSignal } = {} vi.mocked(fetchClaudeRateLimits).mockImplementation( (options) => @@ -371,6 +494,17 @@ describe('RateLimitService', () => { ) }) ) + vi.mocked(fetchGrokRateLimits).mockImplementation( + (options) => + new Promise((resolve) => { + capturedSignals.grok = options?.signal + options?.signal?.addEventListener( + 'abort', + () => resolve(errorProvider('grok', 'aborted')), + { once: true } + ) + }) + ) const activeFetch = serviceInternals(service).fetchAll() await Promise.resolve() @@ -383,12 +517,14 @@ describe('RateLimitService', () => { expect(capturedSignals.claude?.aborted).toBe(true) expect(capturedSignals.codex?.aborted).toBe(true) + expect(capturedSignals.grok?.aborted).toBe(true) await queuedRefresh await activeFetch expect(fetchClaudeRateLimits).toHaveBeenCalledTimes(1) expect(fetchCodexRateLimits).toHaveBeenCalledTimes(1) + expect(fetchGrokRateLimits).toHaveBeenCalledTimes(1) }) it('aborts inactive Claude preview fetches on stop', async () => { @@ -480,6 +616,10 @@ describe('RateLimitService', () => { expect(fetchGeminiRateLimits).toHaveBeenCalledWith(true) expect(fetchOpenCodeGoRateLimits).toHaveBeenCalledTimes(1) expect(fetchOpenCodeGoRateLimits).toHaveBeenCalledWith('session=abc123', undefined) + expect(fetchGrokRateLimits).toHaveBeenCalledWith({ + signal: expect.any(AbortSignal), + authReadResult: { status: 'missing' } + }) const state = service.getState() expect(state.claude?.status).toBe('ok') diff --git a/src/main/rate-limits/service.ts b/src/main/rate-limits/service.ts index d270c6773a8a..b3800b318072 100644 --- a/src/main/rate-limits/service.ts +++ b/src/main/rate-limits/service.ts @@ -21,6 +21,8 @@ import { } from '../claude-accounts/runtime-selection' import { fetchGeminiRateLimits } from './gemini-usage-fetcher' import { fetchKimiRateLimits } from './kimi-fetcher' +import { fetchGrokRateLimits } from './grok-fetcher' +import { readGrokAuthSession } from './grok-auth' import { hasMiniMaxSessionCookie } from '../minimax/minimax-cookie-store' import { fetchMiniMaxRateLimits } from './minimax-fetcher' import { fetchOpenCodeGoRateLimits } from './opencode-go-usage-fetcher' @@ -77,7 +79,9 @@ type InternalRateLimitState = { gemini: ProviderRateLimits | null opencodeGo: ProviderRateLimits | null kimi: ProviderRateLimits | null + antigravity: ProviderRateLimits | null minimax: ProviderRateLimits | null + grok: ProviderRateLimits | null } function normalizePollingInterval(ms: number): number { @@ -110,8 +114,11 @@ export class RateLimitService { gemini: null, opencodeGo: null, kimi: null, - minimax: null + antigravity: null, + minimax: null, + grok: null } + private grokAuthConfigured = readGrokAuthSession().status === 'ok' private pollInterval: number = DEFAULT_POLL_MS private timer: ReturnType | null = null private deferredStartupRefreshTimer: ReturnType | null = null @@ -122,6 +129,7 @@ export class RateLimitService { private fullFetchQueued = false private codexOnlyFetchQueued = false private claudeOnlyFetchQueued = false + private grokOnlyFetchQueued = false private activeFetchAbortControllers = new Set() private fetchIdleResolvers: (() => void)[] = [] private codexFetchGeneration = 0 @@ -269,6 +277,7 @@ export class RateLimitService { // its presence on the pushed state so the renderer keeps the MiniMax // bar visible across reloads and between snapshot refreshes. minimaxCookieConfigured: hasMiniMaxSessionCookie(), + grokAuthConfigured: this.grokAuthConfigured, claudeTarget: this.claudeFetchTarget, codexTarget: this.codexFetchTarget, inactiveClaudeAccounts: this.buildInactiveArray( @@ -291,6 +300,11 @@ export class RateLimitService { return this.getState() } + async refreshGrok(): Promise { + await this.fetchGrokOnly({ force: true }) + return this.getState() + } + invalidateMiniMaxCredentialState(): void { this.minimaxFetchGeneration += 1 // Why: saving or forgetting the browser cookie can race an in-flight usage @@ -740,6 +754,15 @@ export class RateLimitService { break } } + if (this.grokOnlyFetchQueued) { + this.grokOnlyFetchQueued = false + const grokSignal = await this.runWithFetchAbortSignal((fetchSignal) => + this.runFetchGrokOnlyCycle(fetchSignal) + ) + if (grokSignal.aborted) { + break + } + } } } finally { this.isFetching = false @@ -790,6 +813,15 @@ export class RateLimitService { break } } + if (this.grokOnlyFetchQueued) { + this.grokOnlyFetchQueued = false + const grokSignal = await this.runWithFetchAbortSignal((fetchSignal) => + this.runFetchGrokOnlyCycle(fetchSignal) + ) + if (grokSignal.aborted) { + break + } + } } } finally { this.isFetching = false @@ -840,6 +872,74 @@ export class RateLimitService { break } } + if (this.grokOnlyFetchQueued) { + this.grokOnlyFetchQueued = false + const grokSignal = await this.runWithFetchAbortSignal((fetchSignal) => + this.runFetchGrokOnlyCycle(fetchSignal) + ) + if (grokSignal.aborted) { + break + } + } + } + } finally { + this.isFetching = false + this.resolveFetchIdleWaiters() + } + } + + private async fetchGrokOnly(options?: { force?: boolean }): Promise { + if (this.isFetching) { + if (options?.force) { + this.grokOnlyFetchQueued = true + return this.waitForFetchIdle() + } + return + } + this.isFetching = true + + try { + let shouldContinue = true + while (shouldContinue) { + const signal = await this.runWithFetchAbortSignal((fetchSignal) => + this.runFetchGrokOnlyCycle(fetchSignal) + ) + shouldContinue = false + if (signal.aborted) { + break + } + if (this.fullFetchQueued) { + this.fullFetchQueued = false + const fullSignal = await this.runWithFetchAbortSignal((fetchSignal) => + this.runFetchAllCycle(fetchSignal) + ) + if (fullSignal.aborted) { + break + } + continue + } + if (this.grokOnlyFetchQueued) { + this.grokOnlyFetchQueued = false + shouldContinue = true + } + if (this.codexOnlyFetchQueued) { + this.codexOnlyFetchQueued = false + const codexSignal = await this.runWithFetchAbortSignal((fetchSignal) => + this.runFetchCodexOnlyCycle(fetchSignal) + ) + if (codexSignal.aborted) { + break + } + } + if (this.claudeOnlyFetchQueued) { + this.claudeOnlyFetchQueued = false + const claudeSignal = await this.runWithFetchAbortSignal((fetchSignal) => + this.runFetchClaudeOnlyCycle(fetchSignal) + ) + if (claudeSignal.aborted) { + break + } + } } } finally { this.isFetching = false @@ -852,7 +952,8 @@ export class RateLimitService { !this.isFetching && !this.fullFetchQueued && !this.codexOnlyFetchQueued && - !this.claudeOnlyFetchQueued + !this.claudeOnlyFetchQueued && + !this.grokOnlyFetchQueued ) { return Promise.resolve() } @@ -869,7 +970,8 @@ export class RateLimitService { this.isFetching || this.fullFetchQueued || this.codexOnlyFetchQueued || - this.claudeOnlyFetchQueued + this.claudeOnlyFetchQueued || + this.grokOnlyFetchQueued ) { return } @@ -913,6 +1015,7 @@ export class RateLimitService { this.fullFetchQueued = false this.codexOnlyFetchQueued = false this.claudeOnlyFetchQueued = false + this.grokOnlyFetchQueued = false } private resolveAndClearFetchIdleWaiters(): void { @@ -1025,7 +1128,15 @@ export class RateLimitService { private withFetchingStatus( current: ProviderRateLimits | null, - provider: 'claude' | 'codex' | 'gemini' | 'opencode-go' | 'kimi' | 'minimax' + provider: + | 'claude' + | 'codex' + | 'gemini' + | 'opencode-go' + | 'kimi' + | 'minimax' + | 'grok' + | 'antigravity' ): ProviderRateLimits { if (!current) { return { @@ -1064,6 +1175,10 @@ export class RateLimitService { const miniMaxGroupId = miniMaxConfigResult.config.groupId const miniMaxModels = miniMaxConfigResult.config.models const geminiCliOAuthEnabled = this.geminiCliOAuthEnabledResolver?.() ?? false + // Why: getState() is used by renderer pushes and mobile snapshots; keep + // Grok's sync auth-file probe on fetch cycles instead of every state read. + const grokAuthReadResult = readGrokAuthSession() + this.grokAuthConfigured = grokAuthReadResult.status === 'ok' // Detect if configuration changed — if it did, we must discard any stale // data because it belongs to a different session/workspace. @@ -1095,14 +1210,24 @@ export class RateLimitService { ? this.withFetchingStatus(null, 'opencode-go') : this.withFetchingStatus(previousState.opencodeGo, 'opencode-go'), kimi: this.withFetchingStatus(previousState.kimi, 'kimi'), + antigravity: this.withFetchingStatus(previousState.antigravity, 'antigravity'), minimax: miniMaxConfigChanged ? this.withFetchingStatus(null, 'minimax') - : this.withFetchingStatus(previousState.minimax, 'minimax') + : this.withFetchingStatus(previousState.minimax, 'minimax'), + grok: this.withFetchingStatus(previousState.grok, 'grok') }) const missingWslCodexHome = codexHomePath ? null : this.getMissingWslCodexHomeResult(codexTarget) + const grokResultPromise = fetchGrokRateLimits({ + signal, + authReadResult: grokAuthReadResult + }).then( + (value) => ({ status: 'fulfilled', value }) as const, + (reason) => ({ status: 'rejected', reason }) as const + ) + const [claudeResult, codexResult, geminiResult, opencodeGoResult, kimiResult, miniMaxResult] = await Promise.allSettled([ fetchClaudeRateLimits({ @@ -1173,6 +1298,14 @@ export class RateLimitService { status: 'error' } satisfies ProviderRateLimits) + // Why: Antigravity shares Google/Gemini usage credentials today; mirror the + // Gemini snapshot under provider 'antigravity' so status-bar UI that checks + // antigravity state receives a real fetch lifecycle instead of staying null. + const antigravity: ProviderRateLimits = { + ...gemini, + provider: 'antigravity' + } + const opencodeGo = opencodeGoResult.status === 'fulfilled' ? opencodeGoResult.value @@ -1237,7 +1370,7 @@ export class RateLimitService { // generation still match, otherwise an old account could overwrite the // newly selected account's quota state. this.updateState({ - ...previousState, + ...this.state, claude: shouldApplyClaude ? this.applyStalePolicy(claude, previousState.claude) : this.state.claude, @@ -1251,6 +1384,7 @@ export class RateLimitService { : this.applyStalePolicy(opencodeGo, previousState.opencodeGo) : this.state.opencodeGo, kimi: this.applyStalePolicy(kimi, previousState.kimi), + antigravity: this.applyStalePolicy(antigravity, previousState.antigravity), minimax: shouldApplyMiniMax ? miniMaxConfigChanged ? miniMax @@ -1258,6 +1392,26 @@ export class RateLimitService { : this.state.minimax }) + const grokResult = await grokResultPromise + if (signal.aborted) { + return + } + const grok = + grokResult.status === 'fulfilled' + ? grokResult.value + : ({ + provider: 'grok', + session: null, + weekly: null, + updatedAt: Date.now(), + error: grokResult.reason instanceof Error ? grokResult.reason.message : 'Unknown error', + status: 'error' + } satisfies ProviderRateLimits) + this.updateState({ + ...this.state, + grok: this.applyStalePolicy(grok, previousState.grok) + }) + this.lastFetchAt = Date.now() } @@ -1374,6 +1528,45 @@ export class RateLimitService { this.lastFetchAt = Date.now() } + private async runFetchGrokOnlyCycle(signal: AbortSignal): Promise { + if (signal.aborted) { + return + } + const previousState = this.state + const grokAuthReadResult = readGrokAuthSession() + this.grokAuthConfigured = grokAuthReadResult.status === 'ok' + + this.updateState({ + ...previousState, + grok: this.withFetchingStatus(previousState.grok, 'grok') + }) + + const grok = await fetchGrokRateLimits({ + signal, + authReadResult: grokAuthReadResult + }).catch( + (err): ProviderRateLimits => ({ + provider: 'grok', + session: null, + weekly: null, + updatedAt: Date.now(), + error: err instanceof Error ? err.message : 'Unknown error', + status: 'error' + }) + ) + + if (signal.aborted) { + return + } + + this.updateState({ + ...this.state, + grok: this.applyStalePolicy(grok, previousState.grok) + }) + + this.lastFetchAt = Date.now() + } + private applyStalePolicy( fresh: ProviderRateLimits, previous: ProviderRateLimits | null diff --git a/src/main/repo-worktrees.test.ts b/src/main/repo-worktrees.test.ts index fd905bacf08b..3c6910991f00 100644 --- a/src/main/repo-worktrees.test.ts +++ b/src/main/repo-worktrees.test.ts @@ -60,17 +60,21 @@ describe('repo-worktrees', () => { listWorktreesMock.mockResolvedValue([ { path: '/workspace/repo', head: 'abc', branch: '', isBare: false, isMainWorktree: true } ]) + const signal = new AbortController().signal - const result = await listRepoWorktrees({ - id: 'repo-1', - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - kind: 'git' - }) + const result = await listRepoWorktrees( + { + id: 'repo-1', + path: '/workspace/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + kind: 'git' + }, + { signal } + ) - expect(listWorktreesMock).toHaveBeenCalledWith('/workspace/repo') + expect(listWorktreesMock).toHaveBeenCalledWith('/workspace/repo', { signal }) expect(result).toHaveLength(1) }) diff --git a/src/main/repo-worktrees.ts b/src/main/repo-worktrees.ts index e02ba35f9c7d..4f45e7d85641 100644 --- a/src/main/repo-worktrees.ts +++ b/src/main/repo-worktrees.ts @@ -9,6 +9,10 @@ type LocalRepoWorktreeListOptions = { signal?: AbortSignal } +function hasLocalRepoWorktreeListOptions(options: LocalRepoWorktreeListOptions | undefined) { + return options?.wslDistro !== undefined || options?.signal !== undefined +} + export function isRepoRoot(repos: Repo[], resolvedTarget: string): boolean { return repos.some( (repo) => !repo.connectionId && areWorktreePathsEqual(repo.path, resolvedTarget) @@ -30,7 +34,7 @@ export function createFolderWorktree(repo: Repo): GitWorktreeInfo { export async function listRepoWorktrees( repo: Repo, - options: LocalRepoWorktreeListOptions = {} + options?: LocalRepoWorktreeListOptions ): Promise { if (isFolderRepo(repo)) { return [createFolderWorktree(repo)] @@ -42,7 +46,7 @@ export async function listRepoWorktrees( // local git against a server path. return provider ? await provider.listWorktrees(repo.path) : [] } - return options.wslDistro + return hasLocalRepoWorktreeListOptions(options) ? await listWorktrees(repo.path, options) : await listWorktrees(repo.path) } diff --git a/src/main/runtime/fetch-remote-cache.test.ts b/src/main/runtime/fetch-remote-cache.test.ts index fce2a5e6d599..14c181156364 100644 --- a/src/main/runtime/fetch-remote-cache.test.ts +++ b/src/main/runtime/fetch-remote-cache.test.ts @@ -22,10 +22,19 @@ vi.mock('../git/runner', async (importOriginal) => { // normally — none of them trigger IO until a runtime method is called. import { OrcaRuntimeService } from './orca-runtime' +function isFetchArgs(argv: unknown): argv is string[] { + if (!Array.isArray(argv)) { + return false + } + let commandIndex = 0 + while (argv[commandIndex] === '-c' && typeof argv[commandIndex + 1] === 'string') { + commandIndex += 2 + } + return argv[commandIndex] === 'fetch' +} + function fetchCallCount(): number { - return gitExecFileAsyncMock.mock.calls.filter( - ([argv]) => Array.isArray(argv) && argv[0] === 'fetch' - ).length + return gitExecFileAsyncMock.mock.calls.filter(([argv]) => isFetchArgs(argv)).length } function exactBaseRefreshOptions(cwd: string): { @@ -36,6 +45,21 @@ function exactBaseRefreshOptions(cwd: string): { return { cwd, timeout: 60_000, useConfiguredSshCommandForNetwork: true } } +function exactBaseRefreshArgs(branch = 'main'): string[] { + return [ + '-c', + 'maintenance.auto=false', + '-c', + 'maintenance.commit-graph.auto=0', + '-c', + 'gc.auto=0', + 'fetch', + '--no-tags', + 'origin', + `+refs/heads/${branch}:refs/remotes/origin/${branch}` + ] +} + // Why (STA-1292): the broad create-path fetch must carry a timeout so a Windows // credential-manager GUI hang can't wedge worktree creation forever. function fullRemoteFetchOptions(cwd: string): { cwd: string; timeout: number } { @@ -188,11 +212,23 @@ describe('OrcaRuntimeService.fetchRemoteWithCache', () => { }) expect(gitExecFileAsyncMock).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main'], + exactBaseRefreshArgs(), exactBaseRefreshOptions('/repo/f') ) }) + it('keeps automatic maintenance enabled for ordinary full remote fetches', async () => { + mockFetchResults([{ stdout: '', stderr: '' }]) + const runtime = new OrcaRuntimeService(null) + + await runtime.getOrStartRemoteFetch('/repo/full-maintenance', 'origin') + + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['fetch', 'origin'], + fullRemoteFetchOptions('/repo/full-maintenance') + ) + }) + it('shares an in-flight remote-tracking base refresh and reuses exact-base freshness', async () => { let resolveFetch!: () => void const pending = new Promise<{ stdout: string; stderr: string }>((resolve) => { @@ -297,14 +333,9 @@ describe('OrcaRuntimeService.fetchRemoteWithCache', () => { { ok: true }, { ok: true } ]) - const fetchCalls = gitExecFileAsyncMock.mock.calls.filter( - ([argv]) => Array.isArray(argv) && argv[0] === 'fetch' - ) + const fetchCalls = gitExecFileAsyncMock.mock.calls.filter(([argv]) => isFetchArgs(argv)) expect(fetchCalls).toEqual([ - [ - ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main'], - exactBaseRefreshOptions('/repo/h') - ], + [exactBaseRefreshArgs(), exactBaseRefreshOptions('/repo/h')], [['fetch', 'origin'], fullRemoteFetchOptions('/repo/h')] ]) }) @@ -343,15 +374,10 @@ describe('OrcaRuntimeService.fetchRemoteWithCache', () => { { ok: true }, { ok: true } ]) - const fetchCalls = gitExecFileAsyncMock.mock.calls.filter( - ([argv]) => Array.isArray(argv) && argv[0] === 'fetch' - ) + const fetchCalls = gitExecFileAsyncMock.mock.calls.filter(([argv]) => isFetchArgs(argv)) expect(fetchCalls).toEqual([ [['fetch', 'origin'], fullRemoteFetchOptions('/repo/i')], - [ - ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main'], - exactBaseRefreshOptions('/repo/i') - ] + [exactBaseRefreshArgs(), exactBaseRefreshOptions('/repo/i')] ]) }) @@ -389,15 +415,10 @@ describe('OrcaRuntimeService.fetchRemoteWithCache', () => { { ok: false, errorKind: 'git_error' }, { ok: true } ]) - const fetchCalls = gitExecFileAsyncMock.mock.calls.filter( - ([argv]) => Array.isArray(argv) && argv[0] === 'fetch' - ) + const fetchCalls = gitExecFileAsyncMock.mock.calls.filter(([argv]) => isFetchArgs(argv)) expect(fetchCalls).toEqual([ [['fetch', 'origin'], fullRemoteFetchOptions('/repo/i-fail')], - [ - ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main'], - exactBaseRefreshOptions('/repo/i-fail') - ] + [exactBaseRefreshArgs(), exactBaseRefreshOptions('/repo/i-fail')] ]) }) }) diff --git a/src/main/runtime/file-watcher-host.ts b/src/main/runtime/file-watcher-host.ts index 3bbfc0ab1e03..f368ea270e23 100644 --- a/src/main/runtime/file-watcher-host.ts +++ b/src/main/runtime/file-watcher-host.ts @@ -13,10 +13,10 @@ import type { FileWatcherHostMessage, FileWatcherWorkerMessage } from './file-wa // exclusions silently fail and fseventsd delivers full node_modules churn. import { WATCHER_IGNORE_DIRS, - buildParcelWatcherIgnoreOption + buildParcelWatcherIgnoreOptions } from '../ipc/filesystem-watcher-ignore' -const RUNTIME_FILE_WATCH_IGNORE = buildParcelWatcherIgnoreOption(WATCHER_IGNORE_DIRS) +const RUNTIME_FILE_WATCH_IGNORE_OPTIONS = buildParcelWatcherIgnoreOptions(WATCHER_IGNORE_DIRS) // Why: clean teardown is async (the worker awaits subscription.unsubscribe() // before closing its port and exiting). Wait this long for the worker to exit on @@ -66,7 +66,7 @@ export function watchFileExplorerInWorker( ): Promise<() => Promise> { return new Promise((resolve, reject) => { const worker = new Worker(getFileWatcherWorkerPath(), { - workerData: { rootPath, ignore: RUNTIME_FILE_WATCH_IGNORE } + workerData: { rootPath, ignoreOptions: RUNTIME_FILE_WATCH_IGNORE_OPTIONS } }) let ready = false diff --git a/src/main/runtime/file-watcher-worker.ts b/src/main/runtime/file-watcher-worker.ts index ec7e9141b161..9fd8e17cb777 100644 --- a/src/main/runtime/file-watcher-worker.ts +++ b/src/main/runtime/file-watcher-worker.ts @@ -10,13 +10,14 @@ import { stat } from 'node:fs/promises' import { parentPort, workerData } from 'node:worker_threads' import type * as ParcelWatcher from '@parcel/watcher' import type { FsChangeEvent } from '../../shared/types' +import type { ParcelWatcherIgnoreOptions } from '../ipc/filesystem-watcher-ignore' const RUNTIME_FILE_WATCH_EVENT_STAT_LIMIT = 200 const RUNTIME_FILE_WATCH_STAT_CONCURRENCY = 8 type FileWatcherWorkerData = { rootPath: string - ignore: string[] + ignoreOptions: ParcelWatcherIgnoreOptions } // Messages the worker sends back to the host. @@ -117,7 +118,7 @@ async function main(): Promise { // rejection that crashes the worker silently. Surface it instead. .catch((err: unknown) => reportWatchError(err)) }, - { ignore: data.ignore } + data.ignoreOptions as ParcelWatcher.Options ) // The crawl finished and the subscription is live. diff --git a/src/main/runtime/mobile-presence-lock.test.ts b/src/main/runtime/mobile-presence-lock.test.ts index 56581919edc2..eddb3f299cf6 100644 --- a/src/main/runtime/mobile-presence-lock.test.ts +++ b/src/main/runtime/mobile-presence-lock.test.ts @@ -74,13 +74,21 @@ const store = { }) } -function createRuntime() { - const runtime = new OrcaRuntimeService(store) +// Why (#7588): the held-modal repro needs indefinite hold (null) while the +// legacy tests rely on the finite 5s default. Wrap getSettings per-test so a +// caller can pick the hold without mutating the shared stub. +function createRuntime(mobileAutoRestoreFitMs: number | null = 5_000) { + const effectiveStore = { + ...store, + getSettings: () => ({ ...store.getSettings(), mobileAutoRestoreFitMs }) + } + const runtime = new OrcaRuntimeService(effectiveStore) const ptySizes = new Map([ ['pty-1', { cols: 150, rows: 40 }] ]) const resizes: { ptyId: string; cols: number; rows: number }[] = [] const driverEvents: { ptyId: string; driver: { kind: string; clientId?: string } }[] = [] + const fitOverrideEvents: { ptyId: string; mode: string; cols: number; rows: number }[] = [] let resizeSucceeds = true runtime.setPtyController({ @@ -107,7 +115,9 @@ function createRuntime() { focusTerminal: vi.fn(), closeTerminal: vi.fn(), sleepWorktree: vi.fn(), - terminalFitOverrideChanged: vi.fn(), + terminalFitOverrideChanged: (ptyId, mode, cols, rows) => { + fitOverrideEvents.push({ ptyId, mode, cols, rows }) + }, terminalDriverChanged: (ptyId, driver) => { driverEvents.push({ ptyId, driver: { ...driver } }) } @@ -118,6 +128,7 @@ function createRuntime() { ptySizes, resizes, driverEvents, + fitOverrideEvents, setResizeSucceeds: (next: boolean) => { resizeSucceeds = next } @@ -314,11 +325,12 @@ describe('mobile presence lock — multi-mobile semantics', () => { }) it('updateMobileViewport re-fits PTY without flipping the driver', async () => { - const { runtime, ptySizes, driverEvents } = createRuntime() + const { runtime, ptySizes, driverEvents, fitOverrideEvents } = createRuntime() await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 38 }) expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 38 }) expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' }) const before = driverEvents.length + const fitEventsBefore = fitOverrideEvents.length // Keyboard opens — viewport shrinks. await expect( @@ -330,6 +342,10 @@ describe('mobile presence lock — multi-mobile semantics', () => { // Why: a viewport update may re-emit driver to refresh listener // wiring, but it must never go through `idle` (no banner flash). expect(driverEvents.slice(before).every((e) => e.driver.kind === 'mobile')).toBe(true) + // Why: phone→phone dim ticks (keyboard show/hide) are the hottest layout + // path and must not wake the renderer's fit-override listeners — the + // emit gate opens only when layout kind or override presence changes. + expect(fitOverrideEvents.length).toBe(fitEventsBefore) }) it('updateMobileViewport late-binds a viewport-less mobile subscriber', async () => { @@ -467,3 +483,242 @@ describe('mobile presence lock — multi-mobile semantics', () => { expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) }) }) + +// Why (#7588): drive the runtime into the reported held-modal state — a phone +// fit that an indefinite hold left behind, followed by a null-viewport +// resubscribe (app update / WebView reload) that re-registers an active +// subscriber with wasResizedToPhone=false while the override is still held. +// This is the state where the desktop "Your phone left this at phone size" +// modal's Restore buttons used to silently no-op. +async function reachHeldModalWithNullViewportResubscribe( + runtime: OrcaRuntimeService +): Promise { + await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) + runtime.handleMobileUnsubscribe('pty-1', 'phone-A') + await vi.advanceTimersByTimeAsync(300) + // Production RPC passes `params.viewport` straight through, so a client + // that hasn't measured yet arrives here as `undefined`. + await runtime.handleMobileSubscribe('pty-1', 'phone-A', undefined) +} + +describe('mobile presence lock — issue #7588 held-modal restore convergence', () => { + beforeEach(() => vi.useFakeTimers()) + afterEach(() => vi.useRealTimers()) + + // Scenario 1: the reported repro end-to-end. Restore must converge and + // notify BOTH the renderer notifier and a runtime listener (paired), since + // remote/web viewers ride the listener channel. + it('reclaim after a null-viewport resubscribe restores dims, clears override, notifies both channels', async () => { + const { runtime, ptySizes, fitOverrideEvents } = createRuntime(null) + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await reachHeldModalWithNullViewportResubscribe(runtime) + // Held state: driver idle, override still present, phone-sized PTY. + expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' }) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 }) + + const notifierBefore = fitOverrideEvents.length + const listenerBefore = listenerEvents.length + const restored = await runtime.reclaimTerminalForDesktop('pty-1') + + expect(restored).toBe(true) + expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(fitOverrideEvents.slice(notifierBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + expect(listenerEvents.slice(listenerBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + }) + + // Scenario 2: a second click after success is an idempotent no-op. The + // persistent null-viewport subscriber keeps reclaim in the active-subscriber + // branch; assert only "returns true, no new PTY resize, no new fit-override + // event" — a benign mobile-facing mode-change notify is acceptable. + it('second Restore click after success returns true with no new resize or fit-override event', async () => { + const { runtime, resizes, fitOverrideEvents } = createRuntime(null) + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await reachHeldModalWithNullViewportResubscribe(runtime) + expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(true) + + const resizeCount = resizes.length + const notifierCount = fitOverrideEvents.length + const listenerCount = listenerEvents.length + + expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(true) + expect(resizes.length).toBe(resizeCount) + expect(fitOverrideEvents.length).toBe(notifierCount) + expect(listenerEvents.length).toBe(listenerCount) + }) + + // Scenario 3: the existing driving take-back is unregressed — a phone that is + // actively driving (wasResizedToPhone=true) still flips to desktop, clears + // the override, and notifies both channels. + it('driving take-back still converges: driver → desktop, override cleared, both channels notified', async () => { + const { runtime, ptySizes, fitOverrideEvents } = createRuntime() + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) + expect(runtime.getDriver('pty-1').kind).toBe('mobile') + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + + const restored = await runtime.reclaimTerminalForDesktop('pty-1') + + expect(restored).toBe(true) + expect(runtime.getDriver('pty-1')).toEqual({ kind: 'desktop' }) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) + expect(fitOverrideEvents.some((e) => e.mode === 'desktop-fit')).toBe(true) + expect(listenerEvents.some((e) => e.mode === 'desktop-fit')).toBe(true) + }) + + // Scenario 4: an explicit take-back on a HELD (no-subscriber) override must + // ALWAYS release, even when the desktop resize fails. The override is cleared + // optimistically with a paired desktop-fit 0×0 so the banner can't linger; the + // desktop renderer refits the PTY on its next settled frame. (The gesture + // deliberately overrides #7588's keep-lock-on-failed-resize rule, which still + // governs the auto-restore and phone-initiated paths.) + it('held restore with a failing resize still releases and clears the override', async () => { + const { runtime, fitOverrideEvents, setResizeSucceeds } = createRuntime(null) + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) + // Last leaver under indefinite hold → override held, no active subscriber. + runtime.handleMobileUnsubscribe('pty-1', 'phone-A') + await vi.advanceTimersByTimeAsync(300) + expect(runtime.isMobileSubscriberActive('pty-1')).toBe(false) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + + const notifierBefore = fitOverrideEvents.length + const listenerBefore = listenerEvents.length + setResizeSucceeds(false) + + const restored = await runtime.reclaimTerminalForDesktop('pty-1') + + expect(restored).toBe(true) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(fitOverrideEvents.slice(notifierBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + expect(listenerEvents.slice(listenerBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + }) + + // Scenario 5: an explicit ACTIVE-SUBSCRIBER take-back with a failing resize + // must still release — driver → desktop, override cleared, banner dismissed, + // mode reset to 'auto'. This is the "take back all terminals" guarantee: a + // background PTY that can't converge must not strand its banner. + it('active-subscriber take-back with a failing resize still releases the lock', async () => { + const { runtime, fitOverrideEvents, setResizeSucceeds } = createRuntime() + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) + expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' }) + + const notifierBefore = fitOverrideEvents.length + const listenerBefore = listenerEvents.length + setResizeSucceeds(false) + + const restored = await runtime.reclaimTerminalForDesktop('pty-1') + + expect(restored).toBe(true) + // Lock released and banner dismissed despite the failed resize. + expect(runtime.getDriver('pty-1')).toEqual({ kind: 'desktop' }) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(runtime.getMobileDisplayMode('pty-1')).toBe('auto') + expect(fitOverrideEvents.slice(notifierBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + expect(listenerEvents.slice(listenerBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + }) + + // Scenario 5b: the failed-resize take-back leaves NO stranded phone-fit — + // driver released to desktop, override cleared, mode reset to 'auto'. (The + // pre-revision behavior kept the lock and relied on a later auto-restore; the + // explicit gesture now releases unconditionally.) + it('failed take-back leaves no stranded override or lock', async () => { + const { runtime, setResizeSucceeds } = createRuntime() + + await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 }) + + setResizeSucceeds(false) + expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(true) + + expect(runtime.getDriver('pty-1')).toEqual({ kind: 'desktop' }) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(runtime.getMobileDisplayMode('pty-1')).toBe('auto') + }) + + // Scenario 6: a phone-initiated setDisplayMode('desktop') against a stale + // held override converges through the shared applyMobileDisplayMode seam. + it('phone-initiated setDisplayMode(desktop) against a stale held override converges', async () => { + const { runtime, ptySizes, fitOverrideEvents } = createRuntime(null) + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + await reachHeldModalWithNullViewportResubscribe(runtime) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + + const notifierBefore = fitOverrideEvents.length + const listenerBefore = listenerEvents.length + + runtime.setMobileDisplayMode('pty-1', 'desktop') + const converged = await runtime.applyMobileDisplayMode('pty-1') + + expect(converged).toBe(true) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 }) + expect(fitOverrideEvents.slice(notifierBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + expect(listenerEvents.slice(listenerBefore).some((e) => e.mode === 'desktop-fit')).toBe(true) + }) + + // Scenario 7 (white-box): a held override whose `layouts` entry is gone is + // unreachable via public APIs (onPtyExit deletes both in lockstep), so seed + // it directly. Reclaim must still delete the override and emit a paired + // desktop-fit 0×0 rather than stranding the modal on the next hydrate. + it('orphan cleanup: reclaim on a held override with no layout entry converges', async () => { + const { runtime, fitOverrideEvents } = createRuntime(null) + const listenerEvents: { mode: string; cols: number; rows: number }[] = [] + runtime.subscribeToFitOverrideChanges('pty-1', (e) => listenerEvents.push(e)) + + const internal = runtime as unknown as { + terminalFitOverrides: Map< + string, + { + mode: string + cols: number + rows: number + previousCols: number | null + previousRows: number | null + updatedAt: number + clientId: string + } + > + } + internal.terminalFitOverrides.set('pty-1', { + mode: 'mobile-fit', + cols: 45, + rows: 20, + previousCols: 150, + previousRows: 40, + updatedAt: Date.now(), + clientId: 'phone-A' + }) + expect(runtime.getTerminalFitOverride('pty-1')).not.toBeNull() + + const restored = await runtime.reclaimTerminalForDesktop('pty-1') + + expect(restored).toBe(true) + expect(runtime.getTerminalFitOverride('pty-1')).toBeNull() + expect(fitOverrideEvents.find((e) => e.mode === 'desktop-fit')).toEqual({ + ptyId: 'pty-1', + mode: 'desktop-fit', + cols: 0, + rows: 0 + }) + expect(listenerEvents.find((e) => e.mode === 'desktop-fit')).toEqual({ + mode: 'desktop-fit', + cols: 0, + rows: 0 + }) + }) +}) diff --git a/src/main/runtime/mobile-session-tabs-notify-coalescer.test.ts b/src/main/runtime/mobile-session-tabs-notify-coalescer.test.ts new file mode 100644 index 000000000000..44216e64d737 --- /dev/null +++ b/src/main/runtime/mobile-session-tabs-notify-coalescer.test.ts @@ -0,0 +1,120 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createMobileSessionTabsNotifyCoalescer } from './mobile-session-tabs-notify-coalescer' + +describe('createMobileSessionTabsNotifyCoalescer', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('coalesces a rapid burst of title/status flips into one trailing emit (repro)', () => { + // Repro of the churn bug: a spinner-in-title agent flips a PTY title many + // times a second. Without coalescing every flip fans out an emit; with it, + // the whole burst settles into a single trailing-edge emit per worktree. + const emit = vi.fn() + const coalescer = createMobileSessionTabsNotifyCoalescer(emit) + + const FLIPS = 20 + for (let i = 0; i < FLIPS; i++) { + coalescer.schedule('worktree-1') + // Each flip lands well inside the trailing window, resetting the timer. + vi.advanceTimersByTime(10) + } + expect(emit).not.toHaveBeenCalled() + + // Let the trailing window elapse after the last flip. + vi.advanceTimersByTime(50) + + expect(emit).toHaveBeenCalledTimes(1) + expect(emit).toHaveBeenCalledWith('worktree-1') + }) + + it('force-flushes under sustained churn so the emit is never starved', () => { + const emit = vi.fn() + const coalescer = createMobileSessionTabsNotifyCoalescer(emit) + + // Keep flipping faster than the trailing window forever; the max-wait cap + // (250ms) must force at least one emit within that budget. + for (let i = 0; i < 100; i++) { + coalescer.schedule('worktree-1') + vi.advanceTimersByTime(30) + } + + expect(emit).toHaveBeenCalled() + expect(emit).toHaveBeenCalledWith('worktree-1') + }) + + it('keeps per-worktree windows independent', () => { + const emit = vi.fn() + const coalescer = createMobileSessionTabsNotifyCoalescer(emit) + + coalescer.schedule('worktree-1') + coalescer.schedule('worktree-2') + vi.advanceTimersByTime(50) + + expect(emit).toHaveBeenCalledTimes(2) + expect(emit).toHaveBeenCalledWith('worktree-1') + expect(emit).toHaveBeenCalledWith('worktree-2') + }) + + it('cancel() drops a pending notify so a structural emit can supersede it', () => { + const emit = vi.fn() + const coalescer = createMobileSessionTabsNotifyCoalescer(emit) + + coalescer.schedule('worktree-1') + // A structural change (tab add/remove) cancels the coalesced notify because + // it emits immediately elsewhere. + coalescer.cancel('worktree-1') + vi.advanceTimersByTime(50) + + expect(emit).not.toHaveBeenCalled() + }) + + it('flush() emits the pending notify immediately', () => { + const emit = vi.fn() + const coalescer = createMobileSessionTabsNotifyCoalescer(emit) + + coalescer.schedule('worktree-1') + coalescer.flush('worktree-1') + + expect(emit).toHaveBeenCalledTimes(1) + // The timer must not double-fire afterward. + vi.advanceTimersByTime(50) + expect(emit).toHaveBeenCalledTimes(1) + }) + + it('flush() is a no-op when nothing is pending', () => { + const emit = vi.fn() + const coalescer = createMobileSessionTabsNotifyCoalescer(emit) + + coalescer.flush('worktree-1') + + expect(emit).not.toHaveBeenCalled() + }) + + it('flushAll() drains every pending worktree (subscription close)', () => { + const emit = vi.fn() + const coalescer = createMobileSessionTabsNotifyCoalescer(emit) + + coalescer.schedule('worktree-1') + coalescer.schedule('worktree-2') + coalescer.flushAll() + + expect(emit).toHaveBeenCalledTimes(2) + vi.advanceTimersByTime(50) + expect(emit).toHaveBeenCalledTimes(2) + }) + + it('dispose() drops pending timers without emitting', () => { + const emit = vi.fn() + const coalescer = createMobileSessionTabsNotifyCoalescer(emit) + + coalescer.schedule('worktree-1') + coalescer.dispose() + vi.advanceTimersByTime(50) + + expect(emit).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/runtime/mobile-session-tabs-notify-coalescer.ts b/src/main/runtime/mobile-session-tabs-notify-coalescer.ts new file mode 100644 index 000000000000..ac6608b71fb0 --- /dev/null +++ b/src/main/runtime/mobile-session-tabs-notify-coalescer.ts @@ -0,0 +1,109 @@ +// Why: spinner-in-title agents (e.g. the Claude Code braille spinner) flip a +// PTY title several times per second. Each flip touched every session.tabs +// snapshot and fanned a fresh emit out to every subscriber, where the ws layer +// JSON.stringifies it per client — O(clients × snapshot size) of churn work +// with no debounce. Clients gate on snapshotVersion freshness, so only the +// newest version per worktree matters; coalescing the intermediate emits is +// safe. Structural changes (tab added/removed/activated) bypass this via an +// immediate flush so they still propagate promptly. + +// Trailing-edge window: title/status is latency-sensitive UI, so this is +// tighter than files.watch's 150ms but looser than native-chat's 40ms. +const SESSION_TABS_FLUSH_MS = 50 +// Force a flush after this long even under sustained churn, so a title that +// keeps spinning never starves the emit indefinitely. +const SESSION_TABS_MAX_WAIT_MS = 250 + +export type MobileSessionTabsNotifyCoalescer = { + // Schedule a coalesced (trailing-edge) notify for a worktree. + schedule: (worktreeId: string) => void + // Cancel any pending notify for a worktree without emitting. Use when an + // immediate emit has already superseded the pending state, or the worktree + // was removed and a stale notify must not fire. + cancel: (worktreeId: string) => void + // Flush a worktree's pending notify now (emit if one is pending). + flush: (worktreeId: string) => void + // Flush every pending worktree now. + flushAll: () => void + // Drop all pending state without emitting (runtime teardown). + dispose: () => void +} + +type PendingNotify = { + timer: ReturnType + firstScheduledAt: number +} + +/** + * Coalesces per-worktree session.tabs notifications on a short trailing-edge + * window. `emit` is invoked once per settled worktree and is expected to read + * the latest snapshot itself, so only the freshest snapshotVersion is ever + * published — dropped intermediate versions are exactly what clients discard. + */ +export function createMobileSessionTabsNotifyCoalescer( + emit: (worktreeId: string) => void +): MobileSessionTabsNotifyCoalescer { + const pending = new Map() + + const clear = (worktreeId: string): void => { + const entry = pending.get(worktreeId) + if (!entry) { + return + } + clearTimeout(entry.timer) + pending.delete(worktreeId) + } + + const fire = (worktreeId: string): void => { + clear(worktreeId) + emit(worktreeId) + } + + const arm = (worktreeId: string): ReturnType => { + const timer = setTimeout(() => fire(worktreeId), SESSION_TABS_FLUSH_MS) + if (typeof timer.unref === 'function') { + timer.unref() + } + return timer + } + + return { + schedule(worktreeId: string): void { + const now = Date.now() + const existing = pending.get(worktreeId) + if (existing) { + // Cap total delay so sustained churn can't starve the emit forever. + if (now - existing.firstScheduledAt >= SESSION_TABS_MAX_WAIT_MS) { + fire(worktreeId) + return + } + clearTimeout(existing.timer) + existing.timer = arm(worktreeId) + return + } + pending.set(worktreeId, { timer: arm(worktreeId), firstScheduledAt: now }) + }, + cancel(worktreeId: string): void { + clear(worktreeId) + }, + flush(worktreeId: string): void { + if (pending.has(worktreeId)) { + fire(worktreeId) + } + }, + flushAll(): void { + // Snapshot keys first: fire() deletes from `pending`, and emit may + // schedule new work, so mutating the live map mid-iteration is unsafe. + const worktreeIds = Array.from(pending.keys()) + for (const worktreeId of worktreeIds) { + fire(worktreeId) + } + }, + dispose(): void { + for (const entry of pending.values()) { + clearTimeout(entry.timer) + } + pending.clear() + } + } +} diff --git a/src/main/runtime/mobile-subscribe-integration.test.ts b/src/main/runtime/mobile-subscribe-integration.test.ts index 3d36716dd5e0..6c3192710886 100644 --- a/src/main/runtime/mobile-subscribe-integration.test.ts +++ b/src/main/runtime/mobile-subscribe-integration.test.ts @@ -5,6 +5,7 @@ */ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import type * as GitUsernameModule from '../git/git-username' +import type { RuntimeMobileSessionTabsSnapshot } from '../../shared/runtime-types' import { OrcaRuntimeService } from './orca-runtime' vi.mock('../git/worktree', () => ({ @@ -983,4 +984,109 @@ describe('mobile subscribe integration', () => { expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(false) }) }) + + describe('session.tabs title/status churn coalescing', () => { + type SessionTabsPrivate = { + mobileSessionTabsByWorktree: Map + touchMobileSessionSnapshotsForPty: (ptyId: string) => void + notifyMobileSessionTabsChanged: (worktreeId?: string) => void + } + + function seedPtyBackedSnapshot(runtime: OrcaRuntimeService, ptyId: string): void { + const priv = runtime as unknown as SessionTabsPrivate + priv.mobileSessionTabsByWorktree.set('worktree-a', { + worktree: 'worktree-a', + publicationEpoch: 'epoch-1', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: 'tab-1', + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: 'tab-1', + title: 'agent', + parentTabId: 'group-1', + leafId: 'leaf-1', + ptyId, + isActive: true + } + ] + }) + } + + it('collapses a rapid title-flip burst into a single emit (repro)', () => { + const { runtime } = createRuntime() + seedPtyBackedSnapshot(runtime, 'pty-1') + const priv = runtime as unknown as SessionTabsPrivate + + const emits: number[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => { + emits.push(snapshot.snapshotVersion) + }) + + // A spinner-in-title agent flips the title ~20 times within a second. + const FLIPS = 20 + for (let i = 0; i < FLIPS; i++) { + priv.touchMobileSessionSnapshotsForPty('pty-1') + vi.advanceTimersByTime(10) + } + // Nothing has fired yet — all flips landed inside the trailing window. + expect(emits).toHaveLength(0) + + vi.advanceTimersByTime(50) + + // Pre-fix this fanned out one emit per flip; now it is a single emit. + expect(emits).toHaveLength(1) + // The emitted version is the freshest (monotonic, never a stale one). + const stored = priv.mobileSessionTabsByWorktree.get('worktree-a') + expect(emits[0]).toBe(stored?.snapshotVersion) + expect(emits[0]).toBe(1 + FLIPS) + + unsubscribe() + }) + + it('lets a structural change emit immediately and supersede the coalesced notify', () => { + const { runtime } = createRuntime() + seedPtyBackedSnapshot(runtime, 'pty-1') + const priv = runtime as unknown as SessionTabsPrivate + + const emits: number[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => { + emits.push(snapshot.snapshotVersion) + }) + + // Title churn schedules a coalesced notify... + priv.touchMobileSessionSnapshotsForPty('pty-1') + // ...then a structural change (e.g. tab activated) demands a prompt emit. + priv.notifyMobileSessionTabsChanged('worktree-a') + expect(emits).toHaveLength(1) + + // The pending coalesced notify was cancelled by the immediate emit, so no + // duplicate trailing emit fires. + vi.advanceTimersByTime(50) + expect(emits).toHaveLength(1) + + unsubscribe() + }) + + it('flushes a pending notify when the last subscriber closes', () => { + const { runtime } = createRuntime() + seedPtyBackedSnapshot(runtime, 'pty-1') + const priv = runtime as unknown as SessionTabsPrivate + + const emits: number[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => { + emits.push(snapshot.snapshotVersion) + }) + + priv.touchMobileSessionSnapshotsForPty('pty-1') + expect(emits).toHaveLength(0) + + // Closing the subscription flushes the pending window so the final state + // still reaches the listener before it is dropped. + unsubscribe() + expect(emits).toHaveLength(1) + }) + }) }) diff --git a/src/main/runtime/orca-runtime-terminal-cwd.test.ts b/src/main/runtime/orca-runtime-terminal-cwd.test.ts index 214d2a20894e..976b8169fdc1 100644 --- a/src/main/runtime/orca-runtime-terminal-cwd.test.ts +++ b/src/main/runtime/orca-runtime-terminal-cwd.test.ts @@ -52,7 +52,7 @@ describe('OrcaRuntimeService terminal startup cwd', () => { ) }) - it('rejects requested terminal cwd values outside the selected worktree', async () => { + it('spawns terminals at a requested cwd outside the selected worktree (#7685)', async () => { const runtime = new OrcaRuntimeService() stubLaunchScope(runtime) const spawn = vi.fn().mockResolvedValue({ id: 'pty-1' }) @@ -63,10 +63,14 @@ describe('OrcaRuntimeService terminal startup cwd', () => { getForegroundProcess: async () => null }) - await expect(runtime.createTerminal('id:wt-1', { cwd: '/repo/app-other' })).rejects.toThrow( - 'Terminal cwd must be inside the selected worktree.' + await runtime.createTerminal('id:wt-1', { cwd: '/repo/app-other' }) + + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: '/repo/app-other', + worktreeId: 'wt-1' + }) ) - expect(spawn).not.toHaveBeenCalled() }) it('reveals main-spawned terminals with their nested startup cwd', async () => { diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index d2655b3d3723..2b515e230bb9 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -5,6 +5,7 @@ import { performance } from 'node:perf_hooks' import { EventEmitter } from 'node:events' import { randomUUID } from 'node:crypto' import { execFileSync } from 'node:child_process' +import { mkdirSync } from 'node:fs' import { lstat, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { homedir, tmpdir } from 'node:os' import { join } from 'node:path' @@ -20,7 +21,7 @@ import type { WorkspaceSessionState } from '../../shared/types' import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status-types' -import { MAX_OSC_TITLE_CHARS } from '../../shared/agent-detection' +import { detectAgentStatusFromTitle, MAX_OSC_TITLE_CHARS } from '../../shared/agent-detection' import { addWorktree, assertWorktreeCleanForRemoval, @@ -55,17 +56,25 @@ import { } from './orca-runtime' import { HeadlessEmulator } from '../daemon/headless-emulator' import type { RuntimeMobileSessionTabsResult } from '../../shared/runtime-types' +import type { TerminalSideEffectBatch } from '../../shared/terminal-side-effect-facts' import { TERMINAL_INPUT_CHUNK_MAX_BYTES, TERMINAL_INPUT_MAX_BYTES, TERMINAL_INPUT_TOO_LARGE_ERROR } from '../../shared/terminal-input' +import { + AGENT_PROMPT_BRACKETED_PASTE_END, + AGENT_PROMPT_BRACKETED_PASTE_START, + buildAgentPromptPasteBytes +} from '../../shared/agent-prompt-injection' import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../shared/clipboard-text' +import { projectHostSetupProjectionFromRepos } from '../../shared/project-host-setup-projection' import { registerSshFilesystemProvider, unregisterSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch' +import * as localWorktreeFilesystem from '../local-worktree-filesystem' import { DEFAULT_REPO_BADGE_COLOR, FLOATING_TERMINAL_WORKTREE_ID, @@ -81,6 +90,19 @@ import { TERMINAL_METHODS } from './rpc/methods/terminal' const ORIGINAL_PLATFORM = process.platform const ORIGINAL_PLATFORM_DESCRIPTOR = Object.getOwnPropertyDescriptor(process, 'platform') +const removeWorktreeLinkedPathsMock = vi.hoisted(() => vi.fn()) + +vi.mock('../ipc/worktree-symlinks', () => ({ + createWorktreeLinkedPaths: vi.fn(), + removeWorktreeLinkedPaths: removeWorktreeLinkedPathsMock +})) + +async function waitForMobileSessionTabsEvents( + events: RuntimeMobileSessionTabsResult[], + count: number +): Promise { + await vi.waitFor(() => expect(events).toHaveLength(count)) +} function setPlatform(platform: NodeJS.Platform): void { Object.defineProperty(process, 'platform', { @@ -529,6 +551,7 @@ function resetRuntimeTestMocks(): void { vi.mocked(assertWorktreeCleanForRemoval).mockReset() vi.mocked(assertWorktreeCleanForRemoval).mockResolvedValue(undefined) vi.mocked(removeWorktree).mockReset() + removeWorktreeLinkedPathsMock.mockReset() vi.mocked(forceDeleteLocalBranchMock).mockReset() vi.mocked(forceDeleteLocalBranchMock).mockResolvedValue(undefined) sshGitProviders.clear() @@ -1349,6 +1372,7 @@ describe('OrcaRuntimeService', () => { expect(status.capabilities).toContain('workspace-ports.v1') expect(status.capabilities).toContain('mobile.tasks.v1') expect(status.capabilities).toContain('project-host-setup.v1') + expect(status.capabilities).toContain('linear.issue-attribute-filter.v1') expect(status.capabilities).not.toContain('browser.screencast.v1') expect(typeof status.protocolVersion).toBe('number') expect(typeof status.minCompatibleMobileVersion).toBe('number') @@ -1356,6 +1380,18 @@ describe('OrcaRuntimeService', () => { expect(status.minCompatibleMobileVersion).toBeGreaterThanOrEqual(0) }) + it('reports the configured Windows terminal shell on status', () => { + const runtime = new OrcaRuntimeService({ + ...store, + getSettings: () => ({ + ...store.getSettings(), + terminalWindowsShell: 'wsl.exe' + }) + } as never) + + expect(runtime.getStatus().terminalWindowsShell).toBe('wsl.exe') + }) + it('advertises browser screencast only when a renderer window is available', () => { const runtime = createRuntime() electronMocks.BrowserWindow.fromId.mockReturnValue({ isDestroyed: () => false } as never) @@ -1599,6 +1635,318 @@ describe('OrcaRuntimeService', () => { }) }) + it('drops a stale leaf when a woken agent PTY is re-keyed to a new leaf on renderer reload', async () => { + const runtime = createRuntime() + const tabId = 'tab-1' + // Why: the agent holds a pre-allocated ORCA_TERMINAL_HANDLE, so its PTY has a + // handleByPtyId entry — the exact condition the reload preservation loop keys on. + runtime.preAllocateHandleForPty('pty-agent') + runtime.attachWindow(TEST_WINDOW_ID) + runtime.syncWindowGraph(TEST_WINDOW_ID, { + tabs: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + title: 'Claude', + activeLeafId: 'leaf-old', + layout: null + } + ], + leaves: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + leafId: 'leaf-old', + paneRuntimeId: 1, + ptyId: 'pty-agent' + } + ] + }) + const before = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) + expect(before.terminals).toHaveLength(1) + + // Simulate agent sleep + mobile wake: the renderer reloads and cold-restores + // the pane under a NEW leafId while the SAME agent PTY stays live. + runtime.markRendererReloading(TEST_WINDOW_ID) + runtime.syncWindowGraph(TEST_WINDOW_ID, { + tabs: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + title: 'Claude', + activeLeafId: 'leaf-new', + layout: null + } + ], + leaves: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + leafId: 'leaf-new', + paneRuntimeId: 2, + ptyId: 'pty-agent' + } + ] + }) + + const after = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) + // Before the fix the stale leaf-old survived beside leaf-new — two leaves on + // ONE PTY — so both adopted the same ptyId-keyed handle and paired clients + // crashed with a duplicate React key (`term_…`). Now only the live leaf remains. + expect(after.terminals).toHaveLength(1) + expect(after.terminals[0].ptyId).toBe('pty-agent') + // The shared handle must NOT have been invalidated — it belongs to leaf-new now. + await expect(runtime.showTerminal(after.terminals[0].handle)).resolves.toMatchObject({ + ptyId: 'pty-agent' + }) + }) + + it('still preserves a CLI agent leaf when the reloaded renderer has not rebound its PTY', async () => { + const runtime = createRuntime() + const tabId = 'tab-1' + runtime.preAllocateHandleForPty('pty-agent') + runtime.attachWindow(TEST_WINDOW_ID) + runtime.syncWindowGraph(TEST_WINDOW_ID, { + tabs: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + title: 'Claude', + activeLeafId: 'leaf-old', + layout: null + } + ], + leaves: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + leafId: 'leaf-old', + paneRuntimeId: 1, + ptyId: 'pty-agent' + } + ] + }) + expect((await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`)).terminals).toHaveLength(1) + + // Renderer reloads but has NOT yet rebound the pane (empty graph). The live + // CLI agent PTY + exported handle must survive (the original preserve intent). + runtime.markRendererReloading(TEST_WINDOW_ID) + runtime.syncWindowGraph(TEST_WINDOW_ID, { tabs: [], leaves: [] }) + + const after = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) + expect(after.terminals).toHaveLength(1) + expect(after.terminals[0].ptyId).toBe('pty-agent') + }) + + it('invalidates a re-keyed leaf-unique handle so in-flight waiters fail fast', async () => { + const runtime = createRuntime() + const tabId = 'tab-1' + // No preAllocateHandleForPty: a plain terminal's handle is leaf-unique, so a + // re-key leaves it with no next owner and it must go stale immediately. + runtime.attachWindow(TEST_WINDOW_ID) + runtime.syncWindowGraph(TEST_WINDOW_ID, { + tabs: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + title: 'Shell', + activeLeafId: 'leaf-old', + layout: null + } + ], + leaves: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + leafId: 'leaf-old', + paneRuntimeId: 1, + ptyId: 'pty-plain' + } + ] + }) + const before = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) + expect(before.terminals).toHaveLength(1) + const staleHandle = before.terminals[0].handle + const waiting = runtime.waitForTerminal(staleHandle, { condition: 'exit', timeoutMs: 30_000 }) + + // Re-key WITHOUT a renderer reload (e.g. a pane moved across tabs) while the + // same PTY stays live under a new leaf. + runtime.syncWindowGraph(TEST_WINDOW_ID, { + tabs: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + title: 'Shell', + activeLeafId: 'leaf-new', + layout: null + } + ], + leaves: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + leafId: 'leaf-new', + paneRuntimeId: 2, + ptyId: 'pty-plain' + } + ] + }) + + // The waiter must fail fast, not hang until timeout on a dead leaf. + await expect(waiting).rejects.toThrow('terminal_handle_stale') + const after = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) + expect(after.terminals).toHaveLength(1) + expect(after.terminals[0].handle).not.toBe(staleHandle) + }) + + it('keeps a live CLI waiter pending when a re-keyed shared handle transfers to the live leaf', async () => { + const runtime = createRuntime() + const tabId = 'tab-1' + // The counterpart to the leaf-unique case above: a pre-allocated + // ORCA_TERMINAL_HANDLE is ptyId-keyed and shared, so re-keying its live PTY to + // a new leaf (a pane moved across tabs, no renderer reload) must hand the + // handle to the live leaf WITHOUT rejecting the agent's in-flight waiter. This + // pins the shared-handle branch so collapsing it into a blanket + // invalidateLeafHandle can't silently strand a CLI `terminal wait`. (A renderer + // reload is a separate path — markRendererReloading stales every waiter itself.) + runtime.preAllocateHandleForPty('pty-agent') + runtime.attachWindow(TEST_WINDOW_ID) + runtime.syncWindowGraph(TEST_WINDOW_ID, { + tabs: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + title: 'Claude', + activeLeafId: 'leaf-old', + layout: null + } + ], + leaves: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + leafId: 'leaf-old', + paneRuntimeId: 1, + ptyId: 'pty-agent' + } + ] + }) + const before = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) + const sharedHandle = before.terminals[0].handle + const abort = new AbortController() + let settled: 'resolved' | 'rejected' | null = null + const waiting = runtime + .waitForTerminal(sharedHandle, { + condition: 'exit', + timeoutMs: 30_000, + signal: abort.signal + }) + .then( + () => { + settled = 'resolved' + }, + () => { + settled = 'rejected' + } + ) + + // Re-key WITHOUT a renderer reload while the same agent PTY stays live under a + // new leaf. + runtime.syncWindowGraph(TEST_WINDOW_ID, { + tabs: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + title: 'Claude', + activeLeafId: 'leaf-new', + layout: null + } + ], + leaves: [ + { + tabId, + worktreeId: TEST_WORKTREE_ID, + leafId: 'leaf-new', + paneRuntimeId: 2, + ptyId: 'pty-agent' + } + ] + }) + + // Let any synchronous stale-handle rejection propagate. + await new Promise((resolve) => setImmediate(resolve)) + // The shared handle belongs to leaf-new now, so the CLI's live waiter must stay + // pending — a blanket invalidateLeafHandle would reject it here as stale. + expect(settled).toBeNull() + // The same handle still resolves to the live PTY under the new leaf. + await expect(runtime.showTerminal(sharedHandle)).resolves.toMatchObject({ + ptyId: 'pty-agent' + }) + + // Abort only for teardown; the assertion above already proved it was pending. + abort.abort() + await waiting + expect(settled).toBe('rejected') + }) + + it('emits one mobile session terminal tab per live PTY even if two tabs resolve to it', () => { + const runtime = createRuntime() + const internals = runtime as unknown as { + recordPtyWorktree: ( + ptyId: string, + worktreeId: string, + state?: Record + ) => void + mobileSessionTabsByWorktree: Map + getMobileSessionTabsForWorktree: (worktreeId: string) => { + tabs: { type: string; terminal?: string | null }[] + } + } + // Two unclaimed live PTYs on the worktree; the worktree-only fallback binds + // either to a leafless tab that references it. + internals.recordPtyWorktree('pty-shared', TEST_WORKTREE_ID, { connected: true }) + internals.recordPtyWorktree('pty-other', TEST_WORKTREE_ID, { connected: true }) + + const terminalTab = (leafId: string, ptyId: string) => ({ + type: 'terminal' as const, + id: `term_dup::${leafId}`, + parentTabId: 'term_dup', + leafId, + ptyId, + title: 'Agent', + isActive: leafId === 'leaf-new' + }) + + // Two records (a stale headless leaf + the live leaf) that both resolve to + // the SAME live PTY — the renderer-graph origin the leaf fix can't reach. + internals.mobileSessionTabsByWorktree.set(TEST_WORKTREE_ID, { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'renderer:test:1', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: 'term_dup::leaf-new', + activeTabType: 'terminal', + tabs: [terminalTab('leaf-new', 'pty-shared'), terminalTab('leaf-old', 'pty-shared')] + }) + const deduped = internals.getMobileSessionTabsForWorktree(TEST_WORKTREE_ID) + const dedupedTerminals = deduped.tabs.filter((tab) => tab.type === 'terminal') + expect(dedupedTerminals).toHaveLength(1) + expect(dedupedTerminals[0].terminal).toBeTruthy() + + // Split siblings own DISTINCT PTYs, so they must never be collapsed. + internals.mobileSessionTabsByWorktree.set(TEST_WORKTREE_ID, { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'renderer:test:2', + snapshotVersion: 2, + activeGroupId: null, + activeTabId: 'term_dup::leaf-new', + activeTabType: 'terminal', + tabs: [terminalTab('leaf-new', 'pty-shared'), terminalTab('leaf-old', 'pty-other')] + }) + const split = internals.getMobileSessionTabsForWorktree(TEST_WORKTREE_ID) + expect(split.tabs.filter((tab) => tab.type === 'terminal')).toHaveLength(2) + }) + it('keeps targeted terminal lists from adopting controller PTYs for other worktrees', async () => { vi.mocked(listWorktrees).mockResolvedValue([ ...MOCK_GIT_WORKTREES, @@ -2305,7 +2653,7 @@ describe('OrcaRuntimeService', () => { if (args[0] === 'rev-parse' && args[1] === '--verify') { return { stdout: 'base-sha\n', stderr: '' } } - if (args[0] === 'fetch') { + if (args.includes('fetch')) { return refresh.promise } return { stdout: '', stderr: '' } @@ -2318,7 +2666,18 @@ describe('OrcaRuntimeService', () => { await vi.waitFor(() => { expect(gitSpy).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main'], + [ + '-c', + 'maintenance.auto=false', + '-c', + 'maintenance.commit-graph.auto=0', + '-c', + 'gc.auto=0', + 'fetch', + '--no-tags', + 'origin', + '+refs/heads/main:refs/remotes/origin/main' + ], { cwd: TEST_REPO_PATH, useConfiguredSshCommandForNetwork: true, @@ -2436,7 +2795,7 @@ describe('OrcaRuntimeService', () => { if (args[0] === 'rev-parse' && args.includes('refs/remotes/origin/main^{commit}')) { return { stdout: 'base-sha\n', stderr: '' } } - if (args[0] === 'fetch') { + if (args.includes('fetch')) { throw new Error('network unavailable') } return { stdout: '', stderr: '' } @@ -2498,7 +2857,7 @@ describe('OrcaRuntimeService', () => { if (args[0] === 'rev-parse' && args.includes('refs/heads/develop^{commit}')) { return { stdout: 'develop-sha\n', stderr: '' } } - if (args[0] === 'fetch') { + if (args.includes('fetch')) { throw new Error('network unavailable') } return { stdout: '', stderr: '' } @@ -2552,7 +2911,7 @@ describe('OrcaRuntimeService', () => { if (args[0] === 'rev-parse' && args.includes('refs/heads/team/feature^{commit}')) { return { stdout: 'team-feature-sha\n', stderr: '' } } - if (args[0] === 'fetch') { + if (args.includes('fetch')) { throw new Error('network unavailable') } return { stdout: '', stderr: '' } @@ -2573,7 +2932,18 @@ describe('OrcaRuntimeService', () => { false ) expect(gitSpy).not.toHaveBeenCalledWith( - ['fetch', '--no-tags', 'team', '+refs/heads/feature:refs/remotes/team/feature'], + [ + '-c', + 'maintenance.auto=false', + '-c', + 'maintenance.commit-graph.auto=0', + '-c', + 'gc.auto=0', + 'fetch', + '--no-tags', + 'team', + '+refs/heads/feature:refs/remotes/team/feature' + ], expect.any(Object) ) } finally { @@ -2597,7 +2967,7 @@ describe('OrcaRuntimeService', () => { if (args[0] === 'rev-parse' && args[1] === '--verify') { throw new Error('missing ref') } - if (args[0] === 'fetch') { + if (args.includes('fetch')) { throw new Error('network unavailable') } return { stdout: '', stderr: '' } @@ -4082,7 +4452,7 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService(remoteStore as never) try { - await runtime.removeManagedWorktree('path:/remote/feature', true) + await runtime.removeManagedWorktree('path:/remote/feature', true, false) } finally { unregisterSshGitProvider('ssh-1') } @@ -5250,36 +5620,436 @@ describe('OrcaRuntimeService', () => { } }) - it('defaults runtime createRepo badgeColor to DEFAULT_REPO_BADGE_COLOR', async () => { - const added: Record[] = [] - const colorStore = { + it('keeps existing-folder imports split by runtime host on the same normalized path', async () => { + const tempRoot = await mkdtemp(join(tmpdir(), 'orca-runtime-project-host-')) + const repos: Record[] = [] + getRepoUpstreamMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' }) + const runtimeStore = { ...store, - getRepos: () => [...added] as never, + getRepos: () => [...repos] as never, addRepo: (repo: Record) => { - added.push(repo) + repos.push(repo) }, - getRepo: (id: string) => added.find((repo) => repo.id === id) as never + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + }, + getProjects: () => projectHostSetupProjectionFromRepos(repos as never).projects as never, + getProjectHostSetups: () => + projectHostSetupProjectionFromRepos(repos as never).setups as never } - const runtime = new OrcaRuntimeService(colorStore as never) - const parentDir = await mkdtemp('/tmp/orca-runtime-create-') + const runtime = new OrcaRuntimeService(runtimeStore as never) + try { - const result = await runtime.createRepo(parentDir, 'runtime-create-default', 'folder') - if ('error' in result) { - throw new Error(result.error) - } + execFileSync('git', ['init'], { cwd: tempRoot, stdio: 'ignore' }) + const first = await runtime.setupProjectExistingFolder({ + projectId: 'github:stablyai/orca', + hostId: 'runtime:env-1', + path: tempRoot, + kind: 'git', + setupMethod: 'imported-existing-folder' + }) + const second = await runtime.setupProjectExistingFolder({ + projectId: 'github:stablyai/orca', + hostId: 'runtime:env-2', + path: tempRoot, + kind: 'git', + setupMethod: 'imported-existing-folder' + }) - expect(result).toHaveProperty('repo.badgeColor', DEFAULT_REPO_BADGE_COLOR) - expect(added).toEqual([expect.objectContaining({ badgeColor: DEFAULT_REPO_BADGE_COLOR })]) + expect(repos).toHaveLength(2) + expect(repos).toEqual([ + expect.objectContaining({ + path: tempRoot, + executionHostId: 'runtime:env-1' + }), + expect.objectContaining({ + path: tempRoot, + executionHostId: 'runtime:env-2' + }) + ]) + expect(first.repo).toMatchObject({ + path: tempRoot, + executionHostId: 'runtime:env-1' + }) + expect(first.setup).toMatchObject({ + repoId: first.repo.id, + hostId: 'runtime:env-1' + }) + expect(second.repo).toMatchObject({ + path: tempRoot, + executionHostId: 'runtime:env-2' + }) + expect(second.setup).toMatchObject({ + repoId: second.repo.id, + hostId: 'runtime:env-2' + }) + expect(first.repo.id).not.toBe(second.repo.id) + expect(first.setup.repoId).not.toBe(second.setup.repoId) } finally { - await rm(parentDir, { recursive: true, force: true }) + await rm(tempRoot, { recursive: true, force: true }) } }) - it('creates a missing runtime parent before creating the project directory', async () => { - const added: Record[] = [] - const createStore = { + it('keeps path-only runtime addRepo reuse working when a host-qualified repo already exists', async () => { + const repos: Record[] = [ + { + id: 'repo-runtime-1', + path: '/tmp/runtime-shared', + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1, + kind: 'folder', + executionHostId: 'runtime:env-1' + } + ] + const runtimeStore = { ...store, - getRepos: () => [...added] as never, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const repo = await runtime.addRepo('/tmp/runtime-shared', 'folder') + + expect(repo).toMatchObject({ + id: 'repo-runtime-1', + path: '/tmp/runtime-shared', + executionHostId: 'runtime:env-1' + }) + expect(repos).toHaveLength(1) + }) + + it('does not hijack a legacy SSH repo at the same path into a runtime host', async () => { + // A legacy SSH repo resolves to `ssh:` even with a null executionHostId, + // so a same-path runtime import must create a new repo instead of adopting it. + const repos: Record[] = [ + { + id: 'repo-ssh-1', + path: '/workspace', + displayName: 'workspace', + badgeColor: 'blue', + addedAt: 1, + kind: 'folder', + connectionId: 'ssh-target-1' + } + ] + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + } + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const repo = await runtime.addRepo('/workspace', 'folder', 'runtime:env-1') + + expect(repos).toHaveLength(2) + expect(repo.id).not.toBe('repo-ssh-1') + expect(repo).toMatchObject({ path: '/workspace', executionHostId: 'runtime:env-1' }) + // The legacy SSH repo must be untouched (no executionHostId stamped onto it). + expect(repos[0]).toMatchObject({ id: 'repo-ssh-1', connectionId: 'ssh-target-1' }) + expect(repos[0]).not.toHaveProperty('executionHostId') + }) + + it('only a runtime host adopts an unstamped repo; local/ssh imports never stamp it', async () => { + // A genuine local repo is indistinguishable from a legacy runtime repo (both have null + // executionHostId and connectionId). Only a runtime host may backfill it — a local or ssh + // import at the same path must leave it untouched rather than re-attribute it to that host. + for (const importHostId of ['local', 'ssh:ssh-target-9'] as const) { + const repos: Record[] = [ + { + id: 'repo-local-1', + path: '/workspace', + displayName: 'workspace', + badgeColor: 'blue', + addedAt: 1, + kind: 'folder' + } + ] + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + } + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const repo = await runtime.addRepo('/workspace', 'folder', importHostId) + + // The matched repo is returned unchanged — no new repo, no executionHostId stamped. + expect(repos).toHaveLength(1) + expect(repo.id).toBe('repo-local-1') + expect(repos[0]).not.toHaveProperty('executionHostId') + } + }) + + it('keeps project clone setup on the cloned host-qualified repo', async () => { + const destination = await mkdtemp(join(tmpdir(), 'orca-runtime-project-clone-')) + const clonePath = join(destination, 'orca') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') + const repos: Record[] = [] + getRepoUpstreamMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' }) + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + }, + getProjects: () => projectHostSetupProjectionFromRepos(repos as never).projects as never, + getProjectHostSetups: () => + projectHostSetupProjectionFromRepos(repos as never).setups as never + } + spawnSpy.mockImplementation(() => { + const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } + proc.stderr = new EventEmitter() + queueMicrotask(() => { + mkdirSync(clonePath, { recursive: true }) + execFileSync('git', ['init'], { cwd: clonePath, stdio: 'ignore' }) + proc.emit('close', 0, null) + }) + return proc as never + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + try { + const result = await runtime.setupProjectClone({ + projectId: 'github:stablyai/orca', + hostId: 'runtime:env-1', + url: 'https://example.com/orca.git', + destination + }) + + expect(repos).toHaveLength(1) + expect(result.repo).toMatchObject({ + path: clonePath, + executionHostId: 'runtime:env-1', + projectHostSetupMethod: 'cloned' + }) + expect(result.setup).toMatchObject({ + repoId: result.repo.id, + hostId: 'runtime:env-1', + setupMethod: 'cloned' + }) + } finally { + spawnSpy.mockRestore() + await rm(destination, { recursive: true, force: true }) + } + }) + + it('adopts public clone repos into host-qualified project setup', async () => { + const destination = await mkdtemp(join(tmpdir(), 'orca-runtime-project-clone-')) + const clonePath = join(destination, 'orca') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') + const repos: Record[] = [] + getRepoUpstreamMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' }) + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + }, + getProjects: () => projectHostSetupProjectionFromRepos(repos as never).projects as never, + getProjectHostSetups: () => + projectHostSetupProjectionFromRepos(repos as never).setups as never + } + spawnSpy.mockImplementation(() => { + const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } + proc.stderr = new EventEmitter() + queueMicrotask(() => { + mkdirSync(clonePath, { recursive: true }) + execFileSync('git', ['init'], { cwd: clonePath, stdio: 'ignore' }) + proc.emit('close', 0, null) + }) + return proc as never + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + try { + const cloned = await runtime.cloneRepo('https://example.com/orca.git', destination) + expect(cloned).toMatchObject({ + path: clonePath + }) + expect(cloned).not.toHaveProperty('executionHostId') + + const result = await runtime.setupProjectExistingFolder({ + projectId: 'github:stablyai/orca', + hostId: 'runtime:env-1', + path: clonePath, + kind: 'git', + setupMethod: 'cloned' + }) + + expect(repos).toHaveLength(1) + expect(result.repo).toMatchObject({ + id: cloned.id, + path: clonePath, + executionHostId: 'runtime:env-1', + projectHostSetupMethod: 'cloned' + }) + expect(result.setup).toMatchObject({ + repoId: cloned.id, + hostId: 'runtime:env-1', + setupMethod: 'cloned' + }) + } finally { + spawnSpy.mockRestore() + await rm(destination, { recursive: true, force: true }) + } + }) + + it('keeps project clone repos split by runtime host on the same clone path', async () => { + const destination = await mkdtemp(join(tmpdir(), 'orca-runtime-project-clone-')) + const clonePath = join(destination, 'orca') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') + const repos: Record[] = [ + { + id: 'repo-host-a', + path: clonePath, + displayName: 'orca', + badgeColor: 'blue', + addedAt: 1, + kind: 'git', + executionHostId: 'runtime:env-1' + } + ] + getRepoUpstreamMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' }) + const runtimeStore = { + ...store, + getRepos: () => [...repos] as never, + addRepo: (repo: Record) => { + repos.push(repo) + }, + getRepo: (id: string) => repos.find((repo) => repo.id === id) as never, + updateRepo: (id: string, updates: Record) => { + const index = repos.findIndex((repo) => repo.id === id) + if (index === -1) { + return null + } + repos[index] = { ...repos[index], ...updates } + return repos[index] as never + }, + getProjects: () => projectHostSetupProjectionFromRepos(repos as never).projects as never, + getProjectHostSetups: () => + projectHostSetupProjectionFromRepos(repos as never).setups as never + } + spawnSpy.mockImplementation(() => { + const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } + proc.stderr = new EventEmitter() + queueMicrotask(() => { + mkdirSync(clonePath, { recursive: true }) + execFileSync('git', ['init'], { cwd: clonePath, stdio: 'ignore' }) + proc.emit('close', 0, null) + }) + return proc as never + }) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + try { + const result = await runtime.setupProjectClone({ + projectId: 'github:stablyai/orca', + hostId: 'runtime:env-2', + url: 'https://example.com/orca.git', + destination + }) + + expect(repos).toHaveLength(2) + expect(repos[0]).toMatchObject({ + id: 'repo-host-a', + executionHostId: 'runtime:env-1' + }) + expect(result.repo).toMatchObject({ + path: clonePath, + executionHostId: 'runtime:env-2' + }) + expect(result.repo.id).not.toBe('repo-host-a') + expect(result.setup).toMatchObject({ + repoId: result.repo.id, + hostId: 'runtime:env-2', + setupMethod: 'cloned' + }) + } finally { + spawnSpy.mockRestore() + await rm(destination, { recursive: true, force: true }) + } + }) + + it('defaults runtime createRepo badgeColor to DEFAULT_REPO_BADGE_COLOR', async () => { + const added: Record[] = [] + const colorStore = { + ...store, + getRepos: () => [...added] as never, + addRepo: (repo: Record) => { + added.push(repo) + }, + getRepo: (id: string) => added.find((repo) => repo.id === id) as never + } + const runtime = new OrcaRuntimeService(colorStore as never) + const parentDir = await mkdtemp('/tmp/orca-runtime-create-') + try { + const result = await runtime.createRepo(parentDir, 'runtime-create-default', 'folder') + if ('error' in result) { + throw new Error(result.error) + } + + expect(result).toHaveProperty('repo.badgeColor', DEFAULT_REPO_BADGE_COLOR) + expect(added).toEqual([expect.objectContaining({ badgeColor: DEFAULT_REPO_BADGE_COLOR })]) + } finally { + await rm(parentDir, { recursive: true, force: true }) + } + }) + + it('creates a missing runtime parent before creating the project directory', async () => { + const added: Record[] = [] + const createStore = { + ...store, + getRepos: () => [...added] as never, addRepo: (repo: Record) => { added.push(repo) }, @@ -5348,7 +6118,7 @@ describe('OrcaRuntimeService', () => { }) it('defaults runtime cloneRepo badgeColor to DEFAULT_REPO_BADGE_COLOR', async () => { - const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') const added: Record[] = [] const colorStore = { ...store, @@ -5384,7 +6154,7 @@ describe('OrcaRuntimeService', () => { }) it('preserves existing badgeColor on runtime cloneRepo folder->git dedupe upgrade', async () => { - const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') spawnSpy.mockImplementation(() => { const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } proc.stderr = new EventEmitter() @@ -5482,7 +6252,7 @@ describe('OrcaRuntimeService', () => { }) it('rejects runtime cloneRepo dot-segment URLs before spawning git', async () => { - const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') const runtime = createRuntime() const tempRoot = await mkdtemp(join(tmpdir(), 'orca-runtime-clone-')) const destination = join(tempRoot, 'destination') @@ -5499,7 +6269,7 @@ describe('OrcaRuntimeService', () => { }) it('rejects runtime cloneRepo parent-segment URLs before spawning git', async () => { - const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') const runtime = createRuntime() const tempRoot = await mkdtemp(join(tmpdir(), 'orca-runtime-clone-')) const destination = join(tempRoot, 'destination') @@ -5516,7 +6286,7 @@ describe('OrcaRuntimeService', () => { }) it('removes an owned runtime clone target when git exits unsuccessfully', async () => { - const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } proc.stderr = new EventEmitter() spawnSpy.mockReturnValue(proc as never) @@ -5543,7 +6313,7 @@ describe('OrcaRuntimeService', () => { }) it('preserves an existing runtime clone target when git exits unsuccessfully', async () => { - const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } proc.stderr = new EventEmitter() spawnSpy.mockReturnValue(proc as never) @@ -5570,7 +6340,7 @@ describe('OrcaRuntimeService', () => { }) it('skips runtime clone failure cleanup when the owned target is replaced', async () => { - const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') const proc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } proc.stderr = new EventEmitter() spawnSpy.mockReturnValue(proc as never) @@ -5599,7 +6369,7 @@ describe('OrcaRuntimeService', () => { }) it('serializes concurrent runtime clones for the same target', async () => { - const spawnSpy = vi.spyOn(gitRunner, 'wslAwareSpawn') + const spawnSpy = vi.spyOn(gitRunner, 'gitSpawn') const firstProc = new EventEmitter() as EventEmitter & { stderr: EventEmitter } firstProc.stderr = new EventEmitter() spawnSpy.mockReturnValueOnce(firstProc as never) @@ -5715,44 +6485,692 @@ describe('OrcaRuntimeService', () => { }) }) - it('returns OSC titles from headless main terminal snapshots', async () => { + it('resolves tui-idle when a completion title is coalesced with the next working title', async () => { + // Why: node-pty + the main batch window can coalesce "task done" and the + // next task's working title into one chunk. A last-title reader never + // sees the intermediate idle and the waiter hangs (issue #1083 class). const runtime = createRuntime() - syncSinglePty(runtime, 'pty-1') + syncSinglePty(runtime) + runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) + const [terminal] = (await runtime.listTerminals()).terminals + const wait = runtime.waitForTerminal(terminal.handle, { + condition: 'tui-idle', + timeoutMs: 1_000 + }) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07hello\n', 100) + runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07\x1b]0;Codex working\x07', 101) - const snapshot = await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 1000 }) - expect(snapshot).toMatchObject({ - source: 'headless', - lastTitle: 'Codex working' + await expect(wait).resolves.toMatchObject({ + handle: terminal.handle, + condition: 'tui-idle', + status: 'running' }) }) - it('resizes the headless mirror after an accepted desktop PTY resize', async () => { - const spawn = { cols: 80, rows: 24 } - const resized = { cols: 120, rows: 30 } - let currentSize = spawn + it('ignores the bare cursor-agent native title so synthesized spinner state survives', async () => { + const ptyId = `${TEST_REPO_ID}::/tmp/worktree-a@@pty-bg` const runtime = createRuntime() runtime.setPtyController({ write: () => true, kill: () => true, getForegroundProcess: async () => null, - getSize: () => currentSize + listProcesses: async () => [{ id: ptyId, cwd: '/tmp/worktree-a', title: 'shell' }] }) - syncSinglePty(runtime, 'pty-1') + runtime.attachWindow(1) + runtime.markGraphReady(1) - runtime.onPtyData('pty-1', 'user@host % claude\r\n', 100) - currentSize = resized - runtime.onExternalPtyResize('pty-1', resized.cols, resized.rows) - for (let index = 0; index < 5; index += 1) { - runtime.onPtyData('pty-1', makeStatusFrame(index, index === 0), 200 + index) - } + runtime.onPtyData(ptyId, '\x1b]0;⠋ Cursor Agent\x07', 100) + // cursor-agent re-emits its bare native title on internal redraws while + // still working; it must not stomp the synthesized working title. + runtime.onPtyData(ptyId, '\x1b]0;Cursor Agent\x07', 101) - const snapshot = await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 5000 }) - expect(snapshot).toMatchObject({ cols: resized.cols, rows: resized.rows, source: 'headless' }) - await expect(parseHeadlessSnapshotLines(snapshot!, resized)).resolves.toEqual( - await referenceStatusFrameLines(spawn, resized) - ) + expect((await runtime.listTerminals()).terminals[0]).toMatchObject({ + title: '⠋ Cursor Agent' + }) + }) + + it('clears a stale working title after 3s of title-less output', async () => { + vi.useFakeTimers() + try { + const ptyId = `${TEST_REPO_ID}::/tmp/worktree-a@@pty-bg` + const runtime = createRuntime() + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [{ id: ptyId, cwd: '/tmp/worktree-a', title: 'shell' }] + }) + runtime.attachWindow(1) + runtime.markGraphReady(1) + + runtime.onPtyData(ptyId, '\x1b]0;Codex working\x07', 100) + runtime.onPtyData(ptyId, 'output without a title\r\n', 101) + expect((await runtime.listTerminals()).terminals[0]).toMatchObject({ + title: 'Codex working' + }) + + await vi.advanceTimersByTimeAsync(3_000) + + expect((await runtime.listTerminals()).terminals[0]).toMatchObject({ + title: 'Codex' + }) + } finally { + vi.useRealTimers() + } + }) + + it('cancels the stale-title timer when the PTY exits', async () => { + vi.useFakeTimers() + try { + const ptyId = `${TEST_REPO_ID}::/tmp/worktree-a@@pty-bg` + const runtime = createRuntime() + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [{ id: ptyId, cwd: '/tmp/worktree-a', title: 'shell' }] + }) + runtime.attachWindow(1) + runtime.markGraphReady(1) + + runtime.onPtyData(ptyId, '\x1b]0;Codex working\x07', 100) + runtime.onPtyData(ptyId, 'output without a title\r\n', 101) + runtime.onPtyExit(ptyId, 0) + + await vi.advanceTimersByTimeAsync(4_000) + + // The dead session keeps its factual last title — the disposed tracker's + // stale-title rewrite must not fire into the retained record. + expect((await runtime.listTerminals()).terminals[0]).toMatchObject({ + title: 'Codex working' + }) + } finally { + vi.useRealTimers() + } + }) + + it('keeps stale-title timers isolated per PTY', async () => { + vi.useFakeTimers() + try { + const ptyA = `${TEST_REPO_ID}::/tmp/worktree-a@@pty-a` + const ptyB = `${TEST_REPO_ID}::/tmp/worktree-a@@pty-b` + const runtime = createRuntime() + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [ + { id: ptyA, cwd: '/tmp/worktree-a', title: 'shell' }, + { id: ptyB, cwd: '/tmp/worktree-a', title: 'shell' } + ] + }) + runtime.attachWindow(1) + runtime.markGraphReady(1) + + runtime.onPtyData(ptyA, '\x1b]0;Codex working\x07', 100) + runtime.onPtyData(ptyB, '\x1b]0;Aider working\x07', 100) + // Only A receives title-less output, so only A's stale timer arms. + runtime.onPtyData(ptyA, 'output without a title\r\n', 101) + + await vi.advanceTimersByTimeAsync(3_000) + + const { terminals } = await runtime.listTerminals() + expect(terminals.find((t) => t.tabId === `pty:${ptyA}`)).toMatchObject({ title: 'Codex' }) + expect(terminals.find((t) => t.tabId === `pty:${ptyB}`)).toMatchObject({ + title: 'Aider working' + }) + } finally { + vi.useRealTimers() + } + }) + + // ─── pty:sideEffect channel (terminal-side-effect-authority.md, slice 2) ── + describe('terminal side-effect fact channel', () => { + function createSideEffectRuntime(): { + runtime: OrcaRuntimeService + batches: TerminalSideEffectBatch[] + } { + const batches: TerminalSideEffectBatch[] = [] + const runtime = new OrcaRuntimeService(store, undefined, { + onTerminalSideEffects: (batch) => batches.push(batch) + }) + return { runtime, batches } + } + + it('emits one batched event per chunk with facts in byte order and attribution', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + const chunk = '\x1b]0;Codex working\x07response\x1b]0;Codex done\x07\x07' + runtime.onPtyData('pty-1', chunk, 100) + + expect(batches).toHaveLength(1) + expect(batches[0]).toMatchObject({ + ptyId: 'pty-1', + seq: chunk.length, + worktreeId: TEST_WORKTREE_ID, + tabId: 'tab-1', + paneKey: 'tab-1:1' + }) + expect(batches[0].replay).toBeUndefined() + expect(batches[0].facts).toEqual([ + { kind: 'title', normalizedTitle: 'Codex working', rawTitle: 'Codex working' }, + { kind: 'agent-working' }, + { kind: 'title', normalizedTitle: 'Codex done', rawTitle: 'Codex done' }, + { kind: 'agent-idle', title: 'Codex done' }, + { kind: 'bell' } + ]) + }) + + it('keeps per-PTY ordering across chunks and accumulates seq', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) + runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) + + expect(batches.map((batch) => batch.facts[0]?.kind)).toEqual(['title', 'title']) + expect(batches[0].seq).toBeLessThan(batches[1].seq) + }) + + it('emits nothing for chunks without derived facts', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + // Plain output, a BEL-terminated non-title OSC split across chunks, and + // an Orca status payload: none of these is a title/bell/agent fact. + runtime.onPtyData('pty-1', 'plain output\r\n', 100) + runtime.onPtyData('pty-1', '\x1b]7;file://host', 101) + runtime.onPtyData('pty-1', '/tmp\x07', 102) + runtime.onPtyData('pty-1', '\x1b]9999;{"state":"working","agentType":"codex"}\x07', 103) + + expect(batches).toEqual([]) + }) + + it('emits the stale-working-title rewrite as between-chunk fact batches', async () => { + vi.useFakeTimers() + try { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) + runtime.onPtyData('pty-1', 'output without a title\r\n', 101) + batches.length = 0 + + await vi.advanceTimersByTimeAsync(3_000) + + // Timer facts fire outside a chunk, so each emits immediately — + // still strictly ordered per PTY. They carry staleWorkingTitleClear: + // the renderer must clear state without scheduling a task-complete + // notification main's unthrottled timer did not earn. + expect(batches.flatMap((batch) => batch.facts)).toEqual([ + { + kind: 'title', + normalizedTitle: 'Codex', + rawTitle: 'Codex', + staleWorkingTitleClear: true + }, + { kind: 'agent-idle', title: 'Codex', staleWorkingTitleClear: true } + ]) + } finally { + vi.useRealTimers() + } + }) + + it('ingests synthetic title frames without touching the byte pipeline', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;⠋ Cursor Agent\x07') + + expect(batches).toHaveLength(1) + expect(batches[0].facts).toEqual([ + { kind: 'title', normalizedTitle: '⠋ Cursor Agent', rawTitle: '⠋ Cursor Agent' }, + // The synthesized spinner classifies as working — agent facts derive + // from synthetic frames the same as from real bytes. + { kind: 'agent-working' } + ]) + // Synthetic frames are fabricated by main: they must not advance the + // metered output sequence the renderer ACK budget is based on. + expect(runtime.getPtyOutputSequence('pty-1')).toBe(0) + }) + + it('carries the synthetic permission BEL as a bell fact', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;Cursor needs your input\x07\x07') + + expect(batches[0].facts.at(0)).toMatchObject({ kind: 'title' }) + expect(batches[0].facts.at(-1)).toEqual({ kind: 'bell' }) + }) + + it('emits command-finished facts with best-effort exit codes across chunk splits', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', 'output\x1b]133;D;13', 100) + expect(batches).toEqual([]) + runtime.onPtyData('pty-1', '0\x07prompt $ ', 101) + runtime.onPtyData('pty-1', '\x1b]133;D\x07', 102) + + expect(batches.flatMap((batch) => batch.facts)).toEqual([ + { kind: 'command-finished', exitCode: 130 }, + { kind: 'command-finished', exitCode: null } + ]) + }) + + it('emits pr-link facts once per URL with batch attribution', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', 'PR https://github.com/acme/orca/pull/4', 100) + runtime.onPtyData('pty-1', '2\r\nand https://github.com/acme/orca/pull/43 done\r\n', 101) + // Repeated URL: deduped per PTY, like the renderer byte detector. + runtime.onPtyData('pty-1', 'again https://github.com/acme/orca/pull/42\r\n', 102) + + expect(batches).toHaveLength(1) + expect(batches[0]).toMatchObject({ + ptyId: 'pty-1', + worktreeId: TEST_WORKTREE_ID, + tabId: 'tab-1' + }) + expect(batches[0].facts).toEqual([ + { + kind: 'pr-link', + link: { + url: 'https://github.com/acme/orca/pull/42', + slug: { owner: 'acme', repo: 'orca' }, + number: 42 + } + }, + { + kind: 'pr-link', + link: { + url: 'https://github.com/acme/orca/pull/43', + slug: { owner: 'acme', repo: 'orca' }, + number: 43 + } + } + ]) + }) + + it('emits 2031-subscribe facts across chunk splits', () => { + // Why: hidden-delivery-gated views never receive the bytes — this fact + // is their only signal to send the DECSET 2031 color-scheme reply. + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', '\x1b[?20', 100) + expect(batches).toEqual([]) + runtime.onPtyData('pty-1', '31h', 101) + + expect(batches.flatMap((batch) => batch.facts)).toEqual([{ kind: '2031-subscribe' }]) + }) + + it('prefers the tracked title over the renderer snapshot lastTitle', async () => { + const { runtime } = createSideEffectRuntime() + const serializeBuffer = vi.fn().mockResolvedValue({ + data: 'visible content', + cols: 80, + rows: 24, + // The renderer xterm never saw the synthetic frame (it no longer + // rides pty:data), so its serializer reports a stale title. + lastTitle: 'stale shell title' + }) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + serializeBuffer, + hasRendererSerializer: () => true, + getSize: () => ({ cols: 80, rows: 24 }) + }) + syncSinglePty(runtime) + + runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;⠋ Cursor Agent\x07') + + const snapshot = await runtime.serializeTerminalBuffer('pty-1', { scrollbackRows: 10 }) + expect(snapshot?.source).toBe('renderer') + expect(snapshot?.lastTitle).toBe('⠋ Cursor Agent') + }) + + it('prefers the tracked title over the headless emulator lastTitle', async () => { + const { runtime } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07real output\r\n', 100) + // The hook-driven idle frame lands only in main's tracker — the + // emulator never sees fabricated bytes (invariant 5). + runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;Codex ready\x07') + + const snapshot = await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 10 }) + expect(snapshot?.source).toBe('headless') + expect(snapshot?.lastTitle).toBe('Codex ready') + }) + + it('returns a title-only replay snapshot and never historical attention', () => { + const { runtime } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07\x07', 100) + + expect(runtime.getTerminalSideEffectSnapshot('pty-1')).toMatchObject({ + ptyId: 'pty-1', + replay: true, + facts: [{ kind: 'title', normalizedTitle: 'Codex working', rawTitle: 'Codex working' }] + }) + expect(runtime.getTerminalSideEffectSnapshot('pty-unknown')).toBeNull() + }) + + it('drops the cursor-agent literal from record-fallback snapshots', () => { + const { runtime } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', 'plain output\n', 100) + // Simulate a record title restored by a path that bypassed the tracker + // (the tracker itself refuses to store the bare native title). + const records = ( + runtime as unknown as { + ptysById: Map + } + ).ptysById + records.get('pty-1')!.lastOscTitle = 'Cursor Agent' + + expect(runtime.getTerminalSideEffectSnapshot('pty-1')).toBeNull() + }) + + it('emits the chunk agentStatus events before its side-effect batch', () => { + // Cross-channel contract order per chunk: status → titles → bell. + const order: string[] = [] + const runtime = new OrcaRuntimeService(store, undefined, { + onTerminalAgentStatus: () => order.push('agentStatus:set'), + onTerminalSideEffects: () => order.push('pty:sideEffect') + }) + syncSinglePty(runtime) + + runtime.onPtyData( + 'pty-1', + '\x1b]9999;{"state":"working","agentType":"codex"}\x07\x1b]0;Codex working\x07\x07', + 100 + ) + + expect(order).toEqual(['agentStatus:set', 'pty:sideEffect']) + }) + + it('still emits a throwing chunk’s facts under its own seq, not the next chunk’s', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + vi.spyOn( + runtime as unknown as { applyTrackedPtyTitle: (ptyId: string, title: string) => boolean }, + 'applyTrackedPtyTitle' + ).mockImplementationOnce(() => { + throw new Error('tracker boom') + }) + + const first = '\x1b]0;Codex working\x07' + expect(() => runtime.onPtyData('pty-1', first, 100)).toThrow('tracker boom') + runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) + + expect(batches).toHaveLength(2) + expect(batches[0].seq).toBe(first.length) + expect(batches[0].facts).toEqual([ + { kind: 'title', normalizedTitle: 'Codex working', rawTitle: 'Codex working' } + ]) + // The next chunk's batch carries only its own facts (the throw aborted + // the first chunk's agent-tracker pass, so no working state was kept). + expect(batches[1].seq).toBeGreaterThan(batches[0].seq) + expect(batches[1].facts).toEqual([ + { kind: 'title', normalizedTitle: 'Codex done', rawTitle: 'Codex done' } + ]) + }) + + it('parses synthetic frames statelessly so ticks cannot corrupt the bell detector', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', '\x1b]0;split ti', 100) + // An 80ms spinner tick lands between the two halves of the real OSC. + runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;⠋ Cursor Agent\x07') + // Continuation: this BEL terminates the real OSC — it is NOT a bell. + runtime.onPtyData('pty-1', 'tle\x07', 101) + // A later standalone BEL is a real bell and must not be swallowed. + runtime.onPtyData('pty-1', 'ready\x07', 102) + + expect(batches.flatMap((batch) => batch.facts)).toEqual([ + { kind: 'title', normalizedTitle: '⠋ Cursor Agent', rawTitle: '⠋ Cursor Agent' }, + { kind: 'agent-working' }, + { kind: 'title', normalizedTitle: 'split title', rawTitle: 'split title' }, + { kind: 'bell' } + ]) + }) + + it('touches mobile snapshots once for decorative spinner ticks, again on idle', () => { + const { runtime } = createSideEffectRuntime() + syncSinglePty(runtime) + const touchSpy = vi.spyOn( + runtime as unknown as { touchMobileSessionSnapshotsForPty: (ptyId: string) => void }, + 'touchMobileSessionSnapshotsForPty' + ) + + for (const frame of ['⠋', '⠙', '⠹', '⠸', '⠼']) { + runtime.ingestSyntheticTitleFrame('pty-1', `\x1b]0;${frame} Cursor Agent\x07`) + } + // Five ticks with the same de-spinnered title: one snapshot fan-out. + expect(touchSpy).toHaveBeenCalledTimes(1) + + runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;Cursor ready\x07') + expect(touchSpy).toHaveBeenCalledTimes(2) + // Raw record titles still track every frame for worktree ps/mobile tabs. + expect( + ( + runtime as unknown as { + ptysById: Map + } + ).ptysById.get('pty-1')?.lastOscTitle + ).toBe('Cursor ready') + }) + + it('seeds the lazily created tracker from the daemon-snapshot title', async () => { + const { runtime, batches } = createSideEffectRuntime() + const serializeBuffer = vi.fn().mockResolvedValue({ + data: 'restored scrollback\n', + cols: 80, + rows: 24, + lastTitle: 'Codex working' + }) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + serializeBuffer, + hasRendererSerializer: () => true, + getSize: () => ({ cols: 80, rows: 24 }) + }) + syncSinglePty(runtime) + + // First live chunk creates the tracker cold and kicks off hydration; + // the snapshot seed must land in the already-created tracker. + runtime.onPtyData('pty-1', 'plain output without a title\n', 100) + await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 10 }) + batches.length = 0 + + runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) + + // Without the seed the tracker never saw 'working', so this idle title + // could not produce a completion fact. + expect(batches.flatMap((batch) => batch.facts)).toContainEqual({ + kind: 'agent-idle', + title: 'Codex done' + }) + }) + + it('arms the stale-title timer for a seeded working title', async () => { + vi.useFakeTimers() + try { + const { runtime, batches } = createSideEffectRuntime() + const serializeBuffer = vi.fn().mockResolvedValue({ + data: 'restored scrollback\n', + cols: 80, + rows: 24, + lastTitle: 'Codex working' + }) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + serializeBuffer, + hasRendererSerializer: () => true, + getSize: () => ({ cols: 80, rows: 24 }) + }) + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', 'plain output\n', 100) + // Settle the async daemon-snapshot hydration that seeds the tracker. + await vi.advanceTimersByTimeAsync(0) + runtime.onPtyData('pty-1', 'still no title\n', 101) + batches.length = 0 + + await vi.advanceTimersByTimeAsync(3_000) + + expect(batches.flatMap((batch) => batch.facts)).toEqual([ + { + kind: 'title', + normalizedTitle: 'Codex', + rawTitle: 'Codex', + staleWorkingTitleClear: true + }, + { kind: 'agent-idle', title: 'Codex', staleWorkingTitleClear: true } + ]) + } finally { + vi.useRealTimers() + } + }) + + it('emits command-code-working facts only after the banner arms the scrape', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + // Generic status words without the Command Code banner must not arm. + runtime.onPtyData('pty-1', '❯ Fix the spinner\r\nThinking...', 100) + expect(batches.flatMap((batch) => batch.facts)).toEqual([]) + + runtime.onPtyData('pty-1', '# Command Code v0.27.3\r\n', 101) + runtime.onPtyData('pty-1', '❯ Fix the spinner\r\n\x1b[35m✻ Thinking...\x1b[0m', 102) + + expect(batches.at(-1)).toMatchObject({ + ptyId: 'pty-1', + worktreeId: TEST_WORKTREE_ID, + tabId: 'tab-1' + }) + expect(batches.at(-1)?.facts).toEqual([ + { kind: 'command-code-working', prompt: 'Fix the spinner' } + ]) + }) + + it('emits a command-code-done fact when the idle composer returns', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', '# Command Code v0.27.3\r\n', 100) + runtime.onPtyData('pty-1', '❯ say hi\r\n✻ Thinking...', 101) + runtime.onPtyData( + 'pty-1', + '\r\n✻ Thought for 1 second\r\n:: Hi!\r\n❯ Ask your question...', + 102 + ) + + expect(batches.at(-1)?.facts).toEqual([{ kind: 'command-code-done', prompt: 'say hi' }]) + }) + + it('arms the Command Code scrape from the noted spawn command', () => { + const { runtime, batches } = createSideEffectRuntime() + syncSinglePty(runtime) + + // Mirrors the renderer detector's startupCommand fast-arm: no banner + // needed when main saw the launch command at spawn time. + runtime.noteTerminalSpawnCommand('pty-1', 'command-code --trust') + runtime.onPtyData('pty-1', '❯ Fix the spinner\r\n✻ Thinking...', 100) + + expect(batches.flatMap((batch) => batch.facts)).toContainEqual({ + kind: 'command-code-working', + prompt: 'Fix the spinner' + }) + }) + + it('prefers the tracked title over a stale renderer lastTitle in the hydration seed', async () => { + const { runtime } = createSideEffectRuntime() + const serializeBuffer = vi.fn().mockResolvedValue({ + data: 'renderer scrollback\n', + cols: 80, + rows: 24, + // The renderer xterm never saw the synthetic hook frame (it no longer + // rides pty:data), so its serializer reports the pre-agent title. + lastTitle: 'stale shell title' + }) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + serializeBuffer, + hasRendererSerializer: () => true, + getSize: () => ({ cols: 80, rows: 24 }) + }) + syncSinglePty(runtime) + + runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;⠋ Claude working\x07') + // First live chunk kicks off renderer hydration; awaiting the snapshot + // below settles the seed write chain. + runtime.onPtyData('pty-1', 'plain output\n', 100) + await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 10 }) + + const leaves = ( + runtime as unknown as { leaves: Map } + ).leaves + // The seed must not stomp the leaf record (worktree ps status source) + // back to the renderer's stale title. + expect([...leaves.values()][0]?.lastOscTitle).toBe('⠋ Claude working') + }) + }) + + it('returns OSC titles from headless main terminal snapshots', async () => { + const runtime = createRuntime() + syncSinglePty(runtime, 'pty-1') + + runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07hello\n', 100) + + const snapshot = await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 1000 }) + expect(snapshot).toMatchObject({ + source: 'headless', + lastTitle: 'Codex working' + }) + }) + + it('resizes the headless mirror after an accepted desktop PTY resize', async () => { + const spawn = { cols: 80, rows: 24 } + const resized = { cols: 120, rows: 30 } + let currentSize = spawn + const runtime = createRuntime() + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + getSize: () => currentSize + }) + syncSinglePty(runtime, 'pty-1') + + runtime.onPtyData('pty-1', 'user@host % claude\r\n', 100) + currentSize = resized + runtime.onExternalPtyResize('pty-1', resized.cols, resized.rows) + for (let index = 0; index < 5; index += 1) { + runtime.onPtyData('pty-1', makeStatusFrame(index, index === 0), 200 + index) + } + + const snapshot = await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 5000 }) + expect(snapshot).toMatchObject({ cols: resized.cols, rows: resized.rows, source: 'headless' }) + await expect(parseHeadlessSnapshotLines(snapshot!, resized)).resolves.toEqual( + await referenceStatusFrameLines(spawn, resized) + ) }) it('orders headless mirror resizes behind queued PTY writes', async () => { @@ -5973,6 +7391,16 @@ describe('OrcaRuntimeService', () => { expect(serializeBuffer).not.toHaveBeenCalled() }) + it('advances the absolute output sequence across a daemon stream gap', () => { + const runtime = createRuntime() + runtime.onPtyData('pty-gap', 'before', Date.now()) + + runtime.notePtyDataGap('pty-gap', 4096) + runtime.onPtyData('pty-gap', 'after', Date.now()) + + expect(runtime.getPtyOutputSequence('pty-gap')).toBe('before'.length + 4096 + 'after'.length) + }) + it('emits explicit OSC 9999 agent status from runtime PTY data', () => { const statuses: RuntimeTerminalAgentStatusEvent[] = [] const runtime = new OrcaRuntimeService(store, undefined, { @@ -9298,6 +10726,110 @@ describe('OrcaRuntimeService', () => { expect(writes).toEqual(['continue', '\r']) }) + it('sends agent prompts as bracketed paste before submit', async () => { + vi.useFakeTimers() + try { + const writes: string[] = [] + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), + write: (_ptyId, data) => { + writes.push(data) + return true + }, + kill: () => true, + getForegroundProcess: async () => null + }) + const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) + const prompt = 'line one\nline two\x1b[201~' + + const sendPromise = runtime.sendTerminalAgentPrompt(handle, prompt) + await vi.runAllTimersAsync() + const result = await sendPromise + + const pasted = [ + AGENT_PROMPT_BRACKETED_PASTE_START, + 'line one\nline two[201~', + AGENT_PROMPT_BRACKETED_PASTE_END + ].join('') + expect(result).toMatchObject({ + handle, + accepted: true, + bytesWritten: Buffer.byteLength(`${pasted}\r`, 'utf8') + }) + expect(writes).toEqual([pasted, '\r']) + } finally { + vi.useRealTimers() + } + }) + + it('chunks large agent prompt paste frames before delayed submit', async () => { + vi.useFakeTimers() + try { + const writes: string[] = [] + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), + write: (_ptyId, data) => { + writes.push(data) + return true + }, + kill: () => true, + getForegroundProcess: async () => null + }) + const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) + const prompt = `${'x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES)}\ntail` + + const sendPromise = runtime.sendTerminalAgentPrompt(handle, prompt) + await vi.runAllTimersAsync() + const result = await sendPromise + + const pasteWrites = writes.slice(0, -1) + expect(result.bytesWritten).toBe( + Buffer.byteLength(`${buildAgentPromptPasteBytes(prompt)}\r`, 'utf8') + ) + expect(writes.at(-1)).toBe('\r') + expect(pasteWrites.length).toBeGreaterThan(1) + expect(pasteWrites.join('')).toBe(buildAgentPromptPasteBytes(prompt)) + expect(pasteWrites[0]).toContain(AGENT_PROMPT_BRACKETED_PASTE_START) + expect(pasteWrites.at(-1)).toContain(AGENT_PROMPT_BRACKETED_PASTE_END) + } finally { + vi.useRealTimers() + } + }) + + it('closes an incomplete agent prompt paste when a later chunk write fails', async () => { + vi.useFakeTimers() + try { + const writes: string[] = [] + let writeCount = 0 + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), + write: (_ptyId, data) => { + writeCount += 1 + writes.push(data) + return writeCount !== 2 + }, + kill: () => true, + getForegroundProcess: async () => null + }) + const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`) + const prompt = 'x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES + 1) + + const sendPromise = runtime.sendTerminalAgentPrompt(handle, prompt) + const sendRejection = expect(sendPromise).rejects.toThrow('terminal_not_writable') + await vi.runAllTimersAsync() + + await sendRejection + expect(writes[0]).toContain(AGENT_PROMPT_BRACKETED_PASTE_START) + expect(writes.at(-1)).toBe(AGENT_PROMPT_BRACKETED_PASTE_END) + expect(writes).not.toContain('\r') + } finally { + vi.useRealTimers() + } + }) + it('chunks large terminal.send text before provider writes', async () => { const writes: string[] = [] const runtime = new OrcaRuntimeService(store) @@ -10741,24 +12273,260 @@ describe('OrcaRuntimeService', () => { ptysById: Map } ).ptysById.get('pty-1') - expect(pty?.lastOscTitle).toBe('Codex working') - expect(pty?.lastAgentStatus).toBe('working') + expect(pty?.lastOscTitle).toBe('Codex working') + expect(pty?.lastAgentStatus).toBe('working') + }) + + it('preserves a trailing escape after a completed OSC title', async () => { + const runtime = new OrcaRuntimeService(store) + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07\x1b', 100) + runtime.onPtyData('pty-1', ']0;Codex done\x07Visible\n', 101) + + const pty = ( + runtime as unknown as { + ptysById: Map + } + ).ptysById.get('pty-1') + expect(pty?.lastOscTitle).toBe('Codex done') + expect(pty?.lastAgentStatus).toBe('idle') + }) + + it('normalizes rotating Grok working-frame OSC titles to one stable stored title', async () => { + const runtime = new OrcaRuntimeService(store) + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', '\x1b]0;⠋ - Waiting for response… - grok\x07', 100) + const pty = ( + runtime as unknown as { + ptysById: Map + } + ).ptysById.get('pty-1') + expect(pty?.lastOscTitle).toBe('⠋ Grok') + expect(pty?.lastAgentStatus).toBe('working') + + // A different rotating frame must store an identical title — title + // equality is what stops per-frame session-tab and mobile-snapshot touch. + runtime.onPtyData('pty-1', '\x1b]0;⠴ - Thinking - grok\x07', 101) + expect(pty?.lastOscTitle).toBe('⠋ Grok') + expect(pty?.lastAgentStatus).toBe('working') + }) + + it('does not republish mobile session tabs for same-status Grok title frames', async () => { + const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' }) + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + const events: RuntimeMobileSessionTabsResult[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) + + await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'laptop-tab', + leafId: HEADLESS_LEAF_ID + }) + events.length = 0 + + runtime.onPtyData('laptop-created-pty', '\x1b]0;⠋ - Waiting for response… - grok\x07', 100) + runtime.onPtyData('laptop-created-pty', '\x1b]0;⠴ - Thinking - grok\x07', 101) + runtime.onPtyData('laptop-created-pty', '\x1b]0;⠙ - Responding - grok\x07', 102) + + await waitForMobileSessionTabsEvents(events, 1) + expect(events).toHaveLength(1) + expect(events[0]?.tabs[0]).toEqual( + expect.objectContaining({ + type: 'terminal', + title: '⠋ Grok', + agentStatus: expect.objectContaining({ state: 'working' }) + }) + ) + + unsubscribe() + }) + + // #7970: on a headless serve there is no renderer syncing tab.agentStatus, so + // hook-only transitions must republish the PTY-backed snapshot themselves and + // the snapshot must carry the retained hook payload, not just title evidence. + it('republishes mobile session tabs with hook payloads for title-less OSC 9999 transitions', async () => { + const spawn = vi.fn().mockResolvedValue({ id: 'hook-only-pty' }) + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + const events: RuntimeMobileSessionTabsResult[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) + + await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'hook-tab', + leafId: HEADLESS_LEAF_ID + }) + events.length = 0 + + runtime.onPtyData( + 'hook-only-pty', + '\x1b]9999;{"state":"working","prompt":"fix the tests","agentType":"opencode"}\x07', + 100 + ) + + await waitForMobileSessionTabsEvents(events, 1) + expect(events).toHaveLength(1) + expect(events[0]?.tabs[0]).toEqual( + expect.objectContaining({ + type: 'terminal', + agentStatus: expect.objectContaining({ + state: 'working', + prompt: 'fix the tests', + agentType: 'opencode' + }) + }) + ) + + runtime.onPtyData( + 'hook-only-pty', + '\x1b]9999;{"state":"waiting","prompt":"fix the tests","agentType":"opencode"}\x07', + 101 + ) + + await waitForMobileSessionTabsEvents(events, 2) + expect(events).toHaveLength(2) + expect(events[1]?.tabs[0]?.type === 'terminal' && events[1].tabs[0].agentStatus).toEqual( + expect.objectContaining({ state: 'waiting' }) + ) + + unsubscribe() + }) + + it('does not republish mobile session tabs for repeated identical OSC 9999 payloads', async () => { + const spawn = vi.fn().mockResolvedValue({ id: 'hook-ping-pty' }) + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + const events: RuntimeMobileSessionTabsResult[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) + + await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'hook-ping-tab', + leafId: HEADLESS_LEAF_ID + }) + events.length = 0 + + const payload = '\x1b]9999;{"state":"working","prompt":"same","agentType":"codex"}\x07' + runtime.onPtyData('hook-ping-pty', payload, 100) + runtime.onPtyData('hook-ping-pty', payload, 101) + runtime.onPtyData('hook-ping-pty', payload, 102) + + await waitForMobileSessionTabsEvents(events, 1) + expect(events).toHaveLength(1) + + unsubscribe() + }) + + it('suppresses a retained hook working status once the shell owns the pane title again', async () => { + const spawn = vi.fn().mockResolvedValue({ id: 'hook-exit-pty' }) + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + const events: RuntimeMobileSessionTabsResult[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) + + await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { + tabId: 'hook-exit-tab', + leafId: HEADLESS_LEAF_ID + }) + events.length = 0 + + runtime.onPtyData( + 'hook-exit-pty', + '\x1b]9999;{"state":"working","prompt":"long task","agentType":"codex"}\x07', + 100 + ) + // Agent exits without a hook done event; the shell takes the title back. + // The stuck-spinner guard (#1437) must win over the retained hook row. + runtime.onPtyData('hook-exit-pty', '\x1b]0;zsh\x07', 101) + + await waitForMobileSessionTabsEvents(events, 1) + const last = events.at(-1)?.tabs[0] + expect(last?.type).toBe('terminal') + expect(last?.type === 'terminal' ? last.agentStatus : null).toBeFalsy() + + unsubscribe() + }) + + it('stores normalized Pi idle OSC titles that still classify as idle', async () => { + const runtime = new OrcaRuntimeService(store) + syncSinglePty(runtime) + + runtime.onPtyData('pty-1', '\x1b]0;π - my-project\x07', 100) + const pty = ( + runtime as unknown as { + ptysById: Map + } + ).ptysById.get('pty-1') + expect(pty?.lastOscTitle).toBe('Pi') + expect(pty?.lastAgentStatus).toBe('idle') + // Why: worktree.ps / mobile re-detect from stored lastOscTitle, not the + // raw OSC frame. Bare "Pi" must still classify as idle after normalize. + expect(detectAgentStatusFromTitle(pty?.lastOscTitle ?? '')).toBe('idle') + }) + + it('normalizes hydration-seeded Grok and Pi titles the same as live OSC frames', async () => { + const runtime = new OrcaRuntimeService(store) + syncSinglePty(runtime) + + ;( + runtime as unknown as { + applySeededAgentStatus: (ptyId: string, title: string) => void + } + ).applySeededAgentStatus('pty-1', '⠴ - Thinking - grok') + const pty = ( + runtime as unknown as { + ptysById: Map + } + ).ptysById.get('pty-1') + expect(pty?.lastOscTitle).toBe('⠋ Grok') + // Seed writes leaf status only; re-detect from the stored title must still + // report working so later live frames compare equal and do not thrash. + expect(detectAgentStatusFromTitle(pty?.lastOscTitle ?? '')).toBe('working') + + ;( + runtime as unknown as { + applySeededAgentStatus: (ptyId: string, title: string) => void + } + ).applySeededAgentStatus('pty-1', 'π - my-project') + expect(pty?.lastOscTitle).toBe('Pi') + expect(detectAgentStatusFromTitle(pty?.lastOscTitle ?? '')).toBe('idle') }) - it('preserves a trailing escape after a completed OSC title', async () => { + it('stores other-agent OSC titles that merely end in grok unchanged', async () => { const runtime = new OrcaRuntimeService(store) syncSinglePty(runtime) - runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07\x1b', 100) - runtime.onPtyData('pty-1', ']0;Codex done\x07Visible\n', 101) - + runtime.onPtyData('pty-1', '\x1b]0;⠋ wire up grok\x07', 100) const pty = ( runtime as unknown as { - ptysById: Map + ptysById: Map } ).ptysById.get('pty-1') - expect(pty?.lastOscTitle).toBe('Codex done') - expect(pty?.lastAgentStatus).toBe('idle') + expect(pty?.lastOscTitle).toBe('⠋ wire up grok') + + // Claude/Codex braille + task ending " - grok" is not a Grok frame shape. + runtime.onPtyData('pty-1', '\x1b]0;⠋ fix the flaky suite - grok\x07', 101) + expect(pty?.lastOscTitle).toBe('⠋ fix the flaky suite - grok') }) it('seeds newly synced leaves from PTY pending ANSI state', async () => { @@ -12917,6 +14685,7 @@ describe('OrcaRuntimeService', () => { foregroundProcess.resolve('omp') await new Promise((resolve) => setImmediate(resolve)) + await waitForMobileSessionTabsEvents(events, 1) expect(events).toEqual([ expect.objectContaining({ @@ -12967,6 +14736,7 @@ describe('OrcaRuntimeService', () => { foregroundProcess.resolve('omp') await new Promise((resolve) => setImmediate(resolve)) + await waitForMobileSessionTabsEvents(events, 1) expect(events).toEqual([ expect.objectContaining({ @@ -13028,6 +14798,7 @@ describe('OrcaRuntimeService', () => { freshForegroundProcess.resolve('omp') await new Promise((resolve) => setImmediate(resolve)) + await waitForMobileSessionTabsEvents(events, 1) expect(getForegroundProcess).toHaveBeenCalledTimes(2) expect(events).toEqual([ @@ -13092,6 +14863,7 @@ describe('OrcaRuntimeService', () => { freshForegroundProcess.resolve('omp') await new Promise((resolve) => setImmediate(resolve)) + await waitForMobileSessionTabsEvents(events, 1) expect(events).toEqual([ expect.objectContaining({ @@ -14145,6 +15917,188 @@ describe('OrcaRuntimeService', () => { expect(activateWorktree).not.toHaveBeenCalled() }) + it('wakes slept agents on the host renderer when a phone activates a worktree', async () => { + // Seed isUnread:false so the unread-clear branch stays quiet and the + // assertions isolate the mobile slept-agent wake. + const metaById: Record = { + [TEST_WORKTREE_ID]: makeWorktreeMeta({ isUnread: false }) + } + const activateWorktree = vi.fn() + const resumeSleepingAgents = vi.fn() + const runtime = new OrcaRuntimeService({ + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + getWorkspaceSession: () => ({ + ...getDefaultWorkspaceSession(), + sleepingAgentSessionsByPaneKey: { + 'tab-1:leaf-1': { + paneKey: 'tab-1:leaf-1', + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + agent: 'codex', + providerSession: { key: 'session_id', id: 'session-1' }, + prompt: 'test', + state: 'done', + capturedAt: 1, + updatedAt: 1, + origin: 'worktree-sleep' + } + } + }) + } as never) + runtime.setNotifier({ + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree, + createTerminal: vi.fn(), + revealTerminalSession: vi.fn(), + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + focusTerminal: vi.fn(), + closeTerminal: vi.fn(), + sleepWorktree: vi.fn(), + resumeSleepingAgents, + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + }) + // A renderer must be attached to receive the wake — headless serve reports + // the explicit 'unsupported-headless' outcome instead (see below). + electronMocks.BrowserWindow.fromId.mockReturnValue({ isDestroyed: () => false } as never) + runtime.attachWindow(TEST_WINDOW_ID) + runtime.markGraphReady(TEST_WINDOW_ID) + + const result = await runtime.activateManagedWorktree(`id:${TEST_WORKTREE_ID}`, { + notifyClients: false, + clientKind: 'mobile' + }) + + // INV-2: mobile wake never navigates the desktop (no activateWorktree); it + // routes exclusively through the renderer's own navigation-free wake. + expect(resumeSleepingAgents).toHaveBeenCalledWith(TEST_WORKTREE_ID) + expect(activateWorktree).not.toHaveBeenCalled() + expect(result.sleepingAgentWake).toBe('requested') + }) + + it('reports the wake as unsupported when a phone activates a worktree on headless serve', async () => { + // Why: without an attached renderer nothing holds the sleeping records, so + // no agent actually wakes. The result must say so explicitly — activating + // silently would let the phone present slept agents as resumed (#7906). + const metaById: Record = { + [TEST_WORKTREE_ID]: makeWorktreeMeta({ isUnread: false }) + } + const resumeSleepingAgents = vi.fn() + const getWorkspaceSession = vi.fn(() => ({ + ...getDefaultWorkspaceSession(), + sleepingAgentSessionsByPaneKey: { + 'tab-1:leaf-1': { + paneKey: 'tab-1:leaf-1', + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + agent: 'codex', + providerSession: { key: 'session_id', id: 'session-1' }, + prompt: 'test', + state: 'done', + capturedAt: 1, + updatedAt: 1, + origin: 'worktree-sleep' + } + } + })) + const runtime = new OrcaRuntimeService({ + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + getWorkspaceSession + } as never) + runtime.setNotifier({ + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree: vi.fn(), + createTerminal: vi.fn(), + revealTerminalSession: vi.fn(), + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + focusTerminal: vi.fn(), + closeTerminal: vi.fn(), + sleepWorktree: vi.fn(), + resumeSleepingAgents, + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + }) + // Headless/no-live-renderer: the graph is ready but no BrowserWindow backs + // the authoritative id, so getAvailableAuthoritativeWindow() is null. + electronMocks.BrowserWindow.fromId.mockReturnValue(null as never) + runtime.attachWindow(TEST_WINDOW_ID) + runtime.markGraphReady(TEST_WINDOW_ID) + + const result = await runtime.activateManagedWorktree(`id:${TEST_WORKTREE_ID}`, { + notifyClients: false, + clientKind: 'mobile' + }) + + expect(result.activated).toBe(true) + expect(result.sleepingAgentWake).toBe('unsupported-headless') + // Why: sleeping records are host-partitioned; the check must read the + // repo's execution host partition, not always the local one. + expect(getWorkspaceSession).toHaveBeenCalledWith('local') + expect(resumeSleepingAgents).not.toHaveBeenCalled() + }) + + it('does not report headless wake degradation without sleeping records', async () => { + const runtime = new OrcaRuntimeService(store as never) + electronMocks.BrowserWindow.fromId.mockReturnValue(null as never) + runtime.attachWindow(TEST_WINDOW_ID) + runtime.markGraphReady(TEST_WINDOW_ID) + + const result = await runtime.activateManagedWorktree(`id:${TEST_WORKTREE_ID}`, { + notifyClients: false, + clientKind: 'mobile' + }) + + expect(result.sleepingAgentWake).toBe('not-applicable') + }) + + it('does not wake slept agents for non-mobile session-only activation', async () => { + const metaById: Record = { + [TEST_WORKTREE_ID]: makeWorktreeMeta({ isUnread: false }) + } + const resumeSleepingAgents = vi.fn() + const runtime = new OrcaRuntimeService({ + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId] + } as never) + runtime.setNotifier({ + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree: vi.fn(), + createTerminal: vi.fn(), + revealTerminalSession: vi.fn(), + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + focusTerminal: vi.fn(), + closeTerminal: vi.fn(), + sleepWorktree: vi.fn(), + resumeSleepingAgents, + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ isDestroyed: () => false } as never) + runtime.attachWindow(TEST_WINDOW_ID) + runtime.markGraphReady(TEST_WINDOW_ID) + + // INV-3: web/desktop runtime clients keep their existing wake-on-activation + // paths untouched — the renderer notifier wake is mobile-scoped. + const result = await runtime.activateManagedWorktree(`id:${TEST_WORKTREE_ID}`, { + notifyClients: false, + clientKind: 'runtime' + }) + + expect(resumeSleepingAgents).not.toHaveBeenCalled() + expect(result.sleepingAgentWake).toBe('not-applicable') + }) + it('does not rewrite unread metadata when a mobile activation finds the worktree already read', async () => { // Why: seed instanceId so worktree resolution does not emit its own // metadata-stamp write, isolating the assertion to the unread clear. @@ -14996,19 +16950,8 @@ describe('OrcaRuntimeService', () => { runtime.onPtyData('laptop-created-pty', '\x1b]0;Claude working\x07', 123) runtime.onPtyData('laptop-created-pty', '\x1b]0;Claude waiting for permission\x07', 124) + await waitForMobileSessionTabsEvents(events, 1) expect(events).toEqual([ - expect.objectContaining({ - tabs: [ - expect.objectContaining({ - type: 'terminal', - title: 'Claude working', - agentStatus: expect.objectContaining({ - state: 'working', - terminalHandle: laptopTerminal.handle - }) - }) - ] - }), expect.objectContaining({ tabs: [ expect.objectContaining({ @@ -15021,7 +16964,6 @@ describe('OrcaRuntimeService', () => { ] }) ]) - expect(events[1]!.snapshotVersion).toBeGreaterThan(events[0]!.snapshotVersion) unsubscribe() }) @@ -15047,19 +16989,14 @@ describe('OrcaRuntimeService', () => { runtime.onPtyData('laptop-created-pty', '\x1b]0;Claude working\x07', 123) runtime.onPtyData('laptop-created-pty', '\x1b]0;claude agents\x07', 124) + await waitForMobileSessionTabsEvents(events, 1) expect(events[0]?.tabs[0]).toEqual( - expect.objectContaining({ - type: 'terminal', - agentStatus: expect.objectContaining({ state: 'working' }) - }) - ) - expect(events[1]?.tabs[0]).toEqual( expect.objectContaining({ type: 'terminal', title: 'claude agents' }) ) - expect(events[1]?.tabs[0]).not.toHaveProperty('agentStatus') + expect(events[0]?.tabs[0]).not.toHaveProperty('agentStatus') unsubscribe() }) @@ -16042,6 +17979,157 @@ describe('OrcaRuntimeService', () => { }) }) + function makePendingAgentTabActivationRuntime(opts: { disabledTuiAgents?: string[] } = {}): { + runtime: OrcaRuntimeService + spawn: ReturnType + } { + const spawn = vi.fn().mockResolvedValue({ id: 'serve-materialized-pty' }) + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: 'serve-dead-pty', + worktreeId: TEST_WORKTREE_ID, + title: 'Terminal 1', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1, + launchAgent: 'claude' + } + ] + }, + terminalLayoutsByTabId: { + 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: 'serve-dead-pty' }) + } + }) + ) + const runtime = new OrcaRuntimeService({ + ...runtimeStore, + getSettings: () => ({ + ...store.getSettings(), + disabledTuiAgents: opts.disabledTuiAgents ?? [] + }) + } as never) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) + return { runtime, spawn } + } + + it('launches the pending agent when mobile activation materializes an agent tab', async () => { + const { runtime, spawn } = makePendingAgentTabActivationRuntime() + + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + expect(listed.tabs[0]).toMatchObject({ + type: 'terminal', + launchAgent: 'claude', + status: 'pending-handle' + }) + + // Why notifyClients false: this mirrors the phone tapping the tab, which is + // the path that materializes pending tabs headlessly (#7587 aftermath). + const activated = await runtime.activateMobileSessionTab( + `id:${TEST_WORKTREE_ID}`, + `host-tab::${HEADLESS_LEAF_ID}`, + undefined, + { notifyClients: false } + ) + + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ + command: expect.stringContaining('claude'), + sessionId: 'serve-dead-pty', + tabId: 'host-tab', + leafId: HEADLESS_LEAF_ID, + worktreeId: TEST_WORKTREE_ID + }) + ) + expect(activated.tabs[0]).toMatchObject({ + type: 'terminal', + launchAgent: 'claude', + status: 'ready' + }) + }) + + it('materializes a plain shell when the pending tab has no launch agent', async () => { + const spawn = vi.fn().mockResolvedValue({ id: 'serve-materialized-pty' }) + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal({ + tabsByWorktree: { + [TEST_WORKTREE_ID]: [ + { + id: 'host-tab', + ptyId: 'serve-dead-pty', + worktreeId: TEST_WORKTREE_ID, + title: 'Terminal 1', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: { + 'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: 'serve-dead-pty' }) + } + }) + ) + const runtime = new OrcaRuntimeService(runtimeStore as never) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) + + await runtime.activateMobileSessionTab( + `id:${TEST_WORKTREE_ID}`, + `host-tab::${HEADLESS_LEAF_ID}`, + undefined, + { notifyClients: false } + ) + + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: 'serve-dead-pty', worktreeId: TEST_WORKTREE_ID }) + ) + expect(spawn.mock.calls[0]![0].command).toBeUndefined() + }) + + it('falls back to a plain shell when the pending tab agent is disabled', async () => { + const { runtime, spawn } = makePendingAgentTabActivationRuntime({ + disabledTuiAgents: ['claude'] + }) + + const activated = await runtime.activateMobileSessionTab( + `id:${TEST_WORKTREE_ID}`, + `host-tab::${HEADLESS_LEAF_ID}`, + undefined, + { notifyClients: false } + ) + + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: 'serve-dead-pty', worktreeId: TEST_WORKTREE_ID }) + ) + expect(spawn.mock.calls[0]![0].command).toBeUndefined() + // Why: the disabled-agent fallback keeps the tab's agent identity; only the + // startup command is skipped. + expect(activated.tabs[0]).toMatchObject({ + type: 'terminal', + status: 'ready', + launchAgent: 'claude' + }) + }) + it('collapses duplicate mobile terminal entries when renderer and headless leaf ids diverge for the same pty', async () => { const rendererLeafId = HEADLESS_SECOND_LEAF_ID const ptyId = 'serve-persisted-pty' @@ -16527,6 +18615,7 @@ describe('OrcaRuntimeService', () => { events.length = 0 runtime.onPtyData('headless-pty-2', '\x1b]0;tab-other running\x07', 200) + await waitForMobileSessionTabsEvents(events, 1) const afterPtyData = events.at(-1) expect(afterPtyData?.activeTabId).toBe(`tab-other::${SECOND_LEAF}`) expect(afterPtyData?.activeTabType).toBe('terminal') @@ -17648,6 +19737,90 @@ describe('OrcaRuntimeService', () => { expect(first.tab).toMatchObject({ parentTabId: 'tab-renderer' }) }) + it('returns the settled success for a retried clientMutationId whose response was lost', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier({ + focusTerminal: vi.fn(), + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree: vi.fn(), + createTerminal: vi.fn(), + revealTerminalSession: vi.fn(), + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + closeTerminal: vi.fn(), + closeSessionTab: vi.fn(), + sleepWorktree: vi.fn(), + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + }) + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [ + { + tabId: 'tab-renderer', + worktreeId: TEST_WORKTREE_ID, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId: 'pty-renderer', + paneTitle: null + } + ], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'epoch-1', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: null, + activeTabType: null, + tabs: [ + { + type: 'terminal', + id: 'tab-renderer::pane:1', + parentTabId: 'tab-renderer', + leafId: 'pane:1', + title: 'Terminal', + isActive: false + } + ] + } + ] + }) + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-renderer', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const first = await runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: false, + clientMutationId: 'mutation-lost-response' + }) + // Why: the phone retries with the same key when the create response was + // lost in transit; within the retention window it must reuse the terminal. + const retried = await runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: false, + clientMutationId: 'mutation-lost-response' + }) + + const createRequests = send.mock.calls.filter( + ([channel]) => channel === 'terminal:requestTabCreate' + ) + expect(createRequests).toHaveLength(1) + expect(retried).toBe(first) + }) + it('does not dedupe mobile terminal creates across worktrees with the same clientMutationId', async () => { const otherWorktreeId = `${TEST_REPO_ID}::/tmp/worktree-b` vi.mocked(listWorktrees).mockResolvedValue([ @@ -17784,13 +19957,212 @@ describe('OrcaRuntimeService', () => { expect(second.tab).toMatchObject({ parentTabId: 'tab-renderer-b' }) }) - it('materializes a renderer-created mobile terminal whose surface stays pending', async () => { + it('materializes a renderer-created mobile terminal whose surface stays pending', async () => { + vi.useFakeTimers() + try { + const pendingLeafId = '33333333-3333-4333-8333-333333333333' + const closeTerminal = vi.fn() + const revealTerminalSession = vi.fn() + const spawn = vi.fn().mockResolvedValue({ id: 'pty-materialized' }) + const runtime = new OrcaRuntimeService(store) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + runtime.setNotifier({ + focusTerminal: vi.fn(), + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree: vi.fn(), + createTerminal: vi.fn(), + revealTerminalSession, + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + closeTerminal, + closeSessionTab: vi.fn(), + sleepWorktree: vi.fn(), + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + }) + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-pending', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: true + }) + let settled = false + const settledCreate = create.finally(() => { + settled = true + }) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'renderer-pending', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: `tab-pending::${pendingLeafId}`, + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: `tab-pending::${pendingLeafId}`, + parentTabId: 'tab-pending', + leafId: pendingLeafId, + title: 'Terminal', + isActive: true + } + ] + } + ] + }) + await vi.advanceTimersByTimeAsync(999) + + expect(settled).toBe(false) + expect(spawn).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1) + const result = await settledCreate + + expect(result.tab).toMatchObject({ + type: 'terminal', + parentTabId: 'tab-pending', + leafId: pendingLeafId, + status: 'ready', + terminal: expect.stringMatching(/^term_/), + isActive: true + }) + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: TEST_WORKTREE_PATH, + worktreeId: TEST_WORKTREE_ID, + tabId: 'tab-pending', + leafId: pendingLeafId, + persistHostSessionBinding: true, + preAllocatedHandle: expect.stringMatching(/^term_/) + }) + ) + expect(revealTerminalSession).toHaveBeenCalledWith( + TEST_WORKTREE_ID, + expect.objectContaining({ + ptyId: 'pty-materialized', + tabId: 'tab-pending', + leafId: pendingLeafId + }) + ) + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('rolls back a half-created terminal whose surface never publishes', async () => { + vi.useFakeTimers() + try { + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier({ + focusTerminal: vi.fn(), + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree: vi.fn(), + createTerminal: vi.fn(), + revealTerminalSession: vi.fn(), + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + closeTerminal, + closeSessionTab: vi.fn(), + sleepWorktree: vi.fn(), + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + }) + // Why: reply with a tabId but never sync a matching surface graph, so + // waitForMobileTerminalSurface times out and the rollback path runs. + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-ghost', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const pending = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: false + }) + const settled = pending.then( + () => ({ ok: true as const }), + (error: Error) => ({ ok: false as const, error }) + ) + await vi.advanceTimersByTimeAsync(11_000) + const outcome = await settled + + expect(outcome.ok).toBe(false) + expect(closeTerminal).toHaveBeenCalledWith('tab-ghost') + } finally { + vi.useRealTimers() + } + }) + + // Why: the five #7587 mobile-create tests need an identical full notifier where + // only closeTerminal is observed; one factory keeps notifier-interface changes + // in a single place. + function createMobileCreateTestNotifier( + closeTerminal: (tabId: string, paneRuntimeId?: number) => void + ) { + return { + focusTerminal: vi.fn(), + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree: vi.fn(), + createTerminal: vi.fn(), + revealTerminalSession: vi.fn(), + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + closeTerminal, + closeSessionTab: vi.fn(), + sleepWorktree: vi.fn(), + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + } + } + + it('rolls back a mobile create when the materialize spawn fails and no live PTY backs the tab', async () => { vi.useFakeTimers() try { - const pendingLeafId = '33333333-3333-4333-8333-333333333333' + const pendingLeafId = '99999999-9999-4999-8999-999999999999' const closeTerminal = vi.fn() - const revealTerminalSession = vi.fn() - const spawn = vi.fn().mockResolvedValue({ id: 'pty-materialized' }) + // Why: the renderer publishes a handle-less shell surface (no ptyId) and the + // runtime materialize spawn then fails, so NO live PTY ever backs the tab. + // The catch must roll back — the #7587 rescue is gated on a live PTY, not on + // the mere presence of a surface, or a dead shell would resolve as success. + const spawn = vi.fn().mockRejectedValue(new Error('spawn failed')) const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ spawn, @@ -17798,21 +20170,7 @@ describe('OrcaRuntimeService', () => { kill: () => true, getForegroundProcess: async () => null }) - runtime.setNotifier({ - focusTerminal: vi.fn(), - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession, - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - closeTerminal, - closeSessionTab: vi.fn(), - sleepWorktree: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) const webContents = { send: vi.fn() } const send = vi.fn((_channel: string, payload: { requestId: string }) => { ipcMain.emit( @@ -17832,12 +20190,13 @@ describe('OrcaRuntimeService', () => { const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { activate: true }) - let settled = false - const settledCreate = create.finally(() => { - settled = true - }) + const settled = create.then( + () => ({ ok: true as const }), + (error: Error) => ({ ok: false as const, error }) + ) await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + // Only the tab shell publishes (no ptyId → never ready); no PTY ever binds. runtime.syncWindowGraph(1, { tabs: [], leaves: [], @@ -17862,74 +20221,262 @@ describe('OrcaRuntimeService', () => { } ] }) - await vi.advanceTimersByTimeAsync(999) - expect(settled).toBe(false) - expect(spawn).not.toHaveBeenCalled() + // Ready-fallback (1s) expires → materialize runs → spawn rejects → catch. + await vi.advanceTimersByTimeAsync(2_000) + const outcome = await settled - await vi.advanceTimersByTimeAsync(1) + expect(outcome.ok).toBe(false) + expect(closeTerminal).toHaveBeenCalledWith('tab-pending') + } finally { + vi.useRealTimers() + } + }) + + it('keeps a mobile-created terminal alive when the renderer never publishes the surface', async () => { + vi.useFakeTimers() + try { + const leafId = '44444444-4444-4444-8444-444444444444' + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + // Why: reply with a tabId but NEVER sync a matching mobileSessionTabs graph, + // reproducing a throttled/hidden renderer that spawns the PTY yet stalls its + // graph-sync publication past the surface timeout (#7587). + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-alive', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: true + }) + let settled = false + const settledCreate = create.finally(() => { + settled = true + }) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // The renderer's own PTY spawn registers with the tab binding — the same + // call the pty IPC layer now makes — without any mobileSessionTabs sync. + runtime.registerPty('pty-alive', TEST_WORKTREE_ID, null, { + tabId: 'tab-alive', + leafId + }) + + // Resolves promptly, well under MOBILE_TERMINAL_SURFACE_TIMEOUT_MS (10s). + await vi.advanceTimersByTimeAsync(50) const result = await settledCreate + expect(settled).toBe(true) expect(result.tab).toMatchObject({ type: 'terminal', - parentTabId: 'tab-pending', - leafId: pendingLeafId, + parentTabId: 'tab-alive', + leafId, status: 'ready', - terminal: expect.stringMatching(/^term_/), - isActive: true + terminal: expect.stringMatching(/^term_/) }) - expect(spawn).toHaveBeenCalledWith( - expect.objectContaining({ - cwd: TEST_WORKTREE_PATH, - worktreeId: TEST_WORKTREE_ID, - tabId: 'tab-pending', - leafId: pendingLeafId, - persistHostSessionBinding: true, - preAllocatedHandle: expect.stringMatching(/^term_/) - }) - ) - expect(revealTerminalSession).toHaveBeenCalledWith( - TEST_WORKTREE_ID, - expect.objectContaining({ - ptyId: 'pty-materialized', - tabId: 'tab-pending', - leafId: pendingLeafId + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('keeps a mobile-created terminal alive when the renderer PTY spawn races ahead of the reply', async () => { + vi.useFakeTimers() + try { + const leafId = '55555555-5555-4555-8555-555555555555' + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + // Why: the spawn and the tabCreate reply travel independent IPC channels; + // here the renderer registers the live PTY before it replies, so only the + // create's immediate pre-wait check can resolve it — asserting it settles + // well under the surface timeout pins that site, not the catch backstop. + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + runtime.registerPty('pty-early', TEST_WORKTREE_ID, null, { + tabId: 'tab-early', + leafId }) - ) + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-early', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: true + }) + let settled = false + const settledCreate = create.finally(() => { + settled = true + }) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // Resolves via the immediate pre-wait rescue, well under the 10s timeout; + // reverting that site would only resolve later through the catch path. + await vi.advanceTimersByTimeAsync(50) + expect(settled).toBe(true) + const result = await settledCreate + + expect(result.tab).toMatchObject({ + type: 'terminal', + parentTabId: 'tab-early', + leafId, + status: 'ready', + terminal: expect.stringMatching(/^term_/) + }) expect(closeTerminal).not.toHaveBeenCalled() } finally { vi.useRealTimers() } }) - it('rolls back a half-created terminal whose surface never publishes', async () => { + it('keeps a mobile-created terminal alive when the renderer snapshot is rejected by the version guard', async () => { vi.useFakeTimers() try { + const leafId = '66666666-6666-4666-8666-666666666666' const closeTerminal = vi.fn() const runtime = new OrcaRuntimeService(store) - runtime.setNotifier({ - focusTerminal: vi.fn(), - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - revealTerminalSession: vi.fn(), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - closeTerminal, - closeSessionTab: vi.fn(), - sleepWorktree: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-guard', title: 'Terminal' } + ) }) - // Why: reply with a tabId but never sync a matching surface graph, so - // waitForMobileTerminalSurface times out and the rollback path runs. + webContents.send = send + runtime.attachWindow(1) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + // Why: seed an inflated stored version under a stable epoch (no headless / + // serve-owned tabs, so the preserve-merge can't lift the version via + // Math.max) — this is the state prior renderer publications leave behind. + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'epoch-guard', + snapshotVersion: 50, + activeGroupId: 'group-guard', + activeTabId: null, + activeTabType: null, + tabs: [] + } + ] + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: true + }) + let settled = false + const settledCreate = create.finally(() => { + settled = true + }) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // The renderer publishes the new tab, but with a stale (lower) version + // under the same epoch, so syncMobileSessionTabs rejects it and the surface + // never lands via graph-sync — the reporter's exact stall variant (#7587). + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'epoch-guard', + snapshotVersion: 1, + activeGroupId: 'group-guard', + activeTabId: `tab-guard::${leafId}`, + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: `tab-guard::${leafId}`, + parentTabId: 'tab-guard', + leafId, + title: 'Terminal', + isActive: true + } + ] + } + ] + }) + await vi.advanceTimersByTimeAsync(50) + // The rejected renderer sync must not have resolved the create. + expect(settled).toBe(false) + // Prove the rejection: the stored snapshot still lacks the tab. + const beforeRescue = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + expect( + beforeRescue.tabs.some((tab) => tab.type === 'terminal' && tab.parentTabId === 'tab-guard') + ).toBe(false) + + // The renderer's own PTY spawn registers with the binding and rescues it. + runtime.registerPty('pty-guard', TEST_WORKTREE_ID, null, { + tabId: 'tab-guard', + leafId + }) + await vi.advanceTimersByTimeAsync(50) + const result = await settledCreate + + expect(settled).toBe(true) + expect(result.tab).toMatchObject({ + type: 'terminal', + parentTabId: 'tab-guard', + leafId, + status: 'ready', + terminal: expect.stringMatching(/^term_/) + }) + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('keeps a mobile-created terminal alive at the surface timeout when only a leaf-synced PTY backs the tab', async () => { + vi.useFakeTimers() + try { + const leafId = '77777777-7777-4777-8777-777777777777' + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + // Why: the renderer pane identity can reach the runtime via leaf graph-sync + // (recordPtyWorktree) without registerPty, and leaf-sync never calls the + // pty-backed rescue; so when the mobileSessionTabs publication stalls past + // the surface timeout, only the catch-path rescue saves the live session — + // this pins the third #7587 rescue site, which the other tests never reach. const webContents = { send: vi.fn() } const send = vi.fn((_channel: string, payload: { requestId: string }) => { ipcMain.emit( 'terminal:tabCreateReply', { sender: webContents }, - { requestId: payload.requestId, tabId: 'tab-ghost', title: 'Terminal' } + { requestId: payload.requestId, tabId: 'tab-catch', title: 'Terminal' } ) }) webContents.send = send @@ -17940,18 +20487,51 @@ describe('OrcaRuntimeService', () => { webContents }) - const pending = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { - activate: false + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: true }) - const settled = pending.then( - () => ({ ok: true as const }), - (error: Error) => ({ ok: false as const, error }) - ) + let settled = false + const settledCreate = create.finally(() => { + settled = true + }) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // Let the create clear its immediate pre-wait check (no live PTY yet) and + // park in waitForMobileTerminalSurface before any identity arrives. + await vi.advanceTimersByTimeAsync(50) + + // Renderer pane identity arrives via leaf graph-sync — NOT registerPty — so + // no rescue fires here, and the mobileSessionTabs surface is never published. + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [ + { + tabId: 'tab-catch', + worktreeId: TEST_WORKTREE_ID, + leafId, + paneRuntimeId: 1, + ptyId: 'pty-catch' + } + ] + }) + + // Surface still unpublished, so the create is still pending. + expect(settled).toBe(false) + + // Cross MOBILE_TERMINAL_SURFACE_TIMEOUT_MS (10s): the catch path must rescue + // from the live PTY instead of rolling the session back destructively. await vi.advanceTimersByTimeAsync(11_000) - const outcome = await settled + const result = await settledCreate - expect(outcome.ok).toBe(false) - expect(closeTerminal).toHaveBeenCalledWith('tab-ghost') + expect(settled).toBe(true) + expect(result.tab).toMatchObject({ + type: 'terminal', + parentTabId: 'tab-catch', + leafId, + status: 'ready', + terminal: expect.stringMatching(/^term_/) + }) + expect(closeTerminal).not.toHaveBeenCalled() } finally { vi.useRealTimers() } @@ -18464,6 +21044,7 @@ describe('OrcaRuntimeService', () => { workspaceKind: 'git', worktreeId: 'repo-1::/tmp/worktree-a', repoId: 'repo-1', + terminalPlatform: process.platform, repo: 'repo', path: '/tmp/worktree-a', branch: 'feature/foo', @@ -18487,6 +21068,7 @@ describe('OrcaRuntimeService', () => { unread: false, liveTerminalCount: 1, hasAttachedPty: true, + lastActivityAt: 0, lastOutputAt: 321, preview: 'build green', agents: [] @@ -18519,6 +21101,128 @@ describe('OrcaRuntimeService', () => { expect(summary?.linkedPR).toEqual({ number: 42, state: 'merged' }) }) + it('carries persisted worktree host ownership in mobile summaries', async () => { + const metaById = { + [TEST_WORKTREE_ID]: { + ...store.getAllWorktreeMeta()[TEST_WORKTREE_ID], + hostId: 'runtime:owner-runtime' as const + } + } + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId] + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const { worktrees } = await runtime.getWorktreePs() + + expect(worktrees.find((worktree) => worktree.worktreeId === TEST_WORKTREE_ID)).toMatchObject({ + repoId: TEST_REPO_ID, + hostId: 'runtime:owner-runtime' + }) + }) + + it('emits only instance-validated lineage parents in mobile summaries', async () => { + // Regression: shipped mobile clients trust parentWorktreeId without instance + // checks, so worktree.ps must not emit stale same-path lineage from the store. + const parentPath = '/tmp/worktree-parent' + const validChildPath = '/tmp/worktree-child-valid' + const staleChildPath = '/tmp/worktree-child-stale' + const parentId = `${TEST_REPO_ID}::${parentPath}` + const validChildId = `${TEST_REPO_ID}::${validChildPath}` + const staleChildId = `${TEST_REPO_ID}::${staleChildPath}` + const metaById: Record = { + [parentId]: makeWorktreeMeta({ instanceId: 'parent-instance' }), + [validChildId]: makeWorktreeMeta({ instanceId: 'child-instance' }), + // The stale child path was reused by a replacement checkout. + [staleChildId]: makeWorktreeMeta({ instanceId: 'replacement-instance' }) + } + const makeLineage = (childId: string, worktreeInstanceId: string): WorktreeLineage => ({ + worktreeId: childId, + worktreeInstanceId, + parentWorktreeId: parentId, + parentWorktreeInstanceId: 'parent-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 1 + }) + const lineageById: Record = { + [validChildId]: makeLineage(validChildId, 'child-instance'), + [staleChildId]: makeLineage(staleChildId, 'old-child-instance') + } + const runtimeStore = { + ...store, + getAllWorktreeMeta: () => metaById, + getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], + setWorktreeMeta: (worktreeId: string, meta: Partial) => { + metaById[worktreeId] = { ...(metaById[worktreeId] ?? makeWorktreeMeta()), ...meta } + return metaById[worktreeId] + }, + getAllWorktreeLineage: () => lineageById, + getWorktreeLineage: (worktreeId: string) => lineageById[worktreeId] + } + vi.mocked(listWorktrees).mockResolvedValue( + [parentPath, validChildPath, staleChildPath].map((path) => ({ + path, + head: 'abc', + branch: `feature/${path.split('/').pop()}`, + isBare: false, + isMainWorktree: false + })) + ) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const { worktrees } = await runtime.getWorktreePs() + + expect(worktrees.find((worktree) => worktree.worktreeId === validChildId)).toMatchObject({ + parentWorktreeId: parentId, + worktreeInstanceId: 'child-instance', + lineageWorktreeInstanceId: 'child-instance', + parentWorktreeInstanceId: 'parent-instance' + }) + const staleSummary = worktrees.find((worktree) => worktree.worktreeId === staleChildId) + expect(staleSummary).toMatchObject({ + parentWorktreeId: null, + worktreeInstanceId: 'replacement-instance' + }) + expect(staleSummary?.lineageWorktreeInstanceId).toBeUndefined() + expect(staleSummary?.parentWorktreeInstanceId).toBeUndefined() + expect(worktrees.find((worktree) => worktree.worktreeId === parentId)).toMatchObject({ + childWorktreeIds: [validChildId] + }) + }) + + it('reports the resolved terminal platform for WSL project mobile summaries', async () => { + await withPlatform('win32', async () => { + const runtime = new OrcaRuntimeService({ + ...store, + getProjects: () => [ + { + id: 'project-1', + displayName: 'repo', + badgeColor: 'blue', + sourceRepoIds: [TEST_REPO_ID], + localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }, + createdAt: 0, + updatedAt: 0 + } + ], + getSettings: () => ({ + ...store.getSettings(), + localWindowsRuntimeDefault: { kind: 'windows-host' } + }) + } as never) + + const { worktrees } = await runtime.getWorktreePs() + + expect(worktrees.find((worktree) => worktree.worktreeId === TEST_WORKTREE_ID)).toMatchObject({ + repoId: TEST_REPO_ID, + terminalPlatform: 'linux' + }) + }) + }) + it('omits worktrees hidden by the host visibility policy from mobile summaries', async () => { const hiddenExternalRepo = { ...store.getRepos()[0], @@ -19555,19 +22259,22 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService(runtimeStore as never) const result = await runtime.searchRepoRefs('id:remote-repo', '', 1) + const repeatedResult = await runtime.searchRepoRefs('id:remote-repo', '', 1) expect(result).toEqual({ refs: ['origin/main'], refDetails: [{ refName: 'origin/main', localBranchName: 'main' }], truncated: true }) + expect(repeatedResult).toEqual(result) const forEachRefCalls = provider.exec.mock.calls.filter( (call) => (call[0] as string[])[0] === 'for-each-ref' ) - expect(forEachRefCalls).toHaveLength(2) + expect(forEachRefCalls).toHaveLength(3) expect(forEachRefCalls[0][0]).toContain('--exclude=refs/remotes/**/HEAD') expect(forEachRefCalls[1][0]).not.toContain('--exclude=refs/remotes/**/HEAD') expect(forEachRefCalls[1][0]).toContain('--count=108') + expect(forEachRefCalls[2][0]).not.toContain('--exclude=refs/remotes/**/HEAD') }) it('resolves SSH worktrees when manually updating lineage', async () => { @@ -24403,6 +27110,10 @@ describe('OrcaRuntimeService', () => { stderr: 'error: failed to delete deep/file.txt: Filename too long' }) ) + vi.mocked(listWorktreesStrict) + .mockResolvedValueOnce(MOCK_GIT_WORKTREES) + .mockResolvedValueOnce(MOCK_GIT_WORKTREES) + .mockResolvedValue([]) try { const result = await runtime.removeManagedWorktree(TEST_WORKTREE_ID, true) @@ -24424,7 +27135,7 @@ describe('OrcaRuntimeService', () => { } }) - it('keeps runtime metadata when long-path recovery deletes the directory but prune fails', async () => { + it('refuses runtime Windows recovery while Git still reports the row and keeps metadata', async () => { setPlatform('win32') const removeWorktreeMeta = vi.fn() const runtimeStore = { @@ -24432,11 +27143,13 @@ describe('OrcaRuntimeService', () => { removeWorktreeMeta } const runtime = new OrcaRuntimeService(runtimeStore as never) - const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockRejectedValue( - Object.assign(new Error('git prune failed'), { - stderr: 'fatal: unable to lock worktree admin dir' - }) - ) + const gitSpy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockResolvedValue({ + stdout: '', + stderr: '' + }) + const removePathSpy = vi + .spyOn(localWorktreeFilesystem, 'removeLocalWorktreePath') + .mockResolvedValue(undefined) vi.mocked(getEffectiveHooks).mockReturnValue(null) vi.mocked(removeWorktree).mockRejectedValue( Object.assign(new Error('git worktree remove failed'), { @@ -24446,10 +27159,13 @@ describe('OrcaRuntimeService', () => { try { await expect(runtime.removeManagedWorktree(TEST_WORKTREE_ID, true)).rejects.toThrow( - 'Git still has stale worktree registration' + `Failed to force delete worktree at ${TEST_WORKTREE_PATH}. error: failed to delete deep/file.txt: Filename too long` ) + expect(removePathSpy).not.toHaveBeenCalled() + expect(gitSpy).not.toHaveBeenCalledWith(['worktree', 'prune'], expect.anything()) expect(removeWorktreeMeta).not.toHaveBeenCalled() } finally { + removePathSpy.mockRestore() gitSpy.mockRestore() } }) @@ -24481,7 +27197,7 @@ describe('OrcaRuntimeService', () => { stderr: '' }) vi.mocked(listWorktrees).mockResolvedValue(registeredWorktrees) - vi.mocked(listWorktreesStrict).mockResolvedValue(registeredWorktrees) + vi.mocked(listWorktreesStrict).mockResolvedValueOnce(registeredWorktrees).mockResolvedValue([]) vi.mocked(getEffectiveHooks).mockReturnValue({ scripts: { archive: 'pnpm worktree:archive' @@ -24505,6 +27221,34 @@ describe('OrcaRuntimeService', () => { } }) + it('preserves a locked missing runtime registration even with force', async () => { + setPlatform('win32') + const missingWorktreePath = 'C:\\workspace\\locked-already-removed' + const worktreeId = `${TEST_REPO_ID}::${missingWorktreePath}` + const { runtimeStore, removeWorktreeMeta } = createStaleRuntimeWorktreeStore(worktreeId) + const runtime = new OrcaRuntimeService(runtimeStore as never) + const registeredWorktrees = [ + { + path: missingWorktreePath, + head: 'abc', + branch: 'refs/heads/feature/foo', + isBare: false, + isMainWorktree: false, + locked: true, + lockReason: 'active agent session' + } + ] + vi.mocked(listWorktreesStrict).mockResolvedValue(registeredWorktrees) + vi.mocked(removeWorktree).mockResolvedValue({}) + + await expect(runtime.removeManagedWorktree(worktreeId, true, false)).rejects.toThrow( + 'Worktree is locked by Git. Lock reason: active agent session' + ) + + expect(removeWorktree).not.toHaveBeenCalled() + expect(removeWorktreeMeta).not.toHaveBeenCalled() + }) + it('routes runtime worktree removal through the selected WSL project runtime', async () => { setPlatform('win32') const runtimeStore = { @@ -25233,6 +27977,83 @@ describe('OrcaRuntimeService', () => { expect(removeWorktree).not.toHaveBeenCalled() }) + it('fails locked dirty-force deletes before hooks, link cleanup, or PTY teardown', async () => { + const repo = { ...store.getRepos()[0], symlinkPaths: ['node_modules'] } + const runtimeStore = { + ...store, + getRepos: () => [repo], + getRepo: () => repo + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + const killSpy = vi.fn().mockReturnValue(true) + runtime.setPtyController({ + write: () => true, + kill: (id) => killSpy(id), + getForegroundProcess: async () => null + }) + syncSinglePty(runtime, 'pty-1') + vi.mocked(getEffectiveHooks).mockReturnValue({ + scripts: { archive: 'pnpm worktree:archive' } + }) + vi.mocked(listWorktreesStrict).mockResolvedValue([ + { + ...MOCK_GIT_WORKTREES[0], + locked: true, + lockReason: 'active agent session' + } + ]) + + await expect(runtime.removeManagedWorktree(TEST_WORKTREE_ID, true, true)).rejects.toThrow( + `Failed to force delete worktree at ${TEST_WORKTREE_PATH}. Worktree is locked by Git.` + ) + + expect(assertWorktreeCleanForRemoval).not.toHaveBeenCalled() + expect(runHook).not.toHaveBeenCalled() + expect(removeWorktreeLinkedPathsMock).not.toHaveBeenCalled() + expect(killSpy).not.toHaveBeenCalled() + expect(removeWorktree).not.toHaveBeenCalled() + }) + + it('rechecks a runtime Git lock after the archive hook before teardown', async () => { + const repo = { ...store.getRepos()[0], symlinkPaths: ['node_modules'] } + const runtimeStore = { + ...store, + getRepos: () => [repo], + getRepo: () => repo + } + const runtime = new OrcaRuntimeService(runtimeStore as never) + const killSpy = vi.fn().mockReturnValue(true) + runtime.setPtyController({ + write: () => true, + kill: (id) => killSpy(id), + getForegroundProcess: async () => null + }) + syncSinglePty(runtime, 'pty-1') + vi.mocked(getEffectiveHooks).mockReturnValue({ + scripts: { archive: 'pnpm worktree:archive' } + }) + vi.mocked(runHook).mockResolvedValue({ success: true, output: '' }) + vi.mocked(listWorktreesStrict) + .mockResolvedValueOnce(MOCK_GIT_WORKTREES) + .mockResolvedValueOnce([ + { + ...MOCK_GIT_WORKTREES[0], + locked: true, + lockReason: 'locked during archive' + } + ]) + + await expect(runtime.removeManagedWorktree(TEST_WORKTREE_ID, true, true)).rejects.toThrow( + 'Worktree is locked by Git' + ) + + expect(runHook).toHaveBeenCalled() + expect(removeWorktreeLinkedPathsMock).not.toHaveBeenCalled() + expect(assertWorktreeCleanForRemoval).not.toHaveBeenCalled() + expect(killSpy).not.toHaveBeenCalled() + expect(removeWorktree).not.toHaveBeenCalled() + }) + it('formats preflight subprocess failures and skips PTY teardown', async () => { const runtime = new OrcaRuntimeService(store) const killSpy = vi.fn().mockReturnValue(true) @@ -25979,4 +28800,226 @@ describe('OrcaRuntimeService', () => { expect(preDaemonProvider.shutdown).not.toHaveBeenCalled() }) }) + describe('stale terminal handle resolution (#7718)', () => { + function syncSingleTerminalGraph(runtime: OrcaRuntimeService, ptyId: string): void { + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + title: 'Terminal 1', + activeLeafId: 'pane:1', + layout: null + } + ], + leaves: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId, + paneTitle: 'Terminal 1' + } + ], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'epoch-1', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: 'tab-1::pane:1', + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: 'tab-1::pane:1', + parentTabId: 'tab-1', + leafId: 'pane:1', + title: 'Terminal 1', + isActive: true + } + ] + } + ] + }) + } + + // Why: session-tab mirrors travel as PTY handles, but client-created + // terminals (terminal.create) hold LEAF handles — the kind that can + // diverge from the pane's current PTY across reconnects. Issue one + // directly from the leaf record to pin the resolver semantics. + function issueLeafHandle(runtime: OrcaRuntimeService, ptyId: string): string { + const internals = runtime as unknown as { + leaves: Map + issueHandle: (leaf: unknown) => string + } + const leaf = Array.from(internals.leaves.values()).find( + (candidate) => candidate.ptyId === ptyId + ) + if (!leaf) { + throw new Error('expected leaf record') + } + return internals.issueHandle(leaf) + } + + it('errors with terminal_handle_stale instead of adopting a replacement PTY', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.attachWindow(1) + syncSingleTerminalGraph(runtime, 'pty-a') + const handle = issueLeafHandle(runtime, 'pty-a') + + // Simulate the pane's PTY being replaced while the remote client still + // holds the old handle (the record missed the swap, e.g. across a + // renderer graph reload that preserved live PTY records). + const internals = runtime as unknown as { + leaves: Map + } + for (const leaf of internals.leaves.values()) { + if (leaf.ptyId === 'pty-a') { + leaf.ptyId = 'pty-b' + } + } + + // The unguarded resolver silently adopts the new PTY — the misroute. + expect(runtime.resolveLeafForHandle(handle)).toEqual({ ptyId: 'pty-b' }) + // The guarded resolver surfaces the staleness so clients can re-derive. + expect(() => runtime.resolveLiveLeafForHandle(handle)).toThrow('terminal_handle_stale') + }) + + it('lets a handle issued before its first PTY adopt that PTY without erroring', async () => { + const runtime = new OrcaRuntimeService(store) + runtime.attachWindow(1) + syncSingleTerminalGraph(runtime, 'pty-a') + const handle = issueLeafHandle(runtime, 'pty-a') + + // Simulate the mobile pre-spawn flow: the handle record predates the + // PTY (ptyId null); the pane's first PTY must still resolve. + const internals = runtime as unknown as { + handles: Map + } + const record = internals.handles.get(handle) + if (!record) { + throw new Error('expected handle record') + } + record.ptyId = null + + expect(runtime.resolveLiveLeafForHandle(handle)).toEqual({ ptyId: 'pty-a' }) + }) + }) + + describe('mobile terminal create resilience (#7718)', () => { + it('cancels the surface wait without rolling back when the client connection dies', async () => { + vi.useFakeTimers() + try { + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + const abort = new AbortController() + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-abort', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: false, + signal: abort.signal + }) + const settled = create.then( + () => ({ ok: true as const }), + (error: Error) => ({ ok: false as const, error }) + ) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // The client's socket dies mid-wait. The create must settle right away + // (not run down the 10s surface timeout) and must NOT close the tab — + // the renderer spawned a real terminal the host user can see. + abort.abort() + await vi.advanceTimersByTimeAsync(0) + const outcome = await settled + + expect(outcome.ok).toBe(false) + if (outcome.ok === false) { + expect(outcome.error.message).toBe('client_disconnected') + } + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('keeps a mobile-created terminal alive when its live shell has no registered pane key', async () => { + vi.useFakeTimers() + try { + const closeTerminal = vi.fn() + const runtime = new OrcaRuntimeService(store) + runtime.setNotifier(createMobileCreateTestNotifier(closeTerminal)) + const webContents = { send: vi.fn() } + const send = vi.fn((_channel: string, payload: { requestId: string }) => { + ipcMain.emit( + 'terminal:tabCreateReply', + { sender: webContents }, + { requestId: payload.requestId, tabId: 'tab-stall', title: 'Terminal' } + ) + }) + webContents.send = send + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + electronMocks.BrowserWindow.fromId.mockReturnValue({ + isDestroyed: () => false, + webContents + }) + + const create = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { + activate: false + }) + const settled = create.then( + () => ({ ok: true as const }), + (error: Error) => ({ ok: false as const, error }) + ) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1)) + + // A live shell backs the tab, but its leaf id is not a terminal UUID + // so no pane key registers: the surface rescue can't publish it, and + // the surface itself never publishes (stalled renderer publication). + runtime.syncWindowGraph(1, { + tabs: [], + leaves: [ + { + tabId: 'tab-stall', + worktreeId: TEST_WORKTREE_ID, + leafId: 'pane:1', + paneRuntimeId: 1, + ptyId: 'pty-stall', + paneTitle: null + } + ] + }) + + await vi.advanceTimersByTimeAsync(11_000) + const outcome = await settled + + // The create still fails (nothing to return), but the timeout must not + // kill the live terminal — that is the "tab dies after ~10s" symptom. + expect(outcome.ok).toBe(false) + if (outcome.ok === false) { + expect(outcome.error.message).toContain('Timed out') + } + expect(closeTerminal).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + }) }) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index e6a5bcbfa956..b7e4c1d2c30c 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -2,16 +2,28 @@ /* eslint-disable unicorn/no-useless-spread -- Why: waiter sets and handle keys are cloned intentionally before mutation so resolution and rejection can safely remove entries while iterating. */ /* eslint-disable no-control-regex -- Why: terminal normalization must strip ANSI and OSC control sequences from PTY output before returning bounded text to agents. */ import { - extractLastOscTitle, detectAgentStatusFromTitle, isClaudeManagementTitle, - isShellProcess + isCursorNativeAgentTitle, + isShellProcess, + normalizeTerminalTitle } from '../../shared/agent-detection' import { extractOscTitleScanTail } from '../../shared/osc-title-scan-tail' import { extractLastOsc7Uri, extractOscScanTail } from '../daemon/osc7-uri-extraction' import { parseFileUriPathParts } from '../daemon/osc7-file-uri' import type { AgentStatus } from '../../shared/agent-detection' import type { TerminalOscLinkRange } from '../../shared/terminal-osc-link-ranges' +import { + createTerminalTitleTracker, + stripBrailleSpinnerGlyphs, + type TerminalTitleTracker +} from '../../shared/terminal-output-side-effects' +import { createCommandCodeOutputStatusDetector } from '../../shared/command-code-output-status' +import type { + TerminalSideEffectBatch, + TerminalSideEffectFact +} from '../../shared/terminal-side-effect-facts' +import type { TerminalGitHubPRLink } from '../../shared/terminal-github-pr-link-detector' import { AGENT_STATUS_STALE_AFTER_MS, type AgentStatusIpcPayload, @@ -34,7 +46,13 @@ import { TERMINAL_INPUT_TOO_LARGE_ERROR, iterateTerminalInputChunks } from '../../shared/terminal-input' -import { gitExecFileAsync, wslAwareSpawn } from '../git/runner' +import { + AGENT_PROMPT_BRACKETED_PASTE_END, + AGENT_PROMPT_SUBMIT, + AGENT_PROMPT_SUBMIT_DELAY_MS, + buildAgentPromptPasteBytes +} from '../../shared/agent-prompt-injection' +import { gitExecFileAsync, gitSpawn } from '../git/runner' import { cleanupClaimedCloneTarget, claimCloneTarget, @@ -42,6 +60,7 @@ import { getClonePathComparisonKey } from '../git/repo-clone-path' import { getGitCloneFailureMessage } from '../../shared/git-clone-failure-message' +import { GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS } from '../../shared/git-fetch-auto-maintenance' import { createHash, randomUUID } from 'node:crypto' import { homedir } from 'node:os' import { isAbsolute, join, resolve } from 'node:path' @@ -120,9 +139,16 @@ import type { WorkspaceSessionState, DirEntry } from '../../shared/types' +import { assertWorktreeUnlockedForRemoval } from '../../shared/worktree-removal' +import { + getRepoExecutionHostId, + parseExecutionHostId, + type ExecutionHostId +} from '../../shared/execution-host' import type { SleepingAgentLaunchConfig } from '../../shared/agent-session-resume' import type { RuntimeClientEvent } from '../../shared/runtime-client-events' import { toRuntimeActivateWorktreeEvent } from '../../shared/runtime-client-events' +import type { SshConnectionState } from '../../shared/ssh-types' import type { LinearCurrentIssueContextHints, LinearAttachResult, @@ -175,7 +201,7 @@ import { TASK_PROVIDERS } from '../../shared/task-providers' import { FIRST_PANE_ID } from '../../shared/pane-key' import { isTerminalLeafId, makePaneKey, parsePaneKey } from '../../shared/stable-pane-id' import { parseAppSshPtyId } from '../../shared/ssh-pty-id' -import { isValidHostTerminalTabId } from '../../shared/terminal-tab-id' +import { isValidHostTerminalTabId, isValidTerminalTabId } from '../../shared/terminal-tab-id' import { buildAgentDraftLaunchPlan, buildAgentStartupPlan } from '../../shared/tui-agent-startup' import { repoIsRemote } from '../../shared/agent-launch-remote' import { @@ -209,7 +235,6 @@ import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' import { resolveTerminalStartupCwd } from '../../shared/terminal-startup-cwd' -import { localTerminalCwdCanonicalizer } from '../pty/terminal-cwd-realpath' import { isWslUncPath } from '../../shared/wsl-paths' import { folderWorkspaceKey, @@ -234,6 +259,11 @@ import { RUNTIME_PROTOCOL_VERSION, type RuntimeCapability } from '../../shared/protocol-version' +import { + configureAiVaultSessionSources, + listAiVaultSessions +} from '../ai-vault/cached-session-list' +import type { AiVaultListArgs, AiVaultListResult } from '../../shared/ai-vault-types' import type { WorkspacePortKillRequest, WorkspacePortKillResult, @@ -440,8 +470,8 @@ import { toLocalWorktreeRuntimePath } from '../local-worktree-filesystem' import { - pruneStaleLocalWorktreeRegistrationAfterFilesystemRemoval, - recoverLocalWindowsLongPathWorktreeRemoval + removeStaleLocalWorktreeRegistrationAfterFilesystemRemoval, + recoverLocalWindowsWorktreeRemoval } from '../local-worktree-removal-recovery' import { connect as connectLinear, @@ -468,7 +498,8 @@ import { updateIssueForAgent as updateLinearIssueForAgent, updateIssue as updateLinearIssue, LinearWriteFailure, - type LinearListFilter + type LinearListFilter, + type LinearIssueListOptions } from '../linear/issues' import { LinearAgentAccessError, @@ -520,6 +551,7 @@ import { createIssue as createJiraIssue, getIssue as getJiraIssue, getIssueComments as getJiraIssueComments, + getProjectStatusOrder as getJiraProjectStatusOrder, listAssignableUsers as listJiraAssignableUsers, listCreateFields as listJiraCreateFields, listIssueTypes as listJiraIssueTypes, @@ -587,6 +619,7 @@ import { import { hasCommitObjectViaGitExec } from '../git/commit-object-ref' import { hasWorktreeBaseCommitRef } from '../git/worktree-base-ref-probe' import { resolveLocalGitUsername } from '../git/git-username' +import { getSshGitCapabilityCache } from '../git/git-capability-state' import { listWorktrees, listWorktreesStrict, @@ -668,10 +701,28 @@ import { prefetchWorktreeCreateBase } from '../worktree-create-base-prefetch' import { invalidateAuthorizedRootsCache } from '../ipc/filesystem-auth' import { prepareLocalWorktreeRootForRepo } from '../worktree-root-preparation' import { closeLocalWatcherForWorktreePath } from '../ipc/filesystem-watcher' -import { HeadlessEmulator, type HeadlessEmulatorOptions } from '../daemon/headless-emulator' +import { HeadlessEmulator } from '../daemon/headless-emulator' +import { + isNativeWindowsConptyPty, + registerConptyDa1OverrideInstaller, + shouldModelAnswerHiddenPtyQueries +} from './terminal-model-query-authority' +import { + getTerminalViewAttributes, + registerTerminalViewAttributesApplier +} from './terminal-view-attribute-store' import { killAllProcessesForWorktree } from './worktree-teardown' import { MOBILE_SUBSCRIBE_SCROLLBACK_ROWS } from './scrollback-limits' -import type { IFilesystemProvider, IPtyProvider, PtyProcessInfo } from '../providers/types' +import { + createMobileSessionTabsNotifyCoalescer, + type MobileSessionTabsNotifyCoalescer +} from './mobile-session-tabs-notify-coalescer' +import type { + IFilesystemProvider, + IPtyProvider, + PtyProcessInfo, + PtyTransientFact +} from '../providers/types' import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' import { assertFolderWorkspacePathUsable, @@ -807,6 +858,11 @@ type RuntimeStore = { mobileEmulatorDefaultDeviceUdid?: string | null voice?: VoiceSettings claudeAgentTeamsMode?: GlobalSettings['claudeAgentTeamsMode'] + // Why: Phase-5 query responder kill switches — read per chunk in + // onPtyData to capture reply ownership at ingestion. + terminalMainSideEffectAuthority?: GlobalSettings['terminalMainSideEffectAuthority'] + terminalHiddenDeliveryGate?: GlobalSettings['terminalHiddenDeliveryGate'] + terminalModelQueryAuthority?: GlobalSettings['terminalModelQueryAuthority'] } // Why: narrow to `unknown` return so test mocks can return void without // a cast. The runtime never reads the return value — the persisted value @@ -1071,6 +1127,28 @@ export type RuntimeTerminalAgentStatusEvent = { payload: ParsedAgentStatusPayload } +type RuntimePtyTitleTrackerEntry = { + tracker: TerminalTitleTracker + // Why: onPtyData batches the mobile session-tab touch to once per chunk; + // the stale-working-title timer fires between chunks and must touch + // immediately. These flags route the tracker callback to the right mode. + applyingChunk: boolean + // Why: synthetic spinner ticks arrive ~12.5x/sec per working pane; the + // synthetic path gates mobile snapshot fan-out on a non-decorative title + // change (spinner glyph + status comparison key kept below). + applyingSyntheticFrame: boolean + lastMobileTitleGateKey: string | null + chunkTouchedSessionTabs: boolean + // Why: facts observed while applying a chunk are batched into one + // pty:sideEffect emission per chunk, preserving byte order (titles in + // sequence, then bell). Timer-fired facts emit immediately between chunks. + pendingFacts: TerminalSideEffectFact[] + // Why: Command Code lacks hooks, so its working/done state is scraped from + // TUI output. Null when no side-effect consumer exists (headless serve) — + // the scrape produces facts only. + commandCodeDetector: { observe: (data: string) => boolean } | null +} + // Why: the full OSC 9999 payload flows through emitTerminalAgentStatusEvents and // is then forwarded to the renderer and dropped. Mobile is served by the main // process and has no renderer store, so we retain the latest payload per pane @@ -1097,6 +1175,10 @@ type RuntimeHeadlessTerminal = { type HeadlessSeedMetadata = { cwd?: string | null oscLinks?: TerminalOscLinkRange[] + /** Persisted kitty flags from the daemon snapshot, re-applied to the fresh + * emulator so hidden `CSI ? u` answers the real flags instead of ?0u + * (terminal-query-authority.md §kitty). */ + kittyKeyboardFlags?: number } type RuntimePtyController = { @@ -1164,6 +1246,9 @@ function getAgentLaunchPlatformForRepo( return isWindowsAbsolutePathLike(repo.path) ? 'win32' : 'linux' } +// Why: long enough for a phone to reconnect and retry a create whose response +// was lost, short enough that an intentional later re-resume forks fresh. +const MOBILE_TERMINAL_CREATE_RESULT_TTL_MS = 60_000 const FOREGROUND_AGENT_WRAPPER_RETRY_INTERVAL_MS = 150 const FOREGROUND_AGENT_WRAPPER_RETRY_TIMEOUT_MS = 6_500 const BRACKETED_PASTE_BEGIN = '\x1b[200~' @@ -1177,6 +1262,10 @@ const RECENT_PTY_PATH_CANDIDATE_LIMIT = 1024 const RECENT_PTY_PATH_CANDIDATE_MAX_BYTES = 4 * 1024 const RECENT_PTY_PATH_CANDIDATE_TOTAL_BYTES = 64 * 1024 +function isClientDisconnectedError(error: unknown): boolean { + return error instanceof Error && error.message === 'client_disconnected' +} + function createTerminalRevealWarning(handle: string, error?: unknown): string { const reason = error instanceof Error && error.message.trim().length > 0 @@ -1281,6 +1370,11 @@ type RuntimeNotifier = { ): Promise closeTerminal(tabId: string, paneRuntimeId?: number): void sleepWorktree(worktreeId: string): void + // Why: a phone opening a worktree wakes its slept agents by asking the host + // renderer to run its own navigation-free wake (experimental agent sleep); + // the runtime has no in-memory sleeping records or wake authority. Optional to + // match the many renderer-backed notifier methods only the real bridge wires. + resumeSleepingAgents?(worktreeId: string): void terminalFitOverrideChanged( ptyId: string, mode: 'mobile-fit' | 'desktop-fit', @@ -1409,6 +1503,22 @@ function getRuntimeFolderWorkspaceRootId(repo: Repo): string { return `${repo.id}::${repo.path}` } +// Null executionHostId means host-unaware: path-only callers match any repo, and the first runtime +// host can adopt a legacy (unstamped) repo. But an unstamped repo with a connectionId is an SSH repo +// (resolves to ssh:), so it must not be adopted/matched by a runtime host at the same path. +function runtimeRepoMatchesExecutionHost( + repo: Pick, + executionHostId?: ExecutionHostId | null +): boolean { + if (executionHostId == null) { + return true + } + if (repo.executionHostId != null) { + return repo.executionHostId === executionHostId + } + return repo.connectionId == null +} + function getRuntimeFolderWorkspaceInstanceId(repo: Repo, instanceId: string): string { return `${getRuntimeFolderWorkspaceRootId(repo)}${FOLDER_WORKSPACE_INSTANCE_SEPARATOR}${instanceId}` } @@ -2011,7 +2121,23 @@ export class OrcaRuntimeService { string, Promise >() + // Why: a mobile create waits for the renderer to publish the new tab's surface + // via graph-sync, but a throttled/hidden renderer can park that past the surface + // timeout and the create would then destroy the live PTY (#7587). This lets the + // renderer's own PTY spawn publish the surface main-side, scoped to in-flight + // creates so ordinary renderer spawns never publish here. + private pendingMobileTerminalCreatesByKey = new Map< + string, + { activate: boolean; selectIfNoActiveTab: boolean } + >() private mobileSessionTabListeners = new Set<(snapshot: RuntimeMobileSessionTabsResult) => void>() + // Why: coalesces title/status-driven session.tabs emits so spinner churn + // doesn't fan out (and per-client JSON.stringify) a snapshot several times a + // second. Emit reads the latest snapshot, so only the freshest version ships. + private readonly mobileSessionTabsNotifyCoalescer: MobileSessionTabsNotifyCoalescer = + createMobileSessionTabsNotifyCoalescer((worktreeId) => + this.notifyMobileSessionTabsChangedNow(worktreeId) + ) private leaves = new Map() // Why: PTY output is a per-keystroke hot path. Looking up affected leaves by // ptyId keeps active TUI redraws independent of the total open terminal count. @@ -2084,12 +2210,39 @@ export class OrcaRuntimeService { // Why: OSC 9999 status can span PTY chunks. Keeping parser state in the // runtime lets hidden/model-owned terminals observe agent state without a // mounted xterm view. + // Why a throttle: the blocked-reason check builds and scans two full wait + // texts (<=256KB each, lowercased) — measured at ~85% of onPtyData's cost + // under a TUI flood (findings log 2026-07-03). PTY chunk boundaries are + // arbitrary, so running the identical computation over coalesced chunks at + // a bounded cadence (plus a trailing-edge timer so burst-final state is + // always evaluated) preserves semantics while removing it from the hot path. + private waitBlockedCheckStateByPtyId = new Map< + string, + { + lastAt: number + lastWaitState: TerminalTailWaitState | null + appended: string + keywordCarry: string + timer: ReturnType | null + } + >() + private agentStatusOscProcessorsByPtyId = new Map< string, ReturnType >() + // Why: per-PTY shared title trackers (all-titles ordering + stale-working + // timer) replace last-title-per-chunk scanning so main observes the same + // intra-chunk working→idle transitions the renderer does (issue #1083). + // Lazily created like agentStatusOscProcessorsByPtyId; disposed on PTY exit. + private ptyTitleTrackersByPtyId = new Map() + // Why: the Command Code output detector arms early from the launch command + // when known (banner detection covers user-typed launches), mirroring the + // renderer detector's startupCommand seed. + private terminalSpawnCommandsByPtyId = new Map() // Why: ordinary OSC 0/1/2 titles can split across PTY chunks, especially over - // SSH/relay buffering. Keep a small raw scan tail so status titles are not lost. + // SSH/relay buffering. Keep a small raw scan tail and feed reconstructed + // chunks into the title tracker instead of falling back to last-title scans. private oscTitleScanTailByPtyId = new Map() // Why: mobile file taps resolve relative paths on the host. OSC 7 is the // terminal-owned cwd signal, and it can arrive in live output between snapshots. @@ -2156,6 +2309,14 @@ export class OrcaRuntimeService { > >() + // Why: Phase-5 query-responder suppression — a terminal-RPC subscribe + // stream feeds a remote xterm view (mobile/web/remote desktop) that answers + // queries with view authority, so main must yield while one is attached + // (terminal-query-authority.md). Ref-counted per PTY because multiple + // streams can attach concurrently; mobileSubscribers is consulted too so + // grace-window mobile records keep suppressing. + private remoteTerminalViewSubscriberCounts = new Map() + // Why: per-PTY driver state. The "driver" is whoever currently owns the // input/resize floor. While `kind === 'mobile'` the desktop renderer drops // xterm.onData/onResize and shows the lock banner; `terminal.send` / @@ -2303,6 +2464,7 @@ export class OrcaRuntimeService { private readonly getLocalProviderFn: (() => IPtyProvider) | null private readonly onPtyStopped: ((ptyId: string) => void) | null private readonly onTerminalAgentStatus: ((event: RuntimeTerminalAgentStatusEvent) => void) | null + private readonly onTerminalSideEffects: ((batch: TerminalSideEffectBatch) => void) | null private readonly getAgentStatusSnapshotFn: (() => AgentStatusIpcPayload[]) | null private readonly buildAgentHookPtyEnv: (() => Record) | null private accountServices: RuntimeAccountServices | null = null @@ -2327,10 +2489,16 @@ export class OrcaRuntimeService { getLocalProvider?: () => IPtyProvider onPtyStopped?: (ptyId: string) => void onTerminalAgentStatus?: (event: RuntimeTerminalAgentStatusEvent) => void + onTerminalSideEffects?: (batch: TerminalSideEffectBatch) => void // Why: agent status mostly arrives via hooks (agent-hooks/server), not OSC // terminal output. worktree.ps reads this at query time so mobile shows the // same inline agent rows the desktop sidebar does — same source, 1:1. getAgentStatusSnapshot?: () => AgentStatusIpcPayload[] + // Why: codex-home paths for the Agent Session History scan must be sourced + // here, not via the window-only registerCoreHandlers path — that path never + // runs under `orca serve`, so remote/SSH hosts would silently drop + // managed-Codex sessions. The runtime ctor runs in BOTH window and serve. + getAdditionalAiVaultCodexHomePaths?: () => readonly string[] buildAgentHookPtyEnv?: () => Record } ) { @@ -2340,6 +2508,14 @@ export class OrcaRuntimeService { this.agentDetector = new AgentDetector(stats) } this.getAgentStatusSnapshotFn = deps?.getAgentStatusSnapshot ?? null + // Why: configure the shared AiVault scan cache from a serve-mode-reachable + // seam so the aiVault.listSessions RPC includes managed-Codex + WSL sessions + // even on headless `orca serve` hosts where registerCoreHandlers never runs. + if (deps?.getAdditionalAiVaultCodexHomePaths) { + configureAiVaultSessionSources({ + getAdditionalCodexHomePaths: deps.getAdditionalAiVaultCodexHomePaths + }) + } // Why: the daemon adapter is installed via `setLocalPtyProvider()` during // attachMainWindowServices, AFTER this service is constructed. Capturing // `getLocalPtyProvider()` at construction time would freeze a reference to @@ -2350,6 +2526,20 @@ export class OrcaRuntimeService { this.onPtyStopped = deps?.onPtyStopped ?? null this.onTerminalAgentStatus = deps?.onTerminalAgentStatus ?? null this.buildAgentHookPtyEnv = deps?.buildAgentHookPtyEnv ?? null + this.onTerminalSideEffects = deps?.onTerminalSideEffects ?? null + // Why: the ConPTY spawn mark can land after daemon stream data already + // created this PTY's emulator; the mark retrofits the DA1 override here + // (terminal-query-authority.md §ConPTY DA1). + registerConptyDa1OverrideInstaller((ptyId) => this.ensureNativeWindowsConptyDa1Override(ptyId)) + // Why: a renderer attribute push must reach already-live emulators too — + // cursor options for DECRQSS/DECRQM parity plus the per-PTY OSC color + // override reset a theme apply implies (terminal-query-authority.md + // §View-attribute bridge). + registerTerminalViewAttributesApplier((attributes) => { + for (const state of this.headlessTerminals.values()) { + state.emulator.applyPushedViewAttributes(attributes) + } + }) } getLocalProvider(): IPtyProvider | null { @@ -2730,11 +2920,19 @@ export class OrcaRuntimeService { // must not treat browser panes as supported just because runtime RPC is up. capabilities, hostPlatform: process.platform, + terminalWindowsShell: this.store?.getSettings?.().terminalWindowsShell ?? null, protocolVersion: RUNTIME_PROTOCOL_VERSION, minCompatibleMobileVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION } } + // Why: scans the transcript-owning host's disk (correct by construction over + // RPC — a remote/SSH host scans its own disk). Delegates to the one shared + // cache so the desktop panel and the mobile screen never double-scan. + listAiVaultSessions(args?: AiVaultListArgs): Promise { + return listAiVaultSessions(args) + } + setPtyController(controller: RuntimePtyController | null): void { // Why: CLI terminal writes must go through the main-owned PTY registry // instead of tunneling back through renderer IPC, or live handles could @@ -2775,6 +2973,12 @@ export class OrcaRuntimeService { this.emitClientEvent({ type: 'reposChanged' }) } + // Why: SSH state changes originate in main's ssh handlers, not in runtime + // methods, so they need a public entry point onto the client-event stream. + notifySshStateChanged(targetId: string, state: SshConnectionState): void { + this.emitClientEvent({ type: 'sshStateChanged', targetId, state }) + } + private notifyActivateWorktree( repoId: string, worktreeId: string, @@ -2889,26 +3093,47 @@ export class OrcaRuntimeService { } } + // Why: computed BEFORE preserving stale leaves so preservation can refuse a + // leaf whose PTY the incoming graph already rebound to a live leaf. Two + // leaves on one PTY resolve to the same handle (handles are ptyId-keyed) and + // crash paired clients with a duplicate React key. + const nextPtyIds = new Set( + [...nextLeaves.values()].map((leaf) => leaf.ptyId).filter((ptyId): ptyId is string => !!ptyId) + ) for (const oldLeafKey of this.leaves.keys()) { if (!nextLeaves.has(oldLeafKey)) { const oldLeaf = this.leaves.get(oldLeafKey) if ( preserveLivePtysDuringReload && oldLeaf?.ptyId && - this.handleByPtyId.has(oldLeaf.ptyId) + this.handleByPtyId.has(oldLeaf.ptyId) && + !nextPtyIds.has(oldLeaf.ptyId) ) { // Why: a CLI-created agent keeps using its exported handle even if // the reloaded renderer has not rebound the pane yet. nextLeaves.set(oldLeafKey, oldLeaf) + nextPtyIds.add(oldLeaf.ptyId) + } else if (oldLeaf?.ptyId && nextPtyIds.has(oldLeaf.ptyId)) { + // Why: the incoming graph already rebound this PTY to a live leaf (e.g. + // a woken agent re-keyed to a new leaf during renderer reload). Keeping + // the old leaf too would put two leaves on ONE PTY, which emit the same + // terminal handle and crash paired clients. Drop the stale leaf; if its + // handle is the shared ptyId-keyed one it belongs to the live leaf now, + // so release only this dead leaf key's alias. A leaf-unique handle has + // no next owner — invalidate it so in-flight CLI waiters fail fast + // instead of hanging on a dead leaf. + const oldHandle = this.handleByLeafKey.get(oldLeafKey) + if (oldHandle !== undefined && oldHandle === this.handleByPtyId.get(oldLeaf.ptyId)) { + this.handleByLeafKey.delete(oldLeafKey) + } else { + this.invalidateLeafHandle(oldLeafKey) + } } else { this.invalidateLeafHandle(oldLeafKey) } } } - const nextPtyIds = new Set( - [...nextLeaves.values()].map((leaf) => leaf.ptyId).filter((ptyId): ptyId is string => !!ptyId) - ) for (const [ptyId, leaf] of this.detachedPreAllocatedLeaves) { if (nextPtyIds.has(ptyId) || !this.handleByPtyId.has(ptyId)) { this.detachedPreAllocatedLeaves.delete(ptyId) @@ -3478,7 +3703,10 @@ export class OrcaRuntimeService { this.notifyMobileSessionTabsChanged(worktreeId) } - private touchMobileSessionSnapshotsForPty(ptyId: string): void { + private touchMobileSessionSnapshotsForPty( + ptyId: string, + options: { immediate?: boolean } = {} + ): void { for (const [worktreeId, snapshot] of this.mobileSessionTabsByWorktree) { const hasPtyBackedTab = snapshot.tabs.some( (tab) => @@ -3492,7 +3720,15 @@ export class OrcaRuntimeService { ...snapshot, snapshotVersion: snapshot.snapshotVersion + 1 }) - this.notifyMobileSessionTabsChanged(worktreeId) + if (options.immediate) { + // Why: readiness/lifecycle changes are structural and must not wait + // behind the title/status coalescing window. + this.notifyMobileSessionTabsChanged(worktreeId) + } else { + // Why: title/status flips several times a second under spinner-in-title + // agents. Coalesce the emit instead of fanning out every version. + this.mobileSessionTabsNotifyCoalescer.schedule(worktreeId) + } } } @@ -3959,6 +4195,25 @@ export class OrcaRuntimeService { const targetGroupId = snapshot?.tabGroups?.find((group) => group.tabOrder.includes(tab.parentTabId) )?.id + // Why: a pending agent tab may exist without its startup command ever + // having been delivered (the create's renderer stalled, #7587), so a + // bare materialize would put a plain shell under the agent icon. + // Re-resolve the launch like the create path; providers skip startup + // commands when attaching to live sessions, so this cannot double-launch. + let agentStartup: Awaited< + ReturnType + > = {} + if (tab.launchAgent) { + try { + const workspace = await this.resolveTerminalWorkspaceLaunchScope(`id:${worktreeId}`) + agentStartup = await this.resolveMobileSessionTerminalCommand(workspace, { + agent: tab.launchAgent + }) + } catch { + // Why: a disabled or unresolvable agent must not make the tab + // untappable; fall back to the plain-shell materialize. + } + } try { await this.createHeadlessMobileSessionTerminal(worktreeId, true, undefined, { identity: { @@ -3967,6 +4222,10 @@ export class OrcaRuntimeService { sessionId }, cwd: tab.startupCwd, + command: agentStartup.command, + env: agentStartup.env, + startupCommandDelivery: agentStartup.startupCommandDelivery, + launchConfig: agentStartup.launchConfig, launchAgent: tab.launchAgent, targetGroupId }) @@ -5131,6 +5390,9 @@ export class OrcaRuntimeService { ): () => void { this.mobileSessionTabListeners.add(listener) return () => { + // Why: flush pending coalesced notifies before dropping this listener so a + // subscriber closing mid-window still receives the latest settled state. + this.mobileSessionTabsNotifyCoalescer.flushAll() this.mobileSessionTabListeners.delete(listener) } } @@ -5213,16 +5475,46 @@ export class OrcaRuntimeService { } } - registerPty(ptyId: string, worktreeId: string, connectionId: string | null = null): void { - this.recordPtyWorktree(ptyId, worktreeId, { connected: true, connectionId }) + registerPty( + ptyId: string, + worktreeId: string, + connectionId: string | null = null, + binding?: { tabId: string; leafId: string } + ): void { + // Why: record the renderer pane identity at spawn time so a stalled graph + // sync can't hide that a live PTY already backs a pending mobile create. + const paneKey = + binding && isValidTerminalTabId(binding.tabId) && isTerminalLeafId(binding.leafId) + ? makePaneKey(binding.tabId, binding.leafId) + : null + this.recordPtyWorktree(ptyId, worktreeId, { + connected: true, + connectionId, + ...(binding && paneKey ? { tabId: binding.tabId, paneKey } : {}) + }) + // Why: the renderer's own PTY spawn is the reliable signal that the pending + // mobile create's tab is live; publish its surface main-side (#7587). + if (binding && paneKey) { + this.ensurePtyBackedMobileSurfaceForRendererTab(worktreeId, binding.tabId) + } + } + + /** Record the spawn launch command so the per-PTY Command Code detector can + * arm from it (renderer startupCommand parity). Best-effort: a chunk that + * beats this call falls back to the detector's banner arming. */ + noteTerminalSpawnCommand(ptyId: string, command: string | null | undefined): void { + const trimmed = typeof command === 'string' ? command.trim() : '' + if (trimmed.length > 0) { + this.terminalSpawnCommandsByPtyId.set(ptyId, trimmed) + } } /** * Handles incoming data from a PTY process, running agent detection, * updating terminal tail buffers, and triggering foreground agent refreshes. */ - onPtyData(ptyId: string, data: string, at: number): number { - const outputSequence = (this.ptyOutputSequenceById.get(ptyId) ?? 0) + data.length + onPtyData(ptyId: string, data: string, at: number, sequenceChars = data.length): number { + const outputSequence = (this.ptyOutputSequenceById.get(ptyId) ?? 0) + sequenceChars this.ptyOutputSequenceById.set(ptyId, outputSequence) const osc7Metadata = this.recordOsc7MetadataForPty(ptyId, data) const cwd = osc7Metadata.cwd @@ -5237,6 +5529,12 @@ export class OrcaRuntimeService { // panel can surface them in place of the kernel bind address. advertisedUrlWatcher.ingest(ptyId, data, at) serveSimStateWatcher.ingestPtyOutput(ptyId, data) + // Why: reply ownership is captured per chunk, here at ingestion — the + // same module state and tick as the hidden-gate drop sites — and rides + // the writeChain link. A mark/setting/subscriber flip before the queued + // emulator write runs must not change who answers (terminal-query- + // authority.md invariant 1). + const forwardQueryReplies = this.shouldAnswerQueriesForLiveChunk(ptyId) // Ordering invariant (DO NOT REORDER): maybeHydrateHeadlessFromRenderer // MUST run before trackHeadlessTerminalData so the eager-state pattern // (set headlessTerminals + writeChain head = seedPromise) is in place @@ -5245,17 +5543,14 @@ export class OrcaRuntimeService { // that the later seed-resolve would overwrite, dropping the live byte. // See docs/mobile-prefer-renderer-scrollback.md. this.maybeHydrateHeadlessFromRenderer(ptyId) - this.trackHeadlessTerminalData(ptyId, data, outputSequence) - - // Why: extract OSC title from raw PTY data before tail-buffer processing - // strips the escape sequences. Agent CLIs (Claude Code, Gemini, etc.) - // announce status via OSC 0/1/2 title sequences — this is the same - // detection path the renderer uses for notifications and sidebar badges. - const oscTitle = this.extractLastOscTitleForPty(ptyId, data) - const agentStatus = oscTitle ? detectAgentStatusFromTitle(oscTitle) : null + // Our structure wins: OSC title/agent-status extraction runs through the + // shared per-PTY title tracker below (getOrCreatePtyTitleTrackerEntry → + // applyTrackedPtyTitle) in byte order, superseding main's inline + // extractLastOscTitleForPty block (#7880/#7852 title/status semantics are + // preserved via the tracker + detectAgentStatusFromTitle path). + this.trackHeadlessTerminalData(ptyId, data, outputSequence, forwardQueryReplies) const pty = this.getOrCreatePtyWorktreeRecord(ptyId) - let shouldTouchPtyBackedSessionTabs = false const ptyTailBefore = pty ? { lines: pty.tailBuffer, @@ -5273,28 +5568,12 @@ export class OrcaRuntimeService { pty.lastOutputAt = at const normalized = normalizeTerminalChunk(data, pty.tailPendingAnsi) pty.tailPendingAnsi = normalized.pendingAnsi - // Why: the prior chunk's post-append tail is this chunk's pre-append tail, - // so its cached wait scan is exact — reuse it instead of rebuilding and - // rescanning the full tail. Only a tail-derived state is safe to reuse. - const previousWaitState = - pty.tailWaitState?.fromTail === true - ? pty.tailWaitState - : computeTerminalTailWaitState(pty.tailBuffer, pty.tailPartialLine, pty.preview) const nextTail = appendNormalizedToTailBuffer( pty.tailBuffer, pty.tailPartialLine, normalized.text, pty.tailRedrawCursor ) - const nextWaitState = computeTerminalTailWaitState( - nextTail.lines, - nextTail.partialLine, - pty.preview - ) - if (tailGainedNewerBlockedReason(previousWaitState, nextWaitState, normalized.text)) { - pty.waitBlockedAt = at - } - pty.tailWaitState = nextWaitState ptyTailAfter = nextTail pty.tailBuffer = nextTail.lines pty.tailPartialLine = nextTail.partialLine @@ -5302,40 +5581,7 @@ export class OrcaRuntimeService { pty.tailTruncated = pty.tailTruncated || nextTail.truncated pty.tailLinesTotal += nextTail.newCompleteLines pty.preview = buildPreview(pty.tailBuffer, pty.tailPartialLine) - if (oscTitle !== null) { - const prevStatus = pty.lastAgentStatus - const prevTitle = pty.lastOscTitle - const observedAt = this.nextTitleObservationSequence() - pty.lastOscTitle = oscTitle - pty.lastOscTitleAt = observedAt - pty.lastAgentStatus = agentStatus - this.setPtyManagementTitleFromObservedTitle(pty, oscTitle, observedAt) - shouldTouchPtyBackedSessionTabs = - prevTitle !== oscTitle || prevStatus !== pty.lastAgentStatus - if (agentStatus === 'idle' && prevStatus !== 'idle') { - this.resolvePtyTuiIdleWaiters(pty, ptyId) - } - const shouldDelayMobileSnapshot = - shouldTouchPtyBackedSessionTabs && - this.shouldDelayPtyBackedMobileSnapshotForForegroundAgent(pty, oscTitle) - let foregroundRefresh: Promise | undefined - // Why: gate on an actual status transition — braille spinner frames - // mutate the title every tick, so probing per-title-change would stream - // a foreground query per frame during active work. - if (prevStatus !== pty.lastAgentStatus) { - foregroundRefresh = this.refreshPtyForegroundAgentFromController(ptyId, { - afterTitleObservation: observedAt - }) - } else if (shouldDelayMobileSnapshot) { - // Why: same-status compatible title changes can arrive before the - // foreground owner probe settles; publishing them would flicker. - foregroundRefresh = this.getPendingForegroundAgentRefreshForTitle(ptyId, observedAt) - } - if (foregroundRefresh && shouldDelayMobileSnapshot) { - shouldTouchPtyBackedSessionTabs = false - this.delayPtyBackedMobileSnapshotForForegroundAgent(ptyId, observedAt, foregroundRefresh) - } - } + this.scheduleWaitBlockedCheck(ptyId, normalized.text, at) } for (const leaf of this.getLeavesForPty(ptyId)) { @@ -5373,7 +5619,10 @@ export class OrcaRuntimeService { leaf.tailLinesTotal = pty.tailLinesTotal leaf.preview = pty.preview leaf.waitBlockedAt = pty.waitBlockedAt - // Why: the leaf mirrors the PTY tail here, so share the cached wait scan. + // Why undefined on this branch: the PTY record's wait scan is throttled + // (scheduleWaitBlockedCheck), so pty.tailWaitState is never populated; + // copying it here intentionally invalidates the leaf cache and the + // mismatch branch below recomputes an exact state on its next chunk. leaf.tailWaitState = pty.tailWaitState } else { const normalized = normalizeTerminalChunk(data, leaf.tailPendingAnsi) @@ -5404,39 +5653,54 @@ export class OrcaRuntimeService { leaf.tailLinesTotal += nextTail.newCompleteLines leaf.preview = buildPreview(leaf.tailBuffer, leaf.tailPartialLine) } + } - if (oscTitle !== null) { - // Why: keep the latest OSC title on the leaf so worktree.ps can - // recompute status from the live title each call. Without this, - // daemon-hosted terminals (no renderer pushing pane titles) had no - // way to clear a stale 'working' status after the agent exited and - // the shell took over the title — the stuck-spinner bug in #1437. - leaf.lastOscTitle = oscTitle - leaf.lastOscTitleAt = this.nextTitleObservationSequence() - const prevStatus = leaf.lastAgentStatus - // Why: when a new OSC title doesn't classify as an agent state (e.g. - // bare shell title after the agent exits), clear lastAgentStatus so - // it is no longer sticky. Tui-idle waiters that needed the previous - // 'idle' transition were already resolved at the moment of the - // transition below; only fresh waiters registered after the agent - // exits would observe the cleared value, and they correctly fall - // back to title-based detection / polling. - leaf.lastAgentStatus = agentStatus - // Why: resolve tui-idle on any transition TO idle (not just working→idle). - // Claude Code may skip "working" entirely on fast tasks, going null→idle, - // and the coordinator's tui-idle waiter would hang forever waiting for a - // working→idle transition that never comes. Permission→idle is excluded: - // it means the agent was blocked on user approval and the user said no, - // which isn't a task-completion signal. - if (agentStatus === 'idle' && prevStatus !== 'idle') { - this.resolveTuiIdleWaiters(leaf) - this.deliverPendingMessages(leaf) - } + // Why: feed the chunk's OSC titles through the shared per-PTY tracker in + // byte order — the same ordering the renderer transport uses — so + // coalesced working→idle transitions reach tui-idle waiters and + // pending-message delivery instead of being masked by the chunk's last + // title (issue #1083). Uses the OSC 9999-stripped cleanData like the + // renderer, so pure status chunks don't perturb the stale-title probe. + const titleTrackerEntry = this.getOrCreatePtyTitleTrackerEntry(ptyId) + const previousTitleScanTail = this.oscTitleScanTailByPtyId.get(ptyId) + const titleInput = previousTitleScanTail + ? `${previousTitleScanTail}${agentStatusChunk.cleanData}` + : agentStatusChunk.cleanData + const nextTitleScanTail = extractOscTitleScanTail(titleInput) + if (nextTitleScanTail.length > 0) { + this.oscTitleScanTailByPtyId.set(ptyId, nextTitleScanTail) + } else { + this.oscTitleScanTailByPtyId.delete(ptyId) + } + titleTrackerEntry.applyingChunk = true + titleTrackerEntry.chunkTouchedSessionTabs = false + let retainedAgentStatusChanged = false + try { + titleTrackerEntry.tracker.handleChunk(agentStatusChunk.cleanData, { + titleScanData: titleInput + }) + // Why: the Command Code scrape rides the same per-chunk batch (its facts + // trail the tracker's). cleanData keeps OSC 9999 payloads out of the + // detector's bounded recent-text window; the detector strips remaining + // control sequences itself, exactly like the renderer byte path. + titleTrackerEntry.commandCodeDetector?.observe(agentStatusChunk.cleanData) + } finally { + titleTrackerEntry.applyingChunk = false + try { + // Why: per-chunk cross-channel contract order is status → titles → + // bell — the chunk's agentStatus:set events must reach the renderer + // before its pty:sideEffect batch. + retainedAgentStatusChanged = this.emitTerminalAgentStatusEvents(ptyId, agentStatusChunk) + } finally { + // Why: flushed in the finally so a throwing tracker callback cannot + // strand this chunk's facts to be emitted under the next chunk's seq. + this.flushPendingTerminalSideEffectFacts(ptyId, titleTrackerEntry) } } - - this.emitTerminalAgentStatusEvents(ptyId, agentStatusChunk) - if (shouldTouchPtyBackedSessionTabs) { + // Why: hook (OSC 9999) transitions often arrive without a title change, so + // headless-serve snapshots would never republish and paired remote clients + // kept the stale agent state until the next title change (#7970). + if (titleTrackerEntry.chunkTouchedSessionTabs || retainedAgentStatusChanged) { this.touchMobileSessionSnapshotsForPty(ptyId) } @@ -5454,6 +5718,80 @@ export class OrcaRuntimeService { return outputSequence } + private scheduleWaitBlockedCheck(ptyId: string, appendedText: string, at: number): void { + let state = this.waitBlockedCheckStateByPtyId.get(ptyId) + if (!state) { + state = { lastAt: 0, lastWaitState: null, appended: '', keywordCarry: '', timer: null } + this.waitBlockedCheckStateByPtyId.set(ptyId, state) + } + const appendedLower = appendedText.toLowerCase() + const keywordHit = WAIT_BLOCKED_KEYWORD_PATTERN.test(`${state.keywordCarry}${appendedLower}`) + state.keywordCarry = appendedLower.slice(-WAIT_BLOCKED_KEYWORD_CARRY_CHARS) + // Why the cap keeps the tail: the accumulated text only anchors boundary- + // spanning prompt detection; anything past the tail cap has scrolled out + // of the retained tail the check reads anyway. + state.appended = + state.appended.length + appendedText.length > MAX_TAIL_CHARS + ? `${state.appended}${appendedText}`.slice(-MAX_TAIL_CHARS) + : `${state.appended}${appendedText}` + const elapsed = at - state.lastAt + if (keywordHit || elapsed >= WAIT_BLOCKED_CHECK_MIN_INTERVAL_MS || elapsed < 0) { + this.runWaitBlockedCheck(ptyId, state, at) + return + } + if (!state.timer) { + // Why trailing edge: the final chunks of a burst must still be + // evaluated or a prompt arriving right after a flood would go + // unstamped until the next output. + state.timer = setTimeout(() => { + state.timer = null + this.runWaitBlockedCheck(ptyId, state, Date.now()) + }, WAIT_BLOCKED_CHECK_MIN_INTERVAL_MS - elapsed) + } + } + + private runWaitBlockedCheck( + ptyId: string, + state: { + lastAt: number + lastWaitState: TerminalTailWaitState | null + appended: string + keywordCarry: string + timer: ReturnType | null + }, + at: number + ): void { + const pty = this.ptysById.get(ptyId) + if (!pty) { + state.appended = '' + return + } + const nextWaitState = computeTerminalTailWaitState( + pty.tailBuffer, + pty.tailPartialLine, + pty.preview + ) + const previousWaitState = state.lastWaitState ?? { + waitText: '', + signal: null, + fromTail: false + } + if (tailGainedNewerBlockedReason(previousWaitState, nextWaitState, state.appended)) { + pty.waitBlockedAt = at + } + state.lastAt = at + state.lastWaitState = nextWaitState + state.appended = '' + } + + private clearWaitBlockedCheckState(ptyId: string): void { + const state = this.waitBlockedCheckStateByPtyId.get(ptyId) + if (state?.timer) { + clearTimeout(state.timer) + } + this.waitBlockedCheckStateByPtyId.delete(ptyId) + } + private processAgentStatusOscForPty(ptyId: string, data: string): ProcessedAgentStatusChunk { let processor = this.agentStatusOscProcessorsByPtyId.get(ptyId) if (!processor) { @@ -5463,19 +5801,439 @@ export class OrcaRuntimeService { return processor(data) } - private extractLastOscTitleForPty(ptyId: string, data: string): string | null { - const previousTail = this.oscTitleScanTailByPtyId.get(ptyId) - if (!previousTail && !data.includes('\x1b')) { + /** Emit the facts batched while applying one chunk/frame as a single + * pty:sideEffect batch, preserving byte order. */ + private flushPendingTerminalSideEffectFacts( + ptyId: string, + entry: RuntimePtyTitleTrackerEntry + ): void { + if (entry.pendingFacts.length === 0) { + return + } + const facts = entry.pendingFacts + entry.pendingFacts = [] + this.emitTerminalSideEffectBatch(ptyId, facts) + } + + /** Feed a main-fabricated OSC title/BEL frame (agent hook spinners) through + * the per-PTY tracker — NOT onPtyData, so emulator state, tails, + * transcripts, and stats never see synthetic bytes. Parsed via the + * tracker's stateless synthetic path: the shared chunk bell detector must + * never observe fabricated bytes, or a tick interleaved with a split real + * OSC corrupts its escape state (phantom/swallowed bells). While the + * side-effect kill switch is off the legacy pty:data copy still drives + * renderer parsers; this ingest keeps main's facts and records + * authoritative. */ + ingestSyntheticTitleFrame(ptyId: string, data: string): void { + const entry = this.getOrCreatePtyTitleTrackerEntry(ptyId) + entry.applyingChunk = true + entry.applyingSyntheticFrame = true + entry.chunkTouchedSessionTabs = false + try { + entry.tracker.applySyntheticTitleFrame(data) + } finally { + entry.applyingChunk = false + entry.applyingSyntheticFrame = false + this.flushPendingTerminalSideEffectFacts(ptyId, entry) + } + if (entry.chunkTouchedSessionTabs) { + this.touchMobileSessionSnapshotsForPty(ptyId) + } + } + + /** Scan-authority handoff for a backgrounded PTY (daemon keep-tail + * thinning): while delegated, the daemon relays bell/133/pr-link/2031 + * facts itself and the delivered bytes may be gapped — feeding them to + * main's transient scanners would mint phantom or duplicate facts. Title + * processing stays main-side either way. */ + setPtyTransientFactDelegation(ptyId: string, delegated: boolean, scanSeedAnsi?: string): void { + const entry = this.getOrCreatePtyTitleTrackerEntry(ptyId) + entry.tracker.setTransientFactScanningSuppressed(delegated) + if (!delegated && scanSeedAnsi) { + // Prime the freshly reset scanner carry with the emulator's dangling + // incomplete escape at the handoff position — a sequence split across + // the un-background toggle must not mint a phantom bell or lose its + // fact. titleScanData:'' keeps titles out (they were never suppressed). + entry.tracker.handleChunk(scanSeedAnsi, { titleScanData: '' }) + } + } + + /** A transient fact the daemon detected while it held scan authority — + * emitted through the same fact channel as byte-scanned facts. Arrives + * between chunks, so recordTerminalSideEffectFact emits it immediately. */ + emitDaemonPtyTransientFact(ptyId: string, fact: PtyTransientFact): void { + switch (fact.kind) { + case 'bell': + this.recordTerminalSideEffectFact(ptyId, { kind: 'bell' }) + return + case 'command-finished': + this.recordTerminalSideEffectFact(ptyId, { + kind: 'command-finished', + exitCode: fact.exitCode + }) + return + case 'pr-link': + this.recordTerminalSideEffectFact(ptyId, { kind: 'pr-link', link: fact.link }) + return + case '2031-subscribe': + this.recordTerminalSideEffectFact(ptyId, { kind: '2031-subscribe' }) + } + } + + /** The daemon keep-tail dropped this PTY's oldest undelivered output; the + * next delivered chunk is discontinuous. Reset every cross-chunk parse + * carry so a half-open escape from before the gap cannot corrupt what + * follows, and drop the mobile headless mirror — it rebuilds from the + * delivered tail / snapshot seeds instead of parsing a gapped stream. */ + notePtyDataGap(ptyId: string, droppedChars = 0): void { + if (droppedChars > 0) { + // Why: the daemon snapshot's seq counts bytes its monitoring stream + // dropped. Advancing without parsing preserves that absolute domain so + // post-snapshot live chunks can be reconciled instead of duplicated. + const outputSequence = (this.ptyOutputSequenceById.get(ptyId) ?? 0) + droppedChars + this.ptyOutputSequenceById.set(ptyId, outputSequence) + } + const pty = this.getOrCreatePtyWorktreeRecord(ptyId) + if (pty) { + pty.tailPendingAnsi = '' + } + for (const leaf of this.getLeavesForPty(ptyId)) { + leaf.tailPendingAnsi = '' + } + this.oscTitleScanTailByPtyId.delete(ptyId) + this.osc7ScanTailByPtyId.delete(ptyId) + this.agentStatusOscProcessorsByPtyId.delete(ptyId) + this.disposeHeadlessTerminal(ptyId) + } + + /** Record one derived side-effect fact: batched per chunk while applying + * bytes, emitted immediately for between-chunk facts (stale-title timer). */ + private recordTerminalSideEffectFact(ptyId: string, fact: TerminalSideEffectFact): void { + if (!this.onTerminalSideEffects) { + return + } + const entry = this.ptyTitleTrackersByPtyId.get(ptyId) + if (entry?.applyingChunk) { + entry.pendingFacts.push(fact) + return + } + this.emitTerminalSideEffectBatch(ptyId, [fact]) + } + + private emitTerminalSideEffectBatch( + ptyId: string, + facts: TerminalSideEffectFact[], + options: { replay?: boolean } = {} + ): void { + if (!this.onTerminalSideEffects || facts.length === 0) { + return + } + const batch: TerminalSideEffectBatch = { + ptyId, + seq: this.ptyOutputSequenceById.get(ptyId) ?? 0, + facts, + ...(options.replay ? { replay: true } : {}), + ...this.resolveTerminalSideEffectAttribution(ptyId) + } + try { + this.onTerminalSideEffects(batch) + } catch (err) { + console.error('[runtime] terminal side-effect listener threw', { ptyId, err }) + } + } + + /** Same attribution resolution as emitTerminalAgentStatusEvents: prefer the + * first mounted leaf, fall back to the spawn-time PTY record binding. */ + private resolveTerminalSideEffectAttribution(ptyId: string): { + worktreeId?: string + tabId?: string + paneKey?: string + connectionId?: string | null + } { + const pty = this.ptysById.get(ptyId) + const connectionId = pty?.connectionId ?? null + for (const leaf of this.getLeavesForPty(ptyId)) { + return { + worktreeId: leaf.worktreeId, + tabId: leaf.tabId, + paneKey: this.makeRuntimePaneKey(leaf), + connectionId + } + } + if (pty?.paneKey) { + return { + worktreeId: pty.worktreeId, + ...(pty.tabId ? { tabId: pty.tabId } : {}), + paneKey: pty.paneKey, + connectionId + } + } + return {} + } + + /** Title-only replay batch for renderer (re)attach — the no-attention-replay + * rule: snapshots restore title state, never historical bells/completions. */ + getTerminalSideEffectSnapshot(ptyId: string): TerminalSideEffectBatch | null { + const tracker = this.ptyTitleTrackersByPtyId.get(ptyId)?.tracker + const recordTitle = this.ptysById.get(ptyId)?.lastOscTitle + // Why: the cursor-agent literal drop applies to every title surface; a + // record-fallback snapshot must not replay the bare native title the + // tracker would have refused to emit live. + const rawTitle = recordTitle && !isCursorNativeAgentTitle(recordTitle) ? recordTitle : null + const normalizedTitle = tracker?.getLastNormalizedTitle() ?? null + if (normalizedTitle === null && !rawTitle) { return null } - const input = `${previousTail ?? ''}${data}` - const scanTail = extractOscTitleScanTail(input) - if (scanTail.length > 0) { - this.oscTitleScanTailByPtyId.set(ptyId, scanTail) - } else { - this.oscTitleScanTailByPtyId.delete(ptyId) + return { + ptyId, + seq: this.ptyOutputSequenceById.get(ptyId) ?? 0, + replay: true, + facts: [ + { + kind: 'title', + normalizedTitle: normalizedTitle ?? normalizeTerminalTitle(rawTitle!), + rawTitle: rawTitle ?? normalizedTitle! + } + ], + ...this.resolveTerminalSideEffectAttribution(ptyId) + } + } + + /** Raw last title from main's tracked PTY/leaf records — the title surface + * the tracker (live bytes + synthetic frames) keeps current. */ + private getTrackedRawTitleForPty(ptyId: string): string | null { + const recordTitle = this.ptysById.get(ptyId)?.lastOscTitle + if (recordTitle) { + return recordTitle + } + for (const leaf of this.getLeavesForPty(ptyId)) { + if (leaf.lastOscTitle) { + return leaf.lastOscTitle + } + } + return null + } + + /** Why: synthetic agent title frames no longer ride pty:data, so neither + * renderer xterm nor the headless emulator observes them. Mobile-parity + * snapshot titles must prefer main's tracker over snapshot lastTitle, or + * hook-driven spinner/idle titles vanish from mobile tabs. */ + private preferTrackedLastTitle(ptyId: string, snapshot: T): T { + const tracked = this.getTrackedRawTitleForPty(ptyId) + if (!tracked) { + return snapshot + } + return { ...snapshot, lastTitle: tracked } + } + + /** Decorative comparison key: spinner frame glyphs stripped, derived agent + * status kept so a working→idle flip with an otherwise-equal label still + * counts as a change. */ + private makeMobileTitleGateKey(rawTitle: string, normalizedTitle: string): string { + return `${detectAgentStatusFromTitle(rawTitle) ?? ''}\u0000${stripBrailleSpinnerGlyphs( + normalizedTitle + )}` + } + + private getOrCreatePtyTitleTrackerEntry(ptyId: string): RuntimePtyTitleTrackerEntry { + const existing = this.ptyTitleTrackersByPtyId.get(ptyId) + if (existing) { + return existing } - return extractLastOscTitle(input) + // Why: trackers are created lazily on the first observed chunk. After an + // app relaunch the PTY/leaf records can already hold a persisted title; a + // cold tracker would miss the parked working→idle completion and never + // arm the stale-title timer for a persisted 'working' title. + let initialTitle = this.ptysById.get(ptyId)?.lastOscTitle ?? null + if (initialTitle === null) { + for (const leaf of this.getLeavesForPty(ptyId)) { + if (leaf.lastOscTitle) { + initialTitle = leaf.lastOscTitle + break + } + } + } + const tracker = createTerminalTitleTracker( + { + onTitle: (normalizedTitle, rawTitle, meta) => { + this.recordTerminalSideEffectFact(ptyId, { + kind: 'title', + normalizedTitle, + rawTitle, + ...(meta?.staleWorkingTitleClear ? { staleWorkingTitleClear: true } : {}) + }) + const changed = this.applyTrackedPtyTitle(ptyId, rawTitle, normalizedTitle) + if (!changed) { + return + } + const live = this.ptyTitleTrackersByPtyId.get(ptyId) + const gateKey = this.makeMobileTitleGateKey(rawTitle, normalizedTitle) + const decorativeOnly = live?.lastMobileTitleGateKey === gateKey + if (live) { + live.lastMobileTitleGateKey = gateKey + } + if (live?.applyingChunk) { + // Why: synthetic spinner ticks change only the braille glyph + // ~12.5x/sec; fanning out full mobile session snapshots per frame + // is pure churn. Raw lastOscTitle updates above stay cheap. + if (!(live.applyingSyntheticFrame && decorativeOnly)) { + live.chunkTouchedSessionTabs = true + } + } else { + // Stale-working-title timer path — fires between chunks, so the + // per-chunk batching in onPtyData cannot pick it up. + this.touchMobileSessionSnapshotsForPty(ptyId) + } + }, + // Why: agent transitions and bells become pty:sideEffect facts — + // main is the single byte parser for local/SSH PTYs; the renderer + // store handler decides what the facts mean (notification policy). + onAgentBecameWorking: () => { + this.recordTerminalSideEffectFact(ptyId, { kind: 'agent-working' }) + }, + onAgentBecameIdle: (title, meta) => { + this.recordTerminalSideEffectFact(ptyId, { + kind: 'agent-idle', + title, + ...(meta?.staleWorkingTitleClear ? { staleWorkingTitleClear: true } : {}) + }) + }, + onAgentExited: () => { + this.recordTerminalSideEffectFact(ptyId, { kind: 'agent-exited' }) + }, + // Why: bell/command-finished/pr-link/2031 facts exist only for the + // pty:sideEffect channel. Headless serve has no consumer, so skip the + // per-chunk bell walk and 133/URL/2031 scans entirely. + ...(this.onTerminalSideEffects + ? { + onBell: () => { + this.recordTerminalSideEffectFact(ptyId, { kind: 'bell' }) + }, + onCommandFinished: (exitCode: number | null) => { + this.recordTerminalSideEffectFact(ptyId, { kind: 'command-finished', exitCode }) + }, + onPrLink: (link: TerminalGitHubPRLink) => { + this.recordTerminalSideEffectFact(ptyId, { kind: 'pr-link', link }) + }, + // Why: hidden-delivery-gated views never see the bytes, so main + // surfaces DECSET 2031 subscribes as facts; the theme reply is + // still sent by the renderer (query authority stays with the view). + onMode2031Subscribe: () => { + this.recordTerminalSideEffectFact(ptyId, { kind: '2031-subscribe' }) + } + } + : {}) + }, + initialTitle !== null ? { initialTitle } : {} + ) + const entry: RuntimePtyTitleTrackerEntry = { + tracker, + applyingChunk: false, + applyingSyntheticFrame: false, + lastMobileTitleGateKey: null, + chunkTouchedSessionTabs: false, + pendingFacts: [], + // Why: command-code facts exist only for the pty:sideEffect channel — + // headless serve skips the per-chunk scrape entirely. The detector + // self-arms on the Command Code banner; the spawn command (when main + // saw one) mirrors the renderer detector's startupCommand fast-arm. + commandCodeDetector: this.onTerminalSideEffects + ? createCommandCodeOutputStatusDetector({ + startupCommand: this.terminalSpawnCommandsByPtyId.get(ptyId) ?? null, + onWorking: (prompt) => { + this.recordTerminalSideEffectFact(ptyId, { kind: 'command-code-working', prompt }) + }, + onDone: (prompt) => { + this.recordTerminalSideEffectFact(ptyId, { kind: 'command-code-done', prompt }) + } + }) + : null + } + this.ptyTitleTrackersByPtyId.set(ptyId, entry) + return entry + } + + /** Apply one observed OSC title (raw form) to the PTY and leaf records. + * Returns true when the PTY record's title or status changed. */ + private applyTrackedPtyTitle(ptyId: string, rawTitle: string, normalizedTitle: string): boolean { + // Why: status is detected from the RAW title (mirrors the renderer tracker), + // so working/idle transitions are unaffected by normalization; the records + // store the NORMALIZED title so rotating Grok/Pi/Gemini frames collapse to + // one stable stored label (#7880) instead of churning `ps`/mobile tabs. + const agentStatus = detectAgentStatusFromTitle(rawTitle) + let ptyRecordChanged = false + const pty = this.ptysById.get(ptyId) + if (pty) { + const prevStatus = pty.lastAgentStatus + const prevTitle = pty.lastOscTitle + const observedAt = this.nextTitleObservationSequence() + pty.lastOscTitle = normalizedTitle + pty.lastOscTitleAt = observedAt + pty.lastAgentStatus = agentStatus + this.setPtyManagementTitleFromObservedTitle(pty, normalizedTitle, observedAt) + ptyRecordChanged = prevTitle !== normalizedTitle || prevStatus !== agentStatus + if (agentStatus === 'idle' && prevStatus !== 'idle') { + this.resolvePtyTuiIdleWaiters(pty, ptyId) + } + const shouldDelayMobileSnapshot = + ptyRecordChanged && + this.shouldDelayPtyBackedMobileSnapshotForForegroundAgent(pty, normalizedTitle) + let foregroundRefresh: Promise | undefined + // Why: gate on an actual status transition — braille spinner frames + // mutate the title every tick, so probing per-title-change would stream + // a foreground query per frame during active work. + if (prevStatus !== agentStatus) { + foregroundRefresh = this.refreshPtyForegroundAgentFromController(ptyId, { + afterTitleObservation: observedAt + }) + } else if (shouldDelayMobileSnapshot) { + // Why: same-status compatible title changes can arrive before the + // foreground owner probe settles; publishing them would flicker. + foregroundRefresh = this.getPendingForegroundAgentRefreshForTitle(ptyId, observedAt) + } + if (foregroundRefresh && shouldDelayMobileSnapshot) { + // Why: report "unchanged" so the per-chunk batch skips the mobile + // snapshot fan-out; the delayed publish fires when the probe settles. + ptyRecordChanged = false + this.delayPtyBackedMobileSnapshotForForegroundAgent(ptyId, observedAt, foregroundRefresh) + } + } + for (const leaf of this.getLeavesForPty(ptyId)) { + // Why: keep the latest OSC title on the leaf so worktree.ps can + // recompute status from the live title each call. Without this, + // daemon-hosted terminals (no renderer pushing pane titles) had no + // way to clear a stale 'working' status after the agent exited and + // the shell took over the title — the stuck-spinner bug in #1437. + leaf.lastOscTitle = normalizedTitle + leaf.lastOscTitleAt = this.nextTitleObservationSequence() + const prevStatus = leaf.lastAgentStatus + // Why: when a new OSC title doesn't classify as an agent state (e.g. + // bare shell title after the agent exits), clear lastAgentStatus so + // it is no longer sticky. Tui-idle waiters that needed the previous + // 'idle' transition were already resolved at the moment of the + // transition below; only fresh waiters registered after the agent + // exits would observe the cleared value, and they correctly fall + // back to title-based detection / polling. + leaf.lastAgentStatus = agentStatus + // Why: resolve tui-idle on any transition TO idle (not just working→idle). + // Claude Code may skip "working" entirely on fast tasks, going null→idle, + // and the coordinator's tui-idle waiter would hang forever waiting for a + // working→idle transition that never comes. Permission→idle is excluded: + // it means the agent was blocked on user approval and the user said no, + // which isn't a task-completion signal. + if (agentStatus === 'idle' && prevStatus !== 'idle') { + this.resolveTuiIdleWaiters(leaf) + this.deliverPendingMessages(leaf) + } + } + return ptyRecordChanged + } + + /** Cancel the per-PTY title tracker (stale-title timer included) on PTY + * teardown so it cannot fire into pruned records. */ + private disposePtyTitleTracker(ptyId: string): void { + this.ptyTitleTrackersByPtyId.get(ptyId)?.tracker.dispose() + this.ptyTitleTrackersByPtyId.delete(ptyId) } private extractLastOsc7CwdForPty( @@ -5533,12 +6291,14 @@ export class OrcaRuntimeService { return worktreePath && isWindowsAbsolutePathLike(worktreePath) ? 'win32' : 'posix' } - private emitTerminalAgentStatusEvents(ptyId: string, chunk: ProcessedAgentStatusChunk): void { + /** Returns true when any retained agent-row snapshot changed in a + * client-visible way, so the caller can republish session snapshots. */ + private emitTerminalAgentStatusEvents(ptyId: string, chunk: ProcessedAgentStatusChunk): boolean { // Why: snapshot retention (for mobile worktree.ps) must run even when no // renderer listener is attached, so we don't early-return on a missing // onTerminalAgentStatus — only the per-target emit below is gated on it. if (chunk.payloads.length === 0) { - return + return false } const targets = new Map< string, @@ -5571,9 +6331,17 @@ export class OrcaRuntimeService { connectionId }) } + let retainedChanged = false for (const payload of chunk.payloads) { for (const target of targets.values()) { - this.retainAgentRowSnapshot(ptyId, target.paneKey, target.worktreeId, target.tabId, payload) + retainedChanged = + this.retainAgentRowSnapshot( + ptyId, + target.paneKey, + target.worktreeId, + target.tabId, + payload + ) || retainedChanged if (!this.onTerminalAgentStatus) { continue } @@ -5594,6 +6362,7 @@ export class OrcaRuntimeService { } } } + return retainedChanged } private retainAgentRowSnapshot( @@ -5602,7 +6371,7 @@ export class OrcaRuntimeService { worktreeId: string | undefined, tabId: string | undefined, payload: ParsedAgentStatusPayload - ): void { + ): boolean { const now = Date.now() const previous = this.latestAgentStatusByPaneKey.get(paneKey) // Why: stateStartedAt must mark the transition into the current state, not @@ -5619,6 +6388,17 @@ export class OrcaRuntimeService { stateStartedAt, updatedAt: now }) + // Client-visible change detection: snapshot republish is gated on this so + // repeated same-state hook pings don't fan a rebuild out to every client. + return ( + !previous || + previous.payload.state !== payload.state || + previous.payload.prompt !== payload.prompt || + (previous.payload.agentType ?? null) !== (payload.agentType ?? null) || + (previous.payload.toolName ?? null) !== (payload.toolName ?? null) || + (previous.payload.interactivePrompt ?? null) !== (payload.interactivePrompt ?? null) || + (previous.payload.interrupted ?? false) !== (payload.interrupted ?? false) + ) } private clearAgentRowSnapshotsForPty(ptyId: string): void { @@ -5640,6 +6420,53 @@ export class OrcaRuntimeService { return addListenerToMap(this.dataListeners, ptyId, listener) } + /** Set by pty IPC: fires when a PTY gains/loses remote view subscribers so + * the daemon background mark (keep-tail stream thinning) can resync — a + * live mobile/web view consumes raw bytes and must never be thinned, even + * while the desktop pane is hidden. */ + onRemoteTerminalViewPresenceChanged: ((ptyId: string) => void) | null = null + + private notifyRemoteTerminalViewPresenceChanged(ptyId: string): void { + try { + this.onRemoteTerminalViewPresenceChanged?.(ptyId) + } catch (err) { + console.error('[runtime] remote view presence listener threw', { ptyId, err }) + } + } + + /** Registered by terminal-RPC subscribe/multiplex streams: while a remote + * view subscriber is attached its xterm answers queries with view + * authority and the model responder must stay silent. Returns an + * idempotent release. */ + registerRemoteTerminalViewSubscriber(ptyId: string): () => void { + this.remoteTerminalViewSubscriberCounts.set( + ptyId, + (this.remoteTerminalViewSubscriberCounts.get(ptyId) ?? 0) + 1 + ) + this.notifyRemoteTerminalViewPresenceChanged(ptyId) + let released = false + return () => { + if (released) { + return + } + released = true + const next = (this.remoteTerminalViewSubscriberCounts.get(ptyId) ?? 1) - 1 + if (next <= 0) { + this.remoteTerminalViewSubscriberCounts.delete(ptyId) + } else { + this.remoteTerminalViewSubscriberCounts.set(ptyId, next) + } + this.notifyRemoteTerminalViewPresenceChanged(ptyId) + } + } + + hasRemoteTerminalViewSubscriber(ptyId: string): boolean { + if ((this.remoteTerminalViewSubscriberCounts.get(ptyId) ?? 0) > 0) { + return true + } + return (this.mobileSubscribers.get(ptyId)?.size ?? 0) > 0 + } + subscribeToFitOverrideChanges( ptyId: string, listener: (event: { mode: 'mobile-fit' | 'desktop-fit'; cols: number; rows: number }) => void @@ -5679,6 +6506,8 @@ export class OrcaRuntimeService { source?: 'headless' | 'renderer' oscLinks?: TerminalOscLinkRange[] alternateScreen?: boolean + scrollbackAnsi?: string + pendingEscapeTailAnsi?: string } | null> { return this.serializeTerminalBufferFromAvailableState(ptyId, opts) } @@ -5696,6 +6525,7 @@ export class OrcaRuntimeService { source?: 'headless' | 'renderer' oscLinks?: TerminalOscLinkRange[] alternateScreen?: boolean + scrollbackAnsi?: string } | null> { return this.serializeHeadlessTerminalBuffer(ptyId, { ...opts, includeEmpty: true }) } @@ -5713,6 +6543,8 @@ export class OrcaRuntimeService { source?: 'headless' | 'renderer' oscLinks?: TerminalOscLinkRange[] alternateScreen?: boolean + scrollbackAnsi?: string + pendingEscapeTailAnsi?: string } | null> { const headlessSnapshot = await this.serializeHeadlessTerminalBuffer(ptyId, { ...opts, @@ -5779,17 +6611,22 @@ export class OrcaRuntimeService { return } const dims = size ?? this.getTerminalSize(ptyId) ?? { cols: 80, rows: 24 } - const state: RuntimeHeadlessTerminal = { - emulator: this.createHeadlessEmulator(ptyId, { cols: dims.cols, rows: dims.rows }), - outputSequence: 0, - writeChain: Promise.resolve() - } + const state = this.createPtyHeadlessTerminalState(ptyId, dims) this.headlessTerminals.set(ptyId, state) this.recordOsc7MetadataForPty(ptyId, data) this.recordRecentPtyOutputForPathProvenance(ptyId, data) state.writeChain = state.writeChain .then(async () => { + // Why: seed writes never set forwardQueryReplies — the main-side + // replay guard. A snapshot containing old queries must answer no one. await state.emulator.write(data) + // Why AFTER the seed write: the snapshot payload cannot carry kitty + // pushes (rehydrateSequences deliberately omits them), but ordering + // behind it keeps the parse deterministic. Unflagged like the seed — + // re-applying flags must answer no one. + if (typeof metadata.kittyKeyboardFlags === 'number') { + await state.emulator.applyKittyKeyboardFlags(metadata.kittyKeyboardFlags) + } if (metadata.cwd !== undefined) { state.emulator.setCwd(metadata.cwd) } @@ -5830,11 +6667,9 @@ export class OrcaRuntimeService { this.headlessHydrationState.set(ptyId, 'pending') const dims = this.getTerminalSize(ptyId) ?? { cols: 80, rows: 24 } - const state: RuntimeHeadlessTerminal = { - emulator: this.createHeadlessEmulator(ptyId, { cols: dims.cols, rows: dims.rows }), - outputSequence: 0, - writeChain: Promise.resolve() - } + // Why: hydration writes below never set forwardQueryReplies (main-side + // replay guard) — renderer-buffer snapshots can embed stale queries. + const state = this.createPtyHeadlessTerminalState(ptyId, dims) this.headlessTerminals.set(ptyId, state) // Why: append the seed work to writeChain so live writes queued by @@ -5864,9 +6699,14 @@ export class OrcaRuntimeService { if (ptyDims && (ptyDims.cols !== rendered.cols || ptyDims.rows !== rendered.rows)) { state.emulator.resize(ptyDims.cols, ptyDims.rows) } - if (rendered.lastTitle) { - state.emulator.setLastTitle(rendered.lastTitle) - this.applySeededAgentStatus(ptyId, rendered.lastTitle) + // Why: the renderer xterm no longer sees synthetic hook title frames + // (they feed main's tracker only), so its serializer lastTitle can be + // stale here. Prefer main's tracked title; the renderer's is only the + // seed when main has observed none (fresh relaunch, cold tracker). + const seedTitle = this.getTrackedRawTitleForPty(ptyId) ?? rendered.lastTitle + if (seedTitle) { + state.emulator.setLastTitle(seedTitle) + this.applySeededAgentStatus(ptyId, seedTitle) } } catch { // Hydration is best-effort. Live writes continue via the same @@ -5887,19 +6727,28 @@ export class OrcaRuntimeService { if (!title) { return } + // Why: a relaunched main starts its per-PTY title tracker cold — without + // this seed it misses the parked working→idle completion and never arms + // the stale-title timer for a persisted 'working' title. Seeding no-ops + // once a live title was observed, so live state always wins. + this.getOrCreatePtyTitleTrackerEntry(ptyId).tracker.seedInitialTitle(title) const status = detectAgentStatusFromTitle(title) + // Why: live observations store normalized titles, so seeds must match — + // otherwise the first live frame after hydration compares unequal and + // touches session tabs once for no visible change. + const seededTitle = normalizeTerminalTitle(title) const pty = this.ptysById.get(ptyId) if (pty) { const observedAt = this.nextTitleObservationSequence() - pty.lastOscTitle = title + pty.lastOscTitle = seededTitle pty.lastOscTitleAt = observedAt - this.setPtyManagementTitleFromObservedTitle(pty, title, observedAt) + this.setPtyManagementTitleFromObservedTitle(pty, seededTitle, observedAt) } for (const leaf of this.getLeavesForPty(ptyId)) { // Why: seed lastOscTitle even when the seeded title doesn't classify // as an agent state, so worktree.ps recomputes status from the live // title rather than treating the leaf as agentless. - leaf.lastOscTitle = title + leaf.lastOscTitle = seededTitle leaf.lastOscTitleAt = this.nextTitleObservationSequence() if (status !== null) { leaf.lastAgentStatus = status @@ -5907,11 +6756,28 @@ export class OrcaRuntimeService { } } - private trackHeadlessTerminalData(ptyId: string, data: string, outputSequence: number): void { + /** Per-chunk reply-ownership capture (Phase 5). Evaluated synchronously at + * ingestion only — never re-read at reply time. */ + private shouldAnswerQueriesForLiveChunk(ptyId: string): boolean { + return shouldModelAnswerHiddenPtyQueries({ + ptyId, + settings: this.store?.getSettings(), + hasRemoteViewSubscriber: this.hasRemoteTerminalViewSubscriber(ptyId) + }) + } + + private trackHeadlessTerminalData( + ptyId: string, + data: string, + outputSequence: number, + forwardQueryReplies = false + ): void { const state = this.getOrCreateHeadlessTerminal(ptyId) state.writeChain = state.writeChain .then(async () => { - await state.emulator.write(data) + // Why: the ingestion-time ownership decision is closed over this + // chain link; async scheduling cannot retroactively change it. + await state.emulator.write(data, { forwardQueryReplies }) state.outputSequence = outputSequence }) .catch(() => { @@ -5920,17 +6786,69 @@ export class OrcaRuntimeService { }) } + /** Shared factory for the per-PTY runtime emulators (seed, hydration, and + * lazy live-byte creation): wires the Phase-5 query-reply sink and the + * ConPTY DA1 override. The daemon emulator never goes through here. */ + private createPtyHeadlessTerminalState( + ptyId: string, + dims: { cols: number; rows: number } + ): RuntimeHeadlessTerminal { + let state: RuntimeHeadlessTerminal | null = null + const pathFlavor = this.pathFlavorForPty(this.ptysById.get(ptyId)) + const emulator = new HeadlessEmulator({ + cols: dims.cols, + rows: dims.rows, + pathFlavor, + remotePosixFileUriAuthority: + !!this.ptysById.get(ptyId)?.connectionId && pathFlavor !== 'win32', + // Why: replies take the provider input path (same entry as pty:write — + // daemon shell-ready gating and the SSH relay write apply unchanged), + // NOT writePtyInput, so renderer interactive-output metering never + // counts responder traffic as user-input echo. + onQueryReply: (reply) => { + // Why the identity check: queued writeChain links can parse after + // disposeHeadlessTerminal, and daemon respawns reuse session ids — a + // stale link's reply must never reach a successor PTY under this id. + if (state !== null && this.headlessTerminals.get(ptyId) === state) { + // Why this write is safe pre-shell-ready: daemon Session.write + // QUEUES (never drops) input while the POSIX shell-ready gate is + // pending and flushes at the ready marker or the 15s + // SHELL_READY_TIMEOUT_MS bound (session.ts) — a spawn-time query + // reply is delayed at most that bound, not lost. + this.ptyController?.write(ptyId, reply) + } + } + }) + if (isNativeWindowsConptyPty(ptyId)) { + emulator.installConptyPrimaryDeviceAttributesOverride() + } + // Why the lazy getter: replies must use the freshest renderer push at + // parse time, and stay silent (never default) before the first push. + emulator.installViewAttributeResponder(() => getTerminalViewAttributes()) + const viewAttributes = getTerminalViewAttributes() + if (viewAttributes) { + emulator.applyPushedViewAttributes(viewAttributes) + } + state = { emulator, outputSequence: 0, writeChain: Promise.resolve() } + return state + } + + /** Phase-5 ConPTY DA1 retrofit (terminal-query-authority.md): invoked via + * markNativeWindowsConptyPty when the spawn mark lands after daemon stream + * data already created this PTY's emulator. Idempotent emulator-side. */ + private ensureNativeWindowsConptyDa1Override(ptyId: string): void { + if (isNativeWindowsConptyPty(ptyId)) { + this.headlessTerminals.get(ptyId)?.emulator.installConptyPrimaryDeviceAttributesOverride() + } + } + private getOrCreateHeadlessTerminal(ptyId: string): RuntimeHeadlessTerminal { const existing = this.headlessTerminals.get(ptyId) if (existing) { return existing } const size = this.getTerminalSize(ptyId) ?? { cols: 80, rows: 24 } - const state: RuntimeHeadlessTerminal = { - emulator: this.createHeadlessEmulator(ptyId, { cols: size.cols, rows: size.rows }), - outputSequence: 0, - writeChain: Promise.resolve() - } + const state = this.createPtyHeadlessTerminalState(ptyId, size) this.headlessTerminals.set(ptyId, state) return state } @@ -5953,19 +6871,6 @@ export class OrcaRuntimeService { }) } - private createHeadlessEmulator( - ptyId: string, - options: Omit - ): HeadlessEmulator { - const pathFlavor = this.pathFlavorForPty(this.ptysById.get(ptyId)) - return new HeadlessEmulator({ - ...options, - pathFlavor, - remotePosixFileUriAuthority: - !!this.ptysById.get(ptyId)?.connectionId && pathFlavor !== 'win32' - }) - } - // Public: desktop-initiated clears (ipc/pty.ts) must also drop this mobile // mirror or a resubscribing mobile client resurrects the cleared scrollback. async clearHeadlessTerminalBuffer(ptyId: string): Promise { @@ -5993,6 +6898,7 @@ export class OrcaRuntimeService { source?: 'headless' | 'renderer' oscLinks?: TerminalOscLinkRange[] alternateScreen?: boolean + pendingEscapeTailAnsi?: string } | null> { const headlessSnapshot = await this.serializeHeadlessTerminalBuffer(ptyId, opts) if (headlessSnapshot) { @@ -6036,11 +6942,11 @@ export class OrcaRuntimeService { // their existing null fallback paths. } return rendererSnapshot - ? { + ? this.preferTrackedLastTitle(ptyId, { ...rendererSnapshot, cwd: rendererSnapshot.cwd ?? this.terminalCwdByPtyId.get(ptyId), - source: 'renderer' - } + source: 'renderer' as const + }) : null } @@ -6110,39 +7016,46 @@ export class OrcaRuntimeService { source?: 'headless' oscLinks?: TerminalOscLinkRange[] alternateScreen?: boolean + scrollbackAnsi?: string + // Why: dangling mid-escape tail the restorer must write LAST, after any + // reset, so the next live chunk completes it instead of rendering it + // literally (Bug E / #7329). + pendingEscapeTailAnsi?: string } | null> { const state = this.headlessTerminals.get(ptyId) if (!state) { return null } await state.writeChain - // Why: when an alternate-screen TUI (Claude Code, vim, etc.) is currently - // active, the visible content is the alt-screen snapshot — replaying any - // normal-buffer scrollback before it can duplicate shell prompts and - // flatten SGR attributes when the mobile xterm replays the data. Force - // scrollbackRows=0 in that case. When the buffer is in normal mode the - // caller can request scrollback so the user can scroll up to see prior - // agent output. - const requested = opts.scrollbackRows ?? 0 + // Why: normal history is separated from an active alternate frame, so the + // caller's scrollback policy can be honored without painting it into alt. const isAlternateScreen = state.emulator.isAlternateScreen - const scrollbackRows = isAlternateScreen ? 0 : requested + const scrollbackRows = opts.scrollbackRows ?? 0 const snapshot = state.emulator.getSnapshot({ scrollbackRows }) const data = snapshot.rehydrateSequences + snapshot.snapshotAnsi return data.length > 0 || opts.includeEmpty === true - ? { + ? this.preferTrackedLastTitle(ptyId, { data, cols: snapshot.cols, rows: snapshot.rows, cwd: snapshot.cwd ?? this.terminalCwdByPtyId.get(ptyId), lastTitle: snapshot.lastTitle, seq: state.outputSequence, - source: 'headless', + source: 'headless' as const, oscLinks: snapshot.oscLinks, + scrollbackAnsi: snapshot.scrollbackAnsi, + ...(snapshot.pendingEscapeTailAnsi + ? { pendingEscapeTailAnsi: snapshot.pendingEscapeTailAnsi } + : {}), // Why: lets the renderer skip the destructive scrollback clear when // restoring an alt-screen snapshot — clearing wipes xterm's own // history that the TUI relies on for scroll-up after a tab return. - alternateScreen: isAlternateScreen - } + alternateScreen: isAlternateScreen, + // Why NOT folded into data: the renderer writes its post-replay + // reset after data, and any ESC after a dangling partial aborts it. + // The restorer writes this last (Bug E fix). + pendingEscapeTailAnsi: snapshot.pendingEscapeTailAnsi + }) : null } @@ -6153,6 +7066,10 @@ export class OrcaRuntimeService { return } this.headlessTerminals.delete(ptyId) + // Why: queued chain links still parse below before the emulator disposes; + // sever the reply sink now so they cannot write to a respawned PTY that + // reused this id (belt to the sink's state-identity check). + state.emulator.disableQueryReplyForwarding() state.writeChain.finally(() => state.emulator.dispose()).catch(() => state.emulator.dispose()) } @@ -6171,6 +7088,32 @@ export class OrcaRuntimeService { return { ptyId: leaf.ptyId } } + // Why: remote clients hold handles across transport reconnects. A handle + // minted for a concrete PTY must never silently adopt a different PTY that + // later occupies the same pane — that misroutes keystrokes (#7718). Handles + // still awaiting their first PTY (ptyId null) may adopt it, which preserves + // the mobile pre-spawn subscribe flow. + resolveLiveLeafForHandle(handle: string): { ptyId: string | null } | null { + const record = this.handles.get(handle) + if (!record) { + return null + } + if (record.tabId.startsWith('pty:')) { + return { ptyId: record.ptyId } + } + const leaf = this.leaves.get(this.getLeafKey(record.tabId, record.leafId)) + if (!leaf) { + return null + } + if ( + record.ptyId !== null && + (leaf.ptyId !== record.ptyId || leaf.ptyGeneration !== record.ptyGeneration) + ) { + throw new Error('terminal_handle_stale') + } + return { ptyId: leaf.ptyId } + } + async resolveTerminalCwd(handle: string): Promise { const ptyId = this.resolveLeafForHandle(handle)?.ptyId if (!ptyId) { @@ -6691,11 +7634,11 @@ export class OrcaRuntimeService { // `rateLimits:update` IPC channel desktop already uses. onAccountsChanged(listener: (snapshot: AccountsSnapshot) => void): () => void { const services = this.requireAccountServices() - return services.rateLimits.onStateChange(() => { + return services.rateLimits.onStateChange((rateLimits) => { listener({ claude: services.claudeAccounts.listAccounts(), codex: services.codexAccounts.listAccounts(), - rateLimits: services.rateLimits.getState() + rateLimits }) }) } @@ -6927,6 +7870,7 @@ export class OrcaRuntimeService { ? { cols: subscriber.previousCols, rows: subscriber.previousRows } : null inner.delete(clientId) + this.notifyRemoteTerminalViewPresenceChanged(ptyId) if (inner.size > 0) { ptysWithSurvivingPeers.push(ptyId) } else { @@ -7011,13 +7955,17 @@ export class OrcaRuntimeService { serveSimStateWatcher.unbindPty(ptyId) // Clean up new mobile state for this PTY this.mobileSubscribers.delete(ptyId) + this.remoteTerminalViewSubscriberCounts.delete(ptyId) this.mobileDisplayModes.delete(ptyId) this.resizeListeners.delete(ptyId) this.lastRendererSizes.delete(ptyId) this.recentPtyOutputById.delete(ptyId) + this.clearWaitBlockedCheckState(ptyId) this.recentPtyPathCandidatesById.delete(ptyId) this.ptyOutputSequenceById.delete(ptyId) this.agentStatusOscProcessorsByPtyId.delete(ptyId) + this.terminalSpawnCommandsByPtyId.delete(ptyId) + this.disposePtyTitleTracker(ptyId) this.oscTitleScanTailByPtyId.delete(ptyId) this.osc7ScanTailByPtyId.delete(ptyId) this.terminalCwdByPtyId.delete(ptyId) @@ -7071,7 +8019,7 @@ export class OrcaRuntimeService { pty.lastExitCode = exitCode this.resolvePtyExitWaiters(pty, ptyId) this.pruneDisconnectedPtyTranscript(pty) - this.touchMobileSessionSnapshotsForPty(ptyId) + this.touchMobileSessionSnapshotsForPty(ptyId, { immediate: true }) } for (const leaf of this.getLeavesForPty(ptyId)) { @@ -7249,25 +8197,35 @@ export class OrcaRuntimeService { } // Why: invoked from `runtime:restoreTerminalFit` IPC (the desktop "Take - // back" / "Restore" button). Forces the PTY back to desktop dims and - // flips the driver to `desktop`, suppressing further mobile-driven dim - // changes until a mobile actor takes the floor again. Two cases: - // 1. Active mobile subscriber: route through applyMobileDisplayMode so - // the existing 'resized' event reaches the phone. - // 2. Held with no mobile subscriber (post-indefinite-hold): no inner - // subscriber to notify; resolve restore target and enqueueLayout - // directly. applyLayout is the SOLE writer of terminalFitOverrides; - // the held branch must not duplicate that mutation. See - // docs/mobile-fit-hold.md. + // back" / "Restore" button). Forces the PTY back to desktop dims and flips + // the driver to `desktop`, suppressing further mobile-driven dim changes + // until a mobile actor takes the floor again. Three cases, each ending in + // releaseDesktopTakeBack: + // 1. Active mobile subscriber: route through applyMobileDisplayMode so the + // existing 'resized' event reaches the phone. + // 2. Held override, no subscriber (post-indefinite-hold): resolve the + // restore target and enqueueLayout directly. + // 3. Stale mobile driver, no subscriber and no override: nothing to resize, + // just drop the lock. See docs/mobile-fit-hold.md. + // + // Why: explicit desktop take-back is a user command to reclaim input control + // NOW. Unlike the auto-restore timer and phone-initiated setDisplayMode paths + // (which keep the lock when a resize can't converge, #7588), this gesture + // ALWAYS drops the presence lock and banner. "Take back all terminals" + // reclaims several PTYs at once; a background pane whose desktop resize can't + // converge must not strand its banner on the other terminals. The resize is + // best-effort — the desktop renderer refits the PTY on its next settled + // frame. Returns `true` whenever there was a lock to reclaim, `false` only + // when there was nothing to reclaim. async reclaimTerminalForDesktop(ptyId: string): Promise { if (this.isMobileSubscriberActive(ptyId)) { this.setMobileDisplayMode(ptyId, 'desktop') await this.applyMobileDisplayMode(ptyId) - this.setDriver(ptyId, { kind: 'desktop' }) - // Why: a desktop-initiated reclaim is "I'm taking over right now", - // not a sticky preference. The next mobile subscribe (e.g. user - // switches back to the terminal tab on the phone) must default to - // phone-fit again, not stay in passive desktop-watch mode. + this.releaseDesktopTakeBack(ptyId) + // Why: a desktop-initiated reclaim is "I'm taking over right now", not a + // sticky preference. The next mobile subscribe (e.g. user switches back to + // the terminal tab on the phone) must default to phone-fit again, not stay + // in passive desktop-watch mode. this.setMobileDisplayMode(ptyId, 'auto') return true } @@ -7287,18 +8245,37 @@ export class OrcaRuntimeService { const cols = renderer?.cols ?? heldOverride.previousCols ?? fallback.cols const rows = renderer?.rows ?? heldOverride.previousRows ?? fallback.rows await this.enqueueLayout(ptyId, { kind: 'desktop', cols, rows }) - this.setDriver(ptyId, { kind: 'desktop' }) - // Why: a desktop-initiated reclaim is "I'm taking over right now", - // not a sticky preference. Reset to auto so the next mobile subscribe - // re-enters phone-fit. (Held-PTY branch may not have an entry, but - // calling setMobileDisplayMode('auto') is a no-op deletion in that - // case — safe and idempotent.) + this.releaseDesktopTakeBack(ptyId) this.setMobileDisplayMode(ptyId, 'auto') return true } + // Why: a stale lock — driver still reads mobile with no active subscriber + // and no held override (e.g. reclaimed inside the soft-leave grace, or a + // subscriber that dropped without a clean unsubscribe). Release it so the + // banner can't linger; there is nothing to resize. + if (this.getDriver(ptyId).kind === 'mobile') { + this.releaseDesktopTakeBack(ptyId) + return true + } return false } + // Why: the shared "banner must be gone now" step for an explicit desktop + // take-back. Releases the presence lock (driver → desktop) and, if the + // best-effort resize left a fit-override held (resize didn't converge), + // clears it optimistically with a paired desktop-fit 0×0 — the same signal + // onPtyExit emits — so neither the presence-lock banner nor the held-fit + // banner can survive the reclaim. The desktop renderer refits the PTY to real + // dims on its next settled frame. + private releaseDesktopTakeBack(ptyId: string): void { + this.setDriver(ptyId, { kind: 'desktop' }) + if (this.terminalFitOverrides.has(ptyId)) { + this.terminalFitOverrides.delete(ptyId) + this.notifier?.terminalFitOverrideChanged(ptyId, 'desktop-fit', 0, 0) + this.notifyFitOverrideListeners(ptyId, 'desktop-fit', 0, 0) + } + } + // Why: read-side clamp for mobileAutoRestoreFitMs. `null` means // indefinite hold (no auto-restore timer). A finite value is clamped // to [MIN, MAX] to defend against bad config — the smallest useful @@ -7410,7 +8387,8 @@ export class OrcaRuntimeService { // // applyLayout is the SOLE writer of: // - this.layouts - // - this.terminalFitOverrides + // - this.terminalFitOverrides (except the sanctioned dead-pty cleanups in + // onPtyExit and reclaimTerminalForDesktop's orphan branch, which delete) // - this.ptyController.resize (i.e. the actual PTY dims) // // Every trigger that wants to change PTY dims or flip mode goes through @@ -7605,11 +8583,17 @@ export class OrcaRuntimeService { this.resizeHeadlessTerminal(ptyId, target.cols, target.rows) } - // Why: emit fit-override-changed only when the *mode* flips. Layouts - // can change dims without flipping mode (keyboard show/hide while - // phone), and waking the renderer on every viewport tick is wasteful - // churn. - if (modeChanged) { + // Why: emit fit-override-changed when the *mode* flips. Layouts can + // change dims without flipping mode (keyboard show/hide while phone), + // and waking the renderer on every viewport tick is wasteful churn. + // Defense-in-depth (#7588): also emit when the override's presence + // changed even without a kind flip. applyLayout is the sole writer and + // keeps override presence in lockstep with layout kind, so overrideChanged + // ≡ modeChanged in every reachable state today; the extra clause fires + // only if that invariant is ever violated, repairing the renderer instead + // of stranding the held modal. + const overrideChanged = (prevFitOverride != null) !== (target.kind === 'phone') + if (modeChanged || overrideChanged) { // Why: phone→desktop arms the renderer-cascade suppress window // before the collateral safeFit IPCs arrive. See "Renderer cascade // suppression". @@ -7699,6 +8683,20 @@ export class OrcaRuntimeService { ptyId: string, clientId: string, viewport?: { cols: number; rows: number } + ): Promise { + try { + return await this.handleMobileSubscribeInternal(ptyId, clientId, viewport) + } finally { + // Every subscribe path mutates mobileSubscribers — resync the daemon + // background mark once, whatever branch returned. + this.notifyRemoteTerminalViewPresenceChanged(ptyId) + } + } + + private async handleMobileSubscribeInternal( + ptyId: string, + clientId: string, + viewport?: { cols: number; rows: number } ): Promise { const mode = this.getMobileDisplayMode(ptyId) @@ -7871,6 +8869,7 @@ export class OrcaRuntimeService { const wasResizedToPhone = subscriber.wasResizedToPhone inner.delete(clientId) + this.notifyRemoteTerminalViewPresenceChanged(ptyId) if (inner.size > 0) { // Why: if the leaving client was the only one with a non-null restore @@ -8007,7 +9006,13 @@ export class OrcaRuntimeService { // Multi-mobile: the most recent mobile actor's viewport drives the active // phone-fit dims. The earliest-by-subscribe-time subscriber's // previousCols/Rows drive the desktop-restore target. - async applyMobileDisplayMode(ptyId: string): Promise { + // + // Returns the post-condition "no fit-override remains held" (#7588): `true` + // when it cleared a held override OR nothing was held to begin with, `false` + // only when a restore was attempted and the resize failed (override rolled + // back, still held). reclaimTerminalForDesktop gates its driver/mode + // transitions on this; other callers ignore it. + async applyMobileDisplayMode(ptyId: string): Promise { const mode = this.getMobileDisplayMode(ptyId) const inner = this.mobileSubscribers.get(ptyId) const subscriber = inner ? this.pickMostRecentActor(inner) : null @@ -8016,25 +9021,39 @@ export class OrcaRuntimeService { if (mode === 'desktop') { // Reset wasResizedToPhone on every fitted subscriber so a future // toggle back to auto re-issues the resize. applyLayout owns the - // actual PTY resize + override delete + renderer notify. - let anyWasResized = false - if (inner) { - for (const sub of inner.values()) { - if (sub.wasResizedToPhone) { - anyWasResized = true - sub.wasResizedToPhone = false - } - } - } - if (anyWasResized) { + // actual PTY resize + override delete + renderer notify. Track which + // subscribers we cleared so a failed resize can re-arm them. + const clearedFitSubscribers = inner + ? [...inner.values()].filter((sub) => sub.wasResizedToPhone) + : [] + for (const sub of clearedFitSubscribers) { + sub.wasResizedToPhone = false + } + const anyWasResized = clearedFitSubscribers.length > 0 + // Why (#7588): also restore when a fit-override is still held but no + // subscriber carries wasResizedToPhone — e.g. a null-viewport resubscribe + // after an indefinite hold resets the flag yet leaves the override, + // stranding the desktop "phone size" modal. Reuse resolveDesktopRestoreTarget + // (the same resolver the anyWasResized branch uses) so the two adjacent + // restore paths can never resolve to different dims for the same state. + if (anyWasResized || this.terminalFitOverrides.has(ptyId)) { const restore = this.resolveDesktopRestoreTarget(ptyId) - await this.enqueueLayout(ptyId, { + const result = await this.enqueueLayout(ptyId, { kind: 'desktop', cols: restore.cols, rows: restore.rows }) + // Why (#7588): a failed resize rolls the override back (still held), so + // re-arm the flags we cleared. Otherwise a later unsubscribe under a + // finite mobileAutoRestoreFitMs would see wasResizedToPhone=false, skip + // scheduling its auto-restore timer, and strand the held phone-fit. + if (!result.ok) { + for (const sub of clearedFitSubscribers) { + sub.wasResizedToPhone = true + } + } } else { - // No subscriber was fitted — emit a mode-change resize event so + // Nothing was fitted or held — emit a mode-change resize event so // the mobile client still learns the toggle landed. const size = this.getTerminalSize(ptyId) this.notifyTerminalResize(ptyId, { @@ -8053,7 +9072,10 @@ export class OrcaRuntimeService { const viewport = subscriberRecord.viewport if (viewport) { await this.handleMobileSubscribe(ptyId, subscriberRecord.clientId, viewport) - return + // After a phone-fit an override IS held, so this reports false. The + // auto branch is never reached from reclaim (it sets 'desktop' + // first); computed here only to keep the post-condition uniform. + return !this.terminalFitOverrides.has(ptyId) } } // Why: always emit the mode change even when no resize occurred — the @@ -8069,6 +9091,7 @@ export class OrcaRuntimeService { seq: this.layouts.get(ptyId)?.seq }) } + return !this.terminalFitOverrides.has(ptyId) } // Why: called after a desktop renderer path has successfully resized the @@ -8719,19 +9742,48 @@ export class OrcaRuntimeService { if (!leaf.writable || !leaf.ptyId) { throw new Error('terminal_not_writable') } - const payload = buildSendPayload(action) - if (payload === null) { - throw new Error('invalid_terminal_send') - } - await assertTerminalInputWithinLimitWithYield(action.text) - - await this.writeTerminalAction(leaf.ptyId, action, payload, options) - - return { - handle, - accepted: true, - bytesWritten: Buffer.byteLength(payload, 'utf8') - } + const payload = buildSendPayload(action) + if (payload === null) { + throw new Error('invalid_terminal_send') + } + await assertTerminalInputWithinLimitWithYield(action.text) + + await this.writeTerminalAction(leaf.ptyId, action, payload, options) + + return { + handle, + accepted: true, + bytesWritten: Buffer.byteLength(payload, 'utf8') + } + } + + async sendTerminalAgentPrompt( + handle: string, + prompt: string, + options: { + beforeWrite?: (ptyId: string) => void | Promise + suffixFailureError?: string + } = {} + ): Promise { + const payload = buildAgentPromptPasteBytes(prompt) + const bytesWritten = Buffer.byteLength(`${payload}${AGENT_PROMPT_SUBMIT}`, 'utf8') + const pty = this.getLivePtyForHandle(handle) + if (pty) { + if (!pty.pty.connected) { + throw new Error('terminal_not_writable') + } + await assertTerminalInputWithinLimitWithYield(payload) + await this.writeTerminalAgentPrompt(pty.pty.ptyId, payload, options) + return { handle, accepted: true, bytesWritten } + } + + const { leaf } = this.getLiveLeafForHandle(handle) + if (!leaf.writable || !leaf.ptyId) { + throw new Error('terminal_not_writable') + } + await assertTerminalInputWithinLimitWithYield(payload) + await this.writeTerminalAgentPrompt(leaf.ptyId, payload, options) + return { handle, accepted: true, bytesWritten } } async getTerminalAgentStatus(handle: string): Promise { @@ -9091,6 +10143,54 @@ export class OrcaRuntimeService { } } + private async writeTerminalAgentPrompt( + ptyId: string, + pastePayload: string, + options: { + beforeWrite?: (ptyId: string) => void | Promise + suffixFailureError?: string + } = {} + ): Promise { + let wrotePasteBytes = false + let completedPaste = false + try { + const chunks = iterateTerminalInputChunks(pastePayload) + let chunk = chunks.next() + while (!chunk.done) { + await options.beforeWrite?.(ptyId) + const wrote = this.ptyController?.write(ptyId, chunk.value) ?? false + if (!wrote) { + throw new Error('terminal_not_writable') + } + wrotePasteBytes = true + chunk = chunks.next() + if (!chunk.done) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } + } + completedPaste = true + } catch (error) { + if (wrotePasteBytes && !completedPaste) { + this.ptyController?.write(ptyId, AGENT_PROMPT_BRACKETED_PASTE_END) + } + throw error + } + + await new Promise((resolve) => setTimeout(resolve, AGENT_PROMPT_SUBMIT_DELAY_MS)) + try { + await options.beforeWrite?.(ptyId) + } catch (error) { + if (options.suffixFailureError) { + throw new Error(options.suffixFailureError) + } + throw error + } + const suffixWrote = this.ptyController?.write(ptyId, AGENT_PROMPT_SUBMIT) ?? false + if (!suffixWrote) { + throw new Error(options.suffixFailureError ?? 'terminal_not_writable') + } + } + async waitForTerminal( handle: string, options?: { @@ -9347,24 +10447,40 @@ export class OrcaRuntimeService { if (!linkedPR && meta?.linkedPR != null) { linkedPR = { number: meta.linkedPR, state: 'unknown' } } + const terminalPlatform = repo ? this.getAgentLaunchPlatformForRepo(repo) : process.platform + // Why: use the instance-validated lineage from attachLineageToResolvedWorktrees, + // not the raw store entry — shipped mobile clients trust parentWorktreeId as-is, + // so a stale same-path entry would nest replacement checkouts under old parents. + const lineage = worktree.lineage summaries.set(worktree.id, { // Why: mobile mirrors desktop workspace grouping/order from persisted // metadata, while older runtimes may not have hydrated every field yet. workspaceKind: 'git', worktreeId: worktree.id, repoId: worktree.repoId, + ...((worktree.hostId ?? meta?.hostId) ? { hostId: worktree.hostId ?? meta?.hostId } : {}), + terminalPlatform, repo: repo?.displayName ?? worktree.repoId, path: worktree.path, branch: worktree.branch, isArchived: worktree.isArchived, isMainWorktree: worktree.isMainWorktree, hasHostSidebarActivity: false, + ...(worktree.instanceId !== undefined ? { worktreeInstanceId: worktree.instanceId } : {}), + ...(lineage?.worktreeInstanceId !== undefined + ? { lineageWorktreeInstanceId: lineage.worktreeInstanceId } + : {}), + ...(lineage?.parentWorktreeInstanceId !== undefined + ? { parentWorktreeInstanceId: lineage.parentWorktreeInstanceId } + : {}), parentWorktreeId: worktree.parentWorktreeId, childWorktreeIds: worktree.childWorktreeIds, displayName: worktree.displayName, workspaceStatus: meta?.workspaceStatus ?? DEFAULT_WORKSPACE_STATUS_ID, sortOrder: meta?.sortOrder ?? 0, ...(meta?.manualOrder !== undefined ? { manualOrder: meta.manualOrder } : {}), + lastActivityAt: worktree.lastActivityAt, + ...(worktree.createdAt !== undefined ? { createdAt: worktree.createdAt } : {}), linkedIssue: worktree.linkedIssue, linkedPR, linkedLinearIssue: meta?.linkedLinearIssue ?? null, @@ -9404,12 +10520,15 @@ export class OrcaRuntimeService { isArchived: worktree.isArchived, isMainWorktree: worktree.isMainWorktree, hasHostSidebarActivity: false, + ...(worktree.instanceId !== undefined ? { worktreeInstanceId: worktree.instanceId } : {}), parentWorktreeId: null, childWorktreeIds: [], displayName: worktree.displayName, workspaceStatus: worktree.workspaceStatus ?? DEFAULT_WORKSPACE_STATUS_ID, sortOrder: worktree.sortOrder ?? 0, ...(worktree.manualOrder !== undefined ? { manualOrder: worktree.manualOrder } : {}), + lastActivityAt: worktree.lastActivityAt, + ...(worktree.createdAt !== undefined ? { createdAt: worktree.createdAt } : {}), linkedIssue: worktree.linkedIssue ?? null, linkedPR: null, linkedLinearIssue: worktree.linkedLinearIssue ?? null, @@ -9687,7 +10806,7 @@ export class OrcaRuntimeService { if (!this.store) { throw new Error('runtime_unavailable') } - let repo = await this.addRepo(args.path, args.kind === 'folder' ? 'folder' : 'git') + let repo = await this.addRepo(args.path, args.kind === 'folder' ? 'folder' : 'git', args.hostId) let setup = getProjectHostSetupForRepo(this.listProjectHostSetups(), repo) if (setup.projectId !== args.projectId) { const existingProject = this.listProjects().find((project) => project.id === args.projectId) @@ -9726,7 +10845,7 @@ export class OrcaRuntimeService { } async setupProjectClone(args: ProjectHostSetupCloneArgs): Promise { - const repo = await this.cloneRepo(args.url, args.destination) + const repo = await this.cloneRepo(args.url, args.destination, args.hostId) return await this.setupProjectExistingFolder({ projectId: args.projectId, hostId: args.hostId, @@ -10127,7 +11246,11 @@ export class OrcaRuntimeService { }) } - async addRepo(path: string, kind: 'git' | 'folder' = 'git'): Promise { + async addRepo( + path: string, + kind: 'git' | 'folder' = 'git', + executionHostId?: ExecutionHostId | null + ): Promise { if (!this.store) { throw new Error('runtime_unavailable') } @@ -10140,8 +11263,29 @@ export class OrcaRuntimeService { throw new Error(`Not a valid git repository: ${path}`) } - const existing = this.store.getRepos().find((repo) => runtimePathsEqual(repo.path, path)) + const existing = this.store.getRepos().find((repo) => { + if (!runtimePathsEqual(repo.path, path)) { + return false + } + return runtimeRepoMatchesExecutionHost(repo, executionHostId) + }) if (existing) { + // Only a runtime host backfills a legacy unstamped repo. An unstamped repo is + // indistinguishable from a genuine local repo (both have null executionHostId and + // connectionId), so we never stamp local/ssh onto it — that would re-attribute a + // real local project to the wrong host. Runtime is the only host that lost its + // identity to the pre-#7018 path-only import and needs the backfill. + if ( + existing.executionHostId == null && + parseExecutionHostId(executionHostId)?.kind === 'runtime' + ) { + const adopted = + this.store.updateRepo(existing.id, { executionHostId }) ?? + ({ ...existing, executionHostId } as Repo) + this.invalidateResolvedWorktreeCache() + this.notifyReposChanged() + return adopted + } return existing } @@ -10151,6 +11295,7 @@ export class OrcaRuntimeService { path, displayName: getRepoName(path), badgeColor: DEFAULT_REPO_BADGE_COLOR, + ...(executionHostId != null ? { executionHostId } : {}), ...detected, addedAt: Date.now(), kind, @@ -10289,7 +11434,11 @@ export class OrcaRuntimeService { return { repo: this.store.getRepo(repo.id) ?? repo } } - async cloneRepo(url: string, destination: string): Promise { + async cloneRepo( + url: string, + destination: string, + executionHostId?: ExecutionHostId | null + ): Promise { if (!this.store) { throw new Error('runtime_unavailable') } @@ -10317,7 +11466,8 @@ export class OrcaRuntimeService { trimmedUrl, trimmedDestination, clonePath, - clonePathKey + clonePathKey, + executionHostId ) } finally { release() @@ -10331,14 +11481,19 @@ export class OrcaRuntimeService { trimmedUrl: string, trimmedDestination: string, clonePath: string, - clonePathKey: string + clonePathKey: string, + executionHostId?: ExecutionHostId | null ): Promise { if (!this.store) { throw new Error('runtime_unavailable') } const existingBeforeClone = this.store .getRepos() - .find((repo) => getClonePathComparisonKey(repo.path) === clonePathKey) + .find( + (repo) => + getClonePathComparisonKey(repo.path) === clonePathKey && + runtimeRepoMatchesExecutionHost(repo, executionHostId) + ) if (existingBeforeClone && !isFolderRepo(existingBeforeClone)) { return existingBeforeClone } @@ -10346,9 +11501,9 @@ export class OrcaRuntimeService { await mkdir(trimmedDestination, { recursive: true }) const claimedTarget = await claimCloneTarget(clonePath) await new Promise((resolve, reject) => { - let proc: ReturnType + let proc: ReturnType try { - proc = wslAwareSpawn('git', ['clone', '--progress', '--', trimmedUrl, clonePath], { + proc = gitSpawn(['clone', '--progress', '--', trimmedUrl, clonePath], { cwd: trimmedDestination, stdio: ['ignore', 'ignore', 'pipe'] }) @@ -10398,7 +11553,11 @@ export class OrcaRuntimeService { const existing = this.store .getRepos() - .find((repo) => getClonePathComparisonKey(repo.path) === clonePathKey) + .find( + (repo) => + getClonePathComparisonKey(repo.path) === clonePathKey && + runtimeRepoMatchesExecutionHost(repo, executionHostId) + ) if (existing) { if (isFolderRepo(existing)) { const updated = this.store.updateRepo(existing.id, { kind: 'git' }) @@ -10419,6 +11578,7 @@ export class OrcaRuntimeService { path: clonePath, displayName: getRepoName(clonePath), badgeColor: DEFAULT_REPO_BADGE_COLOR, + ...(executionHostId != null ? { executionHostId } : {}), ...detected, addedAt: Date.now(), kind: 'git', @@ -10645,32 +11805,33 @@ export class OrcaRuntimeService { .split('\n') .map((line) => line.trim()) .filter(Boolean) + const capabilities = getSshGitCapabilityCache(provider) const runSearch = async (patternGroup?: 'segmented' | 'branchRoot'): Promise => { - try { - return ( - await provider.exec( - buildSearchBaseRefsArgv(normalizedQuery, limit, { - remoteNames: remotes, - patternGroup - }), - repo.path - ) - ).stdout - } catch (err) { - if (!isForEachRefExcludeUnsupportedError(err)) { - throw err - } - return ( - await provider.exec( - buildSearchBaseRefsArgv(normalizedQuery, limit, { - excludeRemoteHead: false, - remoteNames: remotes, - patternGroup - }), - repo.path - ) - ).stdout - } + return capabilities.runWithFallback( + 'for-each-ref-exclude', + async () => + ( + await provider.exec( + buildSearchBaseRefsArgv(normalizedQuery, limit, { + remoteNames: remotes, + patternGroup + }), + repo.path + ) + ).stdout, + async () => + ( + await provider.exec( + buildSearchBaseRefsArgv(normalizedQuery, limit, { + excludeRemoteHead: false, + remoteNames: remotes, + patternGroup + }), + repo.path + ) + ).stdout, + isForEachRefExcludeUnsupportedError + ) } const searchTokens = normalizedQuery.split('/').filter((token) => token.length > 0) if (searchTokens.length > 1) { @@ -12271,11 +13432,15 @@ export class OrcaRuntimeService { async activateManagedWorktree( worktreeSelector: string, - opts: { notifyClients?: boolean } = {} + opts: { notifyClients?: boolean; clientKind?: 'mobile' | 'runtime' } = {} ): Promise<{ repoId: string worktreeId: string activated: boolean + /** Mobile-scoped slept-agent wake outcome. `unsupported-headless` means no + * renderer holds the sleeping records (headless `orca serve`), so nothing + * woke — clients must not present the worktree's agents as resumed. */ + sleepingAgentWake: 'requested' | 'unsupported-headless' | 'not-applicable' }> { this.assertGraphReady() const worktree = await this.resolveWorktreeSelector(worktreeSelector) @@ -12291,6 +13456,8 @@ export class OrcaRuntimeService { this.notifyWorktreesChanged(repo.id) } + let sleepingAgentWake: 'requested' | 'unsupported-headless' | 'not-applicable' = + 'not-applicable' if (opts.notifyClients !== false) { // Why: inactive worktree terminal panes are renderer-owned and may not have // live PTYs until the desktop activates the worktree and mounts them. @@ -12303,8 +13470,32 @@ export class OrcaRuntimeService { }) await this.refreshMobileSessionPtyRecords() this.notifyMobileSessionTabsChanged(worktree.id) + // Why: a phone open must also wake the worktree's slept agents (experimental + // agent sleep). Only the host renderer holds the sleeping records + wake + // authority, so fire-and-forget ask it — mobile-scoped so web/desktop are + // unaffected. Headless serve has no renderer to wake anything, so report + // that explicitly instead of letting mobile assume the agents resumed. + if (opts.clientKind === 'mobile') { + if (this.getAvailableAuthoritativeWindow()) { + this.notifier?.resumeSleepingAgents?.(worktree.id) + sleepingAgentWake = 'requested' + } else if ( + // Why: sleeping records are partitioned by execution host; reading + // only the local partition would miss slept agents on SSH-host + // worktrees and skip the headless warning for them. + Object.values( + this.store?.getWorkspaceSession?.(getRepoExecutionHostId(repo)) + .sleepingAgentSessionsByPaneKey ?? {} + ).some((record) => record.worktreeId === worktree.id) + ) { + // Why: headless is only degraded when this worktree actually has a + // persisted resume record. Ordinary mobile activation must not show + // an unsupported warning merely because no desktop window is open. + sleepingAgentWake = 'unsupported-headless' + } + } } - return { repoId: repo.id, worktreeId: worktree.id, activated: true } + return { repoId: repo.id, worktreeId: worktree.id, activated: true, sleepingAgentWake } } private async buildStartupForDraft( @@ -14239,8 +15430,15 @@ export class OrcaRuntimeService { if (this.getFreshFetchCompletedAt(key) !== null) { return { ok: true } } + // Why: this exact refresh gates worktree create; ordinary fetches still own maintenance. return gitExecFileAsync( - ['fetch', '--no-tags', base.remote, `+refs/heads/${base.branch}:${base.ref}`], + [ + ...GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS, + 'fetch', + '--no-tags', + base.remote, + `+refs/heads/${base.branch}:${base.ref}` + ], { cwd: repoPath, ...gitOptions, @@ -15352,8 +16550,16 @@ export class OrcaRuntimeService { const canonicalWorktreePath = registeredWorktree.path const deleteBranch = removedMeta?.preserveBranchOnDelete !== true + // Why: a Git lock must block before archive hooks or linked-path cleanup + // mutate the workspace; dirty-file force is a separate permission. + try { + assertWorktreeUnlockedForRemoval(registeredWorktree) + } catch (error) { + throw new Error(formatWorktreeRemovalError(error, canonicalWorktreePath, force)) + } + // Why: a prior forced Windows recovery can delete the directory but leave - // Git's stale registration; retry by pruning instead of removing a missing path. + // Git's stale registration; recover and verify it before clearing metadata. if ( !repo.connectionId && force === true && @@ -15362,7 +16568,7 @@ export class OrcaRuntimeService { removedMeta && (await isRuntimeWorktreePathMissing(repo, canonicalWorktreePath, localWorktreeGitOptions)) ) { - const removalResult = await pruneStaleLocalWorktreeRegistrationAfterFilesystemRemoval({ + const removalResult = await removeStaleLocalWorktreeRegistrationAfterFilesystemRemoval({ canonicalWorktreePath, repoPath: repo.path, localWorktreeGitOptions, @@ -15390,9 +16596,10 @@ export class OrcaRuntimeService { return removalResult ?? {} } if (repo.connectionId) { - const rawRemovalResult = await (deleteBranch - ? provider!.removeWorktree(canonicalWorktreePath, force) - : provider!.removeWorktree(canonicalWorktreePath, force, { deleteBranch })) + const remoteRemoveOptions = !deleteBranch ? { deleteBranch } : {} + const rawRemovalResult = await (Object.keys(remoteRemoveOptions).length > 0 + ? provider!.removeWorktree(canonicalWorktreePath, force, remoteRemoveOptions) + : provider!.removeWorktree(canonicalWorktreePath, force)) const removalResult = this.preserveBranchHeadFallback( rawRemovalResult, registeredWorktree.head @@ -15437,6 +16644,27 @@ export class OrcaRuntimeService { console.warn(`[hooks] ${warning}`) } + const refreshedWorktrees = hasLocalWorktreeGitOptions + ? await listWorktreesStrict(repo.path, localWorktreeGitOptions) + : await listWorktreesStrict(repo.path) + const refreshedRegisteredWorktree = findRegisteredDeletableWorktree( + repo.path, + canonicalWorktreePath, + refreshedWorktrees + ) + if (!refreshedRegisteredWorktree) { + throw new Error( + `Worktree registration changed during deletion: ${canonicalWorktreePath}. Retry deletion.` + ) + } + try { + // Why: an archive hook can race another Git client that locks the row; + // recheck before linked-path, watcher, or terminal teardown side effects. + assertWorktreeUnlockedForRemoval(refreshedRegisteredWorktree) + } catch (error) { + throw new Error(formatWorktreeRemovalError(error, canonicalWorktreePath, force)) + } + let shouldTearDownPtys = true if (repo.symlinkPaths && repo.symlinkPaths.length > 0) { await removeWorktreeLinkedPaths(canonicalWorktreePath, repo.symlinkPaths) @@ -15491,23 +16719,23 @@ export class OrcaRuntimeService { ...(!deleteBranch ? { deleteBranch } : {}), // Why: removal already validated the Git row under the selected // project runtime; keep branch cleanup on that same canonical row. - knownRemovedWorktree: registeredWorktree, + knownRemovedWorktree: refreshedRegisteredWorktree, ...localWorktreeGitOptions } removalResult = this.preserveBranchHeadFallback( await removeWorktree(repo.path, canonicalWorktreePath, force, removeOptions), - registeredWorktree.head + refreshedRegisteredWorktree.head ) } catch (error) { - // Why: Git for Windows can fail long-path directory deletion after - // Orca has already validated the target and explicit force delete. - const recoveredRemovalResult = await recoverLocalWindowsLongPathWorktreeRemoval({ + // Why: Git for Windows can deregister a clean worktree before its + // recursive filesystem deletion fails transiently. + const recoveredRemovalResult = await recoverLocalWindowsWorktreeRemoval({ error, force, canonicalWorktreePath, repoPath: repo.path, localWorktreeGitOptions, - registeredWorktree, + registeredWorktree: refreshedRegisteredWorktree, deleteBranch, closeWatcher: (worktreePath) => closeLocalWatcherForWorktreePath(worktreePath).catch((err) => { @@ -15576,7 +16804,7 @@ export class OrcaRuntimeService { this.rememberPreservedBranchCleanupTarget( removalTarget.id, removalResult, - registeredWorktree.head, + refreshedRegisteredWorktree.head, removedPushTarget ) this.clearOptimisticReconcileToken(removalTarget.id) @@ -15721,7 +16949,7 @@ export class OrcaRuntimeService { const workspace = await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector) const launchOpts = await this.resolveAgentTerminalCreateOptions(workspace, opts) const cwd = - this.resolveGuardedWorkspaceTerminalCwd(workspace, launchOpts.cwd) ?? workspace.path + this.resolveWorkspaceTerminalStartupCwd(workspace, launchOpts.cwd) ?? workspace.path const preAllocatedHandle = this.createPreAllocatedTerminalHandle() // Why: mint tabId in main before spawn so paneKey is known at PTY env // build time. Hook-based agent status (Claude/Codex/Cursor/Gemini) keys @@ -15914,7 +17142,7 @@ export class OrcaRuntimeService { : opts const worktreeId = workspace?.id const cwd = workspace - ? this.resolveGuardedWorkspaceTerminalCwd(workspace, launchOpts.cwd) + ? this.resolveWorkspaceTerminalStartupCwd(workspace, launchOpts.cwd) : launchOpts.cwd const requestId = randomUUID() @@ -16012,6 +17240,7 @@ export class OrcaRuntimeService { launchAgent?: TuiAgent activate?: boolean clientMutationId?: string + signal?: AbortSignal } = {} ): Promise { const mutationId = opts.clientMutationId @@ -16021,21 +17250,23 @@ export class OrcaRuntimeService { const mutationKey = `${worktreeSelector}\0${mutationId}` // Why: a retried create (double-tap, reconnect replay) with the same // idempotency key must return the in-flight operation instead of spawning a - // duplicate terminal. Settled entries are dropped so a later retry — after a - // failure or after the result is consumed — can start a fresh create. + // duplicate terminal. Successes are kept briefly so a retry whose response + // was lost in transit reuses the created terminal; failures are dropped + // immediately so a retry can start a fresh create. const inflight = this.mobileTerminalCreateByMutationId.get(mutationKey) if (inflight) { return inflight } const run = this.runCreateMobileSessionTerminal(worktreeSelector, opts) this.mobileTerminalCreateByMutationId.set(mutationKey, run) - void run - .catch(() => {}) - .finally(() => { - if (this.mobileTerminalCreateByMutationId.get(mutationKey) === run) { - this.mobileTerminalCreateByMutationId.delete(mutationKey) - } - }) + const drop = (): void => { + if (this.mobileTerminalCreateByMutationId.get(mutationKey) === run) { + this.mobileTerminalCreateByMutationId.delete(mutationKey) + } + } + void run.then(() => { + setTimeout(drop, MOBILE_TERMINAL_CREATE_RESULT_TTL_MS).unref?.() + }, drop) return run } @@ -16053,12 +17284,13 @@ export class OrcaRuntimeService { launchAgent?: TuiAgent activate?: boolean clientMutationId?: string + signal?: AbortSignal } = {} ): Promise { this.assertGraphReady() const workspace = await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector) const worktreeId = workspace.id - const cwd = this.resolveGuardedWorkspaceTerminalCwd(workspace, opts.cwd) + const cwd = this.resolveWorkspaceTerminalStartupCwd(workspace, opts.cwd) this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId) let afterDesktopTabId: string | undefined if (opts.afterTabId) { @@ -16092,8 +17324,16 @@ export class OrcaRuntimeService { const reply = await new Promise<{ tabId: string; title: string }>((resolve, reject) => { const timer = setTimeout(() => { ipcMain.removeListener('terminal:tabCreateReply', handler) + opts.signal?.removeEventListener('abort', onAbort) reject(new Error('Terminal creation timed out')) }, 10_000) + // Why: a dead client connection cancels the wait; the renderer tab (and + // its shell) stays alive for the host and mirrors on reconnect (#7718). + const onAbort = (): void => { + clearTimeout(timer) + ipcMain.removeListener('terminal:tabCreateReply', handler) + reject(new Error('client_disconnected')) + } const handler = ( event: Electron.IpcMainEvent, @@ -16104,12 +17344,14 @@ export class OrcaRuntimeService { } clearTimeout(timer) ipcMain.removeListener('terminal:tabCreateReply', handler) + opts.signal?.removeEventListener('abort', onAbort) if (r.error) { reject(new Error(r.error)) } else { resolve({ tabId: r.tabId!, title: r.title ?? '' }) } } + opts.signal?.addEventListener('abort', onAbort, { once: true }) ipcMain.on('terminal:tabCreateReply', handler) win.webContents.send('terminal:requestTabCreate', { requestId, @@ -16130,20 +17372,42 @@ export class OrcaRuntimeService { if (opts.activate !== false) { this.notifier?.focusTerminal(reply.tabId, worktreeId, null) } + // Why: register the wait before the renderer's PTY spawn arrives so that + // spawn (registerPty) can publish the pty-backed surface main-side even if + // graph-sync is stalled (#7587). Removed in the finally below. + const pendingCreateKey = `${worktreeId}::${reply.tabId}` + // Why: a rescue publishes into the active group (opts.targetGroupId is not + // threaded); the renderer's reconciling publication then moves the tab to the + // requested group, so any wrong-group placement is cosmetic and stall-window-only. + this.pendingMobileTerminalCreatesByKey.set(pendingCreateKey, { + activate: opts.activate !== false, + selectIfNoActiveTab: true + }) try { + // Why: the PTY spawn and the tabCreate reply race on independent IPC + // channels; if the spawn already registered, publish immediately so the + // wait resolves without depending on a graph sync. + this.ensurePtyBackedMobileSurfaceForRendererTab(worktreeId, reply.tabId) const surface = await this.waitForMobileTerminalSurface(worktreeId, reply.tabId, { - timeoutMs: MOBILE_TERMINAL_SURFACE_TIMEOUT_MS + timeoutMs: MOBILE_TERMINAL_SURFACE_TIMEOUT_MS, + signal: opts.signal }) if (this.isReadyMobileTerminalSurface(surface)) { return surface } const readySurface = await this.waitForMobileTerminalSurface(worktreeId, reply.tabId, { timeoutMs: MOBILE_TERMINAL_READY_FALLBACK_MS, - requireReady: true + requireReady: true, + signal: opts.signal }).catch(() => null) if (readySurface) { return readySurface } + if (opts.signal?.aborted) { + // Why: nobody is waiting for this create anymore; do not materialize + // or roll back — the renderer's own publication settles the tab. + throw new Error('client_disconnected') + } const pendingSurface = this.findMobileTerminalSurface(worktreeId, reply.tabId) if (!pendingSurface) { throw new Error('Timed out waiting for terminal surface after creation') @@ -16167,12 +17431,34 @@ export class OrcaRuntimeService { } ) } catch (error) { - // Why: the renderer created the tab but its terminal surface never - // published (PTY spawn/handle failure). Roll the half-created tab back via - // the renderer close path so it can't linger as a ghost in mobile - // snapshots, then surface the failure to the caller. + // Why: publication latency (throttled/hidden renderer), not spawn failure, + // can trip the surface timeout. Rescue only when a live PTY actually backs + // the tab — gating on a surface would let a handle-less shell (or a failed + // materialize) resolve as success and skip the ghost-tab rollback (#7587). + if (this.findLiveRegisteredPtyForRendererTab(worktreeId, reply.tabId)) { + const rescued = this.ensurePtyBackedMobileSurfaceForRendererTab(worktreeId, reply.tabId) + if (rescued) { + return rescued + } + } + // Why: don't roll back when (a) the client connection died — the wait + // was cancelled, not the spawn — or (b) a live shell already backs the + // tab (its pane key may simply not be registered yet). Killing a real + // terminal the host user can see is the "tab dies after ~10s" bug (#7718). + if ( + isClientDisconnectedError(error) || + this.hasLiveShellForRendererTab(worktreeId, reply.tabId) + ) { + throw error + } + // Why: the renderer created the tab but no live PTY backs it (true PTY + // spawn/handle failure). Roll the half-created tab back via the renderer + // close path so it can't linger as a ghost in mobile snapshots, then + // surface the failure to the caller. this.notifier?.closeTerminal(reply.tabId) throw error + } finally { + this.pendingMobileTerminalCreatesByKey.delete(pendingCreateKey) } } @@ -16268,7 +17554,7 @@ export class OrcaRuntimeService { } = {} ): Promise { const workspace = await this.resolveTerminalWorkspaceLaunchScope(`id:${worktreeId}`) - const cwd = this.resolveGuardedWorkspaceTerminalCwd(workspace, opts.cwd) + const cwd = this.resolveWorkspaceTerminalStartupCwd(workspace, opts.cwd) // Why: SshPtyProvider treats sessionId as a relay reattach request. Only // synthesize local serve ids; SSH fresh terminals must call pty.spawn. const stableSessionId = @@ -16384,33 +17670,44 @@ export class OrcaRuntimeService { private waitForMobileTerminalSurface( worktreeId: string, parentTabId: string, - options: { timeoutMs?: number; requireReady?: boolean } = {} + options: { timeoutMs?: number; requireReady?: boolean; signal?: AbortSignal } = {} ): Promise { const timeoutMs = options.timeoutMs ?? MOBILE_TERMINAL_SURFACE_TIMEOUT_MS const existing = this.findMobileTerminalSurface(worktreeId, parentTabId, options) if (existing) { return Promise.resolve(existing) } + if (options.signal?.aborted) { + return Promise.reject(new Error('client_disconnected')) + } return new Promise((resolve, reject) => { - const timer = setTimeout(() => { + const cleanup = (): void => { + clearTimeout(timer) + options.signal?.removeEventListener('abort', onAbort) const idx = this.graphSyncCallbacks.indexOf(check) if (idx !== -1) { this.graphSyncCallbacks.splice(idx, 1) } + } + const timer = setTimeout(() => { + cleanup() reject(new Error('Timed out waiting for terminal surface after creation')) }, timeoutMs) + // Why: a dead client connection cancels the wait immediately instead of + // running down the timeout and triggering rollback (#7718). + const onAbort = (): void => { + cleanup() + reject(new Error('client_disconnected')) + } + options.signal?.addEventListener('abort', onAbort, { once: true }) const check = (): void => { const next = this.findMobileTerminalSurface(worktreeId, parentTabId, options) if (!next) { return } - clearTimeout(timer) - const idx = this.graphSyncCallbacks.indexOf(check) - if (idx !== -1) { - this.graphSyncCallbacks.splice(idx, 1) - } + cleanup() resolve(next) } this.graphSyncCallbacks.push(check) @@ -16445,6 +17742,73 @@ export class OrcaRuntimeService { return surface } + // Why: for an in-flight mobile create whose surface hasn't published yet, + // publish it main-side from the live renderer PTY so the create doesn't wait + // on a stalled graph sync and destroy the session (#7587). No-op unless a + // matching create is pending and a live bound PTY exists; never double-inserts. + private ensurePtyBackedMobileSurfaceForRendererTab( + worktreeId: string, + tabId: string + ): RuntimeMobileSessionCreateTerminalResult | null { + const pending = this.pendingMobileTerminalCreatesByKey.get(`${worktreeId}::${tabId}`) + if (!pending) { + return null + } + const existing = this.findMobileTerminalSurface(worktreeId, tabId) + if (existing) { + // Why: the renderer's own publication already landed; stay idempotent. + return existing + } + const pty = this.findLiveRegisteredPtyForRendererTab(worktreeId, tabId) + const leafId = pty ? parsePaneKey(pty.paneKey ?? '')?.leafId : undefined + if (!pty || !leafId) { + return null + } + this.publishPtyBackedMobileSessionTerminal(worktreeId, pty, { + tabId, + leafId, + title: null, + activate: pending.activate, + selectIfNoActiveTab: pending.selectIfNoActiveTab + }) + // Why: waitForMobileTerminalSurface's check closures are drained only inside + // syncWindowGraph; a main-side publish must drain them too or the pending + // wait won't observe the insertion (mirrors syncWindowGraph's drain). + for (const cb of [...this.graphSyncCallbacks]) { + cb() + } + return this.findMobileTerminalSurface(worktreeId, tabId) + } + + private findLiveRegisteredPtyForRendererTab( + worktreeId: string, + tabId: string + ): RuntimePtyWorktreeRecord | null { + for (const pty of this.ptysById.values()) { + if ( + pty.worktreeId === worktreeId && + pty.tabId === tabId && + pty.connected && + parsePaneKey(pty.paneKey ?? '')?.leafId + ) { + return pty + } + } + return null + } + + // Why: rollback guard, looser than findLiveRegisteredPtyForRendererTab — a + // shell whose pane key hasn't registered yet can't be surface-rescued, but + // it is still a real terminal the create timeout must not kill (#7718). + private hasLiveShellForRendererTab(worktreeId: string, tabId: string): boolean { + for (const pty of this.ptysById.values()) { + if (pty.worktreeId === worktreeId && pty.tabId === tabId && pty.connected) { + return true + } + } + return false + } + private isReadyMobileTerminalSurface( surface: RuntimeMobileSessionCreateTerminalResult | null ): boolean { @@ -17137,15 +18501,11 @@ export class OrcaRuntimeService { } } - // Why: every terminal-creation path must apply the same symlink-aware cwd - // guard; keep the canonicalizer wiring in one place. - private resolveGuardedWorkspaceTerminalCwd( - workspace: Pick, + private resolveWorkspaceTerminalStartupCwd( + workspace: Pick, requestedCwd?: string | null ): string | undefined { - return resolveTerminalStartupCwd(workspace.path, requestedCwd, { - canonicalizePath: localTerminalCwdCanonicalizer(workspace.connectionId) - }) + return resolveTerminalStartupCwd(workspace.path, requestedCwd) } private async resolveTerminalWorkspaceLaunchScope( @@ -18245,9 +19605,12 @@ export class OrcaRuntimeService { serveSimStateWatcher.unbindPty(ptyId) this.ptysById.delete(ptyId) this.recentPtyOutputById.delete(ptyId) + this.clearWaitBlockedCheckState(ptyId) this.recentPtyPathCandidatesById.delete(ptyId) this.ptyOutputSequenceById.delete(ptyId) this.agentStatusOscProcessorsByPtyId.delete(ptyId) + this.terminalSpawnCommandsByPtyId.delete(ptyId) + this.disposePtyTitleTracker(ptyId) this.oscTitleScanTailByPtyId.delete(ptyId) this.osc7ScanTailByPtyId.delete(ptyId) this.terminalCwdByPtyId.delete(ptyId) @@ -18365,6 +19728,9 @@ export class OrcaRuntimeService { nextWorktrees.add(worktreeId) } else { this.mobileSessionTabsByWorktree.delete(worktreeId) + // Why: drop any pending coalesced notify so a stale snapshot can't + // land after the removed frame. + this.mobileSessionTabsNotifyCoalescer.cancel(worktreeId) this.notifyMobileSessionTabsRemoved(worktreeId) } } @@ -18539,6 +19905,14 @@ export class OrcaRuntimeService { this.notifyMobileSessionTabSnapshots() return } + // Why: structural changes (tab add/remove/activate) must propagate promptly, + // so cancel any pending coalesced title/status notify — this immediate emit + // already reflects the latest snapshot and supersedes it. + this.mobileSessionTabsNotifyCoalescer.cancel(worktreeId) + this.notifyMobileSessionTabsChangedNow(worktreeId) + } + + private notifyMobileSessionTabsChangedNow(worktreeId: string): void { if (this.mobileSessionTabListeners.size === 0) { return } @@ -18680,6 +20054,15 @@ export class OrcaRuntimeService { ): RuntimeMobileSessionTabsResult { const tabs: RuntimeMobileSessionClientTab[] = [] const liveBrowserTabsByPageId = this.getLiveBrowserTabsByPageId(snapshot.worktree) + // Why: a live PTY backs exactly one terminal surface, so it must map to a + // single emitted tab. After agent sleep + mobile wake, a stale + // headless-hydrated leaf can survive beside the renderer's live leaf and both + // resolve to the freshly-woken agent PTY (same issuePtyHandle handle) — which + // renders two panes with the same React key and crashes the client. Claim + // each live PTY once. Split siblings never collide because distinct leaves own + // distinct PTYs; renderer tabs precede preserved headless tabs, so the live + // one wins. + const claimedLivePtyIds = new Set() for (const tab of snapshot.tabs) { if (tab.type === 'browser') { const liveTab = tab.browserPageId @@ -18716,6 +20099,19 @@ export class OrcaRuntimeService { allowWorktreeOnlyMatch: !snapshot.publicationEpoch.startsWith('headless') }) const livePty = pty?.connected ? pty : null + // Why: enforce the one-live-PTY-per-tab invariant. A later tab resolving to + // a PTY an earlier tab already claimed is a duplicate surface (e.g. a stale + // headless-hydrated leaf re-bound to a woken agent PTY) — drop it so the + // client never sees two tabs sharing a terminal handle. Handles derive purely + // from the PTY id (issuePtyHandle), so the id is a faithful proxy for the + // emitted handle. Pending tabs (no live PTY) are left untouched. + const resolvedLivePtyId = liveLeafPtyId ?? livePty?.ptyId ?? null + if (resolvedLivePtyId !== null) { + if (claimedLivePtyIds.has(resolvedLivePtyId)) { + continue + } + claimedLivePtyIds.add(resolvedLivePtyId) + } const legacyPaneId = /^pane:(\d+)$/.exec(tab.leafId)?.[1] ?? null const paneKey = isTerminalLeafId(tab.leafId) ? makePaneKey(tab.parentTabId, tab.leafId) @@ -18862,45 +20258,117 @@ export class OrcaRuntimeService { tab: RuntimeMobileSessionTerminalTab, terminalHandle: string | null ): { agentStatus: AgentStatusEntry } | Record { - if (!pty?.lastAgentStatus) { + const paneKey = this.getMobileTerminalPaneKey(tab) + const retained = this.getFreshRetainedAgentStatusForMobileTab(paneKey, pty, tab) + if (!pty?.lastAgentStatus && !retained) { return {} } - const ptyTitle = getLatestAgentCandidateTitle( - { title: pty.title, updatedAt: pty.titleUpdatedAt }, - { title: pty.lastOscTitle, updatedAt: pty.lastOscTitleAt } - ) + const leaf = this.leaves.get(this.getLeafKey(tab.parentTabId, tab.leafId)) ?? null + const ptyTitle = pty + ? getLatestAgentCandidateTitle( + { title: pty.title, updatedAt: pty.titleUpdatedAt }, + { title: pty.lastOscTitle, updatedAt: pty.lastOscTitleAt } + ) + : leaf + ? getLatestAgentCandidateTitle( + { title: leaf.paneTitle, updatedAt: leaf.paneTitleUpdatedAt }, + { title: leaf.lastOscTitle, updatedAt: leaf.lastOscTitleAt } + ) + : null const ptyTitleClassification = classifyAgentTitle(ptyTitle) if (ptyTitle !== null && ptyTitleClassification !== 'agent') { - return {} + // Why: a non-agent title means the shell owns the pane again (the agent + // exited or was replaced) — suppressing here is what clears stuck + // spinners (#1437). A live hook signal (question card / active tool) is + // authoritative agent activity even under a task-named title, so it + // survives the suppression, mirroring the renderer-synced branch above. + const hasLiveHookSignal = + retained?.payload.interactivePrompt != null || retained?.payload.toolName != null + if (!hasLiveHookSignal) { + return {} + } + } + const ownerAgent = tab.launchAgent ?? pty?.launchAgent ?? pty?.foregroundAgent ?? null + const terminalTitle = normalizeCompatibleAgentTitleForOwner( + (pty ? getLatestPtyTitle(pty) : null) ?? tab.title, + ownerAgent + ) + // Why: hook (OSC 9999) payloads carry the real state, prompt, and agent + // identity; the title heuristic below is a fallback with none of that. + // Without this, headless-serve clients only ever saw title-derived rows + // and hook-only transitions (e.g. opencode waiting) never surfaced (#7970). + if (retained) { + return { + agentStatus: normalizeCompatibleAgentStatusEntryForOwner( + { + ...retained.payload, + paneKey, + updatedAt: retained.updatedAt, + stateStartedAt: retained.stateStartedAt, + stateHistory: [], + ...(terminalHandle ? { terminalHandle } : {}), + ...((pty?.worktreeId ?? retained.worktreeId) + ? { worktreeId: pty?.worktreeId ?? retained.worktreeId } + : {}), + tabId: tab.parentTabId, + terminalTitle + }, + ownerAgent + ) + } } - const now = pty.lastOutputAt ?? Date.now() - const ownerAgent = tab.launchAgent ?? pty.launchAgent ?? pty.foregroundAgent ?? null + const now = pty!.lastOutputAt ?? Date.now() const agentType = ownerAgent ?? undefined return { agentStatus: { state: - pty.lastAgentStatus === 'working' + pty!.lastAgentStatus === 'working' ? 'working' - : pty.lastAgentStatus === 'permission' + : pty!.lastAgentStatus === 'permission' ? 'blocked' : 'done', prompt: '', updatedAt: now, stateStartedAt: now, - paneKey: this.getMobileTerminalPaneKey(tab), + paneKey, ...(terminalHandle ? { terminalHandle } : {}), ...(agentType ? { agentType } : {}), - worktreeId: pty.worktreeId, + worktreeId: pty!.worktreeId, tabId: tab.parentTabId, - terminalTitle: normalizeCompatibleAgentTitleForOwner( - getLatestPtyTitle(pty) ?? tab.title, - ownerAgent - ), + terminalTitle, stateHistory: [] } } } + /** The retained OSC 9999 hook row for this mobile tab, when fresh enough to + * trust. Looked up by pane identity first, then by PTY ownership because + * legacy `pane:N` leaf ids can drift from the hook-side pane key. */ + private getFreshRetainedAgentStatusForMobileTab( + paneKey: string, + pty: RuntimePtyWorktreeRecord | null, + tab: RuntimeMobileSessionTerminalTab + ): RuntimeAgentRowSnapshot | null { + let retained = this.latestAgentStatusByPaneKey.get(paneKey) ?? null + if (!retained) { + const ptyId = pty?.ptyId ?? tab.ptyId ?? null + if (ptyId) { + for (const snapshot of this.latestAgentStatusByPaneKey.values()) { + if (snapshot.ptyId !== ptyId) { + continue + } + if (!retained || snapshot.updatedAt > retained.updatedAt) { + retained = snapshot + } + } + } + } + if (!retained || Date.now() - retained.updatedAt > AGENT_STATUS_STALE_AFTER_MS) { + return null + } + return retained + } + private findPtyForMobileTerminalTab( worktreeId: string, tab: RuntimeMobileSessionTerminalTab, @@ -20217,7 +21685,9 @@ export class OrcaRuntimeService { : null const workspaceId = team?.workspaceId ?? params.workspaceId try { - const result = await listLinearIssues(filter, limit, workspaceId, team?.id) + const result = await listLinearIssues(filter, limit, workspaceId, { + teamId: team?.id + }) return { issues: result.items.map((issue) => ({ id: issue.id, @@ -20345,9 +21815,9 @@ export class OrcaRuntimeService { filter?: LinearListFilter, limit = 20, workspaceId?: LinearWorkspaceSelection, - teamId?: string + options?: LinearIssueListOptions ): ReturnType { - return listLinearIssues(filter, clampLinearIssueListLimit(limit), workspaceId, teamId) + return listLinearIssues(filter, clampLinearIssueListLimit(limit), workspaceId, options) } linearCreateIssue( @@ -22122,6 +23592,13 @@ export class OrcaRuntimeService { return listJiraTransitions(key, siteId) } + jiraGetProjectStatusOrder( + projectKey: string, + siteId?: string + ): ReturnType { + return getJiraProjectStatusOrder(projectKey, siteId) + } + // ── Browser automation ── private readonly browserCommands = new RuntimeBrowserCommands({ @@ -22625,6 +24102,14 @@ export class OrcaRuntimeService { } } +const WAIT_BLOCKED_CHECK_MIN_INTERVAL_MS = 50 +// Why: chunks that can complete an actionable prompt bypass the throttle so +// blocked stamps stay per-chunk-immediate; the pattern heads mirror +// findTerminalWaitBlockedSignal. Scanned over the new chunk plus a short +// carry only — never the accumulated window. +const WAIT_BLOCKED_KEYWORD_PATTERN = + /press enter|press t to trust|do you trust|trust this|trusted workspace|update available|choose working directory|codex just got an upgrade|hooks need review/ +const WAIT_BLOCKED_KEYWORD_CARRY_CHARS = 31 const MAX_TAIL_LINES = 2000 const MAX_TAIL_CHARS = 256 * 1024 const MAX_TAIL_PARTIAL_CHARS = 4000 @@ -23188,6 +24673,30 @@ function trimTerminalLineRight(line: string): string { return end === line.length ? line : line.slice(0, end) } +// Why a window: the unwindowed implementation below materializes a row object +// per retained tail line and finalize re-allocates + regex-trims every row — +// O(tail) per chunk (~0.9ms at the 2,000-line cap), measured at ~93% of the +// main-process event loop under an agent-TUI flood (findings log 2026-07-03). +// A redraw can only touch rows the cursor can reach, so run the algorithm on +// a suffix window sized by the chunk's maximum upward cursor excursion and +// share the untouched prefix by reference. Equality with the unwindowed +// implementation is fuzz-verified in +// retained-tail-redraw-window.equivalence.test.ts. +const REDRAW_WINDOW_SAFETY_ROWS = 8 + +function maxUpwardCursorReach( + normalizedChunk: string, + previousRedrawCursor: RetainedTailRedrawCursor | null +): number { + let reach = previousRedrawCursor ? previousRedrawCursor.rowFromEnd : 0 + const cursorUpPattern = /\x1b\[(\d*)(?:;[\d;]*)?A/g + let match: RegExpExecArray | null + while ((match = cursorUpPattern.exec(normalizedChunk)) !== null) { + reach += match[1] ? Number.parseInt(match[1], 10) : 1 + } + return reach +} + function appendNormalizedToMultilineTailBuffer( previousLines: string[], boundedPreviousPartialLine: string, @@ -23200,6 +24709,79 @@ function appendNormalizedToMultilineTailBuffer( redrawCursor: RetainedTailRedrawCursor | null truncated: boolean newCompleteLines: number +} { + const windowRows = + maxUpwardCursorReach(normalizedChunk, previousRedrawCursor) + REDRAW_WINDOW_SAFETY_ROWS + if (windowRows >= previousLines.length) { + return appendNormalizedToMultilineTailBufferUnwindowed( + previousLines, + boundedPreviousPartialLine, + normalizedChunk, + previousPartialWasCapped, + previousRedrawCursor + ) + } + const prefixLength = previousLines.length - windowRows + const suffix = previousLines.slice(prefixLength) + const windowed = appendNormalizedToMultilineTailBufferUnwindowed( + suffix, + boundedPreviousPartialLine, + normalizedChunk, + previousPartialWasCapped, + previousRedrawCursor + ) + let lines = previousLines.slice(0, prefixLength) + // Why: the unwindowed finalize trims trailing spaces/tabs on every row; the + // shared prefix must match without paying a regex per untouched row. + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]! + const lastChar = line.charCodeAt(line.length - 1) + if (lastChar === 32 || lastChar === 9) { + lines[index] = line.replace(/[ \t]+$/g, '') + } + } + for (const line of windowed.lines) { + lines.push(line) + } + let truncated = windowed.truncated + if (lines.length > MAX_TAIL_LINES) { + lines = lines.slice(lines.length - MAX_TAIL_LINES) + truncated = true + } + let totalChars = windowed.partialLine.length + for (const line of lines) { + totalChars += line.length + } + let dropCount = 0 + while (dropCount < lines.length && totalChars > MAX_TAIL_CHARS) { + totalChars -= lines[dropCount]!.length + dropCount += 1 + } + if (dropCount > 0) { + lines = lines.slice(dropCount) + truncated = true + } + return { + lines, + partialLine: windowed.partialLine, + redrawCursor: windowed.redrawCursor, + truncated, + newCompleteLines: windowed.newCompleteLines + } +} + +export function appendNormalizedToMultilineTailBufferUnwindowed( + previousLines: string[], + boundedPreviousPartialLine: string, + normalizedChunk: string, + previousPartialWasCapped: boolean, + previousRedrawCursor: RetainedTailRedrawCursor | null +): { + lines: string[] + partialLine: string + redrawCursor: RetainedTailRedrawCursor | null + truncated: boolean + newCompleteLines: number } { const rows: RetainedTerminalRow[] = [ ...previousLines.map((line) => ({ text: line, completed: true })), diff --git a/src/main/runtime/orchestration/coordinator.test.ts b/src/main/runtime/orchestration/coordinator.test.ts index a10c4ea20913..8593fd816227 100644 --- a/src/main/runtime/orchestration/coordinator.test.ts +++ b/src/main/runtime/orchestration/coordinator.test.ts @@ -40,8 +40,8 @@ function createMockRuntime(): CoordinatorRuntime & { setProbeDrift(result: DriftResult): void { mock.probeDriftResult = result }, - async sendTerminal(handle: string, action: { text?: string }) { - mock.sentMessages.push({ handle, text: action.text ?? '' }) + async sendTerminalAgentPrompt(handle: string, prompt: string) { + mock.sentMessages.push({ handle, text: prompt }) return { handle, accepted: true, bytesWritten: 0 } }, async listTerminals() { @@ -275,7 +275,7 @@ describe('Coordinator', () => { db = new OrchestrationDb(':memory:') const runtime = createMockRuntime() runtime.terminals = [{ handle: 'term_a', worktreeId: 'wt1', connected: true, writable: true }] - runtime.sendTerminal = async () => { + runtime.sendTerminalAgentPrompt = async () => { throw new Error('terminal_not_writable') } @@ -690,8 +690,8 @@ describe('Coordinator', () => { const result = await runPromise // Why: silent-skip must NOT burn the circuit-breaker budget. Task must - // stay in `ready`; failDispatch must NOT be called; sendTerminal must - // NOT be called; no dispatch context should exist. + // stay in `ready`; failDispatch must NOT be called; no prompt injection + // should happen; no dispatch context should exist. expect(runtime.sentMessages).toHaveLength(0) expect(db.getTask(task.id)?.status).toBe('ready') expect(db.getDispatchContext(task.id)).toBeUndefined() diff --git a/src/main/runtime/orchestration/coordinator.ts b/src/main/runtime/orchestration/coordinator.ts index 897290c329e8..2313dfdf3203 100644 --- a/src/main/runtime/orchestration/coordinator.ts +++ b/src/main/runtime/orchestration/coordinator.ts @@ -5,7 +5,7 @@ import { buildDispatchPreamble } from './preamble' import { reconcileLifecycleMessage } from './lifecycle-reconciliation' export type CoordinatorRuntime = { - sendTerminal(handle: string, action: { text?: string; enter?: boolean }): Promise + sendTerminalAgentPrompt(handle: string, prompt: string): Promise listTerminals( worktreeSelector?: string, limit?: number @@ -495,10 +495,7 @@ export class Coordinator { } try { - await this.runtime.sendTerminal(targetHandle, { - text: preamble + gateContext, - enter: true - }) + await this.runtime.sendTerminalAgentPrompt(targetHandle, preamble + gateContext) } catch (err) { const updated = this.db.failDispatch( dispatch.id, diff --git a/src/main/runtime/retained-tail-redraw-window.equivalence.test.ts b/src/main/runtime/retained-tail-redraw-window.equivalence.test.ts new file mode 100644 index 000000000000..32685f93b53a --- /dev/null +++ b/src/main/runtime/retained-tail-redraw-window.equivalence.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from 'vitest' +import { + appendNormalizedToTailBuffer, + appendNormalizedToMultilineTailBufferUnwindowed +} from './orca-runtime' + +// Differential guard for the windowed redraw tail path: the public +// appendNormalizedToTailBuffer routes vertical-control chunks through a +// suffix-windowed wrapper (findings log 2026-07-03 — the unwindowed path was +// O(tail) per chunk and dominated main's event loop under agent-TUI floods). +// This fuzz asserts the windowed result is byte-identical to the reference +// implementation across randomized tails and redraw chunks. + +function mulberry32(seed: number): () => number { + let a = seed >>> 0 + return () => { + a = (a + 0x6d2b79f5) | 0 + let t = Math.imul(a ^ (a >>> 15), 1 | a) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +function randomTail(rng: () => number, maxLines: number): string[] { + const count = Math.floor(rng() * maxLines) + return Array.from({ length: count }, (_, i) => { + const base = `line ${i} ${'x'.repeat(Math.floor(rng() * 40))}` + // Trailing whitespace included deliberately: the reference implementation + // trims every row on each call, so the windowed prefix must match. + return rng() < 0.3 ? `${base} ` : base + }) +} + +function randomRedrawChunk(rng: () => number): string { + const parts: string[] = [] + const ops = 1 + Math.floor(rng() * 12) + for (let i = 0; i < ops; i++) { + const roll = rng() + if (roll < 0.2) { + parts.push(`\x1b[${1 + Math.floor(rng() * 12)}A`) + } else if (roll < 0.3) { + parts.push(`\x1b[${Math.floor(rng() * 3)}J`) + } else if (roll < 0.4) { + parts.push(`\x1b[${Math.floor(rng() * 3)}K`) + } else if (roll < 0.5) { + parts.push('\r') + } else if (roll < 0.6) { + parts.push(`\x1b[${1 + Math.floor(rng() * 30)}G`) + } else if (roll < 0.7) { + parts.push('\n') + } else if (roll < 0.75) { + parts.push('') + } else { + parts.push(`text${Math.floor(rng() * 100)} ${'y'.repeat(Math.floor(rng() * 20))}`) + } + } + return parts.join('') +} + +describe('windowed redraw tail equivalence', () => { + it('matches the unwindowed reference across 500 randomized cases', () => { + const rng = mulberry32(42) + for (let round = 0; round < 500; round++) { + const tail = randomTail(rng, round % 5 === 0 ? 2100 : 300) + const partial = rng() < 0.5 ? `partial ${'z'.repeat(Math.floor(rng() * 30))}` : '' + const redrawCursor = + rng() < 0.3 ? { rowFromEnd: Math.floor(rng() * 20), column: Math.floor(rng() * 40) } : null + // Why the guaranteed cursor-up: the public function routes to the + // multiline (windowed) path only for vertical-control chunks; chunks + // without one take the single-line fast path, which is out of scope. + const chunk = `\x1b[${1 + Math.floor(rng() * 4)}A${randomRedrawChunk(rng)}` + + const actual = appendNormalizedToTailBuffer(tail, partial, chunk, redrawCursor) + // Reference path over the full tail. + const expected = appendNormalizedToMultilineTailBufferUnwindowed( + tail, + partial.slice(-4000), + chunk, + partial.length > 4000, + redrawCursor + ) + + expect(actual.lines, `round ${round} lines`).toEqual(expected.lines) + expect(actual.partialLine, `round ${round} partial`).toBe(expected.partialLine) + expect(actual.redrawCursor, `round ${round} cursor`).toEqual(expected.redrawCursor) + expect(actual.truncated, `round ${round} truncated`).toBe(expected.truncated) + expect(actual.newCompleteLines, `round ${round} newLines`).toBe(expected.newCompleteLines) + } + }) +}) diff --git a/src/main/runtime/rpc/dispatcher.ts b/src/main/runtime/rpc/dispatcher.ts index 818ddb92fca8..24ff44597b08 100644 --- a/src/main/runtime/rpc/dispatcher.ts +++ b/src/main/runtime/rpc/dispatcher.ts @@ -102,7 +102,7 @@ export class RpcDispatcher { signal?: AbortSignal clientId?: string clientKind?: 'mobile' | 'runtime' - sendBinary?: (bytes: Uint8Array) => void + sendBinary?: (bytes: Uint8Array) => boolean | void registerBinaryStreamHandler?: ( streamId: number, handler: (frame: TerminalStreamFrame) => void diff --git a/src/main/runtime/rpc/e2ee-channel-text-backpressure.test.ts b/src/main/runtime/rpc/e2ee-channel-text-backpressure.test.ts new file mode 100644 index 000000000000..5d0b2d3da92d --- /dev/null +++ b/src/main/runtime/rpc/e2ee-channel-text-backpressure.test.ts @@ -0,0 +1,98 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { WebSocket } from 'ws' +import { E2EEChannel, type E2EEChannelOptions } from './e2ee-channel' +import { deriveSharedKey, decrypt, encrypt, generateKeyPair } from './e2ee-crypto' + +// Repro for gap (a): the streaming JSON reply path (encryptedReply) had no +// bufferedAmount gate, so a fast producer over a slow link (legacy +// terminal.subscribe, which has NO seq/resync) ballooned ws.bufferedAmount +// without bound. The fix holds replies in order and drains on recovery — never +// dropping a frame (which would recreate the corruption bug on the legacy path). + +function publicKeyToBase64(key: Uint8Array): string { + return Buffer.from(key).toString('base64') +} + +function createMockWs() { + const sent: string[] = [] + return { + OPEN: 1 as const, + readyState: 1, + bufferedAmount: 0, + send: vi.fn((data: string) => { + sent.push(data) + }), + close: vi.fn(), + sent + } +} + +function setup(overrides?: Partial) { + const serverKeys = generateKeyPair() + const clientKeys = generateKeyPair() + const ws = createMockWs() + const onError = vi.fn() + const channel = new E2EEChannel(ws as unknown as WebSocket, { + serverSecretKey: serverKeys.secretKey, + validateToken: (token) => token === 'valid-token', + onReady: vi.fn(), + onError, + ...overrides + }) + const sharedKey = deriveSharedKey(clientKeys.secretKey, serverKeys.publicKey) + channel.handleRawMessage( + JSON.stringify({ type: 'e2ee_hello', publicKeyB64: publicKeyToBase64(clientKeys.publicKey) }) + ) + channel.handleRawMessage( + encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'valid-token' }), sharedKey) + ) + return { channel, ws, sharedKey, onError } +} + +/** Fire a streaming reply through the real channel's encryptedReply closure. */ +function emitReply(ctx: ReturnType, payload: string): void { + ctx.channel.onMessage((_plaintext, encryptedReply) => { + encryptedReply(payload) + }) + ctx.channel.handleRawMessage(encrypt('{"id":"x","method":"status.get"}', ctx.sharedKey)) +} + +describe('E2EE text reply backpressure', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('holds text replies while over the buffer cap and drains them in order', () => { + const ctx = setup() + const baseline = ctx.ws.sent.length // ready + authenticated control frames + + // Simulate a congested socket: bufferedAmount pinned over the 8 MiB cap. + ctx.ws.bufferedAmount = 9 * 1024 * 1024 + + emitReply(ctx, '{"seq":1}') + emitReply(ctx, '{"seq":2}') + emitReply(ctx, '{"seq":3}') + + // Not dropped, not sent yet — parked in order on the queue. + expect(ctx.ws.sent.length).toBe(baseline) + + // Link drains; the queue flushes every reply, in order, none lost. + ctx.ws.bufferedAmount = 0 + vi.runOnlyPendingTimers() + + const replies = ctx.ws.sent.slice(baseline).map((frame) => decrypt(frame, ctx.sharedKey)) + expect(replies).toEqual(['{"seq":1}', '{"seq":2}', '{"seq":3}']) + expect(ctx.onError).not.toHaveBeenCalled() + }) + + it('sends straight through when the socket is not congested', () => { + const ctx = setup() + const baseline = ctx.ws.sent.length + emitReply(ctx, '{"ok":true}') + expect(ctx.ws.sent.length).toBe(baseline + 1) + expect(decrypt(ctx.ws.sent[baseline]!, ctx.sharedKey)).toBe('{"ok":true}') + }) +}) diff --git a/src/main/runtime/rpc/e2ee-channel.ts b/src/main/runtime/rpc/e2ee-channel.ts index 97ce9c5c8132..63cc2c0dfcdf 100644 --- a/src/main/runtime/rpc/e2ee-channel.ts +++ b/src/main/runtime/rpc/e2ee-channel.ts @@ -3,6 +3,10 @@ // handler only sees plaintext JSON, identical to the Unix socket path. import type { WebSocket } from 'ws' import { deriveSharedKey, encrypt, decrypt, encryptBytes, decryptBytes } from './e2ee-crypto' +import { + createWsOutboundBackpressureQueue, + type WsOutboundBackpressureQueue +} from '../../../shared/ws-outbound-backpressure-queue' type ChannelState = 'awaiting_hello' | 'awaiting_auth' | 'ready' @@ -48,6 +52,11 @@ export class E2EEChannel { ) => void) | null = null private binaryMessageHandler: ((plaintext: Uint8Array) => void) | null = null + // Why: the streaming JSON reply path (e.g. legacy terminal.subscribe) has no + // seq/resync, so it must never drop frames under backpressure. Hold text + // replies in order while bufferedAmount is over the cap and drain as it + // clears; only a wedged link (hard cap) closes the socket for a clean resync. + private textReplyQueue: WsOutboundBackpressureQueue | null = null deviceToken: string | null = null @@ -128,7 +137,7 @@ export class E2EEChannel { if (!this.sharedKey || this.ws.readyState !== this.ws.OPEN) { return } - this.ws.send(encrypt(response, this.sharedKey)) + this.ensureTextReplyQueue().enqueue(encrypt(response, this.sharedKey)) } const encryptedBinaryReply = (response: Uint8Array): boolean => { if (!this.sharedKey || this.ws.readyState !== this.ws.OPEN) { @@ -215,6 +224,22 @@ export class E2EEChannel { this.onReady(this) } + private ensureTextReplyQueue(): WsOutboundBackpressureQueue { + if (!this.textReplyQueue) { + this.textReplyQueue = createWsOutboundBackpressureQueue({ + send: (frame) => this.ws.send(frame), + // Encrypted replies are base64 ASCII strings, so length === byte count. + byteLengthOf: (frame) => frame.length, + getBufferedAmount: () => this.ws.bufferedAmount, + isWritable: () => Boolean(this.sharedKey) && this.ws.readyState === this.ws.OPEN, + // 1013 (Try Again Later): the link is wedged; drop the channel so the + // client reconnects and replays a full snapshot instead of unbounded RSS. + onOverflow: () => this.onError(1013, 'Outbound reply buffer overflow') + }) + } + return this.textReplyQueue + } + private sendEncryptedControl(message: unknown): void { if (this.ws.readyState === this.ws.OPEN && this.sharedKey) { this.ws.send(encrypt(JSON.stringify(message), this.sharedKey)) @@ -229,5 +254,7 @@ export class E2EEChannel { this.sharedKey = null this.messageHandler = null this.binaryMessageHandler = null + this.textReplyQueue?.dispose() + this.textReplyQueue = null } } diff --git a/src/main/runtime/rpc/methods/ai-vault.test.ts b/src/main/runtime/rpc/methods/ai-vault.test.ts new file mode 100644 index 000000000000..d676f35e5794 --- /dev/null +++ b/src/main/runtime/rpc/methods/ai-vault.test.ts @@ -0,0 +1,228 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from '../dispatcher' +import type { RpcRequest } from '../core' +import { OrcaRuntimeService } from '../../orca-runtime' +import type { AiVaultListResult, AiVaultSession } from '../../../../shared/ai-vault-types' +import type { AiVaultScanOptions } from '../../../ai-vault/session-scanner-types' + +const { scanAiVaultSessions } = vi.hoisted(() => ({ + scanAiVaultSessions: vi.fn() +})) + +vi.mock('../../../ai-vault/session-scanner', () => ({ + scanAiVaultSessions +})) + +import { AI_VAULT_METHODS, AiVaultListSessionsParams } from './ai-vault' +import { + configureAiVaultSessionSources, + listAiVaultSessions, + resetAiVaultSessionListCacheForTests +} from '../../../ai-vault/cached-session-list' + +function makeRequest(method: string, params?: unknown): RpcRequest { + return { id: 'req-1', authToken: 'tok', method, params } +} + +const SCANNED_AT = '2026-06-29T00:00:00.000Z' + +function makeResult(): AiVaultListResult { + return { sessions: [], issues: [], scannedAt: SCANNED_AT } +} + +function makeSession(): AiVaultSession { + return { + id: 'local:claude:sess-1:/tmp/t.jsonl', + executionHostId: 'local', + agent: 'claude', + sessionId: 'sess-1', + title: 'Test session', + cwd: '/tmp', + branch: null, + model: null, + filePath: '/tmp/t.jsonl', + codexHome: null, + createdAt: null, + updatedAt: null, + modifiedAt: SCANNED_AT, + messageCount: 2, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: 'claude --resume sess-1', + subagent: null + } +} + +function makeDispatcher(): RpcDispatcher { + // Why: the handler only needs getRuntimeId (envelope) + listAiVaultSessions, + // which delegates to the shared cache module the IPC handler also uses. + const runtime = { + getRuntimeId: () => 'test-runtime', + listAiVaultSessions: (args?: Parameters[0]) => + listAiVaultSessions(args) + } as unknown as OrcaRuntimeService + return new RpcDispatcher({ runtime, methods: AI_VAULT_METHODS }) +} + +describe('aiVault.listSessions params schema', () => { + it('accepts a bounded request', () => { + const parsed = AiVaultListSessionsParams.safeParse({ + limit: 500, + force: true, + scopePaths: ['/home/user/repo'] + }) + expect(parsed.success).toBe(true) + }) + + it('rejects a limit above the cap', () => { + const parsed = AiVaultListSessionsParams.safeParse({ limit: 5000 }) + expect(parsed.success).toBe(false) + }) + + it('clamps scopePaths past the cap instead of rejecting', () => { + // Why: uncapped producers (web client, pre-cap desktop parents) may exceed + // the bound; scope paths only widen discovery, so truncation is safe. + const scopePaths = Array.from({ length: 65 }, (_, index) => `/p/${index}`) + const parsed = AiVaultListSessionsParams.safeParse({ scopePaths }) + expect(parsed.success).toBe(true) + expect(parsed.data?.scopePaths).toEqual(scopePaths.slice(0, 64)) + }) + + it('rejects an over-long scopePath', () => { + const parsed = AiVaultListSessionsParams.safeParse({ scopePaths: ['/'.padEnd(5000, 'a')] }) + expect(parsed.success).toBe(false) + }) + + it('rejects non-runtime execution host ids before dispatch', () => { + expect( + AiVaultListSessionsParams.safeParse({ executionHostId: 'not-a-runtime-host' }).success + ).toBe(false) + expect(AiVaultListSessionsParams.safeParse({ executionHostId: 'local' }).success).toBe(false) + expect(AiVaultListSessionsParams.safeParse({ executionHostId: 'ssh:dev-box' }).success).toBe( + false + ) + }) +}) + +describe('aiVault.listSessions handler + shared cache', () => { + beforeEach(() => { + resetAiVaultSessionListCacheForTests() + scanAiVaultSessions.mockReset() + scanAiVaultSessions.mockResolvedValue(makeResult()) + }) + + afterEach(() => { + resetAiVaultSessionListCacheForTests() + }) + + it('returns the AiVaultListResult unchanged', async () => { + const dispatcher = makeDispatcher() + const response = await dispatcher.dispatch(makeRequest('aiVault.listSessions', { limit: 500 })) + expect(response).toMatchObject({ ok: true, result: makeResult() }) + }) + + it('passes only the first 64 scopePaths to the scanner when a request exceeds the cap', async () => { + const dispatcher = makeDispatcher() + const scopePaths = Array.from({ length: 65 }, (_, index) => `/p/${index}`) + const response = await dispatcher.dispatch(makeRequest('aiVault.listSessions', { scopePaths })) + expect(response).toMatchObject({ ok: true }) + expect(scanAiVaultSessions.mock.calls[0]?.[0]).toMatchObject({ + scopePaths: scopePaths.slice(0, 64) + }) + }) + + it('shares one cache between the IPC entry point and the RPC method', async () => { + const dispatcher = makeDispatcher() + // First call via the shared module (what the desktop IPC handler invokes). + await listAiVaultSessions({ limit: 500 }) + // Second call via the RPC method with the same cache key. + await dispatcher.dispatch(makeRequest('aiVault.listSessions', { limit: 500 })) + expect(scanAiVaultSessions).toHaveBeenCalledTimes(1) + }) + + it('keeps a newer different-key scan dedupable after an older scan resolves', async () => { + // Why: the resolving scan's cleanup must not clear tracking a concurrent + // different-key scan replaced, or re-requests start a duplicate rescan. + const deferreds: ((result: AiVaultListResult) => void)[] = [] + scanAiVaultSessions.mockImplementation( + () => new Promise((resolve) => deferreds.push(resolve)) + ) + // The scanner is invoked a microtask after the call (WSL-home await), so + // wait for each deferred to register before driving resolution order. + const scanA = listAiVaultSessions({ limit: 100 }) + await vi.waitFor(() => expect(deferreds).toHaveLength(1)) + const scanB = listAiVaultSessions({ limit: 200 }) + await vi.waitFor(() => expect(deferreds).toHaveLength(2)) + deferreds[0]?.(makeResult()) + await scanA + // Re-request key B while its first scan is still pending: must dedupe. + const scanBAgain = listAiVaultSessions({ limit: 200 }) + // Flush a macrotask so that a wrongly-started duplicate scan would reach the + // mock (it fires a microtask after the WSL-home await): guarded stays 2, a + // reverted guard reads 3, so this assertion — not a Promise.all hang — pins + // the fix. + await new Promise((resolve) => setTimeout(resolve)) + expect(scanAiVaultSessions).toHaveBeenCalledTimes(2) + deferreds[1]?.(makeResult()) + await Promise.all([scanB, scanBAgain]) + }) + + it('restamps the shared cached result as the addressed runtime host', async () => { + scanAiVaultSessions.mockResolvedValue({ + sessions: [makeSession()], + issues: [{ executionHostId: 'local', agent: 'claude', path: '/tmp', message: 'boom' }], + scannedAt: SCANNED_AT + }) + const dispatcher = makeDispatcher() + // A mobile-style caller (no executionHostId) primes the shared cache… + const localResponse = (await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { limit: 500 }) + )) as { ok: boolean; result: AiVaultListResult } + // …then a desktop/web caller addressing this host by runtime id reuses it. + const runtimeResponse = (await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { + limit: 500, + executionHostId: 'runtime:remote-server' + }) + )) as { ok: boolean; result: AiVaultListResult } + + // Why: the host id must never change what is scanned — one host-local scan + // (and one cache entry) serves every caller; only the stamps differ. + expect(scanAiVaultSessions).toHaveBeenCalledTimes(1) + expect(scanAiVaultSessions.mock.calls[0]?.[0]).toMatchObject({ executionHostId: 'local' }) + + expect(localResponse.result.sessions[0]?.executionHostId).toBe('local') + expect(runtimeResponse.result.sessions[0]?.executionHostId).toBe('runtime:remote-server') + expect(runtimeResponse.result.sessions[0]?.id).toBe( + 'runtime:remote-server:claude:sess-1:/tmp/t.jsonl' + ) + expect(runtimeResponse.result.issues[0]?.executionHostId).toBe('runtime:remote-server') + }) + + it('injects codex-home dirs sourced from the runtime (serve-mode reachable)', async () => { + configureAiVaultSessionSources({ + getAdditionalCodexHomePaths: () => ['/runtime/codex/home'] + }) + const dispatcher = makeDispatcher() + await dispatcher.dispatch(makeRequest('aiVault.listSessions', {})) + const options = scanAiVaultSessions.mock.calls[0]?.[0] as AiVaultScanOptions + // Why: the codex-home is sourced from the runtime, not the window-only + // registerCoreHandlers path, so it survives in serve mode. + expect(options.additionalCodexSessionsDirs).toContain('/runtime/codex/home/sessions') + expect(options.wslHomeDirs).toEqual([]) + }) + + it('forwards codex-home through the real OrcaRuntimeService construction path', async () => { + // Why: the dispatcher test above seeds the cache module directly, so it would + // still pass if OrcaRuntimeService stopped forwarding the codex-home source. + // Construct the real runtime to lock that cross-layer wiring in place. + const runtime = new OrcaRuntimeService(null, undefined, { + getAdditionalAiVaultCodexHomePaths: () => ['/ctor/codex/home'] + }) + await runtime.listAiVaultSessions({}) + const options = scanAiVaultSessions.mock.calls[0]?.[0] as AiVaultScanOptions + expect(options.additionalCodexSessionsDirs).toContain('/ctor/codex/home/sessions') + }) +}) diff --git a/src/main/runtime/rpc/methods/ai-vault.ts b/src/main/runtime/rpc/methods/ai-vault.ts new file mode 100644 index 000000000000..50ace9d222a3 --- /dev/null +++ b/src/main/runtime/rpc/methods/ai-vault.ts @@ -0,0 +1,65 @@ +import { z } from 'zod' +import { defineMethod, type RpcMethod } from '../core' +import { OptionalBoolean } from '../schemas' +import { restampAiVaultListResult } from '../../../ai-vault/session-list-results' +import { AI_VAULT_SCOPE_PATHS_MAX_COUNT } from '../../../../shared/ai-vault-types' +import { parseExecutionHostId } from '../../../../shared/execution-host' + +// Why: bound limit + scopePaths so a client cannot force an unbounded scan. +// Each scopePath is a host-local match prefix (validated/capped, never used for +// traversal); the count/length caps mirror the worktree-schemas bounding style. +const AI_VAULT_SCOPE_PATH_MAX_LENGTH = 4096 +const AI_VAULT_LIMIT_MAX = 2000 + +const executionHostIdSchema = z.string().transform((value, ctx): `runtime:${string}` => { + const parsed = parseExecutionHostId(value) + if (parsed?.kind === 'runtime') { + return parsed.id + } + ctx.addIssue({ + code: 'custom', + message: 'Invalid runtime execution host id' + }) + return z.NEVER +}) + +export const AiVaultListSessionsParams = z.object({ + limit: z + .unknown() + .transform((value) => + typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined + ) + .pipe(z.union([z.number().int().max(AI_VAULT_LIMIT_MAX), z.undefined()])) + .optional(), + force: OptionalBoolean, + scopePaths: z + .array(z.string().min(1).max(AI_VAULT_SCOPE_PATH_MAX_LENGTH)) + // Why: clamp instead of reject — scope paths only ever widen discovery, and + // rejecting would hard-break older/uncapped producers (web client, pre-cap + // desktop parents) that send more than the bound. + .transform((paths) => paths.slice(0, AI_VAULT_SCOPE_PATHS_MAX_COUNT)) + .optional(), + // Why: desktop/web callers name the runtime host they are addressing; mobile + // omits it. The scan itself is host-local either way, so the id must never + // change what is scanned — it only restamps the shared cached result. + executionHostId: executionHostIdSchema.optional() +}) + +export const AI_VAULT_METHODS: RpcMethod[] = [ + defineMethod({ + name: 'aiVault.listSessions', + params: AiVaultListSessionsParams, + handler: async (params, { runtime }) => { + const result = await runtime.listAiVaultSessions({ + limit: params.limit, + force: params.force, + scopePaths: params.scopePaths + }) + // Why: web clients consume this response directly (no parent-side retag), + // so sessions must come back stamped as the runtime host they addressed. + return params.executionHostId + ? restampAiVaultListResult(result, params.executionHostId) + : result + } + }) +] diff --git a/src/main/runtime/rpc/methods/client-ui.test.ts b/src/main/runtime/rpc/methods/client-ui.test.ts index 4c692264cc0e..01a3f784e179 100644 --- a/src/main/runtime/rpc/methods/client-ui.test.ts +++ b/src/main/runtime/rpc/methods/client-ui.test.ts @@ -182,10 +182,12 @@ describe('client UI RPC methods', () => { ...getDefaultUIState(), worktreeCardProperties: ['status', 'branch', 'automation', 'inline-agents'], _worktreeCardModeDefaulted: true, - statusBarItems: ['codex', 'kimi', 'minimax', 'ports'], + statusBarItems: ['codex', 'kimi', 'minimax', 'grok', 'antigravity', 'ports'], _portsStatusBarDefaultAdded: true, _kimiStatusBarDefaultAdded: true, _minimaxStatusBarDefaultAdded: true, + _grokStatusBarDefaultAdded: true, + _antigravityStatusBarDefaultAdded: true, taskResumeState: { githubMode: 'items', githubItemsQuery: 'is:open', @@ -221,10 +223,12 @@ describe('client UI RPC methods', () => { const payload = { worktreeCardProperties: ['status', 'branch', 'automation', 'inline-agents'], _worktreeCardModeDefaulted: true, - statusBarItems: ['codex', 'kimi', 'minimax', 'ports'], + statusBarItems: ['codex', 'kimi', 'minimax', 'grok', 'antigravity', 'ports'], _portsStatusBarDefaultAdded: true, _kimiStatusBarDefaultAdded: true, _minimaxStatusBarDefaultAdded: true, + _grokStatusBarDefaultAdded: true, + _antigravityStatusBarDefaultAdded: true, taskResumeState: { githubMode: 'items', githubItemsQuery: 'is:open', diff --git a/src/main/runtime/rpc/methods/client-ui.ts b/src/main/runtime/rpc/methods/client-ui.ts index b5991f669e4c..9b08e6decd3c 100644 --- a/src/main/runtime/rpc/methods/client-ui.ts +++ b/src/main/runtime/rpc/methods/client-ui.ts @@ -44,9 +44,11 @@ const StatusBarItem = z.enum([ 'claude', 'codex', 'gemini', + 'antigravity', 'opencode-go', 'kimi', 'minimax', + 'grok', 'ssh', 'resource-usage', 'ports' @@ -203,6 +205,8 @@ const UiUpdate = z _portsStatusBarDefaultAdded: z.boolean().optional(), _kimiStatusBarDefaultAdded: z.boolean().optional(), _minimaxStatusBarDefaultAdded: z.boolean().optional(), + _antigravityStatusBarDefaultAdded: z.boolean().optional(), + _grokStatusBarDefaultAdded: z.boolean().optional(), statusBarVisible: z.boolean().optional(), dismissedUpdateVersion: NullableString.optional(), lastUpdateCheckAt: z.number().finite().nullable().optional(), diff --git a/src/main/runtime/rpc/methods/index.ts b/src/main/runtime/rpc/methods/index.ts index 8018375a8a06..bc0a73985f93 100644 --- a/src/main/runtime/rpc/methods/index.ts +++ b/src/main/runtime/rpc/methods/index.ts @@ -1,5 +1,6 @@ import type { RpcAnyMethod } from '../core' import { STATUS_METHODS } from './status' +import { AI_VAULT_METHODS } from './ai-vault' import { AUTOMATION_METHODS } from './automations' import { REPO_METHODS } from './repo' import { WORKTREE_METHODS } from './worktree' @@ -39,6 +40,7 @@ import { EMULATOR_METHODS } from './emulator' // auditing the security boundary or wiring new CLI commands. export const ALL_RPC_METHODS: readonly RpcAnyMethod[] = [ ...STATUS_METHODS, + ...AI_VAULT_METHODS, ...AUTOMATION_METHODS, ...REPO_METHODS, ...WORKTREE_METHODS, diff --git a/src/main/runtime/rpc/methods/jira.test.ts b/src/main/runtime/rpc/methods/jira.test.ts index 8df96326c0a7..8bf82eab5932 100644 --- a/src/main/runtime/rpc/methods/jira.test.ts +++ b/src/main/runtime/rpc/methods/jira.test.ts @@ -125,7 +125,10 @@ describe('jira RPC methods', () => { jiraListCreateFields: vi.fn().mockResolvedValue([{ key: 'customfield_10010' }]), jiraListPriorities: vi.fn().mockResolvedValue([{ id: 'priority-1' }]), jiraListAssignableUsers: vi.fn().mockResolvedValue([{ accountId: 'user-1' }]), - jiraListTransitions: vi.fn().mockResolvedValue([{ id: 'transition-1' }]) + jiraListTransitions: vi.fn().mockResolvedValue([{ id: 'transition-1' }]), + jiraGetProjectStatusOrder: vi.fn().mockResolvedValue({ + statusIdsByColumn: [['status-1']] + }) } as unknown as OrcaRuntimeService const dispatcher = new RpcDispatcher({ runtime, methods: JIRA_METHODS }) @@ -151,6 +154,9 @@ describe('jira RPC methods', () => { await dispatcher.dispatch( makeRequest('jira.listTransitions', { key: 'ABC-3', siteId: 'site-1' }) ) + await dispatcher.dispatch( + makeRequest('jira.getProjectStatusOrder', { projectKey: 'ALP', siteId: 'site-1' }) + ) expect(runtime.jiraListProjects).toHaveBeenCalledWith('all') expect(runtime.jiraListIssueTypes).toHaveBeenCalledWith('project-1', 'site-1') @@ -158,5 +164,6 @@ describe('jira RPC methods', () => { expect(runtime.jiraListPriorities).toHaveBeenCalledWith('site-1') expect(runtime.jiraListAssignableUsers).toHaveBeenCalledWith('ABC-3', 'Ada', 'site-1') expect(runtime.jiraListTransitions).toHaveBeenCalledWith('ABC-3', 'site-1') + expect(runtime.jiraGetProjectStatusOrder).toHaveBeenCalledWith('ALP', 'site-1') }) }) diff --git a/src/main/runtime/rpc/methods/jira.ts b/src/main/runtime/rpc/methods/jira.ts index 9a4c614d9ee3..35d1d067ca1e 100644 --- a/src/main/runtime/rpc/methods/jira.ts +++ b/src/main/runtime/rpc/methods/jira.ts @@ -88,6 +88,11 @@ const AssignableUsers = z.object({ siteId: OptionalString }) +const ProjectStatusOrder = z.object({ + projectKey: requiredString('Project key is required'), + siteId: OptionalString +}) + export const JIRA_METHODS: RpcMethod[] = [ defineMethod({ name: 'jira.connect', @@ -204,5 +209,11 @@ export const JIRA_METHODS: RpcMethod[] = [ params: IssueKey, handler: async (params, { runtime }) => runtime.jiraListTransitions(params.key.trim(), params.siteId) + }), + defineMethod({ + name: 'jira.getProjectStatusOrder', + params: ProjectStatusOrder, + handler: async (params, { runtime }) => + runtime.jiraGetProjectStatusOrder(params.projectKey.trim(), params.siteId) }) ] diff --git a/src/main/runtime/rpc/methods/linear-issue-attribute-filter-schema.ts b/src/main/runtime/rpc/methods/linear-issue-attribute-filter-schema.ts new file mode 100644 index 000000000000..8d9dde7ddc81 --- /dev/null +++ b/src/main/runtime/rpc/methods/linear-issue-attribute-filter-schema.ts @@ -0,0 +1,35 @@ +import { z } from 'zod' +import { + LINEAR_ISSUE_ATTRIBUTE_FILTER_ID_MAX_LENGTH, + LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_LABEL_IDS, + LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_PRIORITIES, + LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_STATE_IDS +} from '../../../../shared/linear-issue-attribute-filter' + +// Why: keep ListIssues param validation co-located with shared limits without +// pushing linear.ts past the max-lines ratchet. +const LinearAttributeFilterId = z + .string() + .trim() + .min(1) + .max(LINEAR_ISSUE_ATTRIBUTE_FILTER_ID_MAX_LENGTH) + +export const LinearIssueAttributeFilterSchema = z + .object({ + stateIds: z.array(LinearAttributeFilterId).max(LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_STATE_IDS), + priorities: z + .array(z.number().int().min(0).max(4)) + .max(LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_PRIORITIES), + assignee: z.union([ + z.object({ kind: z.literal('unassigned') }).strict(), + z + .object({ + kind: z.literal('user'), + id: LinearAttributeFilterId + }) + .strict(), + z.null() + ]), + labelIds: z.array(LinearAttributeFilterId).max(LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_LABEL_IDS) + }) + .strict() diff --git a/src/main/runtime/rpc/methods/linear.test.ts b/src/main/runtime/rpc/methods/linear.test.ts index f2c68db7801b..f5726444519c 100644 --- a/src/main/runtime/rpc/methods/linear.test.ts +++ b/src/main/runtime/rpc/methods/linear.test.ts @@ -102,7 +102,9 @@ describe('linear RPC methods', () => { ) expect(runtime.linearSearchIssues).toHaveBeenCalledWith('bug', 30, 'all') - expect(runtime.linearListIssues).toHaveBeenCalledWith('assigned', 20, 'workspace-1') + expect(runtime.linearListIssues).toHaveBeenCalledWith('assigned', 20, 'workspace-1', { + attributeFilter: undefined + }) expect(runtime.linearGetIssue).toHaveBeenCalledWith('issue-3', 'workspace-1') expect(runtime.linearCreateIssue).toHaveBeenCalledWith( 'team-1', diff --git a/src/main/runtime/rpc/methods/linear.ts b/src/main/runtime/rpc/methods/linear.ts index d3581f783107..76b6f0a41287 100644 --- a/src/main/runtime/rpc/methods/linear.ts +++ b/src/main/runtime/rpc/methods/linear.ts @@ -2,6 +2,7 @@ import { z } from 'zod' import { defineMethod, type RpcMethod } from '../core' import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas' import { LINEAR_PROJECT_CREATE_METHOD } from './linear-project-create' +import { LinearIssueAttributeFilterSchema } from './linear-issue-attribute-filter-schema' const VALID_FILTERS = ['assigned', 'created', 'all', 'completed'] as const const VALID_CUSTOM_VIEW_MODELS = ['issue', 'project'] as const @@ -37,8 +38,10 @@ const ListIssues = z .object({ filter: z.enum(VALID_FILTERS).optional(), limit: OptionalFiniteNumber, - workspaceId: OptionalString + workspaceId: OptionalString, + attributeFilter: LinearIssueAttributeFilterSchema.optional() }) + .strict() .optional() const CreateIssue = z.object({ @@ -164,7 +167,9 @@ export const LINEAR_METHODS: RpcMethod[] = [ name: 'linear.listIssues', params: ListIssues, handler: async (params, { runtime }) => - runtime.linearListIssues(params?.filter, params?.limit, params?.workspaceId) + runtime.linearListIssues(params?.filter, params?.limit, params?.workspaceId, { + attributeFilter: params?.attributeFilter + }) }), defineMethod({ name: 'linear.createIssue', diff --git a/src/main/runtime/rpc/methods/orchestration.test.ts b/src/main/runtime/rpc/methods/orchestration.test.ts index 8fd0da2bfa69..e5255595a6a6 100644 --- a/src/main/runtime/rpc/methods/orchestration.test.ts +++ b/src/main/runtime/rpc/methods/orchestration.test.ts @@ -1067,7 +1067,9 @@ describe('orchestration RPC methods', () => { setup() const task = db.createTask({ spec: 'work' }) vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) - vi.spyOn(runtime, 'sendTerminal').mockRejectedValue(new Error('terminal_not_writable')) + vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockRejectedValue( + new Error('terminal_not_writable') + ) await expect( call('orchestration.dispatch', { @@ -1085,7 +1087,7 @@ describe('orchestration RPC methods', () => { setup() const task = db.createTask({ spec: 'work' }) vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) - const send = vi.spyOn(runtime, 'sendTerminal').mockResolvedValue({ + const send = vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ handle: 'term_a', accepted: true, bytesWritten: 1 @@ -1098,7 +1100,35 @@ describe('orchestration RPC methods', () => { devMode: true }) - expect(send.mock.calls[0]?.[1].text).toContain('orca-dev orchestration send') + expect(send).toHaveBeenCalledWith( + 'term_a', + expect.stringContaining('orca-dev orchestration send') + ) + }) + + it('injects preamble through the agent prompt path instead of raw terminal send', async () => { + setup() + const task = db.createTask({ spec: 'line one\nline two' }) + vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) + const agentPrompt = vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({ + handle: 'term_a', + accepted: true, + bytesWritten: 1 + }) + const rawSend = vi.spyOn(runtime, 'sendTerminal') + + await call('orchestration.dispatch', { + task: task.id, + to: 'term_a', + inject: true, + from: 'term_coord' + }) + + expect(agentPrompt).toHaveBeenCalledWith( + 'term_a', + expect.stringContaining('line one\nline two') + ) + expect(rawSend).not.toHaveBeenCalled() }) it('rejects inject to terminal without recognized agent', async () => { diff --git a/src/main/runtime/rpc/methods/orchestration.ts b/src/main/runtime/rpc/methods/orchestration.ts index 705791047cf4..f22ad62d8f43 100644 --- a/src/main/runtime/rpc/methods/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration.ts @@ -492,7 +492,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [ let injected = false if (params.inject) { try { - await runtime.sendTerminal(to, { text: preamble, enter: true }) + await runtime.sendTerminalAgentPrompt(to, preamble) injected = true } catch (err) { db.failDispatch(ctx.id, err instanceof Error ? err.message : String(err)) diff --git a/src/main/runtime/rpc/methods/session-tabs.ts b/src/main/runtime/rpc/methods/session-tabs.ts index f2bf1641bda5..d27d771f3214 100644 --- a/src/main/runtime/rpc/methods/session-tabs.ts +++ b/src/main/runtime/rpc/methods/session-tabs.ts @@ -41,7 +41,7 @@ export const SESSION_TAB_METHODS: RpcAnyMethod[] = [ defineMethod({ name: 'session.tabs.createTerminal', params: CreateTerminalTab, - handler: async (params, { runtime }) => + handler: async (params, { runtime, signal }) => runtime.createMobileSessionTerminal(params.worktree, { afterTabId: params.afterTabId, targetGroupId: params.targetGroupId, @@ -54,7 +54,10 @@ export const SESSION_TAB_METHODS: RpcAnyMethod[] = [ ...(params.launchToken ? { launchToken: params.launchToken } : {}), ...(params.launchAgent ? { launchAgent: params.launchAgent } : {}), activate: params.activate, - clientMutationId: params.clientMutationId + clientMutationId: params.clientMutationId, + // Why: a dead client connection must cancel the surface wait instead + // of running down the timeout and rolling back a live tab (#7718). + signal }) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/ssh.test.ts b/src/main/runtime/rpc/methods/ssh.test.ts index 94791a7fdd36..8efab5083455 100644 --- a/src/main/runtime/rpc/methods/ssh.test.ts +++ b/src/main/runtime/rpc/methods/ssh.test.ts @@ -4,14 +4,23 @@ import type { RpcRequest } from '../core' import type { OrcaRuntimeService } from '../../orca-runtime' import { SSH_METHODS } from './ssh' -const { connectRegisteredSshTargetMock, getRegisteredSshStateMock } = vi.hoisted(() => ({ +const { + connectRegisteredSshTargetMock, + getRegisteredSshStateMock, + listRegisteredSshTargetsMock, + listRegisteredRemovedSshTargetLabelsMock +} = vi.hoisted(() => ({ connectRegisteredSshTargetMock: vi.fn(), - getRegisteredSshStateMock: vi.fn() + getRegisteredSshStateMock: vi.fn(), + listRegisteredSshTargetsMock: vi.fn(), + listRegisteredRemovedSshTargetLabelsMock: vi.fn() })) vi.mock('../../../ipc/ssh', () => ({ connectRegisteredSshTarget: connectRegisteredSshTargetMock, - getRegisteredSshState: getRegisteredSshStateMock + getRegisteredSshState: getRegisteredSshStateMock, + listRegisteredSshTargets: listRegisteredSshTargetsMock, + listRegisteredRemovedSshTargetLabels: listRegisteredRemovedSshTargetLabelsMock })) function makeRequest(method: string, params?: unknown): RpcRequest { @@ -62,4 +71,26 @@ describe('ssh RPC methods', () => { expect(response).toMatchObject({ ok: true, result: { state: null } }) }) + + it('lists the registered SSH targets for paired clients', async () => { + const targets = [{ id: 'ssh-1', label: 'Dev box', host: 'dev', port: 22, username: 'me' }] + listRegisteredSshTargetsMock.mockReturnValueOnce(targets) + const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) + + const response = await dispatcher.dispatch(makeRequest('ssh.listTargets')) + + expect(response).toMatchObject({ ok: true, result: { targets } }) + }) + + it('lists removed-target labels for ghost-host display on paired clients', async () => { + const labels = { 'ssh-old': 'Dev box' } + listRegisteredRemovedSshTargetLabelsMock.mockReturnValueOnce(labels) + const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) + + const response = await dispatcher.dispatch(makeRequest('ssh.listRemovedTargetLabels')) + + expect(response).toMatchObject({ ok: true, result: { labels } }) + }) }) diff --git a/src/main/runtime/rpc/methods/ssh.ts b/src/main/runtime/rpc/methods/ssh.ts index e4d836cedff9..6de8634a8815 100644 --- a/src/main/runtime/rpc/methods/ssh.ts +++ b/src/main/runtime/rpc/methods/ssh.ts @@ -1,5 +1,10 @@ import { z } from 'zod' -import { connectRegisteredSshTarget, getRegisteredSshState } from '../../../ipc/ssh' +import { + connectRegisteredSshTarget, + getRegisteredSshState, + listRegisteredRemovedSshTargetLabels, + listRegisteredSshTargets +} from '../../../ipc/ssh' import { defineMethod, type RpcMethod } from '../core' const SshTarget = z.object({ @@ -16,5 +21,15 @@ export const SSH_METHODS: RpcMethod[] = [ name: 'ssh.connect', params: SshTarget, handler: async (params) => ({ state: await connectRegisteredSshTarget(params.targetId) }) + }), + defineMethod({ + name: 'ssh.listTargets', + params: null, + handler: () => ({ targets: listRegisteredSshTargets() }) + }), + defineMethod({ + name: 'ssh.listRemovedTargetLabels', + params: null, + handler: () => ({ labels: listRegisteredRemovedSshTargetLabels() }) }) ] diff --git a/src/main/runtime/rpc/methods/terminal.ts b/src/main/runtime/rpc/methods/terminal.ts index 48b1bc793b2a..73c77701c974 100644 --- a/src/main/runtime/rpc/methods/terminal.ts +++ b/src/main/runtime/rpc/methods/terminal.ts @@ -36,6 +36,9 @@ const TERMINAL_STREAM_CHUNK_BYTES = 48 * 1024 const TERMINAL_OUTPUT_FLUSH_MS = 5 // Why: output batches become binary stream payloads; byte size is the transport cost. const TERMINAL_OUTPUT_BATCH_MAX_BYTES = 64 * 1024 +// Why: remote clients can apply output pressure without pausing runtime PTY ingestion. +const TERMINAL_MULTIPLEX_ACK_STREAM_HIGH_WATER_BYTES = 512 * 1024 +const TERMINAL_MULTIPLEX_ACK_TOTAL_HIGH_WATER_BYTES = 2 * 1024 * 1024 // Why: pending output is held for later binary frames, so cap the encoded // payload bytes rather than UTF-16 code units. const TERMINAL_MULTIPLEX_PENDING_MAX_BYTES = 256 * 1024 @@ -55,10 +58,12 @@ type SnapshotFrameOptions = { truncatedByByteBudget?: boolean source?: 'headless' | 'renderer' oscLinks?: TerminalOscLinkRange[] + pendingEscapeTailAnsi?: string } type SerializedSnapshot = { data: string + scrollbackAnsi?: string cols: number rows: number seq?: number @@ -67,6 +72,7 @@ type SerializedSnapshot = { oscLinks?: TerminalOscLinkRange[] scrollbackRows: number truncatedByByteBudget: boolean + pendingEscapeTailAnsi?: string } | null type TerminalViewportClient = { @@ -80,7 +86,13 @@ type TerminalMultiplexStream = { ptyId: string client: TerminalViewportClient | undefined isMobile: boolean + ackOutput: boolean + ackInFlightBytes: number buffering: boolean + ackPendingOutput: TerminalOutputFrameChunk[] + ackPendingOutputBytes: number + ackPendingOutputOverflowed: boolean + ackRecoverySnapshotInFlight: boolean pendingOutput: TerminalOutputChunk[] pendingOutputBytes: number pendingOutputOverflowed: boolean @@ -360,6 +372,26 @@ function getOutputAfterSnapshotSeq( return chunk.data.slice(snapshotSeq - chunkStartSeq) } +function appendAckPendingOutput( + stream: TerminalMultiplexStream, + chunk: TerminalOutputFrameChunk +): void { + stream.ackPendingOutput.push(chunk) + stream.ackPendingOutputBytes += chunk.bytes.byteLength + let omittedChunkCount = 0 + while ( + stream.ackPendingOutputBytes > TERMINAL_MULTIPLEX_PENDING_MAX_BYTES && + omittedChunkCount < stream.ackPendingOutput.length + ) { + stream.ackPendingOutputBytes -= stream.ackPendingOutput[omittedChunkCount]!.bytes.byteLength + omittedChunkCount += 1 + } + if (omittedChunkCount > 0) { + stream.ackPendingOutput.splice(0, omittedChunkCount) + stream.ackPendingOutputOverflowed = true + } +} + function trimPendingOutputToBudget( pendingOutput: TerminalOutputChunk[], pendingOutputBytes: number @@ -386,6 +418,43 @@ function measureTerminalStreamByteLength( return measureClipboardTextByteLength(data, options) } +function trimPendingOutputCoveredBySnapshot( + pendingOutput: TerminalOutputChunk[], + snapshotSeq: number | undefined +): { chunks: TerminalOutputChunk[]; bytes: number } { + if (typeof snapshotSeq !== 'number') { + return { + chunks: pendingOutput, + bytes: pendingOutput.reduce((sum, chunk) => sum + chunk.bytes, 0) + } + } + const chunks: TerminalOutputChunk[] = [] + let bytes = 0 + for (const chunk of pendingOutput) { + const chunkSeq = chunk.meta?.seq + const rawLength = chunk.meta?.rawLength ?? chunk.data.length + if (typeof chunkSeq !== 'number' || rawLength !== chunk.data.length) { + chunks.push(chunk) + bytes += chunk.bytes + continue + } + const startSeq = chunkSeq - rawLength + if (snapshotSeq >= chunkSeq) { + continue + } + if (snapshotSeq <= startSeq) { + chunks.push(chunk) + bytes += chunk.bytes + continue + } + const data = chunk.data.slice(snapshotSeq - startSeq) + const slicedBytes = terminalStreamByteLength(data) + chunks.push({ data, bytes: slicedBytes, meta: undefined }) + bytes += slicedBytes + } + return { chunks, bytes } +} + function terminalStreamByteLength(data: string): number { return measureTerminalStreamByteLength(data).byteLength } @@ -434,13 +503,12 @@ async function serializeBudgetedRequestedSnapshot( if (!serialized) { return null } - const overByteBudget = terminalStreamByteLengthExceeds( - serialized.data, - REQUESTED_SNAPSHOT_BYTE_BUDGET - ) + const data = (serialized.scrollbackAnsi ?? '') + serialized.data + const overByteBudget = terminalStreamByteLengthExceeds(data, REQUESTED_SNAPSHOT_BYTE_BUDGET) if (!overByteBudget || rows === 0) { return { ...serialized, + data, scrollbackRows: rows, truncatedByByteBudget: rows < requestedRows || overByteBudget } @@ -466,6 +534,7 @@ function sendSnapshotFrames( cwd: options.cwd, source: options.source, oscLinks: options.oscLinks, + pendingEscapeTailAnsi: options.pendingEscapeTailAnsi, truncated: options.truncated === true, truncatedByByteBudget: options.truncatedByByteBudget === true }) @@ -488,7 +557,14 @@ async function serializeBudgetedMobileSnapshot( ): Promise { if (!isMobile) { const serialized = await runtime.serializeTerminalBuffer(ptyId, { scrollbackRows: 0 }) - return serialized ? { ...serialized, scrollbackRows: 0, truncatedByByteBudget: false } : null + return serialized + ? { + ...serialized, + data: (serialized.scrollbackAnsi ?? '') + serialized.data, + scrollbackRows: 0, + truncatedByByteBudget: false + } + : null } const candidates = [MOBILE_SUBSCRIBE_SCROLLBACK_ROWS, 500, 250, 100, 25, 0] for (const rows of candidates) { @@ -496,13 +572,12 @@ async function serializeBudgetedMobileSnapshot( if (!serialized) { return null } - const overByteBudget = terminalStreamByteLengthExceeds( - serialized.data, - MOBILE_SNAPSHOT_BYTE_BUDGET - ) + const data = (serialized.scrollbackAnsi ?? '') + serialized.data + const overByteBudget = terminalStreamByteLengthExceeds(data, MOBILE_SNAPSHOT_BYTE_BUDGET) if (!overByteBudget || rows === 0) { return { ...serialized, + data, scrollbackRows: rows, truncatedByByteBudget: rows < MOBILE_SUBSCRIBE_SCROLLBACK_ROWS || overByteBudget } @@ -746,7 +821,16 @@ const TerminalMultiplexSubscribeFrame = TerminalHandle.extend({ type: z.enum(['mobile', 'desktop']).default('desktop') }) .optional(), - viewport: TerminalViewport.optional() + viewport: TerminalViewport.optional(), + capabilities: z + .object({ + ackOutput: z.literal(1).optional() + }) + .optional() +}) + +const TerminalMultiplexAckFrame = z.object({ + bytes: z.number().int().nonnegative() }) const TerminalMultiplexSnapshotRequestFrame = z.object({ @@ -901,7 +985,10 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ params: TerminalSend, handler: async (params, { runtime }) => { await assertTerminalSendTextWithinLimit(params.text) - const leaf = runtime.resolveLeafForHandle(params.terminal) + // Why: guarded resolution — a stale handle must fail with + // terminal_handle_stale (clients recover by re-deriving the handle) + // instead of evaluating driver/lock state against the wrong PTY (#7718). + const leaf = runtime.resolveLiveLeafForHandle(params.terminal) const driver = leaf?.ptyId ? runtime.getDriver(leaf.ptyId) : null if (leaf?.ptyId && isTerminalInputLockedForClient(runtime, leaf.ptyId, params.client)) { return { @@ -1077,7 +1164,10 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ name: 'terminal.resizeForClient', params: TerminalResizeForClient, handler: async (params, { runtime }) => { - const leaf = runtime.resolveLeafForHandle(params.terminal) + // Why: guarded resolution — a stale handle (pane's PTY replaced under it) + // must fail with terminal_handle_stale instead of resizing the wrong PTY + // (#7718). Clients recover by re-deriving the handle. + const leaf = runtime.resolveLiveLeafForHandle(params.terminal) if (!leaf?.ptyId) { throw new Error('no_connected_pty') } @@ -1131,7 +1221,10 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ name: 'terminal.setDisplayMode', params: TerminalSetDisplayMode, handler: async (params, { runtime }) => { - const leaf = runtime.resolveLeafForHandle(params.terminal) + // Why: guarded resolution — a stale handle must fail with + // terminal_handle_stale instead of mutating the wrong PTY's display + // mode/viewport (#7718). Clients recover by re-deriving the handle. + const leaf = runtime.resolveLiveLeafForHandle(params.terminal) if (!leaf?.ptyId) { throw new Error('no_connected_pty') } @@ -1153,7 +1246,10 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ name: 'terminal.restoreFit', params: TerminalHandle, handler: async (params, { runtime }) => { - const leaf = runtime.resolveLeafForHandle(params.terminal) + // Why: guarded resolution — a stale handle must fail with + // terminal_handle_stale instead of reclaiming the wrong PTY back to + // desktop dims (#7718). Clients recover by re-deriving the handle. + const leaf = runtime.resolveLiveLeafForHandle(params.terminal) if (!leaf?.ptyId) { throw new Error('no_connected_pty') } @@ -1174,7 +1270,10 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ name: 'terminal.updateViewport', params: TerminalUpdateViewport, handler: async (params, { runtime }) => { - const leaf = runtime.resolveLeafForHandle(params.terminal) + // Why: guarded resolution — a stale handle must fail with + // terminal_handle_stale instead of writing viewport state to the wrong + // PTY (#7718). Clients recover by re-deriving the handle. + const leaf = runtime.resolveLiveLeafForHandle(params.terminal) if (!leaf?.ptyId) { throw new Error('no_connected_pty') } @@ -1206,6 +1305,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ let closed = false let cursor = 0 const streams = new Map() + let ackTotalInFlightBytes = 0 let resolveMultiplex = (): void => {} const multiplexClosed = new Promise((resolve) => { resolveMultiplex = resolve @@ -1215,18 +1315,20 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ opcode: TerminalStreamOpcode, payload: Uint8Array = new Uint8Array(), seq?: number - ): void => { + ): boolean => { if (closed) { - return + return false } - sendBinary( - encodeTerminalStreamFrame({ - opcode, - streamId, - seq: typeof seq === 'number' ? seq : cursor++, - payload - }) + // Why: Output `seq` is a UTF-16 high-water the client uses for frame-drop + // gap detection, so a seq-less Output chunk must carry the sentinel 0 + // (== "no seq") rather than the cursor value that orders control frames; + // a cursor value would poison the client's expected-seq tracker. + const resolvedSeq = + typeof seq === 'number' ? seq : opcode === TerminalStreamOpcode.Output ? 0 : cursor++ + const sent = sendBinary( + encodeTerminalStreamFrame({ opcode, streamId, seq: resolvedSeq, payload }) ) + return sent !== false } const sendStreamError = (streamId: number, message: string): void => { sendFrame(streamId, TerminalStreamOpcode.Error, encodeTerminalStreamText(message)) @@ -1249,6 +1351,136 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ }) ) } + const canSendAckGatedOutput = (stream: TerminalMultiplexStream, bytes: number): boolean => { + if (!stream.ackOutput) { + return true + } + return ( + stream.ackInFlightBytes + bytes <= TERMINAL_MULTIPLEX_ACK_STREAM_HIGH_WATER_BYTES && + ackTotalInFlightBytes + bytes <= TERMINAL_MULTIPLEX_ACK_TOTAL_HIGH_WATER_BYTES + ) + } + const sendAckGatedOutput = ( + stream: TerminalMultiplexStream, + chunk: TerminalOutputFrameChunk + ): void => { + sendFrame(stream.streamId, TerminalStreamOpcode.Output, chunk.bytes, chunk.seq) + if (stream.ackOutput) { + stream.ackInFlightBytes += chunk.bytes.byteLength + ackTotalInFlightBytes += chunk.bytes.byteLength + } + } + const queueOrSendOutput = ( + stream: TerminalMultiplexStream, + chunk: TerminalOutputFrameChunk + ): void => { + if (closed || streams.get(stream.streamId) !== stream) { + return + } + if ( + stream.ackPendingOutputOverflowed || + stream.ackPendingOutput.length > 0 || + !canSendAckGatedOutput(stream, chunk.bytes.byteLength) + ) { + appendAckPendingOutput(stream, chunk) + return + } + sendAckGatedOutput(stream, chunk) + } + const sendAckRecoverySnapshot = async (stream: TerminalMultiplexStream): Promise => { + if ( + closed || + streams.get(stream.streamId) !== stream || + stream.ackRecoverySnapshotInFlight + ) { + return + } + stream.ackRecoverySnapshotInFlight = true + try { + const serialized = await serializeBudgetedRequestedSnapshot(runtime, stream.ptyId, 0) + if (closed || streams.get(stream.streamId) !== stream) { + return + } + const size = runtime.getTerminalSize(stream.ptyId) + const displayMode = runtime.getMobileDisplayMode(stream.ptyId) + // Why: dropped ACK-pending output means live frames are no longer a + // complete replay. Send a fresh model snapshot before resuming output. + // Why: truncated marks an unusable snapshot, and clients discard + // those. The recovery snapshot must be applied to cover dropped + // output, so it is only truncated when serialization failed. + sendSnapshotFrames((opcode, payload) => sendFrame(stream.streamId, opcode, payload), { + kind: 'scrollback', + cols: serialized?.cols ?? size?.cols ?? 80, + rows: serialized?.rows ?? size?.rows ?? 24, + displayMode, + reason: 'ack-pending-overflow', + seq: serialized?.seq, + source: serialized?.source, + truncated: !serialized, + truncatedByByteBudget: serialized?.truncatedByByteBudget, + data: serialized?.data ?? '' + }) + if (serialized && typeof serialized.seq === 'number') { + // Why: retained chunks queued before the snapshot serialized are + // already contained in it; replaying them would duplicate output. + const snapshotSeq = serialized.seq + const retained = stream.ackPendingOutput.filter( + (chunk) => !(typeof chunk.seq === 'number' && chunk.seq <= snapshotSeq) + ) + stream.ackPendingOutput = retained + stream.ackPendingOutputBytes = retained.reduce( + (total, chunk) => total + chunk.bytes.byteLength, + 0 + ) + } + stream.ackPendingOutputOverflowed = false + } catch (error) { + sendStreamError( + stream.streamId, + error instanceof Error ? error.message : 'Remote terminal recovery snapshot failed.' + ) + } finally { + if (streams.get(stream.streamId) === stream) { + stream.ackRecoverySnapshotInFlight = false + flushAckPendingOutput(stream) + } + } + } + const flushAckPendingOutput = (stream: TerminalMultiplexStream): void => { + if (stream.ackPendingOutputOverflowed) { + void sendAckRecoverySnapshot(stream) + return + } + let flushed = 0 + while ( + flushed < stream.ackPendingOutput.length && + canSendAckGatedOutput(stream, stream.ackPendingOutput[flushed]!.bytes.byteLength) + ) { + sendAckGatedOutput(stream, stream.ackPendingOutput[flushed]!) + flushed += 1 + } + if (flushed > 0) { + stream.ackPendingOutput.splice(0, flushed) + stream.ackPendingOutputBytes = stream.ackPendingOutput.reduce( + (total, pending) => total + pending.bytes.byteLength, + 0 + ) + } + } + const flushAllAckPendingOutput = (): void => { + for (const stream of streams.values()) { + flushAckPendingOutput(stream) + } + } + const acknowledgeOutput = (stream: TerminalMultiplexStream, bytes: number): void => { + if (!stream.ackOutput || bytes <= 0) { + return + } + const acknowledged = Math.min(stream.ackInFlightBytes, bytes) + stream.ackInFlightBytes -= acknowledged + ackTotalInFlightBytes = Math.max(0, ackTotalInFlightBytes - acknowledged) + flushAllAckPendingOutput() + } const detachStream = (streamId: number, emitEnd: boolean): void => { const stream = streams.get(streamId) if (!stream) { @@ -1256,12 +1488,19 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ } stream.outputBatcher.flush() stream.outputBatcher.dispose() + ackTotalInFlightBytes = Math.max(0, ackTotalInFlightBytes - stream.ackInFlightBytes) + stream.ackInFlightBytes = 0 + stream.ackPendingOutput = [] + stream.ackPendingOutputBytes = 0 + stream.ackPendingOutputOverflowed = false + stream.ackRecoverySnapshotInFlight = false stream.unsubscribeData() stream.unsubscribeResize() stream.unsubscribeFit() stream.unsubscribeDriver() stream.unregisterBinaryHandler() streams.delete(streamId) + flushAllAckPendingOutput() // Why: release the runtime exit-waiter for this slot (see the field's // note). The .catch below no-ops because the stream is already deleted. stream.exitWaiterAbort.abort() @@ -1294,6 +1533,15 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ detachStream(stream.streamId, false) return } + if (frame.opcode === TerminalStreamOpcode.Ack) { + const parsed = TerminalMultiplexAckFrame.safeParse( + decodeTerminalStreamJson(frame.payload) ?? {} + ) + if (parsed.success) { + acknowledgeOutput(stream, parsed.data.bytes) + } + return + } if (frame.opcode === TerminalStreamOpcode.Input) { const text = decodeTerminalStreamText(frame.payload) if (!text) { @@ -1398,6 +1646,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ cwd: serialized?.cwd, source: serialized?.source, oscLinks: serialized?.oscLinks, + pendingEscapeTailAnsi: serialized?.pendingEscapeTailAnsi, truncated: false, truncatedByByteBudget: serialized?.truncatedByByteBudget, data: serialized?.data ?? '' @@ -1432,8 +1681,19 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ const request = parsed.data detachStream(request.streamId, false) - let leaf = runtime.resolveLeafForHandle(request.terminal) const isMobile = request.client?.type === 'mobile' + let leaf: { ptyId: string | null } | null + try { + // Why: guarded resolution — binding the output stream to whatever + // PTY now occupies a stale handle's pane silently mirrors the wrong + // terminal after a reconnect (#7718). terminal_handle_stale lets the + // client re-derive the handle from the current session snapshot. + leaf = runtime.resolveLiveLeafForHandle(request.terminal) + } catch { + sendStreamError(request.streamId, 'terminal_handle_stale') + emit({ type: 'end', streamId: request.streamId }) + return + } if (!leaf?.ptyId && isMobile) { try { const ptyId = await runtime.waitForLeafPtyId(request.terminal, 10_000, signal) @@ -1450,6 +1710,16 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ emit({ type: 'end', streamId: request.streamId }) return } + if (closed) { + return + } + // Why: a competing subscribe for the same streamId can fully register + // while this one awaited the PTY id above. Overwriting it in + // `streams` would orphan its data/view-subscriber registrations — a + // leaked view subscriber permanently silences the model query + // responder (terminal-query-authority.md). Detach it so every + // registration stays release-balanced. + detachStream(request.streamId, false) const ptyId = leaf.ptyId const stream: TerminalMultiplexStream = { @@ -1458,7 +1728,13 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ ptyId, client: request.client, isMobile, + ackOutput: request.capabilities?.ackOutput === 1, + ackInFlightBytes: 0, buffering: true, + ackPendingOutput: [], + ackPendingOutputBytes: 0, + ackPendingOutputOverflowed: false, + ackRecoverySnapshotInFlight: false, pendingOutput: [], pendingOutputBytes: 0, pendingOutputOverflowed: false, @@ -1474,7 +1750,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ ) } for (const chunk of iterateTerminalOutputFrameChunks(data, meta)) { - sendFrame(request.streamId, TerminalStreamOpcode.Output, chunk.bytes, chunk.seq) + queueOrSendOutput(stream, chunk) } }), unsubscribeData: () => {}, @@ -1490,7 +1766,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ ) try { - stream.unsubscribeData = runtime.subscribeToTerminalData(ptyId, (data, meta) => { + const unsubscribeStreamData = runtime.subscribeToTerminalData(ptyId, (data, meta) => { if (closed || streams.get(request.streamId) !== stream) { return } @@ -1500,6 +1776,15 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ } stream.outputBatcher.push(data, meta) }) + // Why: a multiplexed stream feeds a remote xterm view that answers + // terminal queries with view authority; the main model responder + // yields while it is attached (terminal-query-authority.md). + // Wrapped into unsubscribeData so every detach path releases it. + const releaseViewSubscriber = runtime.registerRemoteTerminalViewSubscriber(ptyId) + stream.unsubscribeData = () => { + releaseViewSubscriber() + unsubscribeStreamData() + } if (isMobile && request.client?.id) { await runtime.handleMobileSubscribe(ptyId, request.client.id, request.viewport) @@ -1602,6 +1887,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ truncatedByByteBudget: serialized?.truncatedByByteBudget, source: serialized?.source, oscLinks: serialized?.oscLinks, + pendingEscapeTailAnsi: serialized?.pendingEscapeTailAnsi, data: serialized?.data ?? (read.tail.length > 0 ? `${read.tail.join('\r\n')}\r\n` : '') }) // Why: baseline for resize re-stream gating; the client already @@ -1685,6 +1971,13 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ } }) } catch (error) { + // Why the ownership check: a newer subscribe may own this streamId + // now (it detached and released this stream on arrival). Detaching + // or erroring the slot here would tear down the successor's live + // registrations instead of this stream's. + if (streams.get(request.streamId) !== stream) { + return + } detachStream(request.streamId, false) sendStreamError(request.streamId, error instanceof Error ? error.message : String(error)) emit({ type: 'end', streamId: request.streamId }) @@ -1786,9 +2079,19 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ const outputBatcher = createTerminalOutputBatcher((chunk) => { emit({ type: 'data', chunk }) }) - const unsubscribeData = runtime.subscribeToTerminalData(ptyId, (data) => { + const unsubscribeStreamData = runtime.subscribeToTerminalData(ptyId, (data) => { outputBatcher.push(data) }) + // Why: this legacy JSON stream can feed a live xterm view too + // (older web/desktop subscribers), so it conservatively registers + // as a remote view subscriber. For read-only watchers the cost is + // a withheld model reply — the pre-Phase-5 status quo — which is + // strictly safer than a double reply under a view consumer. + const releaseViewSubscriber = runtime.registerRemoteTerminalViewSubscriber(ptyId) + const unsubscribeData = (): void => { + releaseViewSubscriber() + unsubscribeStreamData() + } const unsubscribeFit = runtime.subscribeToFitOverrideChanges(ptyId, (event) => { outputBatcher.flush() emit({ @@ -1828,7 +2131,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ // resize re-stream so it only fires on an actual width change. let lastResizeCols: number | undefined let resizeGeneration = 0 - const pendingOutput: TerminalOutputChunk[] = [] + let pendingOutput: TerminalOutputChunk[] = [] let pendingOutputBytes = 0 let pendingOutputOverflowed = false let unsubscribeData = (): void => {} @@ -1942,7 +2245,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ return } - unsubscribeData = runtime.subscribeToTerminalData(ptyId, (data, meta) => { + const unsubscribeStreamData = runtime.subscribeToTerminalData(ptyId, (data, meta) => { if (closed) { return } @@ -1963,6 +2266,14 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ } outputBatcher?.push(data, meta) }) + // Why: binary subscribe streams feed remote xterm views (mobile and + // binary-capable desktop clients) that answer queries with view + // authority; the main model responder yields while attached. + const releaseViewSubscriber = runtime.registerRemoteTerminalViewSubscriber(ptyId) + unsubscribeData = () => { + releaseViewSubscriber() + unsubscribeStreamData() + } let read = await runtime.readTerminal(params.terminal) let serialized = await serializeBudgetedMobileSnapshot(runtime, ptyId, isMobile) @@ -2033,6 +2344,55 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [ // Why: baseline for resize re-stream gating; the client already // rewrapped to these cols via the initial snapshot replay. lastResizeCols = serialized?.cols ?? size?.cols + let recoveryAttempts = 0 + // Why: if the bounded pre-subscribe tail overflowed, only a fresh + // model snapshot can cover the dropped middle without replay gaps. + while (pendingOutputOverflowed && recoveryAttempts < 2) { + pendingOutputOverflowed = false + recoveryAttempts += 1 + const recovery = await serializeBudgetedMobileSnapshot(runtime, ptyId, isMobile) + if (closed) { + return + } + if (!recovery) { + break + } + // Why: without an output seq (renderer-source fallback) covered + // chunks cannot be trimmed exactly, and the renderer view may lag + // the queued chunks under backpressure. Keep the bounded replay + // instead of applying an unverifiable snapshot. + if (typeof recovery.seq !== 'number') { + break + } + // Why: shipped mobile clients drop a second scrollback snapshot for + // an initialized handle but apply a resized snapshot inline by + // re-initializing xterm with fresh scrollback. Omit seq on the wire + // so the client's layout-seq staleness filter is not polluted with + // output-byte sequences. + const recoveryStats = sendSnapshotFrames(sendFrame, { + kind: 'resized', + cols: recovery.cols, + rows: recovery.rows, + displayMode, + reason: 'pending-output-overflow', + source: recovery.source, + truncated: false, + truncatedByByteBudget: recovery.truncatedByByteBudget, + data: recovery.data + }) + console.log('[mobile-terminal-stream] recovery snapshot', { + terminal: params.terminal, + streamId, + reason: 'pending-output-overflow', + bytes: recoveryStats.bytes, + chunks: recoveryStats.chunks, + scrollbackRows: recovery.scrollbackRows, + truncatedByByteBudget: recovery.truncatedByByteBudget === true + }) + const trimmed = trimPendingOutputCoveredBySnapshot(pendingOutput, recovery.seq) + pendingOutput = trimmed.chunks + pendingOutputBytes = trimmed.bytes + } buffering = false const bufferedOutput = pendingOutput.splice(0) if (!initialOutputOverflowed) { diff --git a/src/main/runtime/rpc/methods/worktree.test.ts b/src/main/runtime/rpc/methods/worktree.test.ts index 60836205ef89..ef7ef3910f00 100644 --- a/src/main/runtime/rpc/methods/worktree.test.ts +++ b/src/main/runtime/rpc/methods/worktree.test.ts @@ -38,10 +38,54 @@ describe('worktree RPC methods', () => { expect(response).toMatchObject({ ok: true }) expect(runtime.activateManagedWorktree).toHaveBeenCalledWith('id:wt-1', { - notifyClients: false + notifyClients: false, + clientKind: undefined }) }) + it('forwards the mobile clientKind to the runtime on session-only activation', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + activateManagedWorktree: vi + .fn() + .mockResolvedValue({ repoId: 'repo-1', worktreeId: 'wt-1', activated: true }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) + + // The mobile WebSocket path always uses dispatchStreaming, which threads the + // authenticated device scope as clientKind even for non-streaming methods. + const replies: string[] = [] + await dispatcher.dispatchStreaming( + makeRequest('worktree.activate', { worktree: 'id:wt-1', notifyClients: false }), + (response) => replies.push(response), + { clientKind: 'mobile' } + ) + + expect(runtime.activateManagedWorktree).toHaveBeenCalledWith('id:wt-1', { + notifyClients: false, + clientKind: 'mobile' + }) + }) + + it('routes dirty-file force to the runtime server', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + removeManagedWorktree: vi.fn().mockResolvedValue({}) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('worktree.rm', { + worktree: 'id:wt-1', + force: true, + runHooks: false + }) + ) + + expect(runtime.removeManagedWorktree).toHaveBeenCalledWith('id:wt-1', true, false) + expect(response).toMatchObject({ ok: true, result: { removed: true } }) + }) + it('routes create options to the runtime server', async () => { const runtime = { getRuntimeId: () => 'test-runtime', diff --git a/src/main/runtime/rpc/methods/worktree.ts b/src/main/runtime/rpc/methods/worktree.ts index a95d6ebf00a7..f84a26d1d872 100644 --- a/src/main/runtime/rpc/methods/worktree.ts +++ b/src/main/runtime/rpc/methods/worktree.ts @@ -59,9 +59,12 @@ export const WORKTREE_METHODS: RpcMethod[] = [ defineMethod({ name: 'worktree.activate', params: WorktreeActivate, - handler: async (params, { runtime }) => + handler: async (params, { runtime, clientKind }) => + // Why: clientKind ('mobile'|'runtime') scopes the host-renderer slept-agent + // wake to phones so web/desktop activation behavior is unchanged. runtime.activateManagedWorktree(params.worktree, { - notifyClients: params.notifyClients !== false + notifyClients: params.notifyClients !== false, + clientKind }) }), defineMethod({ diff --git a/src/main/runtime/rpc/streaming.test.ts b/src/main/runtime/rpc/streaming.test.ts index abc9ab203722..9cdc88a021b1 100644 --- a/src/main/runtime/rpc/streaming.test.ts +++ b/src/main/runtime/rpc/streaming.test.ts @@ -9,6 +9,9 @@ import type { RuntimeTerminalWait } from '../../../shared/runtime-types' function stubRuntime(overrides: Partial = {}): OrcaRuntimeService { return { getRuntimeId: () => 'test-runtime', + // Why: subscribe streams register as remote view subscribers for Phase-5 + // query-authority suppression (terminal-query-authority.md). + registerRemoteTerminalViewSubscriber: () => () => {}, ...overrides } as OrcaRuntimeService } diff --git a/src/main/runtime/rpc/terminal-geometry-stale-handle.test.ts b/src/main/runtime/rpc/terminal-geometry-stale-handle.test.ts new file mode 100644 index 000000000000..c34ff54f8480 --- /dev/null +++ b/src/main/runtime/rpc/terminal-geometry-stale-handle.test.ts @@ -0,0 +1,222 @@ +import { describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from './dispatcher' +import type { RpcRequest } from './core' +import type { OrcaRuntimeService } from '../orca-runtime' +import { TERMINAL_METHODS } from './methods/terminal' + +// Why: the terminal geometry family (resize/setDisplayMode/restoreFit/ +// updateViewport) mutates PTY state. A remote client can hold a handle minted +// for a PTY that was later replaced under the pane (restart/re-spawn bumps +// ptyId/generation). The UNGUARDED resolveLeafForHandle returns the pane's +// CURRENT pty, so a stale client would mutate the wrong (new) PTY — visible as +// geometry corruption on the fresh session (#7718). These methods must use the +// guarded resolveLiveLeafForHandle, which throws terminal_handle_stale instead. + +// Models a stale handle exactly as the runtime does: the unguarded resolver +// silently adopts the replacement PTY ('pty-b'); the guarded resolver throws. +const NEW_PTY_UNDER_PANE = 'pty-b' + +function stubStaleHandleRuntime(overrides: Partial = {}): OrcaRuntimeService { + return { + getRuntimeId: () => 'test-runtime', + // Unguarded path: returns the pane's current (replaced) PTY — the misroute. + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: NEW_PTY_UNDER_PANE }), + // Guarded path: surfaces the staleness. + resolveLiveLeafForHandle: vi.fn(() => { + throw new Error('terminal_handle_stale') + }), + ...overrides + } as unknown as OrcaRuntimeService +} + +function makeRequest(method: string, params?: unknown): RpcRequest { + return { id: 'req-1', authToken: 'tok', method, params } +} + +async function expectStale(method: string, params: unknown, mutators: string[]): Promise { + const spies: Record> = {} + for (const name of mutators) { + spies[name] = vi.fn() + } + const runtime = stubStaleHandleRuntime(spies as Partial) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const response = await dispatcher.dispatch(makeRequest(method, params)) + + expect(response.ok).toBe(false) + if (response.ok) { + throw new Error(`expected ${method} to reject a stale handle`) + } + expect(response.error.message).toContain('terminal_handle_stale') + // The wrong (replacement) PTY must never be mutated. + for (const name of mutators) { + expect(spies[name]).not.toHaveBeenCalled() + } +} + +describe('terminal geometry family rejects stale handles instead of mutating the wrong PTY', () => { + it('terminal.resizeForClient fails with terminal_handle_stale', async () => { + await expectStale( + 'terminal.resizeForClient', + { terminal: 'stale-terminal', mode: 'restore', clientId: 'client-1' }, + ['resizeForClient'] + ) + }) + + it('terminal.setDisplayMode fails with terminal_handle_stale', async () => { + await expectStale( + 'terminal.setDisplayMode', + { + terminal: 'stale-terminal', + mode: 'auto', + client: { id: 'client-1', type: 'mobile' }, + viewport: { cols: 80, rows: 24 } + }, + [ + 'setMobileDisplayMode', + 'applyMobileDisplayMode', + 'updateMobileSubscriberViewport', + 'markMobileActor' + ] + ) + }) + + it('terminal.restoreFit fails with terminal_handle_stale', async () => { + await expectStale('terminal.restoreFit', { terminal: 'stale-terminal' }, [ + 'reclaimTerminalForDesktop' + ]) + }) + + it('terminal.updateViewport fails with terminal_handle_stale', async () => { + await expectStale( + 'terminal.updateViewport', + { + terminal: 'stale-terminal', + client: { id: 'client-1', type: 'mobile' }, + viewport: { cols: 80, rows: 24 } + }, + ['updateMobileViewport', 'updateDesktopViewport'] + ) + }) +}) + +describe('terminal geometry family still mutates the live PTY for a fresh handle', () => { + it('terminal.restoreFit reclaims the resolved PTY when the handle is live', async () => { + const reclaimTerminalForDesktop = vi.fn().mockResolvedValue(true) + const runtime = { + getRuntimeId: () => 'test-runtime', + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-a' }), + reclaimTerminalForDesktop + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('terminal.restoreFit', { terminal: 'live-terminal' }) + ) + + expect(response.ok).toBe(true) + if (!response.ok) { + throw new Error(response.error.message) + } + expect(response.result).toEqual({ restored: true }) + expect(reclaimTerminalForDesktop).toHaveBeenCalledWith('pty-a') + }) + + it('terminal.resizeForClient resizes the resolved PTY when the handle is live', async () => { + const resizeForClient = vi.fn().mockResolvedValue({ cols: 80, rows: 24 }) + const runtime = { + getRuntimeId: () => 'test-runtime', + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-a' }), + resizeForClient + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('terminal.resizeForClient', { + terminal: 'live-terminal', + mode: 'restore', + clientId: 'client-1' + }) + ) + + expect(response.ok).toBe(true) + if (!response.ok) { + throw new Error(response.error.message) + } + expect(resizeForClient).toHaveBeenCalledWith( + 'pty-a', + 'restore', + 'client-1', + undefined, + undefined + ) + }) + + it('terminal.setDisplayMode mutates the resolved PTY when the handle is live', async () => { + const setMobileDisplayMode = vi.fn() + const applyMobileDisplayMode = vi.fn().mockResolvedValue(undefined) + const updateMobileSubscriberViewport = vi.fn() + const markMobileActor = vi.fn() + const runtime = { + getRuntimeId: () => 'test-runtime', + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-a' }), + setMobileDisplayMode, + applyMobileDisplayMode, + updateMobileSubscriberViewport, + markMobileActor, + getLayout: vi.fn().mockReturnValue({ seq: 42 }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('terminal.setDisplayMode', { + terminal: 'live-terminal', + mode: 'auto', + client: { id: 'client-1', type: 'mobile' }, + viewport: { cols: 80, rows: 24 } + }) + ) + + expect(response.ok).toBe(true) + if (!response.ok) { + throw new Error(response.error.message) + } + expect(updateMobileSubscriberViewport).toHaveBeenCalledWith('pty-a', 'client-1', { + cols: 80, + rows: 24 + }) + expect(markMobileActor).toHaveBeenCalledWith('pty-a', 'client-1') + expect(setMobileDisplayMode).toHaveBeenCalledWith('pty-a', 'auto') + expect(applyMobileDisplayMode).toHaveBeenCalledWith('pty-a') + expect(response.result).toEqual({ mode: 'auto', seq: 42 }) + }) + + it('terminal.updateViewport updates the resolved PTY when the handle is live', async () => { + const updateMobileViewport = vi.fn().mockResolvedValue({ updated: true, applied: true }) + const runtime = { + getRuntimeId: () => 'test-runtime', + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-a' }), + updateMobileViewport, + getLayout: vi.fn().mockReturnValue({ seq: 7 }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('terminal.updateViewport', { + terminal: 'live-terminal', + client: { id: 'client-1', type: 'mobile' }, + viewport: { cols: 80, rows: 24 } + }) + ) + + expect(response.ok).toBe(true) + if (!response.ok) { + throw new Error(response.error.message) + } + expect(updateMobileViewport).toHaveBeenCalledWith('pty-a', 'client-1', { + cols: 80, + rows: 24 + }) + expect(response.result).toEqual({ updated: true, applied: true, seq: 7 }) + }) +}) diff --git a/src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts b/src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts new file mode 100644 index 000000000000..88125c840b3e --- /dev/null +++ b/src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts @@ -0,0 +1,131 @@ +import { describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from './dispatcher' +import type { RpcRequest } from './core' +import type { OrcaRuntimeService } from '../orca-runtime' +import { TERMINAL_METHODS } from './methods/terminal' +import type { RuntimeTerminalWait } from '../../../shared/runtime-types' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + decodeTerminalStreamJson, + encodeTerminalStreamFrame, + encodeTerminalStreamJson +} from '../../../shared/terminal-stream-protocol' + +// Transport-level regression for #7329: the daemon's mid-escape tail +// (pendingEscapeTailAnsi) must survive the terminal.multiplex wire so the +// renderer can replay it after the reset. Without threading it through the +// SnapshotStart JSON frame, the tail is lost and the next live chunk renders +// literally ("colors/garbage around what I type"). + +function stubRuntime(overrides: Partial = {}): OrcaRuntimeService { + return { + getRuntimeId: () => 'test-runtime', + ...overrides + } as OrcaRuntimeService +} + +function makeRequest(method: string, params?: unknown): RpcRequest { + return { id: 'req-1', authToken: 'tok', method, params } +} + +describe('terminal.multiplex pending-escape-tail threading (#7329)', () => { + it('carries the daemon pendingEscapeTailAnsi through the SnapshotStart frame', async () => { + vi.useFakeTimers() + try { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const runtime = stubRuntime({ + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi.fn().mockResolvedValue({ + data: 'user@host:~$ ', + cols: 80, + rows: 24, + // The dangling partial the emulator could not serialize. + pendingEscapeTailAnsi: '\x1b[3' + }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + registerRemoteTerminalViewSubscriber: vi.fn(() => () => {}), + subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), + getTerminalFitOverride: vi.fn().mockReturnValue(null), + getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + cleanupSubscription: vi.fn((id: string) => { + const cleanup = cleanups.get(id) + cleanups.delete(id) + cleanup?.() + }), + waitForTerminal: vi.fn(() => new Promise(() => {})), + updateDesktopViewport: vi.fn().mockResolvedValue(true) + }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-1', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.runOnlyPendingTimersAsync() + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 5, + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' } + }) + }) + )! + ) + + // Drive the subscribe promise chain (readTerminal/serialize awaits + the + // output-batcher flush timer) to completion. + for (let i = 0; i < 5; i += 1) { + await vi.runOnlyPendingTimersAsync() + } + + const snapshotStart = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .find((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotStart)! + expect(decodeTerminalStreamJson(snapshotStart.payload)).toMatchObject({ + pendingEscapeTailAnsi: '\x1b[3' + }) + + runtime.cleanupSubscription('terminal-multiplex:conn-1') + await dispatchPromise + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/main/runtime/rpc/terminal-multiplex.test.ts b/src/main/runtime/rpc/terminal-multiplex.test.ts index 5ceee818dbbb..62dcfddc5abd 100644 --- a/src/main/runtime/rpc/terminal-multiplex.test.ts +++ b/src/main/runtime/rpc/terminal-multiplex.test.ts @@ -18,6 +18,14 @@ import { function stubRuntime(overrides: Partial = {}): OrcaRuntimeService { return { getRuntimeId: () => 'test-runtime', + // Why: every multiplex stream registers as a remote view subscriber for + // Phase-5 query-authority suppression (terminal-query-authority.md). + registerRemoteTerminalViewSubscriber: () => () => {}, + // Why: the multiplex subscribe path resolves handles via + // resolveLiveLeafForHandle (#7718). Default to a live pty so tests that + // only stub the legacy resolveLeafForHandle still bind; tests that need a + // null/stale leaf override this explicitly. + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), ...overrides } as OrcaRuntimeService } @@ -41,7 +49,7 @@ describe('terminal multiplex RPC', () => { current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void } = {} const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snapshot', @@ -77,14 +85,19 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), (msg) => messages.push(msg), { connectionId: 'conn-1', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: (streamId, handler) => { handlers.set(streamId, handler) return () => handlers.delete(streamId) @@ -199,7 +212,10 @@ describe('terminal multiplex RPC', () => { opcode: TerminalStreamOpcode.SnapshotRequest, streamId: 5, seq: 4, - payload: encodeTerminalStreamJson({ requestId: 7, scrollbackRows: 5000 }) + payload: encodeTerminalStreamJson({ + requestId: 7, + scrollbackRows: 5000 + }) }) )! ) @@ -258,7 +274,7 @@ describe('terminal multiplex RPC', () => { | undefined const restreamResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi .fn() @@ -291,14 +307,19 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateMobileViewport: vi.fn().mockResolvedValue({ updated: true, applied: true }) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), (msg) => messages.push(msg), { connectionId: 'conn-stale-multiplex-resize', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: (streamId, handler) => { handlers.set(streamId, handler) return () => handlers.delete(streamId) @@ -327,8 +348,20 @@ describe('terminal multiplex RPC', () => { await vi.waitFor(() => expect(resizeListener).toBeDefined()) binaryFrames.splice(0) - resizeListener?.({ cols: 90, rows: 24, displayMode: 'auto', reason: 'apply-layout', seq: 2 }) - resizeListener?.({ cols: 100, rows: 24, displayMode: 'auto', reason: 'apply-layout', seq: 3 }) + resizeListener?.({ + cols: 90, + rows: 24, + displayMode: 'auto', + reason: 'apply-layout', + seq: 2 + }) + resizeListener?.({ + cols: 100, + rows: 24, + displayMode: 'auto', + reason: 'apply-layout', + seq: 3 + }) await vi.waitFor(() => expect(restreamResolves).toHaveLength(2)) restreamResolves[1]?.({ data: 'newer', cols: 100, rows: 24 }) @@ -371,7 +404,7 @@ describe('terminal multiplex RPC', () => { current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void } = {} const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snapshot', @@ -402,14 +435,19 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), (msg) => messages.push(msg), { connectionId: 'conn-multibyte-output-batch', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: (streamId, handler) => { handlers.set(streamId, handler) return () => handlers.delete(streamId) @@ -447,25 +485,727 @@ describe('terminal multiplex RPC', () => { rawLength: multibyteOutput.length }) - const outputFrames = binaryFrames + const outputFrames = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + expect(outputFrames.length).toBeGreaterThan(1) + expect(outputFrames.every((frame) => (frame?.payload.byteLength ?? 0) <= 48 * 1024)).toBe( + true + ) + expect(outputFrames.map((frame) => frame?.seq)).toEqual([16_384, 22_000]) + expect( + outputFrames.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')).join('') + ).toBe(multibyteOutput) + expect(encodeSpy).not.toHaveBeenCalledWith(multibyteOutput) + encodeSpy.mockRestore() + + cleanups.get('terminal-multiplex:conn-multibyte-output-batch')?.() + await dispatchPromise + } finally { + vi.useRealTimers() + } + }) + + it('holds ACK-capable multiplex output over budget until the client acknowledges bytes', async () => { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const dataListenerRef: { + current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void + } = {} + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi.fn().mockResolvedValue({ + data: 'snapshot', + cols: 120, + rows: 40 + }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn( + ( + _: string, + listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void + ) => { + dataListenerRef.current = listener + return vi.fn() + } + ), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), + getTerminalFitOverride: vi.fn().mockReturnValue(null), + getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + cleanupSubscription: vi.fn((id: string) => { + const cleanup = cleanups.get(id) + cleanups.delete(id) + cleanup?.() + }), + waitForTerminal: vi.fn(() => new Promise(() => {})), + sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), + updateDesktopViewport: vi.fn().mockResolvedValue(true) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-ack-gated', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 16, + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' }, + viewport: { cols: 120, rows: 40 }, + capabilities: { ackOutput: 1 } + }) + }) + )! + ) + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) + ) + binaryFrames.splice(0) + + const output = 'x'.repeat(700 * 1024) + dataListenerRef.current?.(output, { seq: output.length, rawLength: output.length }) + + const initialOutputFrames = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + const initialBytes = initialOutputFrames.reduce( + (total, frame) => total + (frame?.payload.byteLength ?? 0), + 0 + ) + expect(initialBytes).toBeLessThanOrEqual(512 * 1024) + expect(initialOutputFrames.length).toBeGreaterThan(0) + const initialOutput = initialOutputFrames + .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + .join('') + expect(initialOutput.length).toBeLessThan(output.length) + + handlers.get(16)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Input, + streamId: 16, + seq: 2, + payload: encodeTerminalStreamText('still interactive\r') + }) + )! + ) + await vi.waitFor(() => + expect(runtime.sendTerminal).toHaveBeenCalledWith('terminal-1', { + text: 'still interactive\r', + enter: false, + interrupt: false + }) + ) + + handlers.get(16)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Ack, + streamId: 16, + seq: 3, + payload: encodeTerminalStreamJson({ bytes: initialBytes }) + }) + )! + ) + + const flushedOutputFrames = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + expect(flushedOutputFrames.length).toBeGreaterThan(initialOutputFrames.length) + + runtime.cleanupSubscription('terminal-multiplex:conn-ack-gated') + await dispatchPromise + }) + + it('releases shared ACK budget to other stalled multiplex streams', async () => { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const dataListeners = new Map< + string, + (data: string, meta?: { seq?: number; rawLength?: number }) => void + >() + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn((terminal: string) => ({ + ptyId: terminal.replace('terminal-', 'pty-') + })), + resolveLiveLeafForHandle: vi.fn((terminal: string) => ({ + ptyId: terminal.replace('terminal-', 'pty-') + })), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi.fn(async (ptyId: string) => ({ + data: `snapshot-${ptyId}`, + cols: 120, + rows: 40 + })), + getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn( + ( + ptyId: string, + listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void + ) => { + dataListeners.set(ptyId, listener) + return vi.fn() + } + ), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), + getTerminalFitOverride: vi.fn().mockReturnValue(null), + getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + cleanupSubscription: vi.fn((id: string) => { + const cleanup = cleanups.get(id) + cleanups.delete(id) + cleanup?.() + }), + waitForTerminal: vi.fn(() => new Promise(() => {})), + sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), + updateDesktopViewport: vi.fn().mockResolvedValue(true) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-ack-shared-budget', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + + const streamIds = [21, 22, 23, 24, 25, 26] + for (const streamId of streamIds) { + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: streamId, + payload: encodeTerminalStreamJson({ + streamId, + terminal: `terminal-${streamId - 20}`, + client: { id: `desktop-${streamId}`, type: 'desktop' }, + viewport: { cols: 120, rows: 40 }, + capabilities: { ackOutput: 1 } + }) + }) + )! + ) + } + + await vi.waitFor(() => + expect( + messages + .map((msg) => JSON.parse(msg).result) + .filter((result) => result?.type === 'subscribed') + ).toHaveLength(streamIds.length) + ) + await vi.waitFor(() => expect(dataListeners.size).toBe(streamIds.length)) + binaryFrames.splice(0) + + const fillerOutput = 'f'.repeat(480 * 1024) + for (let index = 1; index <= 4; index += 1) { + dataListeners.get(`pty-${index}`)?.(fillerOutput, { + seq: fillerOutput.length, + rawLength: fillerOutput.length + }) + } + const stalledOutput = 's'.repeat(700 * 1024) + dataListeners.get('pty-5')?.(stalledOutput, { + seq: stalledOutput.length, + rawLength: stalledOutput.length + }) + dataListeners.get('pty-6')?.(stalledOutput, { + seq: stalledOutput.length, + rawLength: stalledOutput.length + }) + + const initialOutputFrames = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + const initialBytesByStream = new Map() + for (const frame of initialOutputFrames) { + if (!frame) { + continue + } + initialBytesByStream.set( + frame.streamId, + (initialBytesByStream.get(frame.streamId) ?? 0) + frame.payload.byteLength + ) + } + const initialBytes = initialOutputFrames.reduce( + (total, frame) => total + (frame?.payload.byteLength ?? 0), + 0 + ) + expect(initialBytes).toBeLessThanOrEqual(2 * 1024 * 1024) + expect(initialBytesByStream.get(21)).toBe(480 * 1024) + expect(initialBytesByStream.get(22)).toBe(480 * 1024) + expect(initialBytesByStream.get(23)).toBe(480 * 1024) + expect(initialBytesByStream.get(24)).toBe(480 * 1024) + expect(initialBytesByStream.get(25)).toBeGreaterThan(0) + expect(initialBytesByStream.get(26) ?? 0).toBe(0) + + handlers.get(26)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Input, + streamId: 26, + seq: 200, + payload: encodeTerminalStreamText('remote-still-interactive\r') + }) + )! + ) + await vi.waitFor(() => + expect(runtime.sendTerminal).toHaveBeenCalledWith('terminal-6', { + text: 'remote-still-interactive\r', + enter: false, + interrupt: false + }) + ) + + const frameCountBeforeAck = binaryFrames.length + handlers.get(21)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Ack, + streamId: 21, + seq: 201, + payload: encodeTerminalStreamJson({ bytes: initialBytesByStream.get(21) ?? 0 }) + }) + )! + ) + + await vi.waitFor(() => + expect( + binaryFrames + .slice(frameCountBeforeAck) + .map((frame) => decodeTerminalStreamFrame(frame)) + .some((frame) => { + if (frame?.streamId !== 25 || frame.opcode !== TerminalStreamOpcode.SnapshotStart) { + return false + } + const payload = decodeTerminalStreamJson<{ reason?: string }>(frame.payload) + return payload?.reason === 'ack-pending-overflow' + }) + ).toBe(true) + ) + const framesAfterAck = binaryFrames + .slice(frameCountBeforeAck) + .map((frame) => decodeTerminalStreamFrame(frame)) + const snapshotStartIndex = framesAfterAck.findIndex((frame) => { + if (frame?.streamId !== 25 || frame.opcode !== TerminalStreamOpcode.SnapshotStart) { + return false + } + const payload = decodeTerminalStreamJson<{ reason?: string }>(frame.payload) + return payload?.reason === 'ack-pending-overflow' + }) + const outputFramesAfterAck = framesAfterAck.filter( + (frame) => frame?.opcode === TerminalStreamOpcode.Output + ) + const bytesAfterAckByStream = new Map() + for (const frame of outputFramesAfterAck) { + if (!frame) { + continue + } + bytesAfterAckByStream.set( + frame.streamId, + (bytesAfterAckByStream.get(frame.streamId) ?? 0) + frame.payload.byteLength + ) + } + expect(snapshotStartIndex).toBeGreaterThanOrEqual(0) + expect( + framesAfterAck + .filter((frame) => frame?.streamId === 25 && frame.opcode === TerminalStreamOpcode.Output) + .every((frame) => framesAfterAck.indexOf(frame) > snapshotStartIndex) + ).toBe(true) + expect(bytesAfterAckByStream.get(25) ?? 0).toBeGreaterThan(0) + expect(bytesAfterAckByStream.get(21) ?? 0).toBe(0) + expect( + outputFramesAfterAck.reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) + ).toBeLessThanOrEqual(initialBytesByStream.get(21) ?? 0) + + runtime.cleanupSubscription('terminal-multiplex:conn-ack-shared-budget') + await dispatchPromise + }) + + it('caps stalled ACK output and snapshots before resuming retained tail frames', async () => { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const dataListenerRef: { + current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void + } = {} + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi + .fn() + .mockResolvedValueOnce({ data: 'initial snapshot', cols: 120, rows: 40 }) + .mockResolvedValue({ data: 'recovered snapshot', cols: 120, rows: 40, seq: 99 }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn( + ( + _: string, + listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void + ) => { + dataListenerRef.current = listener + return vi.fn() + } + ), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), + getTerminalFitOverride: vi.fn().mockReturnValue(null), + getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + cleanupSubscription: vi.fn((id: string) => { + const cleanup = cleanups.get(id) + cleanups.delete(id) + cleanup?.() + }), + waitForTerminal: vi.fn(() => new Promise(() => {})), + sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), + updateDesktopViewport: vi.fn().mockResolvedValue(true) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-ack-overflow', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 17, + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' }, + viewport: { cols: 120, rows: 40 }, + capabilities: { ackOutput: 1 } + }) + }) + )! + ) + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) + ) + binaryFrames.splice(0) + + const output = 'x'.repeat(3 * 1024 * 1024) + dataListenerRef.current?.(output, { seq: output.length, rawLength: output.length }) + + const initialOutputFrames = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + const initialBytes = initialOutputFrames.reduce( + (total, frame) => total + (frame?.payload.byteLength ?? 0), + 0 + ) + expect(initialBytes).toBeLessThanOrEqual(512 * 1024) + + handlers.get(17)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Input, + streamId: 17, + seq: 2, + payload: encodeTerminalStreamText('still interactive\r') + }) + )! + ) + await vi.waitFor(() => + expect(runtime.sendTerminal).toHaveBeenCalledWith('terminal-1', { + text: 'still interactive\r', + enter: false, + interrupt: false + }) + ) + + binaryFrames.splice(0) + handlers.get(17)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Ack, + streamId: 17, + seq: 3, + payload: encodeTerminalStreamJson({ bytes: initialBytes }) + }) + )! + ) + + await vi.waitFor(() => + expect( + binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .some((frame) => { + if (frame?.opcode !== TerminalStreamOpcode.SnapshotStart) { + return false + } + const payload = decodeTerminalStreamJson<{ reason?: string }>(frame.payload) + return payload?.reason === 'ack-pending-overflow' + }) + ).toBe(true) + ) + const drainFrames = binaryFrames.map((frame) => decodeTerminalStreamFrame(frame)) + const recoveryStartIndex = drainFrames.findIndex((frame) => { + if (frame?.opcode !== TerminalStreamOpcode.SnapshotStart) { + return false + } + const payload = decodeTerminalStreamJson<{ reason?: string }>(frame.payload) + return payload?.reason === 'ack-pending-overflow' + }) + const firstOutputAfterAckIndex = drainFrames.findIndex( + (frame) => frame?.opcode === TerminalStreamOpcode.Output + ) + expect(recoveryStartIndex).toBeGreaterThanOrEqual(0) + // Why: clients discard truncated snapshots; a usable recovery snapshot + // must not be marked truncated or the dropped output gap is permanent. + expect( + decodeTerminalStreamJson<{ truncated?: boolean }>(drainFrames[recoveryStartIndex]!.payload) + ?.truncated + ).toBe(false) + expect(firstOutputAfterAckIndex).toBeGreaterThan(recoveryStartIndex) + expect( + drainFrames + .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) + .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + .join('') + ).toBe('recovered snapshot') + + const outputBytesAfterRecovery = drainFrames + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + .reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) + expect(outputBytesAfterRecovery).toBeLessThanOrEqual(256 * 1024) + + runtime.cleanupSubscription('terminal-multiplex:conn-ack-overflow') + await dispatchPromise + }) + + it('trims recovery-covered ACK pending output instead of replaying it', async () => { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const dataListenerRef: { + current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void + } = {} + const floodedChars = 3 * 1024 * 1024 + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi + .fn() + .mockResolvedValueOnce({ data: 'initial snapshot', cols: 120, rows: 40 }) + // Why: the recovery snapshot seq covers the entire flood, so every + // retained pending chunk is already contained in the snapshot. + .mockResolvedValue({ data: 'recovered snapshot', cols: 120, rows: 40, seq: floodedChars }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn( + ( + _: string, + listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void + ) => { + dataListenerRef.current = listener + return vi.fn() + } + ), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()), + getTerminalFitOverride: vi.fn().mockReturnValue(null), + getDriver: vi.fn().mockReturnValue({ kind: 'idle' }), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + cleanupSubscription: vi.fn((id: string) => { + const cleanup = cleanups.get(id) + cleanups.delete(id) + cleanup?.() + }), + waitForTerminal: vi.fn(() => new Promise(() => {})), + sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), + updateDesktopViewport: vi.fn().mockResolvedValue(true) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-ack-trim', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 31, + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' }, + viewport: { cols: 120, rows: 40 }, + capabilities: { ackOutput: 1 } + }) + }) + )! + ) + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) + ) + binaryFrames.splice(0) + + const output = 'x'.repeat(floodedChars) + dataListenerRef.current?.(output, { seq: floodedChars, rawLength: floodedChars }) + const initialBytes = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + .reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) + expect(initialBytes).toBeLessThanOrEqual(512 * 1024) + + binaryFrames.splice(0) + handlers.get(31)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Ack, + streamId: 31, + seq: 2, + payload: encodeTerminalStreamJson({ bytes: initialBytes }) + }) + )! + ) + await vi.waitFor(() => + expect( + binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .some((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotEnd) + ).toBe(true) + ) + + const framesAfterRecovery = binaryFrames.map((frame) => decodeTerminalStreamFrame(frame)) + expect( + framesAfterRecovery + .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) + .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + .join('') + ).toBe('recovered snapshot') + // Why: every retained chunk is covered by the recovery snapshot seq; + // replaying any of them would duplicate snapshot content. + expect( + framesAfterRecovery.filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) + ).toEqual([]) + + binaryFrames.splice(0) + const fresh = 'fresh-after-recovery\r\n' + dataListenerRef.current?.(fresh, { + seq: floodedChars + fresh.length, + rawLength: fresh.length + }) + await vi.waitFor(() => { + const freshOutput = binaryFrames .map((frame) => decodeTerminalStreamFrame(frame)) .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - expect(outputFrames.length).toBeGreaterThan(1) - expect(outputFrames.every((frame) => (frame?.payload.byteLength ?? 0) <= 48 * 1024)).toBe( - true - ) - expect(outputFrames.map((frame) => frame?.seq)).toEqual([16_384, 22_000]) - expect( - outputFrames.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')).join('') - ).toBe(multibyteOutput) - expect(encodeSpy).not.toHaveBeenCalledWith(multibyteOutput) - encodeSpy.mockRestore() + .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + .join('') + expect(freshOutput).toBe(fresh) + }) - cleanups.get('terminal-multiplex:conn-multibyte-output-batch')?.() - await dispatchPromise - } finally { - vi.useRealTimers() - } + runtime.cleanupSubscription('terminal-multiplex:conn-ack-trim') + await dispatchPromise }) it('marks multiplex fallback snapshots truncated when the uncursored read is limited', async () => { @@ -477,10 +1217,12 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi - .fn() - .mockResolvedValue({ tail: ['line 120'], truncated: false, limited: true }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + readTerminal: vi.fn().mockResolvedValue({ + tail: ['line 120'], + truncated: false, + limited: true + }), serializeTerminalBuffer: vi.fn().mockResolvedValue(null), getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), getMobileDisplayMode: vi.fn().mockReturnValue('auto'), @@ -502,14 +1244,19 @@ describe('terminal multiplex RPC', () => { waitForTerminal: vi.fn(() => new Promise(() => {})), sendTerminal: vi.fn().mockResolvedValue({ accepted: true }) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), (msg) => messages.push(msg), { connectionId: 'conn-multiplex-limited', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: (streamId, handler) => { handlers.set(streamId, handler) return () => handlers.delete(streamId) @@ -573,13 +1320,21 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi .fn() .mockResolvedValueOnce({ data: 'initial', cols: 120, rows: 40 }) - .mockResolvedValueOnce({ data: 'x'.repeat(2 * 1024 * 1024 + 1), cols: 120, rows: 40 }) - .mockResolvedValueOnce({ data: 'budgeted snapshot', cols: 120, rows: 40 }), + .mockResolvedValueOnce({ + data: 'x'.repeat(2 * 1024 * 1024 + 1), + cols: 120, + rows: 40 + }) + .mockResolvedValueOnce({ + data: 'budgeted snapshot', + cols: 120, + rows: 40 + }), getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), getMobileDisplayMode: vi.fn().mockReturnValue('auto'), getLayout: vi.fn().mockReturnValue({ seq: 1 }), @@ -596,14 +1351,19 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), (msg) => messages.push(msg), { connectionId: 'conn-budgeted-request', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: (streamId, handler) => { handlers.set(streamId, handler) return () => handlers.delete(streamId) @@ -640,7 +1400,10 @@ describe('terminal multiplex RPC', () => { opcode: TerminalStreamOpcode.SnapshotRequest, streamId: 14, seq: 2, - payload: encodeTerminalStreamJson({ requestId: 55, scrollbackRows: 5000 }) + payload: encodeTerminalStreamJson({ + requestId: 55, + scrollbackRows: 5000 + }) }) )! ) @@ -681,7 +1444,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue(null), getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), @@ -704,7 +1467,10 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), @@ -781,7 +1547,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn().mockResolvedValue(null), getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), @@ -805,7 +1571,10 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), @@ -892,7 +1661,10 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -981,7 +1753,10 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -992,7 +1767,9 @@ describe('terminal multiplex RPC', () => { (msg) => messages.push(msg), { connectionId: 'conn-subscribe-output-chunking', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: (streamId, handler) => { handlers.set(streamId, handler) return () => handlers.delete(streamId) @@ -1067,7 +1844,10 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -1078,13 +1858,18 @@ describe('terminal multiplex RPC', () => { (msg) => messages.push(msg), { connectionId: 'conn-buffered-output-on-subscribe', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: vi.fn(() => vi.fn()) } ) await vi.waitFor(() => expect(dataListenerRef.current).toBeDefined()) - dataListenerRef.current?.('starting shell\r\n', { seq: 16, rawLength: 16 }) + dataListenerRef.current?.('starting shell\r\n', { + seq: 16, + rawLength: 16 + }) resolveSnapshot({ data: '', cols: 120, rows: 40 }) await vi.waitFor(() => expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) @@ -1125,7 +1910,12 @@ describe('terminal multiplex RPC', () => { readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn( () => - new Promise<{ data: string; cols: number; rows: number; seq: number }>((resolve) => { + new Promise<{ + data: string + cols: number + rows: number + seq: number + }>((resolve) => { resolveSnapshot = resolve }) ), @@ -1151,7 +1941,10 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -1162,7 +1955,9 @@ describe('terminal multiplex RPC', () => { (msg) => messages.push(msg), { connectionId: 'conn-buffered-output-covered-by-snapshot', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: vi.fn(() => vi.fn()) } ) @@ -1222,7 +2017,12 @@ describe('terminal multiplex RPC', () => { readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn( () => - new Promise<{ data: string; cols: number; rows: number; seq: number }>((resolve) => { + new Promise<{ + data: string + cols: number + rows: number + seq: number + }>((resolve) => { resolveSnapshot = resolve }) ), @@ -1248,7 +2048,10 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -1259,7 +2062,9 @@ describe('terminal multiplex RPC', () => { (msg) => messages.push(msg), { connectionId: 'conn-buffered-output-partially-covered-by-snapshot', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: vi.fn(() => vi.fn()) } ) @@ -1305,7 +2110,7 @@ describe('terminal multiplex RPC', () => { >() const cleanups = new Map void>() const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), waitForLeafPtyId: vi.fn( (_handle: string, _timeoutMs?: number, signal?: AbortSignal) => new Promise((_resolve, reject) => { @@ -1319,7 +2124,10 @@ describe('terminal multiplex RPC', () => { cleanups.set(id, cleanup) }) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), @@ -1327,7 +2135,9 @@ describe('terminal multiplex RPC', () => { { signal: controller.signal, connectionId: 'conn-phone-multiplex', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: (streamId, handler) => { handlers.set(streamId, handler) return () => handlers.delete(streamId) @@ -1372,6 +2182,315 @@ describe('terminal multiplex RPC', () => { await dispatchPromise }) + it('keeps view-subscriber releases balanced when a same-streamId subscribe overwrites a blocked one', async () => { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + // Why: a leaked registration permanently suppresses the model query + // responder (terminal-query-authority.md) — the count must return to 0. + let viewSubscriberCount = 0 + let leafResolved = false + let resolveFirstWait: (ptyId: string) => void = () => {} + // Why: the multiplex subscribe path resolves via resolveLiveLeafForHandle + // (#7718); null makes subscribe A block in waitForLeafPtyId until B resolves. + const resolveLeaf = (): { ptyId: string | null } => + leafResolved ? { ptyId: 'pty-1' } : { ptyId: null } + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn(resolveLeaf), + resolveLiveLeafForHandle: vi.fn(resolveLeaf), + waitForLeafPtyId: vi.fn( + () => + new Promise((resolve) => { + resolveFirstWait = resolve + }) + ), + registerRemoteTerminalViewSubscriber: vi.fn(() => { + viewSubscriberCount += 1 + let released = false + return () => { + if (!released) { + released = true + viewSubscriberCount -= 1 + } + } + }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snap', cols: 80, rows: 24 }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + handleMobileSubscribe: vi.fn().mockResolvedValue(undefined), + handleMobileUnsubscribe: vi.fn(), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + waitForTerminal: vi.fn(() => new Promise(() => {})) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-overwrite', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + const sendSubscribe = (): void => { + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 7, + terminal: 'terminal-1', + client: { id: 'phone-1', type: 'mobile' } + }) + }) + )! + ) + } + + // Subscribe A blocks in waitForLeafPtyId; subscribe B (same streamId) + // then resolves the leaf directly and fully registers. + sendSubscribe() + await vi.waitFor(() => expect(runtime.waitForLeafPtyId).toHaveBeenCalled()) + leafResolved = true + sendSubscribe() + await vi.waitFor(() => + expect(messages.filter((msg) => JSON.parse(msg).result?.type === 'subscribed')).toHaveLength( + 1 + ) + ) + + // A resumes and takes the slot; B's registration must be released, not + // orphaned by the overwrite. + resolveFirstWait('pty-1') + await vi.waitFor(() => + expect(messages.filter((msg) => JSON.parse(msg).result?.type === 'subscribed')).toHaveLength( + 2 + ) + ) + + handlers.get(7)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Unsubscribe, + streamId: 7, + seq: 2, + payload: new Uint8Array() + }) + )! + ) + expect(viewSubscriberCount).toBe(0) + + cleanups.get('terminal-multiplex:conn-overwrite')?.() + await dispatchPromise + }) + + it('keeps an evicted subscribe error from detaching the successor stream', async () => { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + let viewSubscriberCount = 0 + const mobileSubscribeWaiters: { + resolve: () => void + reject: (error: Error) => void + }[] = [] + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + // Why: the multiplex subscribe path resolves the leaf via + // resolveLiveLeafForHandle (#7718), so it must return a live pty here. + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + registerRemoteTerminalViewSubscriber: vi.fn(() => { + viewSubscriberCount += 1 + let released = false + return () => { + if (!released) { + released = true + viewSubscriberCount -= 1 + } + } + }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snap', cols: 80, rows: 24 }), + getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + handleMobileSubscribe: vi.fn( + () => + new Promise((resolve, reject) => { + mobileSubscribeWaiters.push({ resolve: () => resolve(true), reject }) + }) + ), + handleMobileUnsubscribe: vi.fn(), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + waitForTerminal: vi.fn(() => new Promise(() => {})) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-evicted-error', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + const sendSubscribe = (): void => { + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 9, + terminal: 'terminal-1', + client: { id: 'phone-1', type: 'mobile' } + }) + }) + )! + ) + } + + // A registers, then blocks in handleMobileSubscribe. B (same streamId) + // evicts A on arrival and completes its own registration. + sendSubscribe() + await vi.waitFor(() => expect(mobileSubscribeWaiters).toHaveLength(1)) + sendSubscribe() + await vi.waitFor(() => expect(mobileSubscribeWaiters).toHaveLength(2)) + mobileSubscribeWaiters[1]!.resolve() + await vi.waitFor(() => + expect(messages.filter((msg) => JSON.parse(msg).result?.type === 'subscribed')).toHaveLength( + 1 + ) + ) + expect(viewSubscriberCount).toBe(1) + + // A's pending await now rejects. The evicted stream must not detach the + // successor that owns the slot. + mobileSubscribeWaiters[0]!.reject(new Error('mobile_subscribe_failed')) + await Promise.resolve() + await Promise.resolve() + expect(viewSubscriberCount).toBe(1) + + cleanups.get('terminal-multiplex:conn-evicted-error')?.() + await dispatchPromise + expect(viewSubscriberCount).toBe(0) + }) + + it('rejects a stale terminal handle with terminal_handle_stale instead of binding the wrong PTY', async () => { + // Why: after a reconnect a client can resubscribe with a handle whose + // pane now hosts a different PTY. Binding the stream anyway would mirror + // (and type into) the wrong terminal (#7718); the client recovers from + // terminal_handle_stale by re-deriving the handle from the next snapshot. + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const handlers = new Map< + number, + (frame: NonNullable>) => void + >() + const cleanups = new Map void>() + const runtime = stubRuntime({ + resolveLiveLeafForHandle: vi.fn(() => { + throw new Error('terminal_handle_stale') + }), + subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }) + }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.multiplex', {}), + (msg) => messages.push(msg), + { + connectionId: 'conn-stale-handle', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, + registerBinaryStreamHandler: (streamId, handler) => { + handlers.set(streamId, handler) + return () => handlers.delete(streamId) + } + } + ) + + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true) + ) + handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 9, + terminal: 'stale-terminal', + client: { id: 'desktop-1', type: 'desktop' } + }) + }) + )! + ) + + await vi.waitFor(() => + expect( + messages + .map((msg) => JSON.parse(msg).result) + .some((result) => result?.type === 'end' && result.streamId === 9) + ).toBe(true) + ) + const errorFrame = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .find((frame) => frame?.opcode === TerminalStreamOpcode.Error) + expect(errorFrame && decodeTerminalStreamText(errorFrame.payload)).toBe('terminal_handle_stale') + // The stream must never have bound to any PTY. + expect(runtime.subscribeToTerminalData).not.toHaveBeenCalled() + + cleanups.get('terminal-multiplex:conn-stale-handle')?.() + await dispatchPromise + }) + it('bounds live output queued while a multiplex snapshot is loading', async () => { vi.useFakeTimers() try { @@ -1385,7 +2504,7 @@ describe('terminal multiplex RPC', () => { const dataListenerRef: { current?: (data: string) => void } = {} const snapshotResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn( () => @@ -1412,14 +2531,19 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), (msg) => messages.push(msg), { connectionId: 'conn-buffered', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: (streamId, handler) => { handlers.set(streamId, handler) return () => handlers.delete(streamId) @@ -1494,7 +2618,7 @@ describe('terminal multiplex RPC', () => { const dataListenerRef: { current?: (data: string) => void } = {} const snapshotResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn( () => @@ -1521,14 +2645,19 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), (msg) => messages.push(msg), { connectionId: 'conn-buffered-multibyte', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: (streamId, handler) => { handlers.set(streamId, handler) return () => handlers.delete(streamId) @@ -1607,7 +2736,7 @@ describe('terminal multiplex RPC', () => { rows: number }) => void = () => {} const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi .fn() @@ -1618,7 +2747,11 @@ describe('terminal multiplex RPC', () => { resolveRequestedSnapshot = resolve }) ) - .mockResolvedValueOnce({ data: 'retry snapshot', cols: 120, rows: 40 }), + .mockResolvedValueOnce({ + data: 'retry snapshot', + cols: 120, + rows: 40 + }), getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), getMobileDisplayMode: vi.fn().mockReturnValue('auto'), getLayout: vi.fn().mockReturnValue({ seq: 1 }), @@ -1638,14 +2771,19 @@ describe('terminal multiplex RPC', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateDesktopViewport: vi.fn().mockResolvedValue(true) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.multiplex', {}), (msg) => messages.push(msg), { connectionId: 'conn-request-overflow', - sendBinary: (bytes) => binaryFrames.push(bytes), + sendBinary: (bytes) => { + binaryFrames.push(bytes) + }, registerBinaryStreamHandler: (streamId, handler) => { handlers.set(streamId, handler) return () => handlers.delete(streamId) @@ -1682,7 +2820,10 @@ describe('terminal multiplex RPC', () => { opcode: TerminalStreamOpcode.SnapshotRequest, streamId: 12, seq: 2, - payload: encodeTerminalStreamJson({ requestId: 44, scrollbackRows: 5000 }) + payload: encodeTerminalStreamJson({ + requestId: 44, + scrollbackRows: 5000 + }) }) )! ) diff --git a/src/main/runtime/rpc/terminal-output-batching.test.ts b/src/main/runtime/rpc/terminal-output-batching.test.ts index 2df3dbc71738..d10456c8fa69 100644 --- a/src/main/runtime/rpc/terminal-output-batching.test.ts +++ b/src/main/runtime/rpc/terminal-output-batching.test.ts @@ -15,6 +15,9 @@ import { function stubRuntime(overrides: Partial = {}): OrcaRuntimeService { return { getRuntimeId: () => 'test-runtime', + // Why: subscribe streams register as remote view subscribers for Phase-5 + // query-authority suppression (terminal-query-authority.md). + registerRemoteTerminalViewSubscriber: () => () => {}, ...overrides } as OrcaRuntimeService } @@ -52,7 +55,10 @@ describe('terminal output batching', () => { }), waitForTerminal: vi.fn(() => new Promise(() => {})) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -78,7 +84,9 @@ describe('terminal output batching', () => { .map((msg) => JSON.parse(msg)) .filter((message) => message.result?.type === 'data') expect(dataMessages).toHaveLength(1) - expect(dataMessages[0]).toMatchObject({ result: { type: 'data', chunk: 'ab' } }) + expect(dataMessages[0]).toMatchObject({ + result: { type: 'data', chunk: 'ab' } + }) runtime.cleanupSubscription('terminal-1:desktop-1') await dispatchPromise @@ -123,7 +131,10 @@ describe('terminal output batching', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateMobileViewport: vi.fn().mockResolvedValue(false) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -134,7 +145,9 @@ describe('terminal output batching', () => { (msg) => messages.push(msg), { connectionId: 'conn-1', - sendBinary: (bytes) => binaryFrames.push(bytes) + sendBinary: (bytes) => { + binaryFrames.push(bytes) + } } ) @@ -144,7 +157,10 @@ describe('terminal output batching', () => { const subscribed = messages .map((msg) => JSON.parse(msg)) .find((msg) => msg.result?.type === 'subscribed') - expect(subscribed?.result).toMatchObject({ type: 'subscribed', streamId: expect.any(Number) }) + expect(subscribed?.result).toMatchObject({ + type: 'subscribed', + streamId: expect.any(Number) + }) await vi.waitFor(() => expect(dataListenerRef.current).toBeDefined()) const emitData = dataListenerRef.current @@ -206,7 +222,10 @@ describe('terminal output batching', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateMobileViewport: vi.fn().mockResolvedValue(false) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -286,7 +305,10 @@ describe('terminal output batching', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateMobileViewport: vi.fn().mockResolvedValue(false) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const messages: string[] = [] const dispatchPromise = dispatcher.dispatchStreaming( diff --git a/src/main/runtime/rpc/terminal-send.test.ts b/src/main/runtime/rpc/terminal-send.test.ts index 82e471000885..c426513c9f50 100644 --- a/src/main/runtime/rpc/terminal-send.test.ts +++ b/src/main/runtime/rpc/terminal-send.test.ts @@ -75,9 +75,34 @@ describe('terminal send RPC', () => { expect(runtime.getTerminalAgentStatus).toHaveBeenCalledWith('terminal-1') }) + it('fails terminal.send with terminal_handle_stale for a stale handle instead of probing the wrong PTY', async () => { + const runtime = stubRuntime({ + resolveLiveLeafForHandle: vi.fn(() => { + throw new Error('terminal_handle_stale') + }), + sendTerminal: vi.fn() + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('terminal.send', { + terminal: 'stale-terminal', + text: 'x', + client: { id: 'desktop-1', type: 'desktop' } + }) + ) + + expect(response.ok).toBe(false) + if (response.ok) { + throw new Error('expected stale handle error') + } + expect(response.error.message).toContain('terminal_handle_stale') + expect(runtime.sendTerminal).not.toHaveBeenCalled() + }) + it('drops desktop input while a mobile client owns the terminal floor', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'mobile', clientId: 'mobile-1' }), sendTerminal: vi.fn(), mobileTookFloor: vi.fn() @@ -109,7 +134,7 @@ describe('terminal send RPC', () => { it('accepts legacy clientless mobile input when the current driver is mobile', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'mobile', clientId: 'mobile-1' }), sendTerminal: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -198,7 +223,7 @@ describe('terminal send RPC', () => { vi.useFakeTimers() const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1) const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), sendTerminal: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -236,7 +261,7 @@ describe('terminal send RPC', () => { it('refuses guarded terminal sends when the agent needs permission', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), getTerminalAgentStatus: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -274,7 +299,7 @@ describe('terminal send RPC', () => { it('allows guarded terminal sends when the agent is sendable', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), getTerminalAgentStatus: vi.fn().mockResolvedValue({ handle: 'terminal-1', @@ -316,7 +341,7 @@ describe('terminal send RPC', () => { it('refuses guarded combined text and submit sends before any PTY write', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), getTerminalAgentStatus: vi.fn(), sendTerminal: vi.fn() @@ -350,7 +375,7 @@ describe('terminal send RPC', () => { it('rechecks the mobile floor lock immediately before guarded PTY writes', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), getDriver: vi .fn() .mockReturnValueOnce({ kind: 'desktop' }) @@ -392,7 +417,7 @@ describe('terminal send RPC', () => { it('routes terminal restore fit through the runtime driver state machine', async () => { const runtime = stubRuntime({ - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), reclaimTerminalForDesktop: vi.fn().mockResolvedValue(true) }) const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) diff --git a/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts b/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts index adad88dded02..ba921c6b14e1 100644 --- a/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts +++ b/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts @@ -14,6 +14,9 @@ import { function stubRuntime(overrides: Partial = {}): OrcaRuntimeService { return { getRuntimeId: () => 'test-runtime', + // Why: subscribe streams register as remote view subscribers for Phase-5 + // query-authority suppression (terminal-query-authority.md). + registerRemoteTerminalViewSubscriber: () => () => {}, ...overrides } as OrcaRuntimeService } @@ -40,7 +43,10 @@ describe('terminal subscribe buffering', () => { ), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -77,11 +83,16 @@ describe('terminal subscribe buffering', () => { const messages: string[] = [] const runtime = stubRuntime({ resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: null }), - readTerminal: vi - .fn() - .mockResolvedValue({ tail: ['line 120'], truncated: false, limited: true }) + readTerminal: vi.fn().mockResolvedValue({ + tail: ['line 120'], + truncated: false, + limited: true + }) + }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) await dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { terminal: 'terminal-1' }), @@ -104,9 +115,11 @@ describe('terminal subscribe buffering', () => { const cleanups = new Map void>() const runtime = stubRuntime({ resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi - .fn() - .mockResolvedValue({ tail: ['line 120'], truncated: false, limited: true }), + readTerminal: vi.fn().mockResolvedValue({ + tail: ['line 120'], + truncated: false, + limited: true + }), serializeTerminalBuffer: vi.fn().mockResolvedValue(null), getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), getMobileDisplayMode: vi.fn().mockReturnValue('auto'), @@ -122,7 +135,10 @@ describe('terminal subscribe buffering', () => { }), waitForTerminal: vi.fn(() => new Promise(() => {})) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -172,7 +188,10 @@ describe('terminal subscribe buffering', () => { cleanupSubscription: vi.fn(), waitForTerminal: vi.fn(() => new Promise(() => {})) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -209,9 +228,11 @@ describe('terminal subscribe buffering', () => { const cleanups = new Map void>() const runtime = stubRuntime({ resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi - .fn() - .mockResolvedValue({ tail: ['line 120'], truncated: false, limited: true }), + readTerminal: vi.fn().mockResolvedValue({ + tail: ['line 120'], + truncated: false, + limited: true + }), serializeTerminalBuffer: vi.fn().mockResolvedValue(null), getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }), getMobileDisplayMode: vi.fn().mockReturnValue('auto'), @@ -230,7 +251,10 @@ describe('terminal subscribe buffering', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateMobileViewport: vi.fn().mockResolvedValue(false) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -241,7 +265,9 @@ describe('terminal subscribe buffering', () => { (msg) => messages.push(msg), { connectionId: 'conn-binary-limited', - sendBinary: (bytes) => binaryFrames.push(bytes) + sendBinary: (bytes) => { + binaryFrames.push(bytes) + } } ) @@ -273,9 +299,11 @@ describe('terminal subscribe buffering', () => { const cleanups = new Map void>() const runtime = stubRuntime({ resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - readTerminal: vi - .fn() - .mockResolvedValue({ tail: ['line 120'], truncated: false, limited: true }), + readTerminal: vi.fn().mockResolvedValue({ + tail: ['line 120'], + truncated: false, + limited: true + }), serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'serialized snapshot\r\n', cols: 100, @@ -298,7 +326,10 @@ describe('terminal subscribe buffering', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateMobileViewport: vi.fn().mockResolvedValue(false) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -309,20 +340,15 @@ describe('terminal subscribe buffering', () => { (msg) => messages.push(msg), { connectionId: 'conn-binary-serialized-limited', - sendBinary: (bytes) => binaryFrames.push(bytes) + sendBinary: (bytes) => { + binaryFrames.push(bytes) + } } ) await vi.waitFor(() => expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) ) - const subscribed = messages - .map((msg) => JSON.parse(msg).result) - .find((result) => result?.type === 'subscribed') - expect(subscribed).toMatchObject({ - type: 'subscribed', - truncated: false - }) const snapshotStart = binaryFrames .map((frame) => decodeTerminalStreamFrame(frame)) .find((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotStart) @@ -337,21 +363,35 @@ describe('terminal subscribe buffering', () => { await dispatchPromise }) - it('bounds legacy binary output queued while the initial snapshot is serializing', async () => { + it('recovers binary output overflow queued while the initial snapshot is serializing', async () => { vi.useFakeTimers() try { const messages: string[] = [] const binaryFrames: Uint8Array[] = [] const cleanups = new Map void>() - const dataListenerRef: { current?: (data: string) => void } = {} - const snapshotResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = [] + const dataListenerRef: { + current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void + } = {} + const snapshotResolvers: ((value: { + data: string + cols: number + rows: number + seq?: number + source?: 'headless' | 'renderer' + }) => void)[] = [] const runtime = stubRuntime({ resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), serializeTerminalBuffer: vi.fn( () => - new Promise<{ data: string; cols: number; rows: number }>((resolve) => { - snapshotResolves.push(resolve) + new Promise<{ + data: string + cols: number + rows: number + seq?: number + source?: 'headless' | 'renderer' + }>((resolve) => { + snapshotResolvers.push(resolve) }) ), getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), @@ -375,7 +415,10 @@ describe('terminal subscribe buffering', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateMobileViewport: vi.fn().mockResolvedValue(false) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -386,40 +429,62 @@ describe('terminal subscribe buffering', () => { (msg) => messages.push(msg), { connectionId: 'conn-buffered', - sendBinary: (bytes) => binaryFrames.push(bytes) + sendBinary: (bytes) => { + binaryFrames.push(bytes) + } } ) await vi.waitFor(() => expect(dataListenerRef.current).toBeDefined()) const shiftSpy = vi.spyOn(Array.prototype, 'shift') + let seq = 0 for (let index = 0; index < 400; index += 1) { - dataListenerRef.current?.(`${String(index).padStart(3, '0')}${'x'.repeat(1021)}`) + const data = `${String(index).padStart(3, '0')}${'x'.repeat(1021)}` + seq += data.length + dataListenerRef.current?.(data, { seq, rawLength: data.length }) } const shiftCallCount = shiftSpy.mock.calls.length shiftSpy.mockRestore() await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalled()) - snapshotResolves.shift()?.({ data: '', cols: 120, rows: 40 }) + snapshotResolvers[0]?.({ data: '', cols: 120, rows: 40, seq: 0, source: 'headless' }) await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalledTimes(2)) - snapshotResolves.shift()?.({ data: '399', cols: 120, rows: 40 }) + snapshotResolvers[1]?.({ + data: 'recovered after overflow\r\n', + cols: 120, + rows: 40, + seq, + source: 'headless' + }) await vi.waitFor(() => expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) ) await vi.runOnlyPendingTimersAsync() - const output = binaryFrames + const decodedFrames = binaryFrames .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + .filter((frame): frame is NonNullable => frame !== null) + const snapshotStarts = decodedFrames.filter( + (frame) => frame.opcode === TerminalStreamOpcode.SnapshotStart + ) + const decodedStarts = snapshotStarts.map((frame) => decodeTerminalStreamJson(frame.payload)) + // Why one snapshot: overflow during the initial serialize is recovered + // INLINE (drop pending, re-read, re-serialize) before anything is sent, + // so the client's first scrollback snapshot is already current. The + // 'resized'/pending-output-overflow follow-up path remains only for + // overflow that begins after the initial snapshot went out. + expect(decodedStarts).toEqual([expect.objectContaining({ kind: 'scrollback', seq })]) + const snapshotText = decodedFrames + .filter((frame) => frame.opcode === TerminalStreamOpcode.SnapshotChunk) + .map((frame) => decodeTerminalStreamText(frame.payload)) .join('') - expect(output.length).toBeLessThanOrEqual(256 * 1024) - expect(output).toBe('') - const snapshotPayload = binaryFrames - .map((frame) => decodeTerminalStreamFrame(frame)) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk) - .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + const output = decodedFrames + .filter((frame) => frame.opcode === TerminalStreamOpcode.Output) + .map((frame) => decodeTerminalStreamText(frame.payload)) .join('') - expect(snapshotPayload).toBe('399') + expect(output.length).toBeLessThanOrEqual(256 * 1024) expect(output).not.toContain('000') + expect(output).not.toContain('399') + expect(snapshotText).toContain('recovered after overflow') expect(shiftCallCount).toBe(0) runtime.cleanupSubscription('terminal-1:desktop-1') @@ -446,7 +511,12 @@ describe('terminal subscribe buffering', () => { data: string cols: number rows: number - oscLinks?: { row: number; startCol: number; endCol: number; uri: string }[] + oscLinks?: { + row: number + startCol: number + endCol: number + uri: string + }[] }) => void)[] = [] const serializeTerminalBuffer = vi .fn() @@ -457,7 +527,12 @@ describe('terminal subscribe buffering', () => { data: string cols: number rows: number - oscLinks?: { row: number; startCol: number; endCol: number; uri: string }[] + oscLinks?: { + row: number + startCol: number + endCol: number + uri: string + }[] }>((resolve) => { restreamResolves.push(resolve) }) @@ -490,7 +565,10 @@ describe('terminal subscribe buffering', () => { sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), updateMobileViewport: vi.fn().mockResolvedValue({ updated: true, applied: true }) }) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const dispatcher = new RpcDispatcher({ + runtime, + methods: TERMINAL_METHODS + }) const dispatchPromise = dispatcher.dispatchStreaming( makeRequest('terminal.subscribe', { @@ -501,19 +579,38 @@ describe('terminal subscribe buffering', () => { (msg) => messages.push(msg), { connectionId: 'conn-stale-resize', - sendBinary: (bytes) => binaryFrames.push(bytes) + sendBinary: (bytes) => { + binaryFrames.push(bytes) + } } ) await vi.waitFor(() => expect(resizeListener).toBeDefined()) binaryFrames.splice(0) - resizeListener?.({ cols: 90, rows: 24, displayMode: 'auto', reason: 'apply-layout', seq: 2 }) - resizeListener?.({ cols: 100, rows: 24, displayMode: 'auto', reason: 'apply-layout', seq: 3 }) + resizeListener?.({ + cols: 90, + rows: 24, + displayMode: 'auto', + reason: 'apply-layout', + seq: 2 + }) + resizeListener?.({ + cols: 100, + rows: 24, + displayMode: 'auto', + reason: 'apply-layout', + seq: 3 + }) await vi.waitFor(() => expect(restreamResolves).toHaveLength(2)) const newerOscLinks = [{ row: 0, startCol: 4, endCol: 9, uri: 'https://example.com' }] - restreamResolves[1]?.({ data: 'newer', cols: 100, rows: 24, oscLinks: newerOscLinks }) + restreamResolves[1]?.({ + data: 'newer', + cols: 100, + rows: 24, + oscLinks: newerOscLinks + }) await vi.waitFor(() => expect( binaryFrames.some((frame) => { @@ -545,4 +642,129 @@ describe('terminal subscribe buffering', () => { runtime.cleanupSubscription('terminal-1:phone-1') await dispatchPromise }) + + it('applies inline overflow recovery when the snapshot has no output seq', async () => { + vi.useFakeTimers() + try { + const messages: string[] = [] + const binaryFrames: Uint8Array[] = [] + const cleanups = new Map void>() + const dataListenerRef: { + current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void + } = {} + const snapshotResolvers: ((value: { + data: string + cols: number + rows: number + seq?: number + source?: 'headless' | 'renderer' + }) => void)[] = [] + const runtime = stubRuntime({ + resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), + readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }), + serializeTerminalBuffer: vi.fn( + () => + new Promise<{ + data: string + cols: number + rows: number + seq?: number + source?: 'headless' | 'renderer' + }>((resolve) => { + snapshotResolvers.push(resolve) + }) + ), + getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }), + getMobileDisplayMode: vi.fn().mockReturnValue('auto'), + getLayout: vi.fn().mockReturnValue({ seq: 1 }), + subscribeToTerminalData: vi.fn((_: string, listener: (data: string) => void) => { + dataListenerRef.current = listener + return vi.fn() + }), + subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()), + subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()), + registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => { + cleanups.set(id, cleanup) + }), + cleanupSubscription: vi.fn((id: string) => { + const cleanup = cleanups.get(id) + cleanups.delete(id) + cleanup?.() + }), + waitForTerminal: vi.fn(() => new Promise(() => {})), + sendTerminal: vi.fn().mockResolvedValue({ accepted: true }), + updateMobileViewport: vi.fn().mockResolvedValue(false) + }) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + + const dispatchPromise = dispatcher.dispatchStreaming( + makeRequest('terminal.subscribe', { + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' }, + capabilities: { terminalBinaryStream: 1 } + }), + (msg) => messages.push(msg), + { + connectionId: 'conn-buffered-no-seq', + sendBinary: (bytes) => { + binaryFrames.push(bytes) + } + } + ) + + await vi.waitFor(() => expect(dataListenerRef.current).toBeDefined()) + let seq = 0 + for (let index = 0; index < 400; index += 1) { + const data = `${String(index).padStart(3, '0')}${'x'.repeat(1021)}` + seq += data.length + dataListenerRef.current?.(data, { seq, rawLength: data.length }) + } + await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalled()) + snapshotResolvers[0]?.({ data: '', cols: 120, rows: 40, seq: 0, source: 'headless' }) + await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalledTimes(2)) + // Why applying is safe without a seq here: inline recovery serialized + // AFTER dropping the overflowed pending queue, so the snapshot covers + // those chunks by construction — no seq-based trimming is needed. + snapshotResolvers[1]?.({ + data: 'renderer fallback snapshot\r\n', + cols: 120, + rows: 40, + source: 'renderer' + }) + await vi.waitFor(() => + expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true) + ) + await vi.runOnlyPendingTimersAsync() + + const decodedFrames = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame): frame is NonNullable => frame !== null) + const snapshotStarts = decodedFrames.filter( + (frame) => frame.opcode === TerminalStreamOpcode.SnapshotStart + ) + // Why seq 1 (layout seq): a no-output-seq snapshot falls back to the + // layout seq on the wire; the recovered data still ships as the first + // and only scrollback snapshot. + expect(snapshotStarts.map((frame) => decodeTerminalStreamJson(frame.payload))).toEqual([ + expect.objectContaining({ kind: 'scrollback', seq: 1 }) + ]) + const snapshotText = decodedFrames + .filter((frame) => frame.opcode === TerminalStreamOpcode.SnapshotChunk) + .map((frame) => decodeTerminalStreamText(frame.payload)) + .join('') + expect(snapshotText).toContain('renderer fallback snapshot') + const output = decodedFrames + .filter((frame) => frame.opcode === TerminalStreamOpcode.Output) + .map((frame) => decodeTerminalStreamText(frame.payload)) + .join('') + // Why empty: the overflowed pending queue was dropped before the + // covering snapshot was serialized; nothing needs replay. + expect(output).toBe('') + + runtime.cleanupSubscription('terminal-1:desktop-1') + await dispatchPromise + } finally { + vi.useRealTimers() + } + }) }) diff --git a/src/main/runtime/rpc/ws-fallback-port-store.test.ts b/src/main/runtime/rpc/ws-fallback-port-store.test.ts new file mode 100644 index 000000000000..2edd314c2128 --- /dev/null +++ b/src/main/runtime/rpc/ws-fallback-port-store.test.ts @@ -0,0 +1,35 @@ +import { mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { readWsFallbackPort, writeWsFallbackPort } from './ws-fallback-port-store' + +function makeUserDataPath(): string { + return mkdtempSync(join(tmpdir(), 'ws-fallback-port-test-')) +} + +describe('ws-fallback-port-store', () => { + it('round-trips a persisted fallback port', () => { + const userDataPath = makeUserDataPath() + expect(readWsFallbackPort(userDataPath)).toBeUndefined() + writeWsFallbackPort(userDataPath, 54321) + expect(readWsFallbackPort(userDataPath)).toBe(54321) + }) + + it('ignores corrupt or invalid contents', () => { + const userDataPath = makeUserDataPath() + writeFileSync(join(userDataPath, 'mobile-ws-fallback-port.json'), 'not json', 'utf8') + expect(readWsFallbackPort(userDataPath)).toBeUndefined() + writeFileSync(join(userDataPath, 'mobile-ws-fallback-port.json'), '{"port":-4}', 'utf8') + expect(readWsFallbackPort(userDataPath)).toBeUndefined() + writeFileSync(join(userDataPath, 'mobile-ws-fallback-port.json'), '{"port":"80"}', 'utf8') + expect(readWsFallbackPort(userDataPath)).toBeUndefined() + }) + + it('refuses to persist an invalid port', () => { + const userDataPath = makeUserDataPath() + writeWsFallbackPort(userDataPath, 0) + writeWsFallbackPort(userDataPath, 70000) + expect(readWsFallbackPort(userDataPath)).toBeUndefined() + }) +}) diff --git a/src/main/runtime/rpc/ws-fallback-port-store.ts b/src/main/runtime/rpc/ws-fallback-port-store.ts new file mode 100644 index 000000000000..beedcea8cf27 --- /dev/null +++ b/src/main/runtime/rpc/ws-fallback-port-store.ts @@ -0,0 +1,45 @@ +import { readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' + +// Why: when the preferred WS port is taken (second Orca instance), the OS +// assigns a random port. Paired mobile devices store ws://ip:port endpoints, +// so a port that changes on every restart permanently orphans those pairings +// (STA-1511). Persist the assigned fallback so the same instance re-binds the +// same port next launch — the transport binds a persisted fallback BEFORE the +// preferred port, so pairings survive even when the preferred port is free +// again. + +const FALLBACK_PORT_FILE = 'mobile-ws-fallback-port.json' + +function isValidPort(value: unknown): value is number { + return typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 65535 +} + +export function readWsFallbackPort(userDataPath: string): number | undefined { + try { + const raw = readFileSync(join(userDataPath, FALLBACK_PORT_FILE), 'utf8') + const parsed: unknown = JSON.parse(raw) + if ( + typeof parsed === 'object' && + parsed !== null && + isValidPort((parsed as { port?: unknown }).port) + ) { + return (parsed as { port: number }).port + } + } catch { + // Missing or corrupt file — treated as "no previous fallback". + } + return undefined +} + +export function writeWsFallbackPort(userDataPath: string, port: number): void { + if (!isValidPort(port)) { + return + } + try { + writeFileSync(join(userDataPath, FALLBACK_PORT_FILE), JSON.stringify({ port }), 'utf8') + } catch { + // Why: persistence is best-effort — failing to record the port must not + // break transport startup; the cost is a re-pair after the next restart. + } +} diff --git a/src/main/runtime/rpc/ws-transport.test.ts b/src/main/runtime/rpc/ws-transport.test.ts index b9f4c94ddcd2..391e5e182844 100644 --- a/src/main/runtime/rpc/ws-transport.test.ts +++ b/src/main/runtime/rpc/ws-transport.test.ts @@ -441,4 +441,126 @@ describe('WebSocketTransport', () => { expect(serverClosed).toBe(true) expect(wss.clients.size).toBe(0) }, 5_000) + + // Why: paired mobile devices store ws://ip:port endpoints, so the fallback + // port must stay stable across restarts or pairings go permanently dead + // when the preferred port is held by another instance (STA-1511). + describe('fallback port stability', () => { + async function reserveFreePort(): Promise { + const scratch = new WebSocketTransport({ host: '127.0.0.1', port: 0 }) + await scratch.start() + const port = scratch.resolvedPort + await scratch.stop() + return port + } + + it('binds the persisted fallback port even when the preferred port is free', async () => { + // Why: regression for the STA-1511 follow-up — devices paired while the + // fallback port was active store ws://ip:. A later launch that + // finds the preferred port free must still bind the fallback, or those + // pairings go permanently dead until the user re-pairs. + const preferredPort = await reserveFreePort() + const fallbackPort = await reserveFreePort() + + const transport = new WebSocketTransport({ + host: '127.0.0.1', + port: preferredPort, + fallbackPort + }) + transports.push(transport) + await transport.start() + expect(transport.resolvedPort).toBe(fallbackPort) + }) + + it('binds the preferred port when the persisted fallback is taken', async () => { + const fallbackHolder = new WebSocketTransport({ host: '127.0.0.1', port: 0 }) + transports.push(fallbackHolder) + await fallbackHolder.start() + const takenFallbackPort = fallbackHolder.resolvedPort + const preferredPort = await reserveFreePort() + + const transport = new WebSocketTransport({ + host: '127.0.0.1', + port: preferredPort, + fallbackPort: takenFallbackPort + }) + transports.push(transport) + await transport.start() + expect(transport.resolvedPort).toBe(preferredPort) + }) + + it('falls through to the preferred port when the fallback bind fails with a non-EADDRINUSE error', async () => { + // Why: a persisted fallback can land in an OS-reserved range on a later + // launch (Windows Hyper-V excluded ports → EACCES). That must degrade to + // the preferred port instead of disabling the transport for the session. + const preferredPort = await reserveFreePort() + const fallbackPort = await reserveFreePort() + const transport = new WebSocketTransport({ + host: '127.0.0.1', + port: preferredPort, + fallbackPort + }) + transports.push(transport) + const withListen = transport as unknown as { tryListen(port: number): Promise } + const realTryListen = withListen.tryListen.bind(transport) + withListen.tryListen = (port: number) => + port === fallbackPort + ? Promise.reject(Object.assign(new Error('listen EACCES'), { code: 'EACCES' })) + : realTryListen(port) + + await transport.start() + expect(transport.resolvedPort).toBe(preferredPort) + }) + + it('still throws when the preferred port fails with a non-EADDRINUSE error', async () => { + const transport = new WebSocketTransport({ + host: '127.0.0.1', + port: await reserveFreePort() + }) + transports.push(transport) + const withListen = transport as unknown as { tryListen(port: number): Promise } + withListen.tryListen = () => + Promise.reject(Object.assign(new Error('listen EACCES'), { code: 'EACCES' })) + + await expect(transport.start()).rejects.toThrow('listen EACCES') + }) + + it('retries the persisted fallback port before an OS-assigned one', async () => { + const holder = new WebSocketTransport({ host: '127.0.0.1', port: 0 }) + transports.push(holder) + await holder.start() + const takenPort = holder.resolvedPort + const fallbackPort = await reserveFreePort() + + const transport = new WebSocketTransport({ + host: '127.0.0.1', + port: takenPort, + fallbackPort + }) + transports.push(transport) + await transport.start() + expect(transport.resolvedPort).toBe(fallbackPort) + }) + + it('falls back to an OS-assigned port when the persisted port is also taken', async () => { + const holder = new WebSocketTransport({ host: '127.0.0.1', port: 0 }) + const fallbackHolder = new WebSocketTransport({ host: '127.0.0.1', port: 0 }) + transports.push(holder, fallbackHolder) + await holder.start() + await fallbackHolder.start() + const takenPort = holder.resolvedPort + const takenFallbackPort = fallbackHolder.resolvedPort + + const transport = new WebSocketTransport({ + host: '127.0.0.1', + port: takenPort, + fallbackPort: takenFallbackPort + }) + transports.push(transport) + await transport.start() + expect(transport.resolvedPort).not.toBe(takenPort) + expect(transport.resolvedPort).not.toBe(takenFallbackPort) + expect(transport.resolvedPort).toBeGreaterThan(0) + }) + }) }) diff --git a/src/main/runtime/rpc/ws-transport.ts b/src/main/runtime/rpc/ws-transport.ts index 37f6094b589b..8b88c7a820e3 100644 --- a/src/main/runtime/rpc/ws-transport.ts +++ b/src/main/runtime/rpc/ws-transport.ts @@ -48,6 +48,12 @@ export type WebSocketTransportOptions = { // Why: the pairing server can also serve the browser client, so users do // not need a second dev/static server once the web bundle is built. staticRoot?: string + // Why: paired mobile devices store the full ws://ip:port endpoint. Once a + // fallback port has been assigned and persisted, devices paired while it was + // active point at it, so it must be bound FIRST on later launches — binding + // the (now free) preferred port instead would strand those pairings + // (STA-1511). Callers pass the previously assigned fallback port here. + fallbackPort?: number } export class WebSocketTransport implements RpcTransport { @@ -58,6 +64,7 @@ export class WebSocketTransport implements RpcTransport { private readonly heartbeatIntervalMs: number private readonly preAuthTimeoutMs: number private readonly staticRoot: string | undefined + private readonly fallbackPort: number | undefined private httpServer: HttpsServer | HttpServer | null = null private wss: WebSocketServer | null = null private heartbeatTimer: ReturnType | null = null @@ -81,7 +88,8 @@ export class WebSocketTransport implements RpcTransport { tlsKey, heartbeatIntervalMs, preAuthTimeoutMs, - staticRoot + staticRoot, + fallbackPort }: WebSocketTransportOptions) { this.host = host this.port = port @@ -90,6 +98,7 @@ export class WebSocketTransport implements RpcTransport { this.heartbeatIntervalMs = heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS this.preAuthTimeoutMs = preAuthTimeoutMs ?? PRE_AUTH_TIMEOUT_MS this.staticRoot = staticRoot + this.fallbackPort = fallbackPort } onMessage(handler: WebSocketMessageHandler): void { @@ -141,22 +150,41 @@ export class WebSocketTransport implements RpcTransport { return } - // Why: when the preferred port is occupied (e.g. another Orca instance is - // already running), fall back to an OS-assigned port so mobile pairing - // still works. The QR code reads resolvedPort after start, so it will - // advertise the correct port regardless. - let port = this.port - try { - await this.tryListen(port) - } catch (error: unknown) { - if (isEAddressInUse(error) && port !== 0) { - console.warn(`[ws-transport] Port ${port} is in use, falling back to OS-assigned port`) - port = 0 + // Why: a persisted fallback port is bound FIRST — devices paired while it + // was active store ws://ip: and would be permanently stranded if + // a later launch grabbed the (now free) preferred port instead (STA-1511). + // Without a persisted fallback the preferred port is tried first. On + // EADDRINUSE each candidate falls through to the next, ending at port 0 + // (OS-assigned) so mobile pairing still works when everything is taken. + // The QR code reads resolvedPort after start, so it always advertises the + // port that actually bound. + const persistedFallbackPort = + this.fallbackPort !== undefined && this.fallbackPort !== 0 && this.fallbackPort !== this.port + ? this.fallbackPort + : undefined + const candidatePorts = + persistedFallbackPort !== undefined ? [persistedFallbackPort, this.port] : [this.port] + for (const port of candidatePorts) { + try { await this.tryListen(port) - } else { - throw error + return + } catch (error: unknown) { + // Why: a persisted fallback can become unbindable for reasons beyond + // EADDRINUSE (e.g. Windows reserves dynamic-range ports for Hyper-V + // after a reboot → EACCES). Any fallback failure must degrade to the + // next candidate — aborting would disable the transport every launch + // while the store still names that port. Only preferred-port failures + // other than EADDRINUSE are fatal. + if (port !== persistedFallbackPort && (!isEAddressInUse(error) || port === 0)) { + throw error + } + console.warn( + `[ws-transport] Failed to bind port ${port} (${error instanceof Error ? error.message : String(error)}), trying next candidate` + ) } } + console.warn('[ws-transport] All configured ports failed to bind, using an OS-assigned port') + await this.tryListen(0) } private createHttpServer(): HttpServer | HttpsServer { diff --git a/src/main/runtime/runtime-rpc.test.ts b/src/main/runtime/runtime-rpc.test.ts index 5f50c32845e5..2d7579cce489 100644 --- a/src/main/runtime/runtime-rpc.test.ts +++ b/src/main/runtime/runtime-rpc.test.ts @@ -13,6 +13,15 @@ import * as runtimeMetadataModule from './runtime-metadata' import { readRuntimeMetadata } from './runtime-metadata' import { createRuntimeTransportMetadata, OrcaRuntimeRpcServer } from './runtime-rpc' import { parsePairingCode } from '../../shared/pairing' +import { subscribeRemoteRuntimeRequest } from '../../shared/remote-runtime-client' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + decodeTerminalStreamText, + encodeTerminalStreamFrame, + encodeTerminalStreamJson, + encodeTerminalStreamText +} from '../../shared/terminal-stream-protocol' import { decrypt, deriveSharedKey, encrypt, generateKeyPair } from './rpc/e2ee-crypto' import { DeviceRegistry } from './device-registry' @@ -2760,6 +2769,206 @@ describe('OrcaRuntimeRpcServer', () => { } }) + it('keeps active runtime multiplex streams responsive while a background stream is ACK-limited over WebSocket', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) + const writes: { terminal: string; text: string }[] = [] + const runtime = new OrcaRuntimeService(makeStore() as never) + const spawn = vi + .fn() + .mockResolvedValueOnce({ id: 'multiplex-background-pty' }) + .mockResolvedValueOnce({ id: 'multiplex-active-pty' }) + runtime.setPtyController({ + spawn, + write: (ptyId, data) => { + writes.push({ terminal: ptyId, text: data }) + return true + }, + kill: () => true, + getForegroundProcess: async () => null + }) + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath, + enableWebSocket: true, + wsPort: 0 + }) + + await server.start() + + const phoneOffer = server.createPairingOffer({ + address: '127.0.0.1', + name: 'phone', + scope: 'mobile' + }) + expect(phoneOffer.available).toBe(true) + if (!phoneOffer.available) { + throw new Error('WebSocket pairing unavailable') + } + const pairing = parsePairingCode(phoneOffer.pairingUrl) + expect(pairing).toBeTruthy() + if (!pairing) { + throw new Error('Pairing URL did not parse') + } + + const metadata = readRuntimeMetadata(userDataPath) + const laptopEndpoint = metadata!.transports[0]!.endpoint + const laptopAuthToken = metadata!.authToken + const worktree = 'id:repo-1::/tmp/worktree-a' + const backgroundLeafId = '11111111-1111-4111-8111-111111111111' + const activeLeafId = '22222222-2222-4222-8222-222222222222' + const backgroundCreateResponse = await sendRequest(laptopEndpoint, { + id: 'laptop_create_background', + authToken: laptopAuthToken, + method: 'terminal.create', + params: { + worktree, + command: 'background', + tabId: 'multiplex-background-tab', + leafId: backgroundLeafId + } + }) + const activeCreateResponse = await sendRequest(laptopEndpoint, { + id: 'laptop_create_active', + authToken: laptopAuthToken, + method: 'terminal.create', + params: { + worktree, + command: 'active', + tabId: 'multiplex-active-tab', + leafId: activeLeafId, + activate: true + } + }) + const backgroundTerminal = (backgroundCreateResponse.result as { terminal: { handle: string } }) + .terminal + const activeTerminal = (activeCreateResponse.result as { terminal: { handle: string } }) + .terminal + + const responses: Record[] = [] + const binaryFrames: Uint8Array[] = [] + const onError = vi.fn() + const subscription = await subscribeRemoteRuntimeRequest( + pairing, + 'terminal.multiplex', + {}, + 15_000, + { + onResponse: (response) => responses.push(response as Record), + onBinary: (bytes) => binaryFrames.push(bytes), + onError + } + ) + + try { + await vi.waitFor(() => + expect( + responses.some( + (response) => (response.result as { type?: string } | undefined)?.type === 'ready' + ) + ).toBe(true) + ) + subscription.sendBinary( + encodeTerminalStreamFrame({ + seq: 1, + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + payload: encodeTerminalStreamJson({ + streamId: 21, + terminal: backgroundTerminal.handle, + client: { id: 'desktop-background', type: 'desktop' }, + capabilities: { ackOutput: 1 } + }) + }) + ) + subscription.sendBinary( + encodeTerminalStreamFrame({ + seq: 2, + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + payload: encodeTerminalStreamJson({ + streamId: 22, + terminal: activeTerminal.handle, + client: { id: 'desktop-active', type: 'desktop' }, + capabilities: { ackOutput: 1 } + }) + }) + ) + await vi.waitFor(() => { + const subscribedStreamIds = responses + .map((response) => response.result as { type?: string; streamId?: number } | undefined) + .filter((result) => result?.type === 'subscribed') + .map((result) => result?.streamId) + expect(subscribedStreamIds).toEqual(expect.arrayContaining([21, 22])) + }) + binaryFrames.splice(0) + + const backgroundOutput = 'B'.repeat(700 * 1024) + runtime.onPtyData('multiplex-background-pty', backgroundOutput, 1) + await vi.waitFor(() => { + const backgroundFrames = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output && frame.streamId === 21) + const backgroundBytes = backgroundFrames.reduce( + (total, frame) => total + (frame?.payload.byteLength ?? 0), + 0 + ) + expect(backgroundBytes).toBeGreaterThan(0) + expect(backgroundBytes).toBeLessThan(backgroundOutput.length) + }) + + const frameCountBeforeActive = binaryFrames.length + runtime.onPtyData('multiplex-active-pty', 'ACTIVE_MULTIPLEX_READY\r\n', 2) + await vi.waitFor(() => { + const activeOutput = binaryFrames + .slice(frameCountBeforeActive) + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output && frame.streamId === 22) + .map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')) + .join('') + expect(activeOutput).toContain('ACTIVE_MULTIPLEX_READY') + }) + + subscription.sendBinary( + encodeTerminalStreamFrame({ + seq: 3, + opcode: TerminalStreamOpcode.Input, + streamId: 22, + payload: encodeTerminalStreamText('still interactive\r') + }) + ) + await vi.waitFor(() => + expect(writes).toContainEqual({ + terminal: 'multiplex-active-pty', + text: 'still interactive\r' + }) + ) + + const backgroundBytesBeforeAck = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output && frame.streamId === 21) + .reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) + subscription.sendBinary( + encodeTerminalStreamFrame({ + seq: 4, + opcode: TerminalStreamOpcode.Ack, + streamId: 21, + payload: encodeTerminalStreamJson({ bytes: backgroundBytesBeforeAck }) + }) + ) + await vi.waitFor(() => { + const backgroundBytesAfterAck = binaryFrames + .map((frame) => decodeTerminalStreamFrame(frame)) + .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output && frame.streamId === 21) + .reduce((total, frame) => total + (frame?.payload.byteLength ?? 0), 0) + expect(backgroundBytesAfterAck).toBeGreaterThan(backgroundBytesBeforeAck) + }) + expect(onError).not.toHaveBeenCalled() + } finally { + subscription.close() + await server.stop() + } + }) + it('serves worktree.ps from the runtime summary builder', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const runtime = new OrcaRuntimeService(makeStore({ isUnread: true }) as never) diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index a5418500c1dd..ace969138c4e 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -16,6 +16,7 @@ import { errorResponse } from './rpc/errors' import type { RpcMessageContext, RpcTransport } from './rpc/transport' import { UnixSocketTransport } from './rpc/unix-socket-transport' import { WebSocketTransport } from './rpc/ws-transport' +import { readWsFallbackPort, writeWsFallbackPort } from './rpc/ws-fallback-port-store' import type { WebSocket } from 'ws' import { DeviceRegistry, type DeviceScope } from './device-registry' import { loadOrCreateE2EEKeypair, type E2EEKeypair } from './e2ee-keypair' @@ -123,6 +124,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'accounts.selectCodex', 'accounts.subscribe', 'accounts.unsubscribe', + 'aiVault.listSessions', 'browser.back', 'browser.dialogAccept', 'browser.dialogDismiss', @@ -159,6 +161,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'files.readTerminalArtifactPreview', 'files.resolveTerminalPath', 'files.writeTerminalArtifact', + 'folderWorkspace.list', 'git.abortMerge', 'git.abortRebase', 'git.bulkStage', @@ -281,6 +284,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'preflight.check', 'preflight.detectAgents', 'preflight.detectRemoteAgents', + 'projectGroup.list', 'repo.baseRefDefault', 'repo.gitAvailable', 'repo.hooks', @@ -308,6 +312,8 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'settings.update', 'ssh.connect', 'ssh.getState', + 'ssh.listRemovedTargetLabels', + 'ssh.listTargets', 'speech.dictation.cancel', 'speech.dictation.chunk', 'speech.dictation.finish', @@ -700,7 +706,13 @@ export class OrcaRuntimeRpcServer { const wsTransport = new WebSocketTransport({ host: '0.0.0.0', port: this.wsPort, - staticRoot: this.webClientRoot + staticRoot: this.webClientRoot, + // Why: keep the fallback port stable across restarts so paired + // devices' stored endpoints stay valid (STA-1511) — the transport + // binds a persisted fallback before the preferred port. wsPort 0 + // means the caller explicitly wants a random port (E2E) — don't + // pin it. + ...(this.wsPort !== 0 ? { fallbackPort: readWsFallbackPort(this.userDataPath) } : {}) }) this.wsTransport = wsTransport @@ -783,6 +795,9 @@ export class OrcaRuntimeRpcServer { }) await wsTransport.start() + if (this.wsPort !== 0 && wsTransport.resolvedPort !== this.wsPort) { + writeWsFallbackPort(this.userDataPath, wsTransport.resolvedPort) + } activeTransports.push(wsTransport) transportsMeta.push({ kind: 'websocket', diff --git a/src/main/runtime/terminal-model-query-authority.test.ts b/src/main/runtime/terminal-model-query-authority.test.ts new file mode 100644 index 000000000000..3217a98022e6 --- /dev/null +++ b/src/main/runtime/terminal-model-query-authority.test.ts @@ -0,0 +1,140 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { + _resetTerminalModelQueryAuthorityForTest, + clearNativeWindowsConptyPty, + isNativeWindowsConptyPty, + isNativeWindowsLocalPtySpawn, + isTerminalModelQueryAuthorityEnabled, + markNativeWindowsConptyPty, + shouldModelAnswerHiddenPtyQueries +} from './terminal-model-query-authority' +import { + _resetHiddenRendererPtyDeliveryGateForTest, + markHiddenRendererPty, + setRendererPtyDeliveryInterest +} from '../ipc/pty-hidden-delivery-gate' + +const ALL_ON = { + terminalMainSideEffectAuthority: true, + terminalHiddenDeliveryGate: true, + terminalModelQueryAuthority: true +} + +afterEach(() => { + _resetTerminalModelQueryAuthorityForTest() + _resetHiddenRendererPtyDeliveryGateForTest() +}) + +describe('isTerminalModelQueryAuthorityEnabled', () => { + it('defaults on, including for absent settings', () => { + expect(isTerminalModelQueryAuthorityEnabled(ALL_ON)).toBe(true) + expect(isTerminalModelQueryAuthorityEnabled({})).toBe(true) + expect(isTerminalModelQueryAuthorityEnabled(null)).toBe(true) + expect(isTerminalModelQueryAuthorityEnabled(undefined)).toBe(true) + }) + + it('is an independent off switch for the responder alone', () => { + expect( + isTerminalModelQueryAuthorityEnabled({ ...ALL_ON, terminalModelQueryAuthority: false }) + ).toBe(false) + }) + + it('requires both Phase-4 gate switches — no marks exist without them', () => { + expect( + isTerminalModelQueryAuthorityEnabled({ ...ALL_ON, terminalHiddenDeliveryGate: false }) + ).toBe(false) + expect( + isTerminalModelQueryAuthorityEnabled({ ...ALL_ON, terminalMainSideEffectAuthority: false }) + ).toBe(false) + }) +}) + +describe('shouldModelAnswerHiddenPtyQueries', () => { + const answer = (ptyId: string, overrides: Record = {}): boolean => + shouldModelAnswerHiddenPtyQueries({ + ptyId, + settings: { ...ALL_ON, ...overrides }, + hasRemoteViewSubscriber: false + }) + + it('answers only for hidden-marked PTYs (the delivery decision is the reply decision)', () => { + expect(answer('pty-1')).toBe(false) + markHiddenRendererPty('pty-1') + expect(answer('pty-1')).toBe(true) + expect(answer('pty-other')).toBe(false) + }) + + it('yields to registered renderer delivery interest (chunk is delivered to a sidecar)', () => { + markHiddenRendererPty('pty-1') + setRendererPtyDeliveryInterest('pty-1', true) + expect(answer('pty-1')).toBe(false) + setRendererPtyDeliveryInterest('pty-1', false) + expect(answer('pty-1')).toBe(true) + }) + + it('yields while a remote view subscriber is attached', () => { + markHiddenRendererPty('pty-1') + expect( + shouldModelAnswerHiddenPtyQueries({ + ptyId: 'pty-1', + settings: ALL_ON, + hasRemoteViewSubscriber: true + }) + ).toBe(false) + }) + + it('stays silent under any kill switch', () => { + markHiddenRendererPty('pty-1') + expect(answer('pty-1', { terminalModelQueryAuthority: false })).toBe(false) + expect(answer('pty-1', { terminalHiddenDeliveryGate: false })).toBe(false) + expect(answer('pty-1', { terminalMainSideEffectAuthority: false })).toBe(false) + }) +}) + +describe('isNativeWindowsLocalPtySpawn (main-side mirror of isLocalNativeWindowsPty)', () => { + const base = { + connectionId: null, + cwd: 'C:\\repo', + shellOverride: undefined, + platform: 'win32' as NodeJS.Platform + } + + it('matches local native Windows spawns', () => { + expect(isNativeWindowsLocalPtySpawn(base)).toBe(true) + expect(isNativeWindowsLocalPtySpawn({ ...base, connectionId: undefined })).toBe(true) + expect( + isNativeWindowsLocalPtySpawn({ ...base, shellOverride: 'C:\\Tools\\powershell.exe' }) + ).toBe(true) + }) + + it('rejects non-Windows hosts', () => { + expect(isNativeWindowsLocalPtySpawn({ ...base, platform: 'darwin' })).toBe(false) + expect(isNativeWindowsLocalPtySpawn({ ...base, platform: 'linux' })).toBe(false) + }) + + it('rejects SSH-backed spawns', () => { + expect(isNativeWindowsLocalPtySpawn({ ...base, connectionId: 'ssh-1' })).toBe(false) + }) + + it('rejects WSL cwds and WSL shell overrides', () => { + expect( + isNativeWindowsLocalPtySpawn({ ...base, cwd: '\\\\wsl.localhost\\Ubuntu\\home\\me' }) + ).toBe(false) + expect(isNativeWindowsLocalPtySpawn({ ...base, shellOverride: 'wsl.exe' })).toBe(false) + expect( + isNativeWindowsLocalPtySpawn({ ...base, shellOverride: 'C:\\Windows\\System32\\wsl.exe' }) + ).toBe(false) + expect(isNativeWindowsLocalPtySpawn({ ...base, shellOverride: 'wsl' })).toBe(false) + }) +}) + +describe('native-Windows ConPTY spawn record', () => { + it('marks, reads, and clears per PTY', () => { + expect(isNativeWindowsConptyPty('pty-1')).toBe(false) + markNativeWindowsConptyPty('pty-1') + expect(isNativeWindowsConptyPty('pty-1')).toBe(true) + expect(isNativeWindowsConptyPty('pty-2')).toBe(false) + clearNativeWindowsConptyPty('pty-1') + expect(isNativeWindowsConptyPty('pty-1')).toBe(false) + }) +}) diff --git a/src/main/runtime/terminal-model-query-authority.ts b/src/main/runtime/terminal-model-query-authority.ts new file mode 100644 index 000000000000..e1e0f9c28ef2 --- /dev/null +++ b/src/main/runtime/terminal-model-query-authority.ts @@ -0,0 +1,111 @@ +/** + * Phase 5 of the terminal model/view architecture: main-side terminal query + * authority (docs/reference/terminal-query-authority.md). + * + * The delivery decision is the reply decision: main answers a query iff the + * hidden-delivery gate dropped the chunk that carried it. This module owns + * the responder kill-switch predicate and the main-side mirror of the + * renderer's native-Windows-ConPTY determination, recorded per PTY at spawn + * so the runtime emulator can register the DA1 override before byte zero. + */ +import type { GlobalSettings } from '../../shared/types' +import { isWslUncPath } from '../../shared/wsl-paths' +import { + isHiddenPtyDeliveryGateEnabled, + shouldDropHiddenRendererPtyData +} from '../ipc/pty-hidden-delivery-gate' + +export type TerminalModelQueryAuthoritySettings = Pick< + GlobalSettings, + 'terminalMainSideEffectAuthority' | 'terminalHiddenDeliveryGate' | 'terminalModelQueryAuthority' +> + +/** Responder kill switch: requires BOTH Phase-4 gate switches (no marks/drops + * exist without them) plus the Phase-5-specific independent off switch. */ +export function isTerminalModelQueryAuthorityEnabled( + settings: TerminalModelQueryAuthoritySettings | null | undefined +): boolean { + return isHiddenPtyDeliveryGateEnabled(settings) && settings?.terminalModelQueryAuthority !== false +} + +/** Per-chunk reply-ownership predicate, evaluated once at ingestion in + * OrcaRuntimeService.onPtyData — the same module state and tick as the + * hidden-gate drop sites, so "chunk dropped" and "main answers" cannot + * diverge for live chunks. Remote view subscribers (mobile/web/remote + * desktop xterms on the multiplexed stream) keep view authority, so main + * yields while one is attached. */ +export function shouldModelAnswerHiddenPtyQueries(opts: { + ptyId: string + settings: TerminalModelQueryAuthoritySettings | null | undefined + hasRemoteViewSubscriber: boolean +}): boolean { + return ( + isTerminalModelQueryAuthorityEnabled(opts.settings) && + !opts.hasRemoteViewSubscriber && + shouldDropHiddenRendererPtyData(opts.ptyId, opts.settings) + ) +} + +/** Main-side mirror of the renderer's isLocalNativeWindowsPty + * (windows-pty-compatibility.ts), computed from spawn-time facts: local or + * daemon provider (no SSH connection), win32 host, and not a WSL shell. */ +export function isNativeWindowsLocalPtySpawn(opts: { + connectionId: string | null | undefined + cwd: string | null | undefined + shellOverride: string | null | undefined + platform?: NodeJS.Platform +}): boolean { + if ((opts.platform ?? process.platform) !== 'win32') { + return false + } + if (opts.connectionId) { + return false + } + if (isWslUncPath(opts.cwd ?? '')) { + return false + } + if (/(?:^|[/\\])wsl(?:\.exe)?$/i.test(opts.shellOverride ?? '')) { + return false + } + return true +} + +// Why module state (pattern of pty-hidden-delivery-gate.ts): pty.ts records +// the determination at spawn, the runtime consults it at emulator creation. +// Daemon-adopted PTYs from a previous app run carry no mark — acceptable: +// ConPTY's blocking DA1 only fires at spawn, which happened in a prior life. +const nativeWindowsConptyPtys = new Set() + +// Why installers: the mark lands after the awaited spawn response, but daemon +// stream data (warm-reattach flush) can lazy-create the runtime emulator +// first. The runtime registers an installer so marking retrofits the DA1 +// override onto an existing emulator; installation is idempotent emulator-side. +type ConptyDa1OverrideInstaller = (ptyId: string) => void +const conptyDa1OverrideInstallers = new Set() + +export function registerConptyDa1OverrideInstaller(installer: ConptyDa1OverrideInstaller): void { + conptyDa1OverrideInstallers.add(installer) +} + +export function markNativeWindowsConptyPty(id: string): void { + nativeWindowsConptyPtys.add(id) + for (const installer of conptyDa1OverrideInstallers) { + installer(id) + } +} + +export function isNativeWindowsConptyPty(id: string): boolean { + return nativeWindowsConptyPtys.has(id) +} + +/** Wired into clearProviderPtyState so every PTY teardown path releases the + * spawn record. */ +export function clearNativeWindowsConptyPty(id: string): void { + nativeWindowsConptyPtys.delete(id) +} + +/** Test seam: reset module state between tests. */ +export function _resetTerminalModelQueryAuthorityForTest(): void { + nativeWindowsConptyPtys.clear() + conptyDa1OverrideInstallers.clear() +} diff --git a/src/main/runtime/terminal-query-responder.test.ts b/src/main/runtime/terminal-query-responder.test.ts new file mode 100644 index 000000000000..b6988e067317 --- /dev/null +++ b/src/main/runtime/terminal-query-responder.test.ts @@ -0,0 +1,827 @@ +/** + * Phase 5 model query responder (docs/reference/terminal-query-authority.md): + * reply parity through the runtime emulator, the per-chunk ownership matrix, + * the main-side replay guard, and the ingestion-time capture race. + */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from './orca-runtime' +import { HeadlessEmulator } from '../daemon/headless-emulator' +import { + _resetHiddenRendererPtyDeliveryGateForTest, + markHiddenRendererPty, + setRendererPtyDeliveryInterest, + unmarkHiddenRendererPty +} from '../ipc/pty-hidden-delivery-gate' +import { + _resetTerminalModelQueryAuthorityForTest, + markNativeWindowsConptyPty +} from './terminal-model-query-authority' +import { + _resetTerminalViewAttributesForTest, + setTerminalViewAttributes +} from './terminal-view-attribute-store' +import type { TerminalViewAttributes, TerminalViewRgb } from '../../shared/terminal-view-attributes' + +const settingsState = { + terminalMainSideEffectAuthority: true as boolean, + terminalHiddenDeliveryGate: true as boolean, + terminalModelQueryAuthority: true as boolean +} + +const store = { + getRepo: () => undefined, + getRepos: () => [], + addRepo: () => {}, + updateRepo: () => undefined as never, + getAllWorktreeMeta: () => ({}), + getWorktreeMeta: () => undefined, + setWorktreeMeta: () => undefined as never, + removeWorktreeMeta: () => {}, + getGitHubCache: () => ({ pr: {}, issue: {} }) as never, + getSettings: () => ({ + workspaceDir: '/tmp/workspaces', + nestWorkspaces: false, + refreshLocalBaseRefOnWorktreeCreate: false, + branchPrefix: 'none', + branchPrefixCustom: '', + terminalMainSideEffectAuthority: settingsState.terminalMainSideEffectAuthority, + terminalHiddenDeliveryGate: settingsState.terminalHiddenDeliveryGate, + terminalModelQueryAuthority: settingsState.terminalModelQueryAuthority + }) +} + +type RendererBufferStub = { data: string; cols: number; rows: number } + +function createResponderRuntime(opts: { rendererBuffer?: RendererBufferStub } = {}) { + const runtime = new OrcaRuntimeService(store) + const replies: { ptyId: string; data: string }[] = [] + runtime.setPtyController({ + write: (ptyId, data) => { + replies.push({ ptyId, data }) + return true + }, + kill: () => true, + getForegroundProcess: async () => null, + getSize: () => ({ cols: 80, rows: 24 }), + resize: () => true, + ...(opts.rendererBuffer + ? { + hasRendererSerializer: () => true, + serializeBuffer: async () => opts.rendererBuffer ?? null + } + : {}) + }) + return { runtime, replies } +} + +/** Awaits the per-PTY emulator writeChain so queued chunk links (and the + * replies they forward) have settled. */ +async function settle(runtime: OrcaRuntimeService, ptyId: string): Promise { + await runtime.serializeMainTerminalBuffer(ptyId) +} + +/** Renderer-pushed attribute snapshot with distinct, pinned slot values so + * reply fixtures cannot pass by coincidence. */ +function viewAttributes(overrides: Partial = {}): TerminalViewAttributes { + const ansi = Array.from( + { length: 256 }, + (_, i) => [i, (i * 2) % 256, (i * 3) % 256] as TerminalViewRgb + ) + ansi[1] = [0xcc, 0x00, 0x00] + return { + foreground: [0xd0, 0xd0, 0xd0], + background: [0x1e, 0x1e, 0x2e], + cursor: [0xff, 0x99, 0x00], + ansi, + colorSchemeMode: 'dark', + cursorStyle: 'bar', + cursorBlink: true, + ...overrides + } +} + +afterEach(() => { + _resetHiddenRendererPtyDeliveryGateForTest() + _resetTerminalModelQueryAuthorityForTest() + _resetTerminalViewAttributesForTest() + settingsState.terminalMainSideEffectAuthority = true + settingsState.terminalHiddenDeliveryGate = true + settingsState.terminalModelQueryAuthority = true +}) + +describe('reply parity for hidden-dropped chunks', () => { + // Expected replies pinned from the design doc and verified against the + // bundled @xterm/headless build — the same core the renderer runs, so + // parity is structural for static and model-state classes. + it.each([ + ['DA1 CSI c', '\x1b[c', ['\x1b[?1;2c']], + ['DA1 CSI 0 c variant', '\x1b[0c', ['\x1b[?1;2c']], + ['DA2', '\x1b[>c', ['\x1b[>0;276;0c']], + ['DSR 5n operating status', '\x1b[5n', ['\x1b[0n']], + ['CPR 6n at origin', '\x1b[6n', ['\x1b[1;1R']], + ['CPR 6n reports the model cursor position', 'hello\r\nworld\x1b[6n', ['\x1b[2;6R']], + ['DECXCPR ?6n', '\x1b[?6n', ['\x1b[?1;1R']], + ['DECRPM ?1 DECCKM default', '\x1b[?1$p', ['\x1b[?1;2$y']], + ['DECRPM ?6 DECOM default', '\x1b[?6$p', ['\x1b[?6;2$y']], + ['DECRPM ?7 DECAWM default', '\x1b[?7$p', ['\x1b[?7;1$y']], + ['DECRPM ?25 DECTCEM default', '\x1b[?25$p', ['\x1b[?25;1$y']], + ['DECRPM ?1004 focus events default', '\x1b[?1004$p', ['\x1b[?1004;2$y']], + ['DECRPM ?1006 SGR mouse default', '\x1b[?1006$p', ['\x1b[?1006;2$y']], + ['DECRPM ?1016 SGR pixels default', '\x1b[?1016$p', ['\x1b[?1016;2$y']], + ['DECRPM ?1049 alt screen default', '\x1b[?1049$p', ['\x1b[?1049;2$y']], + ['DECRPM ?2004 bracketed paste default', '\x1b[?2004$p', ['\x1b[?2004;2$y']], + ['DECRPM ?2026 synchronized output default', '\x1b[?2026$p', ['\x1b[?2026;2$y']], + ['DECRPM reports a set mode as enabled', '\x1b[?2004h\x1b[?2004$p', ['\x1b[?2004;1$y']], + ['DECRPM unknown mode reports 0', '\x1b[?12345$p', ['\x1b[?12345;0$y']], + ['DECRQM ANSI insert mode', '\x1b[4$p', ['\x1b[4;2$y']], + ['DECRQSS DECSTBM default margins', '\x1bP$qr\x1b\\', ['\x1bP1$r1;24r\x1b\\']], + ['DECRQSS DECSTBM after margin set', '\x1b[5;20r\x1bP$qr\x1b\\', ['\x1bP1$r5;20r\x1b\\']], + ['DECRQSS DECSCUSR default cursor', '\x1bP$q q\x1b\\', ['\x1bP1$r2 q\x1b\\']], + ['DECRQSS DECSCA', '\x1bP$q"q\x1b\\', ['\x1bP1$r0"q\x1b\\']], + ['DECRQSS SGR', '\x1bP$qm\x1b\\', ['\x1bP1$r0m\x1b\\']], + ['XTVERSION', '\x1b[>0q', ['\x1bP>|xterm.js(6.0.0)\x1b\\']], + ['kitty CSI ? u default flags', '\x1b[?u', ['\x1b[?0u']], + ['kitty CSI ? u reports pushed flags', '\x1b[=5;1u\x1b[?u', ['\x1b[?5u']] + ])('%s', async (_label, chunk, expectedReplies) => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-q') + + runtime.onPtyData('pty-q', chunk, Date.now()) + await settle(runtime, 'pty-q') + + expect(replies.map((reply) => reply.data)).toEqual(expectedReplies) + expect(replies.every((reply) => reply.ptyId === 'pty-q')).toBe(true) + }) + + it.each([ + ['XTWINOPS', '\x1b[14t'], + ['XTGETTCAP', '\x1bP+q544e\x1b\\'], + ['DSR ?15n printer status', '\x1b[?15n'], + ['DSR ?25n UDK status', '\x1b[?25n'], + ['DSR ?26n keyboard status', '\x1b[?26n'], + ['DSR ?53n locator status', '\x1b[?53n'], + // View-attribute class: silent until the slice-2 renderer attribute push + // — a fabricated default would resurrect the default-black OSC-11 bug. + ['OSC 10 foreground query', '\x1b]10;?\x07'], + ['OSC 11 background query', '\x1b]11;?\x07'], + ['OSC 12 cursor-color query', '\x1b]12;?\x1b\\'], + ['OSC 4 palette query', '\x1b]4;1;?\x07'], + ['DSR ?996n color-scheme query', '\x1b[?996n'] + ])('stays silent for %s', async (_label, chunk) => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-q') + + runtime.onPtyData('pty-q', chunk, Date.now()) + await settle(runtime, 'pty-q') + + expect(replies).toEqual([]) + }) +}) + +describe('reply ownership matrix', () => { + const DA1 = '\x1b[c' + + it('never answers delivered (unmarked) chunks — the visible xterm owns them', async () => { + const { runtime, replies } = createResponderRuntime() + + runtime.onPtyData('pty-v', DA1, Date.now()) + await settle(runtime, 'pty-v') + + expect(replies).toEqual([]) + }) + + it('never answers while renderer delivery interest holds the chunk delivered', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-i') + setRendererPtyDeliveryInterest('pty-i', true) + + runtime.onPtyData('pty-i', DA1, Date.now()) + await settle(runtime, 'pty-i') + + expect(replies).toEqual([]) + }) + + it.each([ + ['terminalModelQueryAuthority', () => (settingsState.terminalModelQueryAuthority = false)], + ['terminalHiddenDeliveryGate', () => (settingsState.terminalHiddenDeliveryGate = false)], + [ + 'terminalMainSideEffectAuthority', + () => (settingsState.terminalMainSideEffectAuthority = false) + ] + ])('never answers with kill switch %s off', async (_label, flip) => { + flip() + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-k') + + runtime.onPtyData('pty-k', DA1, Date.now()) + await settle(runtime, 'pty-k') + + expect(replies).toEqual([]) + }) + + it('yields while a remote view subscriber is attached and resumes on release', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-r') + const release = runtime.registerRemoteTerminalViewSubscriber('pty-r') + + runtime.onPtyData('pty-r', DA1, Date.now()) + await settle(runtime, 'pty-r') + expect(replies).toEqual([]) + + release() + // Releases are idempotent: a double release must not unbalance the count. + release() + runtime.onPtyData('pty-r', DA1, Date.now()) + await settle(runtime, 'pty-r') + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?1;2c']) + }) + + it('counts overlapping remote view subscribers', () => { + const { runtime } = createResponderRuntime() + const releaseA = runtime.registerRemoteTerminalViewSubscriber('pty-m') + const releaseB = runtime.registerRemoteTerminalViewSubscriber('pty-m') + expect(runtime.hasRemoteTerminalViewSubscriber('pty-m')).toBe(true) + releaseA() + expect(runtime.hasRemoteTerminalViewSubscriber('pty-m')).toBe(true) + releaseB() + expect(runtime.hasRemoteTerminalViewSubscriber('pty-m')).toBe(false) + }) + + it('treats mobile subscriber records as remote view subscribers', async () => { + const { runtime } = createResponderRuntime() + await runtime.handleMobileSubscribe('pty-mob', 'client-1', { cols: 40, rows: 20 }) + expect(runtime.hasRemoteTerminalViewSubscriber('pty-mob')).toBe(true) + }) + + it('answers a dropped-chunk query exactly once', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-once') + + runtime.onPtyData('pty-once', DA1, Date.now()) + await settle(runtime, 'pty-once') + + expect(replies).toHaveLength(1) + }) +}) + +describe('main-side replay guard', () => { + const DA1 = '\x1b[c' + + it('never answers queries embedded in a seeded snapshot, then answers live bytes', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-seed') + + runtime.seedHeadlessTerminal('pty-seed', `restored prompt${DA1}`) + await settle(runtime, 'pty-seed') + expect(replies).toEqual([]) + + runtime.onPtyData('pty-seed', DA1, Date.now()) + await settle(runtime, 'pty-seed') + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?1;2c']) + }) + + it('never answers queries replayed by renderer-buffer hydration', async () => { + const { runtime, replies } = createResponderRuntime({ + rendererBuffer: { data: `restored screen${DA1}`, cols: 80, rows: 24 } + }) + markHiddenRendererPty('pty-hyd') + + // First live byte triggers maybeHydrateHeadlessFromRenderer; the hydration + // seed parses the embedded DA1 but must not forward its reply. + runtime.onPtyData('pty-hyd', 'live output', Date.now()) + await settle(runtime, 'pty-hyd') + + expect(replies).toEqual([]) + }) +}) + +describe('kitty flag re-seed parity (terminal-query-authority.md §kitty)', () => { + it('answers ?u with the persisted snapshot flags after a re-seed, silently applied', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-kitty') + + // Daemon warm-reattach threads modes.kittyKeyboardFlags through the + // spawn result into the seed; applying them is a seed-side write and + // must answer no one (main-side replay guard). + runtime.seedHeadlessTerminal('pty-kitty', 'restored prompt', undefined, { + kittyKeyboardFlags: 5 + }) + await settle(runtime, 'pty-kitty') + expect(replies).toEqual([]) + + runtime.onPtyData('pty-kitty', '\x1b[?u', Date.now()) + await settle(runtime, 'pty-kitty') + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?5u']) + }) + + it('answers ?0u when the snapshot carried no flags (fresh-shell paths)', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-kitty0') + + runtime.seedHeadlessTerminal('pty-kitty0', 'restored prompt') + runtime.onPtyData('pty-kitty0', '\x1b[?u', Date.now()) + await settle(runtime, 'pty-kitty0') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?0u']) + }) +}) + +describe('ingestion-time ownership capture', () => { + const DA1 = '\x1b[c' + + it('still answers when the hidden mark flips off between ingestion and the async write', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-race') + + runtime.onPtyData('pty-race', DA1, Date.now()) + // Flip before the queued writeChain link runs: the captured decision wins. + unmarkHiddenRendererPty('pty-race') + await settle(runtime, 'pty-race') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?1;2c']) + }) + + it('stays silent when the hidden mark lands after ingestion', async () => { + const { runtime, replies } = createResponderRuntime() + + runtime.onPtyData('pty-race2', DA1, Date.now()) + markHiddenRendererPty('pty-race2') + await settle(runtime, 'pty-race2') + + expect(replies).toEqual([]) + }) +}) + +describe('stale writeChain links after dispose', () => { + const DA1 = '\x1b[c' + + it('never forwards a queued reply once the PTY state is disposed', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-stale') + + // Queue a forward-flagged chain link, then dispose before it runs. + runtime.onPtyData('pty-stale', DA1, Date.now()) + runtime.onPtyExit('pty-stale', 0) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(replies).toEqual([]) + }) + + it('never injects a stale reply into a successor PTY reusing the session id', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-reuse') + + // Daemon respawns reuse session ids: dispose with the flagged link still + // queued, then re-create the same id before the link runs. + runtime.onPtyData('pty-reuse', DA1, Date.now()) + runtime.onPtyExit('pty-reuse', 0) + runtime.onPtyData('pty-reuse', 'fresh shell banner', Date.now()) + await settle(runtime, 'pty-reuse') + + expect(replies).toEqual([]) + }) +}) + +describe('ConPTY DA1 override', () => { + it('retrofits the override when the spawn mark lands after data created the emulator', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-win-late') + + // Daemon warm-reattach flush: stream data creates the emulator before + // the awaited spawn response marks the PTY native-Windows. + runtime.onPtyData('pty-win-late', 'warm reattach flush', Date.now()) + markNativeWindowsConptyPty('pty-win-late') + + runtime.onPtyData('pty-win-late', '\x1b[c', Date.now()) + await settle(runtime, 'pty-win-late') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?61;4c']) + }) + + it('keeps the override single-reply when installed at creation and marked again', async () => { + const { runtime, replies } = createResponderRuntime() + markNativeWindowsConptyPty('pty-win-idem') + markHiddenRendererPty('pty-win-idem') + + runtime.onPtyData('pty-win-idem', 'boot output', Date.now()) + // A duplicate mark (e.g. respawn against a live emulator) must not stack + // a second handler that double-replies. + markNativeWindowsConptyPty('pty-win-idem') + + runtime.onPtyData('pty-win-idem', '\x1b[c', Date.now()) + await settle(runtime, 'pty-win-idem') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?61;4c']) + }) + + it('answers CSI ?61;4c for marked native-Windows PTYs, suppressing the core ?1;2c', async () => { + const { runtime, replies } = createResponderRuntime() + markNativeWindowsConptyPty('pty-win') + markHiddenRendererPty('pty-win') + + runtime.onPtyData('pty-win', '\x1b[c', Date.now()) + await settle(runtime, 'pty-win') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?61;4c']) + }) + + it('lets non-primary device-attribute queries fall through to the core', async () => { + const { runtime, replies } = createResponderRuntime() + markNativeWindowsConptyPty('pty-win2') + markHiddenRendererPty('pty-win2') + + runtime.onPtyData('pty-win2', '\x1b[>c', Date.now()) + await settle(runtime, 'pty-win2') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[>0;276;0c']) + }) + + it('keeps the override silent for delivered chunks', async () => { + const { runtime, replies } = createResponderRuntime() + markNativeWindowsConptyPty('pty-win3') + + runtime.onPtyData('pty-win3', '\x1b[c', Date.now()) + await settle(runtime, 'pty-win3') + + expect(replies).toEqual([]) + }) +}) + +describe('HeadlessEmulator forwarding window', () => { + it('forwards replies only for writes flagged forwardQueryReplies', async () => { + const onQueryReply = vi.fn() + const emulator = new HeadlessEmulator({ cols: 80, rows: 24, onQueryReply }) + try { + await emulator.write('\x1b[c') + expect(onQueryReply).not.toHaveBeenCalled() + + await emulator.write('\x1b[c', { forwardQueryReplies: true }) + expect(onQueryReply).toHaveBeenCalledTimes(1) + expect(onQueryReply).toHaveBeenCalledWith('\x1b[?1;2c') + } finally { + emulator.dispose() + } + }) + + it('scopes the async-fallback forwarding window to the flagged chunk parse', async () => { + const onQueryReply = vi.fn() + const emulator = new HeadlessEmulator({ cols: 80, rows: 24, onQueryReply }) + // Force the async write path (xterm deprecates writeSync; the fallback + // must stay structurally safe without writeChain serialization). + const internals = emulator as unknown as { terminal: { _core: { writeSync?: unknown } } } + internals.terminal._core.writeSync = undefined + try { + // Enqueue an unflagged seed carrying a query, then a flagged live + // chunk, WITHOUT awaiting between them: both sit in xterm's write + // queue together. The seed parse must not see an open window. + const seed = emulator.write('seeded\x1b[c') + const live = emulator.write('\x1b[5n', { forwardQueryReplies: true }) + await Promise.all([seed, live]) + + expect(onQueryReply.mock.calls.map((call) => call[0])).toEqual(['\x1b[0n']) + } finally { + emulator.dispose() + } + }) + + it('keeps the ConPTY override inside the forwarding window', async () => { + const onQueryReply = vi.fn() + const emulator = new HeadlessEmulator({ cols: 80, rows: 24, onQueryReply }) + emulator.installConptyPrimaryDeviceAttributesOverride() + try { + // Unflagged (replayed/seeded) DA1 must answer no one even with the + // override installed. + await emulator.write('\x1b[c') + expect(onQueryReply).not.toHaveBeenCalled() + + await emulator.write('\x1b[c', { forwardQueryReplies: true }) + expect(onQueryReply).toHaveBeenCalledTimes(1) + expect(onQueryReply).toHaveBeenCalledWith('\x1b[?61;4c') + } finally { + emulator.dispose() + } + }) +}) + +describe('view-attribute bridge replies (after renderer push)', () => { + // Reply bytes pinned to the renderer xterm's format: OSC replies use the + // queried ident, 16-bit doubled-byte channels, and ST termination + // (CoreBrowserTerminal._handleColorEvent + toRgbString); ?996n answers with + // the contour 997 report, same bytes as mode2031SequenceFor. + it.each([ + ['OSC 10 foreground', '\x1b]10;?\x07', ['\x1b]10;rgb:d0d0/d0d0/d0d0\x1b\\']], + ['OSC 11 background', '\x1b]11;?\x07', ['\x1b]11;rgb:1e1e/1e1e/2e2e\x1b\\']], + ['OSC 12 cursor color', '\x1b]12;?\x1b\\', ['\x1b]12;rgb:ffff/9999/0000\x1b\\']], + ['OSC 4 named palette slot', '\x1b]4;1;?\x07', ['\x1b]4;1;rgb:cccc/0000/0000\x1b\\']], + ['OSC 4 extended palette slot', '\x1b]4;196;?\x07', ['\x1b]4;196;rgb:c4c4/8888/4c4c\x1b\\']], + [ + 'OSC 4 multiple slots in one sequence', + '\x1b]4;1;?;196;?\x07', + ['\x1b]4;1;rgb:cccc/0000/0000\x1b\\', '\x1b]4;196;rgb:c4c4/8888/4c4c\x1b\\'] + ], + [ + 'OSC 10 stacked params report foreground then background', + '\x1b]10;?;?\x07', + ['\x1b]10;rgb:d0d0/d0d0/d0d0\x1b\\', '\x1b]11;rgb:1e1e/1e1e/2e2e\x1b\\'] + ], + ['DSR ?996n dark', '\x1b[?996n', ['\x1b[?997;1n']], + ['DECRQSS DECSCUSR from pushed cursor options', '\x1bP$q q\x1b\\', ['\x1bP1$r5 q\x1b\\']], + ['DECRQM ?12 from pushed cursorBlink', '\x1b[?12$p', ['\x1b[?12;1$y']] + ])('%s', async (_label, chunk, expectedReplies) => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-view') + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData('pty-view', chunk, Date.now()) + await settle(runtime, 'pty-view') + + expect(replies.map((reply) => reply.data)).toEqual(expectedReplies) + }) + + it('answers ?996n from palette luminance, not the pushed app mode (dark palette, light app mode)', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-lum-dark') + // Supported divergence: light app mode with terminalUseSeparateLightTheme + // off renders a dark terminal theme. A visible xterm answers ?996n from + // bg/fg relative luminance (CoreBrowserTerminal._reportColorScheme), so + // the hidden reply must say dark here too. + setTerminalViewAttributes(viewAttributes({ colorSchemeMode: 'light' })) + + runtime.onPtyData('pty-lum-dark', '\x1b[?996n', Date.now()) + await settle(runtime, 'pty-lum-dark') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?997;1n']) + }) + + it('answers ?996n light for a light palette regardless of the pushed app mode', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-lum-light') + setTerminalViewAttributes( + viewAttributes({ + foreground: [0x33, 0x33, 0x33], + background: [0xfa, 0xfa, 0xfa], + colorSchemeMode: 'dark' + }) + ) + + runtime.onPtyData('pty-lum-light', '\x1b[?996n', Date.now()) + await settle(runtime, 'pty-lum-light') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?997;2n']) + }) + + it('answers ?996n from OSC-SET-mutated colors like a visible xterm', async () => { + // _reportColorScheme reads the CURRENT theme-service colors, which include + // OSC 10/11 SET mutations — the per-PTY overlays layer the same way. + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-lum-set') + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData('pty-lum-set', '\x1b]11;#ffffff\x07\x1b]10;#101010\x07\x1b[?996n', Date.now()) + await settle(runtime, 'pty-lum-set') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?997;2n']) + }) + + it('stays silent before the first push, then answers the same query after it', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-first') + + runtime.onPtyData('pty-first', '\x1b]11;?\x07\x1b[?996n', Date.now()) + await settle(runtime, 'pty-first') + // No fabricated defaults: silence is the documented hidden status quo. + expect(replies).toEqual([]) + + setTerminalViewAttributes(viewAttributes()) + runtime.onPtyData('pty-first', '\x1b]11;?\x07', Date.now()) + await settle(runtime, 'pty-first') + expect(replies.map((reply) => reply.data)).toEqual(['\x1b]11;rgb:1e1e/1e1e/2e2e\x1b\\']) + }) + + it('retrofits cursor options onto already-live emulators when the push lands late', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-late') + + // Emulator exists before any push: core default DECSCUSR is steady block. + runtime.onPtyData('pty-late', '\x1bP$q q\x1b\\', Date.now()) + await settle(runtime, 'pty-late') + expect(replies.map((reply) => reply.data)).toEqual(['\x1bP1$r2 q\x1b\\']) + + setTerminalViewAttributes(viewAttributes({ cursorStyle: 'underline', cursorBlink: false })) + runtime.onPtyData('pty-late', '\x1bP$q q\x1b\\', Date.now()) + await settle(runtime, 'pty-late') + expect(replies.map((reply) => reply.data).at(-1)).toBe('\x1bP1$r4 q\x1b\\') + }) +}) + +describe('per-PTY OSC color SET layering', () => { + it('layers an OSC 4 SET over the pushed base, isolated per PTY', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-a') + markHiddenRendererPty('pty-b') + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData('pty-a', '\x1b]4;1;rgb:00/ff/00\x07\x1b]4;1;?\x07', Date.now()) + runtime.onPtyData('pty-b', '\x1b]4;1;?\x07', Date.now()) + await settle(runtime, 'pty-a') + await settle(runtime, 'pty-b') + + expect(replies).toEqual([ + { ptyId: 'pty-a', data: '\x1b]4;1;rgb:0000/ffff/0000\x1b\\' }, + { ptyId: 'pty-b', data: '\x1b]4;1;rgb:cccc/0000/0000\x1b\\' } + ]) + }) + + it('restores a single indexed color via OSC 104;', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-104') + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData('pty-104', '\x1b]4;1;#00ff00\x07\x1b]104;1\x07\x1b]4;1;?\x07', Date.now()) + await settle(runtime, 'pty-104') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b]4;1;rgb:cccc/0000/0000\x1b\\']) + }) + + it('restores the whole indexed table via bare OSC 104', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-104all') + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData( + 'pty-104all', + '\x1b]4;1;#00ff00;196;#0000ff\x07\x1b]104\x07\x1b]4;1;?;196;?\x07', + Date.now() + ) + await settle(runtime, 'pty-104all') + + expect(replies.map((reply) => reply.data)).toEqual([ + '\x1b]4;1;rgb:cccc/0000/0000\x1b\\', + '\x1b]4;196;rgb:c4c4/8888/4c4c\x1b\\' + ]) + }) + + it('layers OSC 10/11/12 SETs and restores them via 110/111/112', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-special') + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData( + 'pty-special', + '\x1b]10;#010203\x07\x1b]11;rgb:ff/ff/ff\x07\x1b]12;#0a0b0c\x07' + + '\x1b]10;?\x07\x1b]11;?\x07\x1b]12;?\x07' + + '\x1b]110\x07\x1b]111\x07\x1b]112\x07' + + '\x1b]10;?\x07\x1b]11;?\x07\x1b]12;?\x07', + Date.now() + ) + await settle(runtime, 'pty-special') + + expect(replies.map((reply) => reply.data)).toEqual([ + '\x1b]10;rgb:0101/0202/0303\x1b\\', + '\x1b]11;rgb:ffff/ffff/ffff\x1b\\', + '\x1b]12;rgb:0a0a/0b0b/0c0c\x1b\\', + '\x1b]10;rgb:d0d0/d0d0/d0d0\x1b\\', + '\x1b]11;rgb:1e1e/1e1e/2e2e\x1b\\', + '\x1b]12;rgb:ffff/9999/0000\x1b\\' + ]) + }) + + it('tracks SET mutations parsed from a seed without replying, like renderer replay', async () => { + // Cold-restore scrollback replayed into a visible renderer xterm re-applies + // OSC SETs to its theme service; the model mirrors that state — but the + // replay guard still keeps the seed from ANSWERING anything. + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-seedset') + setTerminalViewAttributes(viewAttributes()) + + runtime.seedHeadlessTerminal('pty-seedset', 'restored\x1b]4;1;#00ff00\x07\x1b]4;1;?\x07') + await settle(runtime, 'pty-seedset') + expect(replies).toEqual([]) + + runtime.onPtyData('pty-seedset', '\x1b]4;1;?\x07', Date.now()) + await settle(runtime, 'pty-seedset') + expect(replies.map((reply) => reply.data)).toEqual(['\x1b]4;1;rgb:0000/ffff/0000\x1b\\']) + }) + + it('preserves per-PTY overrides on an identical re-push (fresh renderer process)', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-idem') + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData('pty-idem', '\x1b]11;#ffffff\x07', Date.now()) + await settle(runtime, 'pty-idem') + + // A second window / renderer reload / macOS re-activation re-pushes + // byte-identical attributes (its publisher dedupe is per-process). That is + // not a theme apply, so the OSC SET overlay must survive. + setTerminalViewAttributes(viewAttributes()) + runtime.onPtyData('pty-idem', '\x1b]11;?\x07', Date.now()) + await settle(runtime, 'pty-idem') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b]11;rgb:ffff/ffff/ffff\x1b\\']) + }) + + it('clears per-PTY overrides when a new push lands (theme apply parity)', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-clear') + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData('pty-clear', '\x1b]11;#ffffff\x07', Date.now()) + await settle(runtime, 'pty-clear') + + // A theme apply overwrites OSC-SET-mutated colors on visible panes too + // (ThemeService._setTheme), so the model mirrors that on every CHANGED + // push (identical re-pushes are filtered — see the test above). + setTerminalViewAttributes(viewAttributes({ background: [0x10, 0x20, 0x30] })) + runtime.onPtyData('pty-clear', '\x1b]11;?\x07', Date.now()) + await settle(runtime, 'pty-clear') + + expect(replies.map((reply) => reply.data)).toEqual(['\x1b]11;rgb:1010/2020/3030\x1b\\']) + }) +}) + +describe('view-attribute replay guard and suppression', () => { + it('never answers view-attribute queries embedded in a seeded snapshot', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-vseed') + setTerminalViewAttributes(viewAttributes()) + + runtime.seedHeadlessTerminal('pty-vseed', 'prompt\x1b]11;?\x07\x1b[?996n') + await settle(runtime, 'pty-vseed') + expect(replies).toEqual([]) + + runtime.onPtyData('pty-vseed', '\x1b]11;?\x07', Date.now()) + await settle(runtime, 'pty-vseed') + expect(replies.map((reply) => reply.data)).toEqual(['\x1b]11;rgb:1e1e/1e1e/2e2e\x1b\\']) + }) + + it('never answers view-attribute queries replayed by renderer-buffer hydration', async () => { + const { runtime, replies } = createResponderRuntime({ + rendererBuffer: { data: 'restored\x1b]11;?\x07\x1b[?996n', cols: 80, rows: 24 } + }) + markHiddenRendererPty('pty-vhyd') + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData('pty-vhyd', 'live output', Date.now()) + await settle(runtime, 'pty-vhyd') + + expect(replies).toEqual([]) + }) + + it('never answers a delivered (unmarked) view-attribute query — the visible xterm owns it', async () => { + const { runtime, replies } = createResponderRuntime() + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData('pty-vvis', '\x1b]11;?\x07\x1b[?996n', Date.now()) + await settle(runtime, 'pty-vvis') + + expect(replies).toEqual([]) + }) + + it('never answers while renderer delivery interest holds the chunk delivered', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-vint') + setRendererPtyDeliveryInterest('pty-vint', true) + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData('pty-vint', '\x1b]11;?\x07', Date.now()) + await settle(runtime, 'pty-vint') + + expect(replies).toEqual([]) + }) + + it('yields view-attribute replies while a remote view subscriber is attached', async () => { + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-vrem') + setTerminalViewAttributes(viewAttributes()) + const release = runtime.registerRemoteTerminalViewSubscriber('pty-vrem') + + runtime.onPtyData('pty-vrem', '\x1b]11;?\x07', Date.now()) + await settle(runtime, 'pty-vrem') + expect(replies).toEqual([]) + + release() + runtime.onPtyData('pty-vrem', '\x1b]11;?\x07', Date.now()) + await settle(runtime, 'pty-vrem') + expect(replies.map((reply) => reply.data)).toEqual(['\x1b]11;rgb:1e1e/1e1e/2e2e\x1b\\']) + }) + + it.each([ + ['terminalModelQueryAuthority', () => (settingsState.terminalModelQueryAuthority = false)], + ['terminalHiddenDeliveryGate', () => (settingsState.terminalHiddenDeliveryGate = false)], + [ + 'terminalMainSideEffectAuthority', + () => (settingsState.terminalMainSideEffectAuthority = false) + ] + ])('never answers view-attribute queries with kill switch %s off', async (_label, flip) => { + flip() + const { runtime, replies } = createResponderRuntime() + markHiddenRendererPty('pty-vkill') + setTerminalViewAttributes(viewAttributes()) + + runtime.onPtyData('pty-vkill', '\x1b]11;?\x07\x1b[?996n', Date.now()) + await settle(runtime, 'pty-vkill') + + expect(replies).toEqual([]) + }) +}) diff --git a/src/main/runtime/terminal-view-attribute-store.ts b/src/main/runtime/terminal-view-attribute-store.ts new file mode 100644 index 000000000000..ee55581bfe98 --- /dev/null +++ b/src/main/runtime/terminal-view-attribute-store.ts @@ -0,0 +1,57 @@ +/** + * Phase 5 slice 2 (docs/reference/terminal-query-authority.md §View-attribute + * bridge): main-side cache of the renderer's `pty:terminalViewAttributes` + * push. One app-global snapshot, not per-PTY — per-pane font zoom never + * affects these attributes and the color/cursor settings are global. + * + * Null until the first push, and the responder answers NO view-attribute + * query while null (silent-until-first-push): a fabricated default would + * resurrect the default-black OSC-11 bug. Staleness is bounded by one IPC + * hop; subscribed TUIs are corrected by the renderer-owned 2031/997 flip. + */ +import { + terminalViewAttributesEqual, + type TerminalViewAttributes +} from '../../shared/terminal-view-attributes' + +// Why module state (pattern of pty-hidden-delivery-gate.ts): pty.ts receives +// the push, the runtime emulators consult it at reply time via the getter. +let currentAttributes: TerminalViewAttributes | null = null + +// Why appliers (pattern of registerConptyDa1OverrideInstaller): each push +// must also reach already-live emulators — cursor options under the replay +// guard, plus the per-PTY override reset a theme apply implies. +type TerminalViewAttributesApplier = (attributes: TerminalViewAttributes) => void +const pushAppliers = new Set() + +export function registerTerminalViewAttributesApplier( + applier: TerminalViewAttributesApplier +): void { + pushAppliers.add(applier) +} + +/** Called from the pty:terminalViewAttributes IPC handler with a validated + * payload. Last push wins (replies always use the freshest snapshot). */ +export function setTerminalViewAttributes(attributes: TerminalViewAttributes): void { + // Why idempotent: the renderer publisher's dedupe is per-process, so a + // fresh renderer (second window, reload, macOS re-activation) re-pushes + // identical attributes. That is not a theme apply — fanning out would wipe + // every PTY's OSC SET overlay while visible panes keep theirs. + if (currentAttributes && terminalViewAttributesEqual(currentAttributes, attributes)) { + return + } + currentAttributes = attributes + for (const applier of pushAppliers) { + applier(attributes) + } +} + +export function getTerminalViewAttributes(): TerminalViewAttributes | null { + return currentAttributes +} + +/** Test seam: reset module state between tests. */ +export function _resetTerminalViewAttributesForTest(): void { + currentAttributes = null + pushAppliers.clear() +} diff --git a/src/main/shell-templates.ts b/src/main/shell-templates.ts index dccd5e2c87f5..d11bdbcfbc08 100644 --- a/src/main/shell-templates.ts +++ b/src/main/shell-templates.ts @@ -10,6 +10,13 @@ export function getZshEnvTemplate(zshDir: string, headerPrefix = ''): string { ? `Orca ${headerPrefix} zsh shell-ready wrapper` : 'Orca zsh shell-ready wrapper' return `# ${header} +# Why: capture the runtime wrapper dir before it is unset below. On WSL this +# file is generated with a Windows path but sourced via /mnt/c, so the baked +# literal is unusable there and ZDOTDIR must be restored from this value. +_orca_wrapper_zdotdir_self="\${ZDOTDIR:-}" +while [[ "\${_orca_wrapper_zdotdir_self:-}" == */ ]]; do + _orca_wrapper_zdotdir_self="\${_orca_wrapper_zdotdir_self%/}" +done _orca_spawn_orig_zdotdir="\${ORCA_ORIG_ZDOTDIR:-}" _orca_user_zdotdir="\${_orca_spawn_orig_zdotdir:-$HOME}" _orca_zshenv_source_dir="\${ORCA_ZSHENV_SOURCE_DIR:-$HOME}" @@ -67,8 +74,14 @@ case "\${ORCA_ORIG_ZDOTDIR}" in ""|*/shell-ready/zsh) export ORCA_ORIG_ZDOTDIR="$HOME" ;; esac -export ZDOTDIR=${quotePosixSingle(zshDir)} -unset _orca_spawn_orig_zdotdir _orca_user_zdotdir _orca_zshenv_source_dir _orca_zshenv_path _orca_discovered_zdotdir +# Why: use :- after user .zshenv — a pathological unset under set -u must not +# abort the wrapper; empty falls through to the baked-literal branch. +if [[ -n "\${_orca_wrapper_zdotdir_self:-}" && -f "\${_orca_wrapper_zdotdir_self:-}/.zshenv" ]]; then + export ZDOTDIR="\${_orca_wrapper_zdotdir_self:-}" +else + export ZDOTDIR=${quotePosixSingle(zshDir)} +fi +unset _orca_spawn_orig_zdotdir _orca_user_zdotdir _orca_zshenv_source_dir _orca_zshenv_path _orca_discovered_zdotdir _orca_wrapper_zdotdir_self ` } diff --git a/src/main/speech/stt-offline-audio-chunker.test.ts b/src/main/speech/stt-offline-audio-chunker.test.ts new file mode 100644 index 000000000000..4b90976b2c2b --- /dev/null +++ b/src/main/speech/stt-offline-audio-chunker.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from 'vitest' +import { OFFLINE_DECODE_CHUNK_SECONDS, OfflineAudioChunker } from './stt-offline-audio-chunker' + +// Why: a small rate keeps test arrays tiny while exercising the same +// seconds-based limits used with real 16 kHz audio. +const SAMPLE_RATE = 1000 +const CHUNK_LIMIT = OFFLINE_DECODE_CHUNK_SECONDS * SAMPLE_RATE + +function loudSignal(length: number): Float32Array { + const samples = new Float32Array(length) + for (let i = 0; i < length; i += 1) { + samples[i] = Math.sin(i * 0.3) * 0.8 + } + return samples +} + +describe('OfflineAudioChunker', () => { + it('buffers audio below the chunk limit without emitting chunks', () => { + const chunker = new OfflineAudioChunker(SAMPLE_RATE) + + expect(chunker.push(loudSignal(CHUNK_LIMIT - 1))).toEqual([]) + }) + + it('emits a bounded chunk once the limit is reached and keeps the remainder', () => { + const chunker = new OfflineAudioChunker(SAMPLE_RATE) + const total = CHUNK_LIMIT + 500 + + const ready = chunker.push(loudSignal(total)) + const remainder = chunker.flush() + + expect(ready).toHaveLength(1) + expect(ready[0].length).toBeLessThanOrEqual(CHUNK_LIMIT) + expect(ready[0].length).toBeGreaterThan(0) + expect(ready[0].length + (remainder?.length ?? 0)).toBe(total) + }) + + it('never emits a chunk larger than the limit across many small pushes', () => { + const chunker = new OfflineAudioChunker(SAMPLE_RATE) + const emitted: Float32Array[] = [] + const pushSize = 160 + const pushes = Math.ceil((CHUNK_LIMIT * 3.5) / pushSize) + for (let i = 0; i < pushes; i += 1) { + emitted.push(...chunker.push(loudSignal(pushSize))) + } + const remainder = chunker.flush() + + expect(emitted.length).toBeGreaterThanOrEqual(3) + for (const chunk of emitted) { + expect(chunk.length).toBeLessThanOrEqual(CHUNK_LIMIT) + } + const totalOut = emitted.reduce((sum, c) => sum + c.length, 0) + (remainder?.length ?? 0) + expect(totalOut).toBe(pushes * pushSize) + }) + + it('splits multiple chunks out of one oversized push', () => { + const chunker = new OfflineAudioChunker(SAMPLE_RATE) + + const ready = chunker.push(loudSignal(CHUNK_LIMIT * 2 + 100)) + + expect(ready.length).toBeGreaterThanOrEqual(2) + for (const chunk of ready) { + expect(chunk.length).toBeLessThanOrEqual(CHUNK_LIMIT) + } + }) + + it('splits at a silent pause near the chunk boundary instead of mid-speech', () => { + const chunker = new OfflineAudioChunker(SAMPLE_RATE) + const samples = loudSignal(CHUNK_LIMIT + 200) + // Quiet gap 2 s before the limit, inside the 5 s split-search window. + const gapStart = CHUNK_LIMIT - 2 * SAMPLE_RATE + const gapEnd = gapStart + Math.round(0.2 * SAMPLE_RATE) + samples.fill(0, gapStart, gapEnd) + + const [chunk] = chunker.push(samples) + + expect(chunk.length).toBeGreaterThanOrEqual(gapStart) + expect(chunk.length).toBeLessThanOrEqual(gapEnd) + }) + + it('conserves sample values across the split', () => { + const chunker = new OfflineAudioChunker(SAMPLE_RATE) + const samples = loudSignal(CHUNK_LIMIT + 50) + + const [chunk] = chunker.push(samples) + const remainder = chunker.flush() + + const rejoined = new Float32Array(samples.length) + rejoined.set(chunk, 0) + rejoined.set(remainder!, chunk.length) + expect(rejoined).toEqual(samples) + }) + + it('flush returns null when nothing is buffered', () => { + const chunker = new OfflineAudioChunker(SAMPLE_RATE) + + expect(chunker.flush()).toBeNull() + expect(chunker.push(new Float32Array(0))).toEqual([]) + expect(chunker.flush()).toBeNull() + }) +}) diff --git a/src/main/speech/stt-offline-audio-chunker.ts b/src/main/speech/stt-offline-audio-chunker.ts new file mode 100644 index 000000000000..291454bf0835 --- /dev/null +++ b/src/main/speech/stt-offline-audio-chunker.ts @@ -0,0 +1,92 @@ +// Why: offline recognizers decode a whole buffer per call, and ONNX Runtime's +// arena allocations scale with buffer length. Chromium's allocator shim kills +// the entire app on any single allocation >= 2 GiB (#7925), so audio must be +// decoded in bounded chunks regardless of how long dictation runs. +export const OFFLINE_DECODE_CHUNK_SECONDS = 30 + +// Why: cutting audio mid-word degrades transcription at chunk boundaries. +// Search the tail of each chunk for its quietest window and split at its +// center, so cuts land on real inter-word pauses whenever one exists. The +// window must be pause-sized (~100ms): shorter windows match momentary +// quiet inside a word (e.g. plosive closures) and cut mid-word. +const SPLIT_SEARCH_SECONDS = 5 +const SPLIT_ENERGY_WINDOW_SECONDS = 0.1 + +export class OfflineAudioChunker { + private buffered: Float32Array[] = [] + private bufferedSamples = 0 + private readonly chunkSampleLimit: number + private readonly splitSearchSamples: number + private readonly energyWindowSamples: number + + constructor(sampleRate: number) { + this.chunkSampleLimit = Math.max(1, Math.round(OFFLINE_DECODE_CHUNK_SECONDS * sampleRate)) + this.splitSearchSamples = Math.round(SPLIT_SEARCH_SECONDS * sampleRate) + this.energyWindowSamples = Math.max(1, Math.round(SPLIT_ENERGY_WINDOW_SECONDS * sampleRate)) + } + + /** Buffers samples and returns any full chunks now ready to decode. */ + push(samples: Float32Array): Float32Array[] { + if (samples.length === 0) { + return [] + } + this.buffered.push(samples) + this.bufferedSamples += samples.length + + const ready: Float32Array[] = [] + while (this.bufferedSamples >= this.chunkSampleLimit) { + const combined = this.combineBuffered() + const splitIndex = this.findQuietSplitIndex(combined) + ready.push(combined.slice(0, splitIndex)) + const tail = combined.slice(splitIndex) + this.buffered = tail.length > 0 ? [tail] : [] + this.bufferedSamples = tail.length + } + return ready + } + + /** Returns all remaining buffered audio (any length below the chunk limit). */ + flush(): Float32Array | null { + if (this.bufferedSamples === 0) { + return null + } + const combined = this.combineBuffered() + this.buffered = [] + this.bufferedSamples = 0 + return combined + } + + private combineBuffered(): Float32Array { + if (this.buffered.length === 1) { + return this.buffered[0] + } + const combined = new Float32Array(this.bufferedSamples) + let offset = 0 + for (const chunk of this.buffered) { + combined.set(chunk, offset) + offset += chunk.length + } + return combined + } + + private findQuietSplitIndex(samples: Float32Array): number { + const limit = Math.min(this.chunkSampleLimit, samples.length) + const window = this.energyWindowSamples + const searchStart = Math.max(0, limit - this.splitSearchSamples) + const hop = Math.max(1, Math.floor(window / 2)) + let bestIndex = limit + let bestEnergy = Infinity + for (let start = searchStart; start + window <= limit; start += hop) { + let energy = 0 + for (let i = start; i < start + window; i += 1) { + energy += samples[i] * samples[i] + } + if (energy < bestEnergy) { + bestEnergy = energy + bestIndex = start + Math.floor(window / 2) + } + } + // Why: the split must consume at least one sample or push() would loop forever. + return Math.max(1, bestIndex) + } +} diff --git a/src/main/speech/stt-service.test.ts b/src/main/speech/stt-service.test.ts index 5138831d8aed..f35ad4ac5903 100644 --- a/src/main/speech/stt-service.test.ts +++ b/src/main/speech/stt-service.test.ts @@ -17,6 +17,8 @@ const { terminated = false emitStoppedOnStop = true emitReadyOnInit = HoistedMockWorker.emitReadyOnInit + emitExitOnTerminate = true + terminatePromise: Promise | null = null messages: WorkerMessage[] = [] private listeners = new Map void>>() @@ -68,8 +70,10 @@ const { terminate(): Promise { this.terminated = true - this.emit('exit', 0) - return Promise.resolve() + if (this.emitExitOnTerminate) { + this.emit('exit', 0) + } + return this.terminatePromise ?? Promise.resolve() } } @@ -239,6 +243,26 @@ describe('SttService', () => { expect(worker!.messages.filter((message) => message.type === 'feed')).toHaveLength(0) }) + it('drops in-flight audio while stop is waiting for the worker', async () => { + const service = new SttService({ + getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }), + getModelDir: vi.fn().mockReturnValue('/tmp/model-a') + } as never) + + await service.startDictation('model-a', vi.fn(), undefined, 'desktop:1') + const worker = getLastWorker() + expect(worker).toBeDefined() + worker!.emitStoppedOnStop = false + + const stopPromise = service.stopDictation('desktop:1') + await Promise.resolve() + service.feedAudio(new Float32Array([1]), 16000, 'desktop:1') + expect(worker!.messages.filter((message) => message.type === 'feed')).toHaveLength(0) + + worker!.emit('message', { type: 'stopped' }) + await stopPromise + }) + it('rejects deletion prep while the target model is starting', async () => { let resolveModelState: (state: { id: string; status: string }) => void = () => {} const modelStatePromise = new Promise<{ id: string; status: string }>((resolve) => { @@ -457,6 +481,95 @@ describe('SttService', () => { } }) + it('settles stop when the worker exits during stop and does not reuse it', async () => { + const service = new SttService({ + getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }), + getModelDir: vi.fn().mockReturnValue('/tmp/model-a') + } as never) + const events: unknown[] = [] + + await service.startDictation('model-a', (event) => events.push(event), undefined, 'desktop') + const firstWorker = getLastWorker() + expect(firstWorker).toBeDefined() + firstWorker!.emitStoppedOnStop = false + + const stopPromise = service.stopDictation('desktop') + firstWorker!.emit('exit', 1) + await stopPromise + + expect(events).toContainEqual({ type: 'stopped' }) + + await service.startDictation('model-a', vi.fn(), undefined, 'desktop') + + expect(getCreatedWorkerCount()).toBe(2) + expect(getLastWorker()).not.toBe(firstWorker) + }) + + it('settles stop when the worker errors during stop and shares the outcome with follow-up stop', async () => { + const service = new SttService({ + getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }), + getModelDir: vi.fn().mockReturnValue('/tmp/model-a') + } as never) + const events: unknown[] = [] + + await service.startDictation( + 'model-a', + (event) => { + events.push(event) + if (event.type === 'error') { + void service.stopDictation('desktop') + } + }, + undefined, + 'desktop' + ) + const worker = getLastWorker() + expect(worker).toBeDefined() + worker!.emitStoppedOnStop = false + + const stopPromise = service.stopDictation('desktop') + worker!.emit('error', new Error('native failure')) + await stopPromise + + expect(worker!.messages.filter((message) => message.type === 'stop')).toHaveLength(1) + expect(events).toContainEqual({ type: 'error', error: 'Error: native failure' }) + expect(events).toContainEqual({ type: 'stopped' }) + }) + + it('shares one stop message across concurrent stop callers', async () => { + const service = new SttService({ + getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }), + getModelDir: vi.fn().mockReturnValue('/tmp/model-a') + } as never) + + await service.startDictation('model-a', vi.fn(), undefined, 'desktop') + const worker = getLastWorker() + expect(worker).toBeDefined() + worker!.emitStoppedOnStop = false + + const firstStop = service.stopDictation('desktop') + const secondStop = service.stopDictation('desktop') + expect(worker!.messages.filter((message) => message.type === 'stop')).toHaveLength(1) + + worker!.emit('message', { type: 'stopped' }) + await Promise.all([firstStop, secondStop]) + }) + + it('does not emit synthetic stopped when the worker reports stopped', async () => { + const service = new SttService({ + getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }), + getModelDir: vi.fn().mockReturnValue('/tmp/model-a') + } as never) + const events: unknown[] = [] + + await service.startDictation('model-a', (event) => events.push(event), undefined, 'desktop') + await service.stopDictation('desktop') + + expect(events.filter((event) => (event as { type?: string }).type === 'stopped')).toHaveLength( + 1 + ) + }) + it('does not retain or reuse a worker that timed out while stopping', async () => { vi.useFakeTimers() try { @@ -485,4 +598,59 @@ describe('SttService', () => { vi.useRealTimers() } }) + + it('does not wait for worker termination to resolve a timed-out stop', async () => { + vi.useFakeTimers() + try { + const service = new SttService({ + getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }), + getModelDir: vi.fn().mockReturnValue('/tmp/model-a') + } as never) + + await service.startDictation('model-a', vi.fn(), undefined, 'desktop') + const worker = getLastWorker() + expect(worker).toBeDefined() + worker!.emitStoppedOnStop = false + worker!.emitExitOnTerminate = false + worker!.terminatePromise = new Promise(() => {}) + + const stopPromise = service.stopDictation('desktop').then(() => 'resolved') + await vi.advanceTimersByTimeAsync(60_000) + const outcome = await Promise.race([stopPromise, Promise.resolve('pending')]) + + expect(outcome).toBe('resolved') + expect(worker!.terminated).toBe(true) + } finally { + vi.useRealTimers() + } + }) + + it('rejects idle warm reuse when the model is no longer ready', async () => { + let modelStatus = 'ready' + const getModelState = vi.fn().mockImplementation(async () => ({ + id: 'model-a', + status: modelStatus + })) + const service = new SttService({ + getModelState, + getModelDir: vi.fn().mockReturnValue('/tmp/model-a') + } as never) + + await service.startDictation('model-a', vi.fn(), undefined, 'desktop') + const firstWorker = getLastWorker() + expect(firstWorker).toBeDefined() + await service.stopDictation('desktop') + + modelStatus = 'missing' + await expect(service.startDictation('model-a', vi.fn(), undefined, 'desktop')).rejects.toThrow( + 'Model not ready: missing' + ) + expect(firstWorker!.terminated).toBe(true) + + modelStatus = 'ready' + await service.startDictation('model-a', vi.fn(), undefined, 'desktop') + + expect(getCreatedWorkerCount()).toBe(2) + expect(getLastWorker()).not.toBe(firstWorker) + }) }) diff --git a/src/main/speech/stt-service.ts b/src/main/speech/stt-service.ts index d9d2129dd71b..e8b8d5fadb49 100644 --- a/src/main/speech/stt-service.ts +++ b/src/main/speech/stt-service.ts @@ -22,6 +22,14 @@ export type SttEvent = export type SttEventSink = (event: SttEvent) => void +type StopInFlight = { + worker: Worker + owner: string + promise: Promise +} + +type StopOutcome = 'stopped' | 'error' | 'exit' | 'timeout' + export class SttService { private worker: Worker | null = null private cloudSession: OpenAiTranscriptionSession | null = null @@ -35,6 +43,11 @@ export class SttService { private canceledOwners = new Set() private eventSink: SttEventSink | null = null private idleTeardownTimer: NodeJS.Timeout | null = null + private stopInFlight: StopInFlight | null = null + // Why: stop resolves only after the worker flushes; in-flight feedAudio IPC + // must not enqueue samples after that flush or they stick on the warm worker + // and contaminate the next dictation session. + private stopping = false // Why: warm workers intentionally keep lifecycle listeners while reusable; // stale workers must not retain this service after error, exit, or teardown. private cleanupWorkerLifecycleListeners: (() => void) | null = null @@ -91,8 +104,9 @@ export class SttService { if (manifest.provider === 'openai') { if (this.worker) { + const existingWorker = this.worker await this.stopDictation(owner, { cancelStarting: false }) - await this.teardownIdleWorker() + await this.teardownWorker(existingWorker) } const modelState = await this.modelManager.getModelState(modelId) @@ -112,19 +126,37 @@ export class SttService { await this.stopDictation(owner, { cancelStarting: false }) } + const reusableWorker = this.worker if ( - this.worker && + reusableWorker && this.activeModelId === modelId && - this.activeHotwordsFilePath === hotwordsFilePath + this.activeHotwordsFilePath === hotwordsFilePath && + this.stopInFlight?.worker !== reusableWorker ) { - this.eventSink = sink - sink({ type: 'ready' }) - return + const worker = reusableWorker + if (!this.activeOwner) { + const modelState = await this.modelManager.getModelState(modelId) + if (modelState.status !== 'ready') { + await this.teardownWorker(worker) + throw new Error(`Model not ready: ${modelState.status}`) + } + } + if ( + this.worker === worker && + this.activeModelId === modelId && + this.activeHotwordsFilePath === hotwordsFilePath && + this.stopInFlight?.worker !== worker + ) { + this.eventSink = sink + sink({ type: 'ready' }) + return + } } if (this.worker) { + const existingWorker = this.worker await this.stopDictation(owner, { cancelStarting: false }) - await this.teardownIdleWorker() + await this.teardownWorker(existingWorker) } const modelState = await this.modelManager.getModelState(modelId) @@ -194,12 +226,14 @@ export class SttService { }) const onWorkerMessage = (msg: SttEvent) => { - this.eventSink?.(msg) + if (this.worker === worker) { + this.eventSink?.(msg) + } } const onWorkerError = (err: Error) => { - this.eventSink?.({ type: 'error', error: String(err) }) if (this.worker === worker) { + this.eventSink?.({ type: 'error', error: String(err) }) this.cleanupActiveWorkerLifecycleListeners() this.worker = null this.activeModelId = null @@ -259,6 +293,9 @@ export class SttService { } feedAudio(samples: Float32Array, sampleRate: number, owner = 'desktop'): void { + if (this.stopping) { + return + } const currentOwner = this.activeOwner ?? this.startingOwner if (!currentOwner) { return @@ -289,24 +326,29 @@ export class SttService { } if (this.cloudSession) { - const session = this.cloudSession - this.cloudSession = null + this.stopping = true try { - const text = await session.finish() - if (text) { - this.eventSink?.({ type: 'final', text }) + const session = this.cloudSession + this.cloudSession = null + try { + const text = await session.finish() + if (text) { + this.eventSink?.({ type: 'final', text }) + } + } catch (error) { + this.eventSink?.({ + type: 'error', + error: error instanceof Error ? error.message : String(error) + }) + } finally { + this.eventSink?.({ type: 'stopped' }) + this.activeModelId = null + this.activeHotwordsFilePath = undefined + this.activeOwner = null + this.eventSink = null } - } catch (error) { - this.eventSink?.({ - type: 'error', - error: error instanceof Error ? error.message : String(error) - }) } finally { - this.eventSink?.({ type: 'stopped' }) - this.activeModelId = null - this.activeHotwordsFilePath = undefined - this.activeOwner = null - this.eventSink = null + this.stopping = false } return } @@ -315,11 +357,36 @@ export class SttService { if (!worker) { return } - worker.postMessage({ type: 'stop' }) + if (this.stopInFlight?.worker === worker) { + if (this.stopInFlight.owner !== owner) { + throw new Error('dictation_owner_mismatch') + } + return this.stopInFlight.promise + } - let forcedTeardown = false - await new Promise((resolve) => { + const capturedSink = this.eventSink + let stopPromise!: Promise + stopPromise = this.createStopPromise(worker, capturedSink).finally(() => { + if (this.stopInFlight?.worker === worker && this.stopInFlight.promise === stopPromise) { + this.stopInFlight = null + } + }) + this.stopInFlight = { worker, owner, promise: stopPromise } + this.stopping = true + try { + // Why: keep the stop message inside the try so a postMessage throw still + // clears `stopping` — otherwise feedAudio silently drops all future audio. + worker.postMessage({ type: 'stop' }) + await stopPromise + } finally { + this.stopping = false + } + } + + private createStopPromise(worker: Worker, capturedSink: SttEventSink | null): Promise { + return new Promise((resolve) => { let settled = false + let receivedStopped = false let timeout: ReturnType | null = null const cleanup = (): void => { @@ -328,53 +395,70 @@ export class SttService { timeout = null } worker.off('message', onStopped) + worker.off('error', onError) + worker.off('exit', onExit) } - const finish = (): void => { + const finish = (outcome: StopOutcome): void => { if (settled) { return } settled = true cleanup() + if (outcome === 'stopped') { + if (this.worker === worker) { + this.activeOwner = null + this.eventSink = null + this.scheduleIdleTeardown() + } + resolve() + return + } + + if (!receivedStopped) { + capturedSink?.({ type: 'stopped' }) + } + // Why: a worker that cannot finish dictation is no longer reusable; drop + // its lifecycle listeners so a stale worker can't retain this service. + this.cleanupActiveWorkerLifecycleListeners() + worker.removeAllListeners() + if (outcome !== 'exit') { + void worker.terminate().catch(() => undefined) + } + if (this.worker === worker) { + this.worker = null + this.activeModelId = null + this.activeHotwordsFilePath = undefined + this.activeOwner = null + this.eventSink = null + } resolve() } const onStopped = (msg: { type: string; text?: string; error?: string }) => { if (msg.type === 'stopped') { - finish() + receivedStopped = true + finish('stopped') } } + const onError = (): void => { + finish('error') + } + + const onExit = (): void => { + finish('exit') + } + timeout = setTimeout(() => { - if (settled) { - return - } - settled = true - forcedTeardown = true - cleanup() - // Why: a worker that cannot finish dictation is no longer reusable; do - // not keep it in the warm-worker slot or retain its message listeners. - this.cleanupActiveWorkerLifecycleListeners() - worker.removeAllListeners() - void worker.terminate().finally(resolve) + finish('timeout') }, STOP_DICTATION_TIMEOUT_MS) + timeout.unref?.() worker.on('message', onStopped) + worker.on('error', onError) + worker.on('exit', onExit) }) - - if (this.worker === worker) { - if (forcedTeardown) { - this.worker = null - this.activeModelId = null - this.activeHotwordsFilePath = undefined - this.activeOwner = null - this.eventSink = null - } else { - this.activeOwner = null - this.eventSink = null - this.scheduleIdleTeardown() - } - } } isActive(): boolean { @@ -429,8 +513,24 @@ export class SttService { if (!this.worker || this.activeOwner || this.startingOwner) { return } - const worker = this.worker - worker.postMessage({ type: 'teardown' }) + await this.teardownWorker(this.worker, options) + } + + private async teardownWorker( + worker: Worker, + options: { ignoreTerminateErrors?: boolean } = { ignoreTerminateErrors: true } + ): Promise { + this.clearIdleTeardownTimer() + if (this.stopInFlight?.worker === worker) { + await this.stopInFlight.promise + } + try { + worker.postMessage({ type: 'teardown' }) + } catch { + // The worker may already have exited on a forced stop path. + } + this.cleanupActiveWorkerLifecycleListeners() + worker.removeAllListeners() try { await worker.terminate() } catch (error) { @@ -438,12 +538,11 @@ export class SttService { throw error } } - this.cleanupActiveWorkerLifecycleListeners() - worker.removeAllListeners() if (this.worker === worker) { this.worker = null this.activeModelId = null this.activeHotwordsFilePath = undefined + this.activeOwner = null this.eventSink = null } } diff --git a/src/main/speech/stt-worker-model-config.ts b/src/main/speech/stt-worker-model-config.ts new file mode 100644 index 000000000000..de4687d9f468 --- /dev/null +++ b/src/main/speech/stt-worker-model-config.ts @@ -0,0 +1,81 @@ +import { readdirSync } from 'node:fs' +import { join } from 'node:path' + +// Why: different models name their ONNX files differently (e.g. +// encoder.int8.onnx vs tiny-encoder.onnx vs encoder-epoch-99-avg-1.onnx). +// We resolve the actual path from the manifest's files list by searching +// for the role name anywhere in the filename. +export function resolveFile( + files: string[], + role: string, + modelDir: string, + ext = '.onnx' +): string { + const match = files.find((f) => f.includes(role) && f.endsWith(ext)) + if (!match) { + throw new Error(`No *${role}*${ext} found in model files: ${files.join(', ')}`) + } + return join(modelDir, match) +} + +export function resolveTokens(files: string[], modelDir: string): string { + const match = files.find((f) => f.endsWith('tokens.txt')) + if (!match) { + throw new Error(`No *tokens.txt found in model files: ${files.join(', ')}`) + } + return join(modelDir, match) +} + +// Why: BPE models need a vocab file for hotwords token matching. The file +// ships in the model archive but isn't listed in the manifest. We discover +// it at runtime to avoid breaking existing downloads. +function discoverBpeVocab(modelDir: string): string | undefined { + try { + const entries = readdirSync(modelDir) + const vocabFile = entries.find((f) => f.endsWith('.vocab')) + return vocabFile ? join(modelDir, vocabFile) : undefined + } catch { + return undefined + } +} + +export type HotwordsConfig = { + decodingMethod: string + hotwordsFile?: string + hotwordsScore?: number + modelingUnit?: string + bpeVocab?: string +} + +export function buildHotwordsConfig(opts: { + modelDir: string + modelType: string + hotwordsFilePath?: string + modelingUnit?: string +}): HotwordsConfig { + if (opts.modelType !== 'transducer' || !opts.hotwordsFilePath) { + return { decodingMethod: 'greedy_search' } + } + + const unit = opts.modelingUnit + if (unit?.includes('bpe')) { + const bpeVocab = discoverBpeVocab(opts.modelDir) + if (!bpeVocab) { + return { decodingMethod: 'greedy_search' } + } + return { + decodingMethod: 'modified_beam_search', + hotwordsFile: opts.hotwordsFilePath, + hotwordsScore: 1.5, + modelingUnit: unit, + bpeVocab + } + } + + return { + decodingMethod: 'modified_beam_search', + hotwordsFile: opts.hotwordsFilePath, + hotwordsScore: 1.5, + modelingUnit: unit + } +} diff --git a/src/main/speech/stt-worker.ts b/src/main/speech/stt-worker.ts index 9456f95c8b5a..1e6cd8bb75c5 100644 --- a/src/main/speech/stt-worker.ts +++ b/src/main/speech/stt-worker.ts @@ -1,7 +1,8 @@ /* oxlint-disable typescript-eslint/no-explicit-any -- sherpa-onnx native addon has no type definitions */ import { parentPort, workerData } from 'node:worker_threads' -import { readdirSync } from 'node:fs' import { resampleToRate } from './stt-audio-resample' +import { OfflineAudioChunker } from './stt-offline-audio-chunker' +import { buildHotwordsConfig, resolveFile, resolveTokens } from './stt-worker-model-config' type WorkerMessage = | { @@ -27,7 +28,7 @@ let sherpa: any = null let recognizer: any = null let stream: any = null let isStreaming = false -let offlineBuffer: Float32Array[] = [] +let offlineChunker: OfflineAudioChunker | null = null let offlineSampleRate = 16000 function loadSherpa(): any { @@ -38,80 +39,13 @@ function loadSherpa(): any { return require(modulePath) } -// Why: different models name their ONNX files differently (e.g. -// encoder.int8.onnx vs tiny-encoder.onnx vs encoder-epoch-99-avg-1.onnx). -// We resolve the actual path from the manifest's files list by searching -// for the role name anywhere in the filename. -function resolveFile(files: string[], role: string, modelDir: string, ext = '.onnx'): string { - const match = files.find((f) => f.includes(role) && f.endsWith(ext)) - if (!match) { - throw new Error(`No *${role}*${ext} found in model files: ${files.join(', ')}`) - } - return `${modelDir}/${match}` -} - -function resolveTokens(files: string[], modelDir: string): string { - const match = files.find((f) => f.endsWith('tokens.txt')) - if (!match) { - throw new Error(`No *tokens.txt found in model files: ${files.join(', ')}`) - } - return `${modelDir}/${match}` -} - -// Why: BPE models need a vocab file for hotwords token matching. The file -// ships in the model archive but isn't listed in the manifest. We discover -// it at runtime to avoid breaking existing downloads. -function discoverBpeVocab(modelDir: string): string | undefined { - try { - const entries = readdirSync(modelDir) - const vocabFile = entries.find((f) => f.endsWith('.vocab')) - return vocabFile ? `${modelDir}/${vocabFile}` : undefined - } catch { - return undefined - } -} - -function buildHotwordsConfig(msg: Extract): { - decodingMethod: string - hotwordsFile?: string - hotwordsScore?: number - modelingUnit?: string - bpeVocab?: string -} { - if (msg.modelType !== 'transducer' || !msg.hotwordsFilePath) { - return { decodingMethod: 'greedy_search' } - } - - const unit = msg.modelingUnit - if (unit?.includes('bpe')) { - const bpeVocab = discoverBpeVocab(msg.modelDir) - if (!bpeVocab) { - return { decodingMethod: 'greedy_search' } - } - return { - decodingMethod: 'modified_beam_search', - hotwordsFile: msg.hotwordsFilePath, - hotwordsScore: 1.5, - modelingUnit: unit, - bpeVocab - } - } - - return { - decodingMethod: 'modified_beam_search', - hotwordsFile: msg.hotwordsFilePath, - hotwordsScore: 1.5, - modelingUnit: unit - } -} - function handleInit(msg: Extract): void { try { sherpa = loadSherpa() const { modelDir, modelType, streaming, sampleRate, files } = msg isStreaming = streaming - offlineBuffer = [] + offlineChunker = streaming ? null : new OfflineAudioChunker(sampleRate) offlineSampleRate = sampleRate const tokens = resolveTokens(files, modelDir) @@ -203,6 +137,35 @@ function handleInit(msg: Extract): void { } } +// Why: an offline stream is single-use — always mint a fresh stream after an +// attempt so a failed decode cannot leave a spent stream on a warm worker. +function decodeOfflineChunk(samples: Float32Array): string { + try { + sherpa.acceptWaveformOffline(stream, { sampleRate: offlineSampleRate, samples }) + sherpa.decodeOfflineStream(recognizer, stream) + const resultJson = sherpa.getOfflineStreamResultAsJson(stream) + const result = JSON.parse(resultJson) + return result?.text?.trim() ?? '' + } finally { + if (sherpa && recognizer) { + stream = sherpa.createOfflineStream(recognizer) + } + } +} + +// Why: warm-worker reuse must not see residual audio or a spent offline stream. +// Recovery failures are swallowed so they cannot skip the stopped lifecycle signal. +function resetOfflineSessionState(): void { + try { + offlineChunker = new OfflineAudioChunker(offlineSampleRate) + if (sherpa && recognizer) { + stream = sherpa.createOfflineStream(recognizer) + } + } catch { + // Non-fatal: prefer posting stopped over stranding stopDictation for 60s. + } +} + function handleFeed(msg: Extract): void { if (!recognizer || !stream) { return @@ -236,9 +199,28 @@ function handleFeed(msg: Extract): void { sherpa.reset(recognizer, stream) } } else { - // Why: offline recognizers cannot decode incrementally — they need all - // audio buffered first, then decoded in one shot when dictation stops. - offlineBuffer.push(new Float32Array(samples)) + // Why: decoding one unbounded capture in a single call makes ONNX tensor + // sizes scale with dictation length until a >=2 GiB allocation SIGTRAPs + // the whole app (#7925). Decode bounded chunks as they fill instead; + // each consumer already appends multiple 'final' segments per session. + const readyChunks = offlineChunker?.push(new Float32Array(samples)) ?? [] + // Why: keep decoding later ready windows after one failure — push() has + // already removed them from the chunker, and decodeOfflineChunk refreshes + // the stream in finally so a spent stream cannot poison the next attempt. + let firstError: unknown = null + for (const chunk of readyChunks) { + try { + const text = decodeOfflineChunk(chunk) + if (text) { + parentPort?.postMessage({ type: 'final', text }) + } + } catch (err) { + firstError ??= err + } + } + if (firstError) { + throw firstError + } } } catch (err) { parentPort?.postMessage({ type: 'error', error: String(err) }) @@ -265,40 +247,33 @@ function handleStop(): void { } stream = sherpa.createOnlineStream(recognizer) } else { - // Why: offline recognizer decodes all audio at once — concatenate - // buffered chunks into a single Float32Array and feed it to the stream. - const totalLength = offlineBuffer.reduce((sum, chunk) => sum + chunk.length, 0) - if (totalLength > 0) { - const combined = new Float32Array(totalLength) - let offset = 0 - for (const chunk of offlineBuffer) { - combined.set(chunk, offset) - offset += chunk.length - } - sherpa.acceptWaveformOffline(stream, { sampleRate: offlineSampleRate, samples: combined }) - sherpa.decodeOfflineStream(recognizer, stream) - const resultJson = sherpa.getOfflineStreamResultAsJson(stream) - const result = JSON.parse(resultJson) - const text = result?.text?.trim() + // Why: the remainder is below the chunk limit by construction, so this + // last decode is bounded too. + const remaining = offlineChunker?.flush() + if (remaining && remaining.length > 0) { + const text = decodeOfflineChunk(remaining) if (text) { parentPort?.postMessage({ type: 'final', text }) } } - offlineBuffer = [] - stream = sherpa.createOfflineStream(recognizer) + resetOfflineSessionState() } } catch (err) { + if (!isStreaming) { + resetOfflineSessionState() + } parentPort?.postMessage({ type: 'error', error: String(err) }) + } finally { + // Why: stopDictation waits on this signal; recovery must never prevent it. + parentPort?.postMessage({ type: 'stopped' }) } - - parentPort?.postMessage({ type: 'stopped' }) } function handleTeardown(): void { stream = null recognizer = null sherpa = null - offlineBuffer = [] + offlineChunker = null process.exit(0) } diff --git a/src/main/ssh/relay-protocol.test.ts b/src/main/ssh/relay-protocol.test.ts index c4e9f089743c..459eaef88df1 100644 --- a/src/main/ssh/relay-protocol.test.ts +++ b/src/main/ssh/relay-protocol.test.ts @@ -8,10 +8,27 @@ import { FrameDecoder, parseJsonRpcMessage, parseUnameToRelayPlatform, + isGitResponseStreamMarker, type JsonRpcRequest, type DecodedFrame } from './relay-protocol' +describe('git response stream marker', () => { + it('accepts only complete non-negative integer metadata', () => { + expect( + isGitResponseStreamMarker({ + __orcaGitResponseStream: { streamId: 1, totalBytes: 1024, chunkCount: 2 } + }) + ).toBe(true) + expect(isGitResponseStreamMarker({ __orcaGitResponseStream: {} })).toBe(false) + expect( + isGitResponseStreamMarker({ + __orcaGitResponseStream: { streamId: -1, totalBytes: 1024, chunkCount: 2 } + }) + ).toBe(false) + }) +}) + describe('frame encoding', () => { it('encodes a frame with 13-byte header', () => { const payload = Buffer.from('hello') diff --git a/src/main/ssh/relay-protocol.ts b/src/main/ssh/relay-protocol.ts index db57c4d19aa0..c05b6c33bfe3 100644 --- a/src/main/ssh/relay-protocol.ts +++ b/src/main/ssh/relay-protocol.ts @@ -55,6 +55,45 @@ export const STREAM_CHUNK_SIZE = 256 * 1024 * client. */ export const MAX_CONCURRENT_STREAMS = 16 +// ── Git response streaming (see docs/relay-git-response-stream-design.md) ── + +/** Serialized-JSON size above which the relay chunks a streamable git response + * (diff family + exec) onto the bulk lane instead of one JSON-RPC frame. Mirror + * of the relay-side constant; the client only opts in — the relay owns the + * decision — so this is documentation of the shared contract. */ +export const GIT_RESPONSE_STREAM_THRESHOLD = 256 * 1024 + +/** Per-chunk size (serialized-result UTF-8 bytes) for git response streaming. + * The client reassembles by concatenation and does not depend on this value, + * so it stays cross-version safe. */ +export const GIT_RESPONSE_CHUNK_SIZE = 128 * 1024 + +/** Sentinel the relay returns as the RPC result when the real payload streams + * as git.responseChunk frames. Absent from old relays, so a new client falls + * back to the plain result they return. */ +export type GitResponseStreamMarker = { + __orcaGitResponseStream: { streamId: number; totalBytes: number; chunkCount: number } +} + +export function isGitResponseStreamMarker(value: unknown): value is GitResponseStreamMarker { + if (typeof value !== 'object' || value === null || !('__orcaGitResponseStream' in value)) { + return false + } + const marker = (value as { __orcaGitResponseStream?: unknown }).__orcaGitResponseStream + if (typeof marker !== 'object' || marker === null) { + return false + } + const fields = marker as Record + return ( + Number.isInteger(fields.streamId) && + (fields.streamId as number) > 0 && + Number.isInteger(fields.totalBytes) && + (fields.totalBytes as number) >= 0 && + Number.isInteger(fields.chunkCount) && + (fields.chunkCount as number) >= 0 + ) +} + // ── JSON-RPC types ────────────────────────────────────────────────── export type JsonRpcRequest = { diff --git a/src/main/ssh/ssh-channel-multiplexer.test.ts b/src/main/ssh/ssh-channel-multiplexer.test.ts index 8c56ae145b09..10123d56a254 100644 --- a/src/main/ssh/ssh-channel-multiplexer.test.ts +++ b/src/main/ssh/ssh-channel-multiplexer.test.ts @@ -307,6 +307,81 @@ describe('SshChannelMultiplexer', () => { }) }) + describe('wake guard (timer pause across system sleep, #7773)', () => { + it('does not kill a healthy link on the first tick after a long timer pause', () => { + // Reach steady state with pending unacked keepalives (<5s old at pause). + vi.advanceTimersByTime(5_000) + expect(mux.isDisposed()).toBe(false) + + // Simulate sleep/App Nap: wall clock jumps far ahead with no ticks. + // Without the guard, the first post-wake tick sees lastReceivedAt and + // the pre-pause keepalive both >20s stale and disposes the mux. + vi.setSystemTime(Date.now() + 60 * 60 * 1000) + const writesBefore = transport.written.length + vi.advanceTimersByTime(5_000) + + expect(mux.isDisposed()).toBe(false) + // The guard probes immediately with a fresh keepalive. + expect(transport.written.length).toBeGreaterThan(writesBefore) + expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive) + }) + + it('keeps the link alive after wake when frames resume', () => { + vi.advanceTimersByTime(5_000) + vi.setSystemTime(Date.now() + 60 * 60 * 1000) + vi.advanceTimersByTime(5_000) // guard tick + + // The relay answers the post-wake probe; the link must stay up. + let seq = 1 + for (let i = 0; i < 8; i++) { + vi.advanceTimersByTime(5_000) + transport.dataCallbacks[0](encodeKeepAliveFrame(seq++, 0)) + } + expect(mux.isDisposed()).toBe(false) + }) + + it('still detects a genuinely dead link within the next window after wake', () => { + vi.advanceTimersByTime(5_000) + vi.setSystemTime(Date.now() + 60 * 60 * 1000) + vi.advanceTimersByTime(5_000) // guard tick: reset + probe, no kill + + expect(mux.isDisposed()).toBe(false) + // No frames arrive after the guard reset; the honest window expires. + vi.advanceTimersByTime(25_000) + expect(mux.isDisposed()).toBe(true) + }) + }) + + describe('probeLiveness', () => { + it('sends a keepalive and resolves true when any frame arrives', async () => { + const writesBefore = transport.written.length + const probe = mux.probeLiveness(5_000) + + expect(transport.written.length).toBe(writesBefore + 1) + expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive) + + transport.dataCallbacks[0](encodeKeepAliveFrame(1, 0)) + await expect(probe).resolves.toBe(true) + }) + + it('resolves false when no frame arrives before the timeout', async () => { + const probe = mux.probeLiveness(5_000) + vi.advanceTimersByTime(5_000) + await expect(probe).resolves.toBe(false) + }) + + it('resolves false when the mux is disposed while probing', async () => { + const probe = mux.probeLiveness(5_000) + mux.dispose() + await expect(probe).resolves.toBe(false) + }) + + it('resolves false immediately on a disposed mux', async () => { + mux.dispose() + await expect(mux.probeLiveness(5_000)).resolves.toBe(false) + }) + }) + describe('dispose', () => { it('rejects all pending requests on dispose', async () => { const promise = mux.request('pty.spawn') diff --git a/src/main/ssh/ssh-channel-multiplexer.ts b/src/main/ssh/ssh-channel-multiplexer.ts index 09642387ee81..8cb0a24f3026 100644 --- a/src/main/ssh/ssh-channel-multiplexer.ts +++ b/src/main/ssh/ssh-channel-multiplexer.ts @@ -34,6 +34,9 @@ export type MethodNotificationHandler = (params: Record) => voi export type RequestHandler = (params: Record) => Promise | unknown const REQUEST_TIMEOUT_MS = 30_000 +// Why: a tick gap far beyond the interval means the process was paused +// (system sleep, App Nap timer throttling) — not that the link is dead (#7773). +const WAKE_GAP_MS = KEEPALIVE_SEND_MS * 3 export class SshChannelMultiplexer { private decoder: FrameDecoder @@ -58,6 +61,10 @@ export class SshChannelMultiplexer { // Track the oldest unacked outgoing message timestamp private unackedTimestamps = new Map() + // Why: liveness probes (#7773) resolve on the first frame of any kind — + // a keepalive ack proves the relay round-trip without a full RPC. + private livenessProbeWaiters: { succeed: () => void; fail: () => void }[] = [] + constructor(transport: MultiplexerTransport) { this.transport = transport @@ -232,6 +239,31 @@ export class SshChannelMultiplexer { this.sendMessage(msg) } + /** + * Send a fresh keepalive and resolve true when any frame arrives before the + * timeout. Used on system resume to distinguish a link that survived sleep + * from a dead one before tearing the session down (#7773). + */ + probeLiveness(timeoutMs: number): Promise { + if (this.disposed) { + return Promise.resolve(false) + } + return new Promise((resolve) => { + const settle = (alive: boolean): void => { + clearTimeout(timer) + const idx = this.livenessProbeWaiters.indexOf(waiter) + if (idx !== -1) { + this.livenessProbeWaiters.splice(idx, 1) + } + resolve(alive) + } + const waiter = { succeed: () => settle(true), fail: () => settle(false) } + const timer = setTimeout(() => settle(false), timeoutMs) + this.livenessProbeWaiters.push(waiter) + this.sendKeepAlive() + }) + } + dispose(reason: 'shutdown' | 'connection_lost' = 'shutdown'): void { if (this.disposed) { return @@ -259,6 +291,10 @@ export class SshChannelMultiplexer { reason === 'connection_lost' ? 'SSH connection lost, reconnecting...' : 'Multiplexer disposed' const errorCode = reason === 'connection_lost' ? 'CONNECTION_LOST' : 'DISPOSED' + for (const waiter of this.livenessProbeWaiters.splice(0)) { + waiter.fail() + } + for (const [id, pending] of this.pendingRequests) { pending.cleanup() const err = new Error(errorMessage) as Error & { code: string } @@ -322,6 +358,12 @@ export class SshChannelMultiplexer { } private handleFrame(frame: DecodedFrame): void { + // Why: any decoded frame proves the relay round-trip is alive; resolve + // pending resume probes before ordinary dispatch (#7773). + for (const waiter of this.livenessProbeWaiters.splice(0)) { + waiter.succeed() + } + // Update ack tracking if (frame.id > this.highestReceivedSeq) { this.highestReceivedSeq = frame.id @@ -453,12 +495,28 @@ export class SshChannelMultiplexer { } private startTimeoutCheck(): void { + let lastTickAt = Date.now() this.timeoutTimer = setInterval(() => { if (this.disposed) { return } const now = Date.now() + const sinceLastTick = now - lastTickAt + lastTickAt = now + // Why: after sleep/App Nap the pre-pause keepalive looks stale on the + // first post-wake tick, killing a healthy link (#7773). Reset staleness + // tracking, probe with a fresh keepalive, and let the NEXT full window + // make an honest liveness determination. + if (sinceLastTick > WAKE_GAP_MS) { + this.lastReceivedAt = now + for (const seq of this.unackedTimestamps.keys()) { + this.unackedTimestamps.set(seq, now) + } + this.sendKeepAlive() + return + } + const noDataReceived = now - this.lastReceivedAt > TIMEOUT_MS // Check oldest unacked message diff --git a/src/main/ssh/ssh-connection-store.test.ts b/src/main/ssh/ssh-connection-store.test.ts index f1bf80d17aa9..02e69c6dc974 100644 --- a/src/main/ssh/ssh-connection-store.test.ts +++ b/src/main/ssh/ssh-connection-store.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { SshConnectionStore } from './ssh-connection-store' -import type { SshTarget } from '../../shared/ssh-types' +import type { RemovedSshTargetTombstone, SshTarget } from '../../shared/ssh-types' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), @@ -15,6 +15,8 @@ vi.mock('./ssh-config-parser', () => ({ function createMockStore() { const targets: SshTarget[] = [] let deletedAliases: string[] = [] + const removedTombstones: RemovedSshTargetTombstone[] = [] + const reassignments: { oldTargetId: string; newTargetId: string }[] = [] return { getSshTargets: vi.fn(() => [...targets]), @@ -45,6 +47,24 @@ function createMockStore() { }), clearDeletedSshConfigAliases: vi.fn(() => { deletedAliases = [] + }), + removedTombstones, + reassignments, + getRemovedSshTargetTombstones: vi.fn(() => [...removedTombstones]), + addRemovedSshTargetTombstone: vi.fn((tombstone: RemovedSshTargetTombstone) => { + const filtered = removedTombstones.filter((t) => t.oldTargetId !== tombstone.oldTargetId) + removedTombstones.length = 0 + removedTombstones.push(...filtered, tombstone) + }), + removeRemovedSshTargetTombstone: vi.fn((oldTargetId: string) => { + const kept = removedTombstones.filter((t) => t.oldTargetId !== oldTargetId) + removedTombstones.length = 0 + removedTombstones.push(...kept) + }), + reassignSshTargetId: vi.fn((oldTargetId: string, newTargetId: string) => { + reassignments.push({ oldTargetId, newTargetId }) + // Pretend one repo referenced the old id. + return 1 }) } } @@ -439,4 +459,140 @@ describe('SshConnectionStore', () => { expect(result).toHaveLength(1) }) }) + + describe('re-adoption of orphaned workspaces', () => { + it('records a tombstone when removing any user-facing target', () => { + mockStore.addSshTarget({ + id: 'ssh-1', + label: 'Dev', + host: 'dev.example.com', + port: 22, + username: 'tim', + source: 'manual' + }) + + sshStore.removeTarget('ssh-1') + + expect(mockStore.addRemovedSshTargetTombstone).toHaveBeenCalledWith( + expect.objectContaining({ + oldTargetId: 'ssh-1', + host: 'dev.example.com', + port: 22, + username: 'tim' + }) + ) + }) + + it('does not tombstone runtime-owned targets', () => { + mockStore.addSshTarget({ + id: 'runtime-ssh-abc', + label: 'VM', + host: 'vm.example.com', + port: 22, + username: 'tim', + owner: { type: 'on-demand-runtime', runtimeId: 'abc' } + }) + + sshStore.removeTarget('runtime-ssh-abc') + + expect(mockStore.addRemovedSshTargetTombstone).not.toHaveBeenCalled() + }) + + it('re-adopts orphaned repos when the same host is re-added', () => { + // Simulate a prior removal by seeding a matching tombstone. + mockStore.addRemovedSshTargetTombstone({ + oldTargetId: 'ssh-old', + host: 'dev.example.com', + port: 22, + username: 'tim', + label: 'Dev', + removedAt: 1 + }) + + sshStore.addTarget({ + label: 'Dev', + host: 'dev.example.com', + port: 22, + username: 'tim' + }) + + expect(mockStore.reassignSshTargetId).toHaveBeenCalledTimes(1) + const [oldId, newId] = mockStore.reassignSshTargetId.mock.calls[0] + expect(oldId).toBe('ssh-old') + expect(newId).toMatch(/^ssh-/) + // Re-adoption count surfaces so the IPC layer can refresh the repo list. + expect(sshStore.lastReadoptedRepoCount).toBe(1) + }) + + // Why: drive the real remove→re-add path so the tombstone carries the + // defaulted configHost (host) that buildRemovedSshTargetTombstone produces, + // rather than a hand-seeded tombstone without one. + it('re-adopts through an actual removeTarget then re-add of the same host', () => { + const added = sshStore.addTarget({ + label: 'Dev', + host: 'dev.example.com', + port: 22, + username: 'tim' + }) + sshStore.removeTarget(added.id) + // The tombstone was built from the real target (configHost defaulted to host). + const tombstones = mockStore.getRemovedSshTargetTombstones() + expect(tombstones).toHaveLength(1) + expect(tombstones[0]).toMatchObject({ oldTargetId: added.id, configHost: 'dev.example.com' }) + + mockStore.reassignSshTargetId.mockClear() + const readded = sshStore.addTarget({ + label: 'Dev', + host: 'dev.example.com', + port: 22, + username: 'tim' + }) + + expect(mockStore.reassignSshTargetId).toHaveBeenCalledWith(added.id, readded.id) + expect(sshStore.lastReadoptedRepoCount).toBe(1) + }) + + // A different account on the SAME host must NOT re-adopt, even though both + // manual adds default configHost to the shared hostname. + it('does not re-adopt a different account on the same host', () => { + const alice = sshStore.addTarget({ + label: 'alice', + host: 'dev.example.com', + port: 22, + username: 'alice' + }) + sshStore.removeTarget(alice.id) + mockStore.reassignSshTargetId.mockClear() + + sshStore.addTarget({ + label: 'bob', + host: 'dev.example.com', + port: 2222, + username: 'bob' + }) + + expect(mockStore.reassignSshTargetId).not.toHaveBeenCalled() + }) + + it('does not re-adopt when the re-added host identity differs', () => { + mockStore.addRemovedSshTargetTombstone({ + oldTargetId: 'ssh-old', + host: 'other.example.com', + port: 22, + username: 'root', + label: 'Other', + removedAt: 1 + }) + + sshStore.addTarget({ + label: 'Dev', + host: 'dev.example.com', + port: 22, + username: 'tim' + }) + + expect(mockStore.reassignSshTargetId).not.toHaveBeenCalled() + expect(sshStore.lastReadoptedRepoCount).toBe(0) + }) + }) }) diff --git a/src/main/ssh/ssh-connection-store.ts b/src/main/ssh/ssh-connection-store.ts index 975da8cdbc25..df3e6cd8fee8 100644 --- a/src/main/ssh/ssh-connection-store.ts +++ b/src/main/ssh/ssh-connection-store.ts @@ -2,6 +2,10 @@ import type { Store } from '../persistence' import type { SshTarget } from '../../shared/ssh-types' import { RUNTIME_OWNED_SSH_TARGET_ID_PREFIX } from '../../shared/execution-host' import { loadUserSshConfig, sshConfigHostsToTargets } from './ssh-config-parser' +import { + buildRemovedSshTargetTombstone, + readoptOrphanedWorkspacesForTarget +} from './ssh-target-readoption' export class SshConnectionStore { constructor(private store: Store) {} @@ -10,6 +14,17 @@ export class SshConnectionStore { return this.store.getSshTargets().filter((target) => !isRuntimeOwnedSshTarget(target)) } + /** Map of removed-target id → its last known label, from the re-adoption + * tombstones. Lets the renderer show a friendly host name for a workspace + * still pinned to a target that no longer exists. */ + listRemovedTargetLabels(): Record { + const labels: Record = {} + for (const tombstone of this.store.getRemovedSshTargetTombstones()) { + labels[tombstone.oldTargetId] = tombstone.label + } + return labels + } + getTarget(id: string): SshTarget | undefined { return this.store.getSshTarget(id) } @@ -27,9 +42,17 @@ export class SshConnectionStore { // keep it — lift any tombstone so config sync stops suppressing this alias. this.reclaimAlias(full.configHost ?? full.label) this.store.addSshTarget(full) + // Why: re-adopt workspaces that were orphaned when the same host was removed + // (repos/worktrees still point at the old, now-dead target id). Track the + // count so the IPC layer knows whether to refresh the repo list. + this.lastReadoptedRepoCount = readoptOrphanedWorkspacesForTarget(this.store, full) return full } + /** Repos re-adopted by the most recent addTarget/importFromSshConfig call. + * Lets the IPC layer broadcast repos:changed only when workspaces reattached. */ + lastReadoptedRepoCount = 0 + upsertRuntimeOwnedTarget( runtimeId: string, target: Omit @@ -75,6 +98,13 @@ export class SshConnectionStore { this.store.addDeletedSshConfigAlias(alias) } } + // Why: record the removed target's host identity (for ALL user-facing + // targets, config-managed or manual) so a later re-add of the same host can + // re-adopt any workspaces orphaned on this id. Runtime-owned targets manage + // their own lifecycle and are never re-adopted. + if (target && !isRuntimeOwnedSshTarget(target)) { + this.store.addRemovedSshTargetTombstone(buildRemovedSshTargetTombstone(target, Date.now())) + } this.store.removeSshTarget(id) } @@ -90,6 +120,7 @@ export class SshConnectionStore { * manual targets. Returns the inserted and updated targets. */ importFromSshConfig(options?: { reAdopt?: boolean }): SshTarget[] { + let readoptedThisImport = 0 // Why: the explicit Import action re-adopts every config host, so it clears // all tombstones first. The passive on-open sync passes no flag and keeps // deleted hosts suppressed. @@ -178,10 +209,15 @@ export class SshConnectionStore { } else { const inserted: SshTarget = { ...candidate, source: 'ssh-config' } this.store.addSshTarget(inserted) + // Why: a freshly-inserted config host may be one the user removed and is + // now re-importing — re-adopt its orphaned workspaces. Updated-in-place + // targets keep their id, so their repos were never orphaned. + readoptedThisImport += readoptOrphanedWorkspacesForTarget(this.store, inserted) changed.push(inserted) } } + this.lastReadoptedRepoCount = readoptedThisImport return changed } } diff --git a/src/main/ssh/ssh-git-response-stream-reader.ts b/src/main/ssh/ssh-git-response-stream-reader.ts new file mode 100644 index 000000000000..ef63c7a6dc00 --- /dev/null +++ b/src/main/ssh/ssh-git-response-stream-reader.ts @@ -0,0 +1,311 @@ +import type { SshChannelMultiplexer } from './ssh-channel-multiplexer' +import { RelayErrorCode, isGitResponseStreamMarker } from './relay-protocol' + +const SENTINEL_STREAM_ID = -1 + +/** Reject if no stream frame (chunk/end/error) arrives within this window, + * reset on each frame. mux.request's own timeout only bounds the fast sentinel + * response; without this, a relay pump that breaks on staleness (which sends no + * responseEnd) while the SSH channel stays up would hang the client forever. */ +const STREAM_INACTIVITY_TIMEOUT_MS = 30_000 + +/** Bound transient buffering of other concurrent streams' chunks while this + * reader awaits its sentinel: every reader sees all git.responseChunk frames + * and can't filter by streamId until its own sentinel resolves. Foreign frames + * are dropped on drain anyway; this just caps the pre-sentinel backlog. */ +const MAX_PENDING_FRAMES = 64 + +export class GitResponseStreamError extends Error { + readonly code = RelayErrorCode.StreamProtocolError + constructor(message: string) { + super(message) + } +} + +type PendingFrame = + | { kind: 'chunk'; params: Record } + | { kind: 'end'; params: Record } + | { kind: 'error'; params: Record } + +/** + * Request a git method that may return a large payload, opting into response + * streaming so a big diff/exec response is chunked onto the relay's bulk lane + * instead of one JSON-RPC frame (which would head-of-line-block pty.data echo + * on the shared SSH channel). + * + * Cross-version behavior: + * - New relay + big result → returns the stream sentinel; we reassemble chunks. + * - New relay + small result, or old client → plain single-frame result. + * - Old relay (ignores `__streamResponse`) → returns the plain result; the + * marker check fails and we return it directly, i.e. today's behavior. + */ +export function requestGitStreamable( + mux: SshChannelMultiplexer, + method: string, + params: Record, + options?: { + signal?: AbortSignal + /** Bounds only the sentinel request (forwarded to mux.request), like today. */ + timeoutMs?: number + /** Bounds the post-sentinel reassembly stall; resets on each chunk. */ + inactivityTimeoutMs?: number + } +): Promise { + // Why: subscribe to chunk/end/error BEFORE awaiting the sentinel response so a + // chunk that lands in the same dispatch tick as the response is not dropped + // (mirrors readFileViaStream). streamIdRef stays SENTINEL until the sentinel + // resolves; frames are queued until then and drained. + const streamIdRef = { current: SENTINEL_STREAM_ID } + const unsubscribers: (() => void)[] = [] + const cleanup = (): void => { + while (unsubscribers.length > 0) { + try { + unsubscribers.pop()?.() + } catch { + // best-effort + } + } + } + + return new Promise((resolve, reject) => { + const parts: Buffer[] = [] + let expectedSeq = 0 + let receivedBytes = 0 + let totalBytes = 0 + let chunkCount = 0 + let settled = false + let metadataReady = false + const pending: PendingFrame[] = [] + + const inactivityMs = options?.inactivityTimeoutMs ?? STREAM_INACTIVITY_TIMEOUT_MS + let inactivityTimer: ReturnType | null = null + const clearInactivity = (): void => { + if (inactivityTimer) { + clearTimeout(inactivityTimer) + inactivityTimer = null + } + } + // Why: reset on every stream frame so a legitimately long stream is not + // killed, but a wedged stream (no frames arriving) rejects instead of + // hanging the caller forever. + const armInactivity = (): void => { + clearInactivity() + inactivityTimer = setTimeout(() => { + fail( + new GitResponseStreamError( + `Git response stream stalled (>${inactivityMs}ms without data)` + ) + ) + }, inactivityMs) + inactivityTimer.unref?.() + } + + const cancel = (): void => { + if (streamIdRef.current !== SENTINEL_STREAM_ID && !mux.isDisposed()) { + try { + mux.notify('git.cancelResponseStream', { streamId: streamIdRef.current }) + } catch { + // best-effort + } + } + } + const fail = (err: Error): void => { + if (settled) { + return + } + settled = true + clearInactivity() + cancel() + cleanup() + reject(err) + } + const succeed = (value: unknown): void => { + if (settled) { + return + } + settled = true + clearInactivity() + cleanup() + resolve(value) + } + + const handleChunk = (p: Record): void => { + if (settled || p.streamId !== streamIdRef.current) { + return + } + const seq = p.seq as number + const data = p.data as string + if (typeof seq !== 'number' || typeof data !== 'string') { + fail(new GitResponseStreamError(`Malformed chunk for git stream ${streamIdRef.current}`)) + return + } + if (seq !== expectedSeq) { + fail( + new GitResponseStreamError( + `Out-of-order chunk for git stream ${streamIdRef.current}: expected ${expectedSeq}, got ${seq}` + ) + ) + return + } + const decoded = Buffer.from(data, 'base64') + parts.push(decoded) + receivedBytes += decoded.length + expectedSeq += 1 + armInactivity() + // Why: credit-based flow control — the relay caps unacked chunks so a big + // response cannot queue unbounded ahead of interactive pty.data frames. + if (!mux.isDisposed()) { + try { + mux.notify('git.responseAck', { streamId: streamIdRef.current, seq }) + } catch { + // Disposal can race the check; the ACK is best-effort during teardown. + } + } + } + + const handleEnd = (p: Record): void => { + if (settled || p.streamId !== streamIdRef.current) { + return + } + if (expectedSeq !== chunkCount || receivedBytes !== totalBytes) { + fail( + new GitResponseStreamError( + `Git stream ${streamIdRef.current} incomplete: chunks ${expectedSeq}/${chunkCount}, bytes ${receivedBytes}/${totalBytes}` + ) + ) + return + } + try { + succeed(JSON.parse(Buffer.concat(parts).toString('utf-8'))) + } catch (err) { + fail( + new GitResponseStreamError( + `Git stream ${streamIdRef.current} JSON parse failed: ${String(err)}` + ) + ) + } + } + + const handleStreamError = (p: Record): void => { + if (settled || p.streamId !== streamIdRef.current) { + return + } + fail(new Error((p.message as string | undefined) ?? 'git response stream error')) + } + + const drainPending = (): void => { + while (!settled && pending.length > 0) { + const frame = pending.shift()! + if (frame.kind === 'chunk') { + handleChunk(frame.params) + } else if (frame.kind === 'end') { + handleEnd(frame.params) + } else { + handleStreamError(frame.params) + } + } + } + + // Why: pre-sentinel we cannot filter by streamId (our id is unknown yet), so + // every concurrent reader transiently buffers all readers' chunks. Cap the + // backlog by dropping the oldest; foreign frames are dropped on drain anyway, + // and if our own seq-0 were ever dropped the seq check fails loudly rather + // than corrupting. The sentinel normally resolves long before this cap. + const pushPending = (frame: PendingFrame): void => { + pending.push(frame) + if (pending.length > MAX_PENDING_FRAMES) { + pending.shift() + } + } + + unsubscribers.push( + mux.onNotificationByMethod('git.responseChunk', (p) => { + if (!metadataReady) { + pushPending({ kind: 'chunk', params: p }) + return + } + handleChunk(p) + }) + ) + unsubscribers.push( + mux.onNotificationByMethod('git.responseEnd', (p) => { + if (!metadataReady) { + pushPending({ kind: 'end', params: p }) + return + } + handleEnd(p) + }) + ) + unsubscribers.push( + mux.onNotificationByMethod('git.responseError', (p) => { + if (!metadataReady) { + pushPending({ kind: 'error', params: p }) + return + } + handleStreamError(p) + }) + ) + unsubscribers.push( + mux.onDispose((reason) => { + const err = new Error( + reason === 'connection_lost' + ? 'SSH connection lost, reconnecting...' + : 'Multiplexer disposed' + ) as Error & { code: string } + err.code = reason === 'connection_lost' ? 'CONNECTION_LOST' : 'DISPOSED' + fail(err) + }) + ) + + if (options?.signal) { + const signal = options.signal + if (signal.aborted) { + const err = new Error('Request was cancelled') as Error & { name: string } + err.name = 'AbortError' + fail(err) + return + } + const onAbort = (): void => { + const err = new Error('Request was cancelled') as Error & { name: string } + err.name = 'AbortError' + fail(err) + } + signal.addEventListener('abort', onAbort, { once: true }) + unsubscribers.push(() => signal.removeEventListener('abort', onAbort)) + } + + // Why: forward only the mux-request options (signal/timeoutMs) and omit them + // entirely when absent, so callers that previously issued a 2-arg + // mux.request keep the same call shape (and their tests). inactivityTimeoutMs + // governs reassembly here, not the sentinel request. + const streamParams = { ...params, __streamResponse: true } + const requestOptions = + options?.signal !== undefined || options?.timeoutMs !== undefined + ? { signal: options.signal, timeoutMs: options.timeoutMs } + : undefined + const requestPromise = requestOptions + ? mux.request(method, streamParams, requestOptions) + : mux.request(method, streamParams) + void requestPromise + .then((result) => { + if (settled) { + return + } + // Old relay / small result: plain single-frame value, no stream follows. + if (!isGitResponseStreamMarker(result)) { + succeed(result) + return + } + const marker = result.__orcaGitResponseStream + totalBytes = marker.totalBytes + chunkCount = marker.chunkCount + streamIdRef.current = marker.streamId + metadataReady = true + // Why: start the inactivity deadline now — mux.request's timeout only + // covered the sentinel; the reassembly phase needs its own guard. + armInactivity() + drainPending() + }) + .catch((err) => fail(err as Error)) + }) +} diff --git a/src/main/ssh/ssh-port-forward.test.ts b/src/main/ssh/ssh-port-forward.test.ts index 31e26a5bc408..b49c627b8b3d 100644 --- a/src/main/ssh/ssh-port-forward.test.ts +++ b/src/main/ssh/ssh-port-forward.test.ts @@ -267,6 +267,27 @@ describe('SshPortForwardManager', () => { ) }) + it('keeps only a bounded tail of a chatty forward stderr (memory-leak regression)', async () => { + const onForwardClosed = vi.fn() + manager.setCallbacks({ onForwardClosed }) + const forward = createFakeSystemSshForward() + startSystemSshPortForwardProcessMock.mockReturnValue(forward) + const conn = createSystemSshConn() + + await manager.addForward('conn-1', conn as never, 3000, '127.0.0.1', 8080) + // A long-lived forward against a chatty remote sshd: emit >64 KB of stderr. + forward.process.stderr.emit('data', Buffer.from(`HEAD_MARKER${'x'.repeat(70 * 1024)}`)) + forward.process.stderr.emit('data', Buffer.from('TAIL_MARKER')) + forward.process.emit('exit', 255) + + const detail = onForwardClosed.mock.calls[0]?.[1]?.detail as string + // The oldest bytes are trimmed; the most-recent tail is retained. + expect(detail).toContain('TAIL_MARKER') + expect(detail).not.toContain('HEAD_MARKER') + // Bounded well below the ~70 KB produced. + expect(detail.length).toBeLessThan(66 * 1024) + }) + it('lists forwards filtered by connectionId', async () => { const conn = createMockConn() await manager.addForward('conn-1', conn as never, 3000, 'localhost', 8080) diff --git a/src/main/ssh/ssh-port-scanner.test.ts b/src/main/ssh/ssh-port-scanner.test.ts new file mode 100644 index 000000000000..09be7c1f6864 --- /dev/null +++ b/src/main/ssh/ssh-port-scanner.test.ts @@ -0,0 +1,261 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + PortScanner, + SSH_PORT_SCAN_BASE_INTERVAL_MS, + SSH_PORT_SCAN_MAX_INTERVAL_MS, + type PortScannerWindowVisibility +} from './ssh-port-scanner' +import type { SshChannelMultiplexer } from './ssh-channel-multiplexer' +import type { DetectedPort } from '../../shared/ssh-types' + +type VisibilityHarness = { + visibility: PortScannerWindowVisibility + setVisible: (visible: boolean) => void + listenerCount: () => number +} + +function createVisibilityHarness(initiallyVisible: boolean): VisibilityHarness { + let visible = initiallyVisible + const listeners = new Set<() => void>() + return { + visibility: { + isWindowVisible: () => visible, + onWindowBecameVisible: (listener) => { + listeners.add(listener) + return () => { + listeners.delete(listener) + } + } + }, + setVisible: (next) => { + const wasVisible = visible + visible = next + if (!wasVisible && next) { + for (const listener of Array.from(listeners)) { + listener() + } + } + }, + listenerCount: () => listeners.size + } +} + +function port(portNumber: number): DetectedPort { + return { port: portNumber, host: '127.0.0.1', pid: 100 + portNumber, processName: 'node' } +} + +function createMux(ports: () => DetectedPort[]): { + mux: SshChannelMultiplexer + request: ReturnType +} { + const request = vi.fn(async () => ({ ports: ports(), platform: 'linux' })) + return { mux: { request } as unknown as SshChannelMultiplexer, request } +} + +const BASE = SSH_PORT_SCAN_BASE_INTERVAL_MS +const MAX = SSH_PORT_SCAN_MAX_INTERVAL_MS + +describe('PortScanner', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('sends zero ports.detect requests while the window is hidden, then scans immediately on show', async () => { + const harness = createVisibilityHarness(false) + const { mux, request } = createMux(() => [port(3000)]) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', mux, vi.fn()) + + await vi.advanceTimersByTimeAsync(10 * 60_000) + expect(request).not.toHaveBeenCalled() + + harness.setVisible(true) + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(1) + + scanner.dispose() + }) + + it('polls at the base cadence while visible when results keep changing', async () => { + const harness = createVisibilityHarness(true) + let next = 3000 + const { mux, request } = createMux(() => [port(next++)]) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', mux, vi.fn()) + + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(1) + + // 5 simulated base intervals -> 5 more scans (no backoff while changing). + await vi.advanceTimersByTimeAsync(5 * BASE) + expect(request).toHaveBeenCalledTimes(6) + + scanner.dispose() + }) + + it('doubles the interval up to the cap while unchanged and resets to base on a change', async () => { + const harness = createVisibilityHarness(true) + let ports = [port(3000)] + const { mux, request } = createMux(() => ports) + const onChanged = vi.fn() + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', mux, onChanged) + + // t=0: first scan is a change (empty -> {3000}) and stays at base. + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(1) + expect(onChanged).toHaveBeenCalledTimes(1) + + // t=12s: unchanged -> next wait doubles to 24s. + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(2) + + // t=24s: nothing (waiting until t=36s). + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(2) + + // t=36s: unchanged -> next wait caps at 30s (not 48s). + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(3) + + // t=65.999s: still waiting. + await vi.advanceTimersByTimeAsync(MAX - 1) + expect(request).toHaveBeenCalledTimes(3) + + // t=66s: unchanged -> next wait remains capped at 30s. + await vi.advanceTimersByTimeAsync(1) + expect(request).toHaveBeenCalledTimes(4) + + await vi.advanceTimersByTimeAsync(MAX - 1) + expect(request).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(1) + expect(request).toHaveBeenCalledTimes(5) + expect(onChanged).toHaveBeenCalledTimes(1) + + // A changed result resets the cadence back to base. + ports = [port(3000), port(4000)] + await vi.advanceTimersByTimeAsync(MAX) + expect(request).toHaveBeenCalledTimes(6) + expect(onChanged).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(7) + expect(scanner.getDetectedPorts('t1').map((p) => p.port)).toEqual([3000, 4000]) + + scanner.dispose() + }) + + it('resets backoff and scans immediately when scanning restarts (reconnect/session-ready)', async () => { + const harness = createVisibilityHarness(true) + const { mux, request } = createMux(() => [port(3000)]) + const scanner = new PortScanner(harness.visibility) + const onChanged = vi.fn() + scanner.startScanning('t1', mux, onChanged) + + // Back off: scans at t=0, t=12s, t=36s -> interval now 48s. + await vi.advanceTimersByTimeAsync(3 * BASE) + expect(request).toHaveBeenCalledTimes(3) + + // Reconnect paths call startScanning again: immediate scan, base cadence. + scanner.startScanning('t1', mux, onChanged) + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(5) + + scanner.dispose() + }) + + it('parks when the window hides mid-run and resumes with an immediate scan on show', async () => { + const harness = createVisibilityHarness(true) + let next = 3000 + const { mux, request } = createMux(() => [port(next++)]) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', mux, vi.fn()) + + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(2) + + harness.setVisible(false) + await vi.advanceTimersByTimeAsync(30 * 60_000) + expect(request).toHaveBeenCalledTimes(2) + + harness.setVisible(true) + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(4) + + scanner.dispose() + }) + + it('never overlaps a slow in-flight request and resumes the chain after it settles', async () => { + const harness = createVisibilityHarness(true) + let resolveFirst: ((value: { ports: DetectedPort[]; platform: string }) => void) | null = null + const request = vi.fn( + () => + new Promise<{ ports: DetectedPort[]; platform: string }>((resolve) => { + resolveFirst = resolve + }) + ) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', { request } as unknown as SshChannelMultiplexer, vi.fn()) + expect(request).toHaveBeenCalledTimes(1) + + // The chain waits for the in-flight request instead of stacking more. + await vi.advanceTimersByTimeAsync(10 * BASE) + expect(request).toHaveBeenCalledTimes(1) + + resolveFirst!({ ports: [port(3000)], platform: 'linux' }) + await vi.advanceTimersByTimeAsync(BASE) + expect(request).toHaveBeenCalledTimes(2) + + scanner.dispose() + }) + + it('stopScanning halts polling and detaches the visibility listener', async () => { + const harness = createVisibilityHarness(true) + const { mux, request } = createMux(() => [port(3000)]) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('t1', mux, vi.fn()) + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(1) + expect(harness.listenerCount()).toBe(1) + + scanner.stopScanning('t1') + expect(harness.listenerCount()).toBe(0) + await vi.advanceTimersByTimeAsync(10 * 60_000) + harness.setVisible(false) + harness.setVisible(true) + await vi.advanceTimersByTimeAsync(10 * 60_000) + expect(request).toHaveBeenCalledTimes(1) + expect(scanner.getDetectedPorts('t1')).toEqual([]) + }) + + it('keeps targets independent: stopping one host leaves the other scanning', async () => { + const harness = createVisibilityHarness(true) + let nextA = 3000 + let nextB = 4000 + const a = createMux(() => [port(nextA++)]) + const b = createMux(() => [port(nextB++)]) + const scanner = new PortScanner(harness.visibility) + scanner.startScanning('host-a', a.mux, vi.fn()) + scanner.startScanning('host-b', b.mux, vi.fn()) + await vi.advanceTimersByTimeAsync(0) + expect(a.request).toHaveBeenCalledTimes(1) + expect(b.request).toHaveBeenCalledTimes(1) + + scanner.stopScanning('host-a') + await vi.advanceTimersByTimeAsync(BASE) + expect(a.request).toHaveBeenCalledTimes(1) + expect(b.request).toHaveBeenCalledTimes(2) + + scanner.dispose() + await vi.advanceTimersByTimeAsync(10 * BASE) + expect(b.request).toHaveBeenCalledTimes(2) + expect(harness.listenerCount()).toBe(0) + }) +}) diff --git a/src/main/ssh/ssh-port-scanner.ts b/src/main/ssh/ssh-port-scanner.ts index 3746308db36d..6404d035f228 100644 --- a/src/main/ssh/ssh-port-scanner.ts +++ b/src/main/ssh/ssh-port-scanner.ts @@ -1,10 +1,30 @@ import type { SshChannelMultiplexer } from './ssh-channel-multiplexer' import type { DetectedPort } from '../../shared/ssh-types' -const POLL_INTERVAL_MS = 3_000 +// Why: every tick walks /proc/*/fd on the remote relay, so cadence is remote +// CPU, not just a local timer. 12s cuts steady-state request volume 4x vs the +// old 3s while keeping new-port detection well under the 30s workspace-scanner +// cadence users already accept. +export const SSH_PORT_SCAN_BASE_INTERVAL_MS = 12_000 +// Why: idle backoff cap — an unchanged port set doubles the interval up to +// this bound, so a quiet remote costs two scans per minute instead of twenty +// without exceeding the existing workspace-port scanner's visible cadence. +export const SSH_PORT_SCAN_MAX_INTERVAL_MS = 30_000 + +export type PortScannerWindowVisibility = { + isWindowVisible: () => boolean + // Fires when a hidden/minimized window is shown again; returns unsubscribe. + onWindowBecameVisible: (listener: () => void) => () => void +} type ScanHandle = { - timer: ReturnType + timer: ReturnType | null + intervalMs: number + // Why: while the window is hidden the scan chain is parked outright — no + // timer wakeups, no remote requests — and the visibility listener resumes + // it with an immediate scan so ports opened while hidden surface at once. + parkedWhileHidden: boolean + unsubscribeVisibility: () => void // Why: keyed by "host:port" (not just port) so that host-distinct listeners // on the same port (e.g. 127.0.0.1:3000 + 0.0.0.0:3000) are tracked separately. previousPorts: Map @@ -17,6 +37,8 @@ type ScanHandle = { export class PortScanner { private handles = new Map() + constructor(private visibility: PortScannerWindowVisibility) {} + startScanning( targetId: string, mux: SshChannelMultiplexer, @@ -25,14 +47,18 @@ export class PortScanner { this.stopScanning(targetId) const handle: ScanHandle = { - timer: null!, + timer: null, + intervalMs: SSH_PORT_SCAN_BASE_INTERVAL_MS, + parkedWhileHidden: false, + unsubscribeVisibility: () => {}, previousPorts: new Map(), initialPorts: null } + const isCurrent = (): boolean => this.handles.get(targetId) === handle - // Why: guard against overlapping scans. On slow remotes, /proc/*/fd walks - // can take longer than POLL_INTERVAL_MS. Without this guard, setInterval - // would stack up concurrent requests on the shared SSH multiplexer. + // Why: guard against overlapping scans. The timer chain only reschedules + // after a poll completes, but the visibility-resume path can race a poll + // still in flight on a slow remote. let polling = false const poll = async (): Promise => { if (polling) { @@ -45,7 +71,7 @@ export class PortScanner { platform: string } - if (!this.handles.has(targetId)) { + if (!isCurrent()) { return } @@ -60,7 +86,10 @@ export class PortScanner { if (!portsEqual(handle.previousPorts, currentPorts)) { handle.previousPorts = currentPorts + handle.intervalMs = SSH_PORT_SCAN_BASE_INTERVAL_MS onChanged(targetId, result.ports, result.platform) + } else { + handle.intervalMs = Math.min(handle.intervalMs * 2, SSH_PORT_SCAN_MAX_INTERVAL_MS) } } catch { // Relay disconnected or request timed out — retry on next interval @@ -69,10 +98,32 @@ export class PortScanner { } } - handle.timer = setInterval(() => void poll(), POLL_INTERVAL_MS) - this.handles.set(targetId, handle) + const tick = async (): Promise => { + handle.timer = null + if (!isCurrent()) { + return + } + if (!this.visibility.isWindowVisible()) { + handle.parkedWhileHidden = true + return + } + await poll() + if (!isCurrent()) { + return + } + handle.timer = setTimeout(() => void tick(), handle.intervalMs) + } - void poll() + handle.unsubscribeVisibility = this.visibility.onWindowBecameVisible(() => { + if (!isCurrent() || !handle.parkedWhileHidden) { + return + } + handle.parkedWhileHidden = false + void tick() + }) + + this.handles.set(targetId, handle) + void tick() } getDetectedPorts(targetId: string): DetectedPort[] { @@ -88,7 +139,10 @@ export class PortScanner { if (!handle) { return } - clearInterval(handle.timer) + if (handle.timer) { + clearTimeout(handle.timer) + } + handle.unsubscribeVisibility() this.handles.delete(targetId) } diff --git a/src/main/ssh/ssh-relay-deploy.ts b/src/main/ssh/ssh-relay-deploy.ts index 78e7dec44431..26501a8371b3 100644 --- a/src/main/ssh/ssh-relay-deploy.ts +++ b/src/main/ssh/ssh-relay-deploy.ts @@ -756,7 +756,12 @@ async function launchRelay( // Fire-and-forget via conn.exec: we don't need the output — the socket // poll below detects readiness. const logFile = `${remoteDir}/relay.log` - const launchCmd = `cd ${escapedDir} && nohup ${escapedNode} relay.js --detached --grace-time ${graceTime} --sock-path ${shellEscape(sockFile)} > ${shellEscape(logFile)} 2>&1 ${shellEscape(logFile)} 2>&1 {}) launchChannel.on('error', () => {}) @@ -1052,6 +1057,10 @@ function windowsRelayLaunchCommand( quoted(sockPath), '--endpoint-dir', quoted(endpointDir), + // Why: in-process rotation owns relay.log (the tail-diagnostics target); + // the shell redirects remain for pre-JS boot/crash output. + '--log-file', + quoted(logFile), `1>${quoted(logFile)}`, `2>${quoted(errFile)}` ].join(' ') diff --git a/src/main/ssh/ssh-relay-session-test-fixtures.ts b/src/main/ssh/ssh-relay-session-test-fixtures.ts new file mode 100644 index 000000000000..0b4e8188c077 --- /dev/null +++ b/src/main/ssh/ssh-relay-session-test-fixtures.ts @@ -0,0 +1,48 @@ +import { vi, type Mock } from 'vitest' +import type { BrowserWindow } from 'electron' +import type { SshConnection } from './ssh-connection' +import type { Store } from '../persistence' +import type { SshPortForwardManager } from './ssh-port-forward' +import { deployAndLaunchRelay } from './ssh-relay-deploy' + +type SshRelaySessionTestDeps = { + mockConn: SshConnection + mockStore: Store + mockPortForward: SshPortForwardManager + getMainWindow: Mock<() => BrowserWindow | null> + mockWindow: BrowserWindow +} + +export function createMockDeps(): SshRelaySessionTestDeps { + const mockConn = {} as SshConnection + const mockStore = { + getRepos: vi.fn().mockReturnValue([]), + getSshRemotePtyLeases: vi.fn().mockReturnValue([]), + markSshRemotePtyLease: vi.fn(), + markSshRemotePtyLeases: vi.fn() + } as unknown as Store + const mockPortForward = { + removeAllForwards: vi.fn() + } as unknown as SshPortForwardManager + const mockWindow = { + isDestroyed: () => false, + // Why: the port scanner visibility-gates its ticks; a visible mock window + // keeps establish-path tests exercising the scan-on-ready behavior. + isVisible: () => true, + isMinimized: () => false, + webContents: { send: vi.fn() } + } as unknown as BrowserWindow + const getMainWindow = vi.fn().mockReturnValue(mockWindow) + return { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } +} + +export function mockDeploySuccess(): void { + vi.mocked(deployAndLaunchRelay).mockResolvedValue({ + transport: { + write: vi.fn(), + onData: vi.fn(), + onClose: vi.fn() + }, + platform: 'linux-x64' + }) +} diff --git a/src/main/ssh/ssh-relay-session.test.ts b/src/main/ssh/ssh-relay-session.test.ts index 0dfa2edc8d86..82cbfaee42c5 100644 --- a/src/main/ssh/ssh-relay-session.test.ts +++ b/src/main/ssh/ssh-relay-session.test.ts @@ -1,10 +1,9 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import { SshRelaySession } from './ssh-relay-session' import type { SshConnection } from './ssh-connection' -import type { Store } from '../persistence' -import type { SshPortForwardManager } from './ssh-port-forward' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../shared/agent-hook-relay' import { SSH_RELAY_CONFIGURE_GRACE_TIME_METHOD } from '../../shared/ssh-types' +import { createMockDeps, mockDeploySuccess } from './ssh-relay-session-test-fixtures' const { muxRequestMock, installRemoteManagedAgentHooksMock } = vi.hoisted(() => ({ muxRequestMock: vi.fn(), @@ -90,6 +89,12 @@ vi.mock('../providers/ssh-git-dispatch', () => ({ })) const { deployAndLaunchRelay } = await import('./ssh-relay-deploy') +// Why: the hidden-delivery gate module is intentionally real (pure state, no +// electron deps) so the SSH parity tests exercise the same gate main uses. +const { markHiddenRendererPty, setRendererPtyDeliveryInterest } = + await import('../ipc/pty-hidden-delivery-gate') +const { _resetHiddenRendererPtyDeliveryGateForTest } = + await import('../ipc/pty-hidden-delivery-gate') const { execCommand } = await import('./ssh-relay-deploy-helpers') const { getRemoteHostPlatform } = await import('./ssh-remote-platform') const { @@ -105,37 +110,6 @@ const { registerSshFilesystemProvider, unregisterSshFilesystemProvider } = const { registerSshGitProvider, unregisterSshGitProvider } = await import('../providers/ssh-git-dispatch') -function createMockDeps() { - const mockConn = {} as SshConnection - const mockStore = { - getRepos: vi.fn().mockReturnValue([]), - getSshRemotePtyLeases: vi.fn().mockReturnValue([]), - markSshRemotePtyLease: vi.fn(), - markSshRemotePtyLeases: vi.fn() - } as unknown as Store - const mockPortForward = { - removeAllForwards: vi.fn() - } as unknown as SshPortForwardManager - const mockWindow = { - isDestroyed: () => false, - webContents: { send: vi.fn() } - } - const getMainWindow = vi.fn().mockReturnValue(mockWindow) - return { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } -} - -function mockDeploySuccess() { - const mockTransport = { - write: vi.fn(), - onData: vi.fn(), - onClose: vi.fn() - } - vi.mocked(deployAndLaunchRelay).mockResolvedValue({ - transport: mockTransport, - platform: 'linux-x64' - }) -} - describe('SshRelaySession', () => { beforeEach(() => { vi.clearAllMocks() @@ -146,6 +120,95 @@ describe('SshRelaySession', () => { installRemoteManagedAgentHooksMock.mockResolvedValue([]) mockDeploySuccess() vi.mocked(getPtyIdsForConnection).mockReturnValue([]) + _resetHiddenRendererPtyDeliveryGateForTest() + }) + + it('drops hidden-gated PTY data after runtime ingestion with one restore marker', async () => { + const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps() + const runtime = { + onPtyData: vi.fn(() => 99), + onPtyExit: vi.fn() + } + const session = new SshRelaySession( + 'target-1', + getMainWindow, + mockStore, + mockPortForward, + runtime as never + ) + await session.establish(mockConn) + const ptyProvider = vi.mocked(registerSshPtyProvider).mock.calls[0]?.[1] as unknown as { + onData: ReturnType + } + const onData = ptyProvider.onData.mock.calls[0]?.[0] as (payload: { + id: string + data: string + }) => void + + markHiddenRendererPty('ssh-pty-1') + onData({ id: 'ssh-pty-1', data: 'hidden ssh output' }) + + // Runtime ingestion still ran; renderer delivery shrank to one marker. + expect(runtime.onPtyData).toHaveBeenCalledWith( + 'ssh-pty-1', + 'hidden ssh output', + expect.any(Number) + ) + expect(mockWindow.webContents.send).toHaveBeenCalledTimes(1) + // Why out-of-band: an in-band empty pty:data sentinel is ambiguous with + // chunks fully consumed by renderer OSC-9999 stripping. + expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:modelRestoreNeeded', { + id: 'ssh-pty-1', + reason: 'hidden-drop', + markerSeq: 99 + }) + + onData({ id: 'ssh-pty-1', data: 'more hidden ssh output' }) + expect(mockWindow.webContents.send).toHaveBeenCalledTimes(1) + + // Delivery interest (renderer sidecars) suppresses the gate — parity with + // the local path in ipc/pty.ts. + setRendererPtyDeliveryInterest('ssh-pty-1', true) + onData({ id: 'ssh-pty-1', data: 'sidecar ssh bytes' }) + expect(mockWindow.webContents.send).toHaveBeenLastCalledWith('pty:data', { + id: 'ssh-pty-1', + data: 'sidecar ssh bytes', + seq: 99, + rawLength: 'sidecar ssh bytes'.length + }) + + // Non-hidden PTYs are unaffected. + onData({ id: 'ssh-pty-2', data: 'visible ssh output' }) + expect(mockWindow.webContents.send).toHaveBeenLastCalledWith('pty:data', { + id: 'ssh-pty-2', + data: 'visible ssh output', + seq: 99, + rawLength: 'visible ssh output'.length + }) + }) + + it('keeps hidden SSH delivery when the gate kill switch is off', async () => { + const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps() + ;(mockStore as unknown as { getSettings: () => unknown }).getSettings = vi.fn(() => ({ + terminalHiddenDeliveryGate: false + })) + const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward) + await session.establish(mockConn) + const ptyProvider = vi.mocked(registerSshPtyProvider).mock.calls[0]?.[1] as unknown as { + onData: ReturnType + } + const onData = ptyProvider.onData.mock.calls[0]?.[0] as (payload: { + id: string + data: string + }) => void + + markHiddenRendererPty('ssh-pty-1') + onData({ id: 'ssh-pty-1', data: 'still delivered' }) + + expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: 'ssh-pty-1', + data: 'still delivered' + }) }) it('starts in idle state', () => { @@ -168,6 +231,39 @@ describe('SshRelaySession', () => { expect(registerSshGitProvider).toHaveBeenCalledWith('target-1', expect.anything()) }) + it.each([ + ['/bin/bash', "'/bin/bash' -lc 'printenv GROK_HOME | head -c 4097'"], + ['/usr/bin/fish', "'/usr/bin/fish' -lc 'printenv GROK_HOME | head -c 4097'"], + ['/bin/tcsh', "'/bin/tcsh' -lc 'printenv GROK_HOME | head -c 4097'"], + ['/bin/sh', "'/bin/sh' -c 'printenv GROK_HOME | head -c 4097'"] + ])('uses a shell-independent GROK_HOME probe with login shell %s', async (shell, command) => { + process.env.ORCA_FEATURE_REMOTE_AGENT_HOOKS = '1' + muxRequestMock.mockImplementation(async (method: string) => + method === 'session.resolveHome' ? { resolvedPath: '/home/orca' } : { ok: true } + ) + vi.mocked(execCommand).mockResolvedValueOnce(`${shell}\n`).mockResolvedValueOnce('/srv/grok\n') + const sftp = { end: vi.fn() } + const { mockStore, mockPortForward, getMainWindow } = createMockDeps() + const mockConn = { sftp: vi.fn().mockResolvedValue(sftp) } as unknown as SshConnection + const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward) + + await session.establish(mockConn) + + expect(execCommand).toHaveBeenNthCalledWith( + 1, + mockConn, + "printenv SHELL || printf '/bin/sh\\n'", + { timeoutMs: 8_000 } + ) + expect(execCommand).toHaveBeenNthCalledWith(2, mockConn, command, { + wrapCommand: false, + timeoutMs: 8_000 + }) + expect(installRemoteManagedAgentHooksMock).toHaveBeenCalledWith(sftp, '/home/orca', { + grokHomeDir: '/srv/grok' + }) + }) + it('installs remote managed hooks and relay-owned plugin assets before registering the SSH PTY provider', async () => { process.env.ORCA_FEATURE_REMOTE_AGENT_HOOKS = '1' muxRequestMock.mockImplementation(async (method: string) => { @@ -177,6 +273,9 @@ describe('SshRelaySession', () => { return { ok: true } }) const sftp = { end: vi.fn() } + vi.mocked(execCommand) + .mockResolvedValueOnce('/bin/bash\n') + .mockResolvedValueOnce('/srv/grok profile\n') const { mockStore, mockPortForward, getMainWindow } = createMockDeps() const mockConn = { sftp: vi.fn().mockResolvedValue(sftp) @@ -195,7 +294,9 @@ describe('SshRelaySession', () => { ompExtensionSource: expect.stringContaining('/hook/omp') }) expect(mockConn.sftp).toHaveBeenCalledTimes(1) - expect(installRemoteManagedAgentHooksMock).toHaveBeenCalledWith(sftp, '/home/orca') + expect(installRemoteManagedAgentHooksMock).toHaveBeenCalledWith(sftp, '/home/orca', { + grokHomeDir: '/srv/grok profile' + }) expect(sftp.end).toHaveBeenCalledTimes(1) expect(installRemoteManagedAgentHooksMock.mock.invocationCallOrder[0]).toBeLessThan( muxRequestMock.mock.invocationCallOrder[installPluginsCallIndex] @@ -205,6 +306,26 @@ describe('SshRelaySession', () => { ) }) + it('falls back to login-home Grok config when the remote env probe is invalid', async () => { + process.env.ORCA_FEATURE_REMOTE_AGENT_HOOKS = '1' + muxRequestMock.mockImplementation(async (method: string) => + method === 'session.resolveHome' ? { resolvedPath: '/home/orca' } : { ok: true } + ) + vi.mocked(execCommand) + .mockResolvedValueOnce('/bin/bash\n') + .mockResolvedValueOnce('relative/grok-home\n') + const sftp = { end: vi.fn() } + const { mockStore, mockPortForward, getMainWindow } = createMockDeps() + const mockConn = { sftp: vi.fn().mockResolvedValue(sftp) } as unknown as SshConnection + const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward) + + await session.establish(mockConn) + + expect(installRemoteManagedAgentHooksMock).toHaveBeenCalledWith(sftp, '/home/orca', { + grokHomeDir: '/home/orca/.grok' + }) + }) + it('does not run POSIX managed hook installers on Windows remotes', async () => { process.env.ORCA_FEATURE_REMOTE_AGENT_HOOKS = '1' const { mockStore, mockPortForward, getMainWindow } = createMockDeps() diff --git a/src/main/ssh/ssh-relay-session.ts b/src/main/ssh/ssh-relay-session.ts index 2462bbd94c31..5176d06411fd 100644 --- a/src/main/ssh/ssh-relay-session.ts +++ b/src/main/ssh/ssh-relay-session.ts @@ -44,6 +44,11 @@ import { setPtyOwnership, answerStartupTerminalColorQueriesForPty } from '../ipc/pty' +import { + recordHiddenRendererPtyDataDrop, + shouldDropHiddenRendererPtyData +} from '../ipc/pty-hidden-delivery-gate' +import type { PtyModelRestoreNeededEvent } from '../../shared/pty-model-restore-marker' import { registerSshFilesystemProvider, unregisterSshFilesystemProvider, @@ -52,6 +57,7 @@ import { import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch' import { notifyRemoteWorkspaceHandlers } from '../ipc/remote-workspace-events' import { PortScanner } from './ssh-port-scanner' +import { isMainWindowVisible, onMainWindowBecameVisible } from '../window/main-window-visibility' import type { SshPortForwardManager } from './ssh-port-forward' import type { SshConnection } from './ssh-connection' import { joinRemotePath, isWindowsRemoteHost, type RemoteHostPlatform } from './ssh-remote-platform' @@ -69,6 +75,7 @@ import { runRemoteOrcaCli } from './ssh-remote-orca-cli' import { toSshExecutionHostId, type ExecutionHostId } from '../../shared/execution-host' import { isTerminalLeafId, makePaneKey } from '../../shared/stable-pane-id' import { isValidTerminalTabId } from '../../shared/terminal-tab-id' +import { shellEscape } from './ssh-connection-utils' export type RelaySessionState = 'idle' | 'deploying' | 'ready' | 'reconnecting' | 'disposed' @@ -84,6 +91,69 @@ type RemoteCliBridgeEnv = { type ExpectedPtyIdentity = { paneKey?: string; tabId?: string } +const REMOTE_GROK_HOME_MAX_LENGTH = 4096 +const REMOTE_GROK_HOME_PROBE_TIMEOUT_MS = 8_000 + +function defaultRemoteGrokHome(remoteHome: string): string { + const home = remoteHome.replace(/\/+$/, '') || remoteHome + return `${home}/.grok` +} + +function normalizeRemoteGrokHome(candidate: string): string | null { + if ( + candidate.length === 0 || + candidate.length > REMOTE_GROK_HOME_MAX_LENGTH || + candidate !== candidate.trim() || + !candidate.startsWith('/') || + candidate.includes('\\') || + hasControlCharacter(candidate) + ) { + return null + } + return candidate.replace(/\/+$/, '') || '/' +} + +function hasControlCharacter(value: string): boolean { + return Array.from(value).some((character) => { + const code = character.charCodeAt(0) + return code <= 0x1f || code === 0x7f + }) +} + +function loginShellCommand(shell: string, command: string): string { + const shellName = shell.split('/').at(-1) + const mode = shellName === 'sh' || shellName === 'dash' ? '-c' : '-lc' + return `${shellEscape(shell)} ${mode} ${shellEscape(command)}` +} + +async function resolveRemoteGrokHome( + connection: SshConnection, + remoteHome: string +): Promise { + const fallback = defaultRemoteGrokHome(remoteHome) + try { + // Why: remote PTYs start login shells, so probe the same profile-derived + // environment instead of the relay service or local Electron environment. + const shellOutput = await execCommand(connection, "printenv SHELL || printf '/bin/sh\\n'", { + timeoutMs: REMOTE_GROK_HOME_PROBE_TIMEOUT_MS + }) + const shell = shellOutput.trim().split(/\r?\n/, 1)[0] + if (!shell?.startsWith('/') || hasControlCharacter(shell)) { + return fallback + } + // Why: this runs inside the user's actual login shell, which may be fish or + // tcsh. External commands avoid shell-specific variable/conditional syntax. + const probe = `printenv GROK_HOME | head -c ${REMOTE_GROK_HOME_MAX_LENGTH + 1}` + const output = await execCommand(connection, loginShellCommand(shell, probe), { + wrapCommand: false, + timeoutMs: REMOTE_GROK_HOME_PROBE_TIMEOUT_MS + }) + return normalizeRemoteGrokHome(output.split(/\r?\n/, 1)[0] ?? '') ?? fallback + } catch { + return fallback + } +} + function expectedIdentityForLease(lease: { tabId?: string leafId?: string @@ -672,8 +742,10 @@ export class SshRelaySession { let sftp: Awaited> | null = null try { - sftp = await this.requireReadyConnection().sftp() - await installRemoteManagedAgentHooks(sftp, remoteHome) + const connection = this.requireReadyConnection() + const remoteGrokHome = await resolveRemoteGrokHome(connection, remoteHome) + sftp = await connection.sftp() + await installRemoteManagedAgentHooks(sftp, remoteHome, { grokHomeDir: remoteGrokHome }) } catch (error) { console.warn( `[ssh-relay-session] remote managed hook install failed for ${this.targetId}: ${ @@ -982,7 +1054,13 @@ export class SshRelaySession { if (!this.mux || this.isDisposed()) { return } - const scanner = new PortScanner() + // Why: each scan walks /proc/*/fd on the remote host, so the scanner skips + // ticks entirely while no window can show the results (hidden to tray or + // minimized overnight) and rescans immediately when the window returns. + const scanner = new PortScanner({ + isWindowVisible: () => isMainWindowVisible(this.getMainWindow()), + onWindowBecameVisible: onMainWindowBecameVisible + }) this.portScanner = scanner // Why: capture the scanner instance so that a late ports.detect callback // from a previous relay session (before reconnect replaced it) is silently @@ -1007,7 +1085,30 @@ export class SshRelaySession { const seq = this.runtime?.onPtyData(payload.id, payload.data, Date.now()) const rendererData = answerStartupTerminalColorQueriesForPty(payload.id, payload.data) const win = this.getMainWindow() - if (win && !win.isDestroyed() && rendererData.length > 0) { + if (!win || win.isDestroyed()) { + return + } + // Why: hidden-delivery gate parity with ipc/pty.ts — runtime ingestion + // above already consumed the chunk; gated renderer delivery is dropped + // and one out-of-band pty:modelRestoreNeeded signal latches + // model-restore-needed for reveal. Never an in-band pty:data sentinel: + // OSC-9999-only chunks legitimately strip to empty in the renderer. + const store = this.store as { getSettings?: Store['getSettings'] } + if (shouldDropHiddenRendererPtyData(payload.id, store.getSettings?.())) { + const drop = recordHiddenRendererPtyDataDrop(payload.id, payload.data.length) + if (drop.shouldEmitRestoreMarker) { + win.webContents.send('pty:modelRestoreNeeded', { + id: payload.id, + reason: 'hidden-drop', + ...(typeof seq === 'number' ? { markerSeq: seq } : {}) + } satisfies PtyModelRestoreNeededEvent) + } + return + } + // Why: startup color-query answering can strip query-only chunks to + // empty; skip empty sends and only attach seq metadata when the chunk + // reaches the renderer unmodified (seq tracks raw stream offsets). + if (rendererData.length > 0) { win.webContents.send('pty:data', { ...payload, data: rendererData, diff --git a/src/main/ssh/ssh-remote-cli-host-passthrough.test.ts b/src/main/ssh/ssh-remote-cli-host-passthrough.test.ts new file mode 100644 index 000000000000..22920a666362 --- /dev/null +++ b/src/main/ssh/ssh-remote-cli-host-passthrough.test.ts @@ -0,0 +1,250 @@ +import { EventEmitter } from 'node:events' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { + isPackaged: false, + getAppPath: () => '/host/app' + } +})) +vi.mock('../persistence', () => ({ + getCanonicalUserDataPath: () => '/host/user-data' +})) + +import { + HostCliUnavailableError, + buildHostCliEnv, + resolveHostCliEntryPath, + resolveHostCliKillTimeoutMs, + runHostOrcaCliPassthrough +} from './ssh-remote-cli-host-passthrough' + +type FakeChild = EventEmitter & { + stdout: EventEmitter + stderr: EventEmitter + stdin: { end: ReturnType; on: ReturnType } + kill: ReturnType +} + +function createFakeChild(): FakeChild { + const child = new EventEmitter() as FakeChild + child.stdout = new EventEmitter() + child.stderr = new EventEmitter() + child.stdin = { end: vi.fn(), on: vi.fn() } + child.kill = vi.fn() + return child +} + +const BASE_OPTIONS = { + execPath: '/host/electron', + cliEntryPath: '/host/app/out/cli/index.js', + userDataPath: '/host/user-data', + entryExists: () => true +} + +describe('resolveHostCliEntryPath', () => { + it('uses the in-repo entry for dev builds and the unpacked asar entry when packaged', () => { + expect( + resolveHostCliEntryPath({ isPackaged: false, resourcesPath: '/r', appPath: '/host/app' }) + ).toBe(join('/host/app', 'out', 'cli', 'index.js')) + expect( + resolveHostCliEntryPath({ isPackaged: true, resourcesPath: '/r', appPath: '/host/app' }) + ).toBe(join('/r', 'app.asar.unpacked', 'out', 'cli', 'index.js')) + }) +}) + +describe('buildHostCliEnv', () => { + it('forwards only Orca terminal-context vars from the remote env', () => { + const env = buildHostCliEnv({ + hostEnv: { PATH: '/host/bin', NODE_OPTIONS: '--inspect' }, + remoteEnv: { + ORCA_TERMINAL_HANDLE: 'term_remote', + ORCA_WORKTREE_ID: 'repo::/home/alice/wt', + ORCA_PANE_KEY: 'pane-9', + ORCA_WORKSPACE_ID: 'ws-1', + // Why: these are remote-machine paths and must not leak into the host + // subprocess (PATH would break host binary lookup; user-data would + // retarget the CLI at a different local instance). + PATH: '/remote/bin', + ORCA_USER_DATA_PATH: '/remote/user-data' + }, + userDataPath: '/host/user-data', + remoteCwd: '/home/alice/wt/sub' + }) + + expect(env.ORCA_TERMINAL_HANDLE).toBe('term_remote') + expect(env.ORCA_WORKTREE_ID).toBe('repo::/home/alice/wt') + expect(env.ORCA_PANE_KEY).toBe('pane-9') + expect(env.ORCA_WORKSPACE_ID).toBe('ws-1') + expect(env.PATH).toBe('/host/bin') + expect(env.ORCA_USER_DATA_PATH).toBe('/host/user-data') + expect(env.ORCA_CLI_CWD).toBe('/home/alice/wt/sub') + expect(env.ELECTRON_RUN_AS_NODE).toBe('1') + expect(env.NODE_OPTIONS).toBeUndefined() + expect(env.ORCA_NODE_OPTIONS).toBe('--inspect') + }) +}) + +describe('resolveHostCliKillTimeoutMs', () => { + it('extends the kill timer past an explicit --timeout-ms budget', () => { + expect(resolveHostCliKillTimeoutMs(['terminal', 'wait', '--timeout-ms', '1800000'])).toBe( + 1_920_000 + ) + expect(resolveHostCliKillTimeoutMs(['orchestration', 'check', '--timeout-ms=5000'])).toBe( + 600_000 + ) + expect(resolveHostCliKillTimeoutMs(['worktree', 'list'])).toBe(600_000) + }) +}) + +describe('runHostOrcaCliPassthrough', () => { + it('spawns the bundled CLI entry with the remote argv and returns captured output', async () => { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { + argv: ['orchestration', 'task-create', '--spec', 'do the thing', '--json'], + cwd: '/home/alice/wt', + env: { ORCA_TERMINAL_HANDLE: 'term_remote' } + }, + { ...BASE_OPTIONS, spawn: spawn as never } + ) + + await Promise.resolve() + child.stdout.emit('data', Buffer.from('{"ok":true}\n')) + child.stderr.emit('data', Buffer.from('warn\n')) + child.emit('close', 0) + + const result = await resultPromise + expect(result).toEqual({ stdout: '{"ok":true}\n', stderr: 'warn\n', exitCode: 0 }) + + expect(spawn).toHaveBeenCalledTimes(1) + const [execPath, args, options] = spawn.mock.calls[0] as unknown as [ + string, + string[], + { env: NodeJS.ProcessEnv } + ] + expect(execPath).toBe('/host/electron') + expect(args).toEqual([ + '/host/app/out/cli/index.js', + 'orchestration', + 'task-create', + '--spec', + 'do the thing', + '--json' + ]) + expect(options.env.ELECTRON_RUN_AS_NODE).toBe('1') + expect(options.env.ORCA_CLI_CWD).toBe('/home/alice/wt') + expect(options.env.ORCA_TERMINAL_HANDLE).toBe('term_remote') + // Why: stdin must be closed even without a payload so CLI handlers that + // stream stdin see EOF instead of hanging forever. + expect(child.stdin.end).toHaveBeenCalledWith() + }) + + it('pipes a stdin payload to the CLI subprocess', async () => { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { + argv: ['linear', 'comment', 'add', 'ENG-1', '--body-file', '-'], + cwd: '/home/alice/wt', + env: {}, + stdin: 'comment body' + }, + { ...BASE_OPTIONS, spawn: spawn as never } + ) + + await Promise.resolve() + child.emit('close', 0) + await resultPromise + + expect(child.stdin.end).toHaveBeenCalledWith('comment body') + }) + + it('propagates non-zero exit codes', async () => { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { argv: ['worktree', 'show'], cwd: '/', env: {} }, + { ...BASE_OPTIONS, spawn: spawn as never } + ) + + await Promise.resolve() + child.stderr.emit('data', Buffer.from('boom\n')) + child.emit('close', 3) + + await expect(resultPromise).resolves.toEqual({ stdout: '', stderr: 'boom\n', exitCode: 3 }) + }) + + it('throws HostCliUnavailableError when the CLI entry is missing', async () => { + const spawn = vi.fn() + await expect( + runHostOrcaCliPassthrough( + { argv: ['status'], cwd: '/', env: {} }, + { ...BASE_OPTIONS, entryExists: () => false, spawn: spawn as never } + ) + ).rejects.toBeInstanceOf(HostCliUnavailableError) + expect(spawn).not.toHaveBeenCalled() + }) + + it('throws HostCliUnavailableError when the subprocess fails to launch', async () => { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { argv: ['status'], cwd: '/', env: {} }, + { ...BASE_OPTIONS, spawn: spawn as never } + ) + + await Promise.resolve() + child.emit('error', new Error('spawn ENOENT')) + + await expect(resultPromise).rejects.toBeInstanceOf(HostCliUnavailableError) + }) + + it('kills the subprocess and reports an error when the kill timeout elapses', async () => { + vi.useFakeTimers() + try { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { argv: ['terminal', 'wait', '--for', 'exit'], cwd: '/', env: {} }, + { ...BASE_OPTIONS, spawn: spawn as never, killTimeoutMs: 1000 } + ) + + await vi.advanceTimersByTimeAsync(1001) + const result = await resultPromise + expect(child.kill).toHaveBeenCalledWith('SIGKILL') + expect(result.exitCode).toBe(1) + expect(result.stderr).toContain('timed out') + } finally { + vi.useRealTimers() + } + }) + + it('caps runaway output instead of buffering it unbounded', async () => { + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runHostOrcaCliPassthrough( + { argv: ['terminal', 'read'], cwd: '/', env: {} }, + { ...BASE_OPTIONS, spawn: spawn as never } + ) + + await Promise.resolve() + const chunk = Buffer.alloc(3 * 1024 * 1024, 97) + for (let i = 0; i < 4; i += 1) { + child.stdout.emit('data', chunk) + } + child.emit('close', 0) + + const result = await resultPromise + expect(result.stdout.length).toBeLessThanOrEqual(8 * 1024 * 1024 + 64) + expect(result.stdout).toContain('output truncated') + }) +}) diff --git a/src/main/ssh/ssh-remote-cli-host-passthrough.ts b/src/main/ssh/ssh-remote-cli-host-passthrough.ts new file mode 100644 index 000000000000..3ca55edfd699 --- /dev/null +++ b/src/main/ssh/ssh-remote-cli-host-passthrough.ts @@ -0,0 +1,270 @@ +// Why: the SSH relay shim (`~/.orca-relay/bin/orca`) forwards CLI invocations +// to the host app. Instead of re-implementing every command in a hand-rolled +// switch (the cause of "Unsupported SSH Orca CLI command", #7716), the host +// runs the real bundled `orca` CLI entry in Electron node mode — the same +// entry the local shell command uses — so remote invocations get the full +// command surface (orchestration, worktree, terminal, ...) by construction. +import { app } from 'electron' +import { spawn as nodeSpawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { getCanonicalUserDataPath } from '../persistence' + +export type RemoteOrcaCliRequest = { + argv: string[] + cwd: string + env: Record + stdin?: string +} + +export type RemoteOrcaCliResult = { + stdout: string + stderr: string + exitCode: number +} + +export type HostCliPassthroughOptions = { + execPath?: string + cliEntryPath?: string + userDataPath?: string + hostEnv?: NodeJS.ProcessEnv + spawn?: typeof nodeSpawn + entryExists?: (path: string) => boolean + killTimeoutMs?: number +} + +/** Thrown when the host CLI entry cannot be launched at all; callers fall back + * to the legacy in-process command switch so previously-working commands keep + * working even on broken installs. */ +export class HostCliUnavailableError extends Error {} + +// Why: only Orca terminal-context vars may cross from the remote shell into +// the host CLI process. Remote PATH / ORCA_USER_DATA_PATH are paths on the +// remote machine (meaningless or instance-hijacking on the host), and +// NODE_OPTIONS-style vars could alter host execution. +const REMOTE_CONTEXT_ENV_VARS = [ + 'ORCA_TERMINAL_HANDLE', + 'ORCA_WORKTREE_ID', + 'ORCA_PANE_KEY', + 'ORCA_WORKSPACE_ID' +] as const + +// Why: bound captured output so a runaway command cannot balloon the relay +// JSON-RPC response or main-process memory. +const MAX_CAPTURED_OUTPUT_BYTES = 8 * 1024 * 1024 +const DEFAULT_KILL_TIMEOUT_MS = 10 * 60_000 +const KILL_TIMEOUT_GRACE_MS = 2 * 60_000 + +export function resolveHostCliEntryPath(app: { + isPackaged: boolean + resourcesPath: string + appPath: string +}): string { + // Why: mirrors the packaged launcher scripts (resources/*/bin) and the dev + // launcher in cli-installer.ts — packaged builds ship the CLI entry outside + // app.asar so Electron node mode can execute it directly. + return app.isPackaged + ? join(app.resourcesPath, 'app.asar.unpacked', 'out', 'cli', 'index.js') + : join(app.appPath, 'out', 'cli', 'index.js') +} + +/** Kill timer for the host CLI subprocess. Long-poll commands carry their wait + * budget in `--timeout-ms`; extend past it so the CLI's own timeout fires + * first and produces a proper error message. */ +export function resolveHostCliKillTimeoutMs(argv: string[]): number { + const explicit = parseTimeoutMsFlag(argv) + if (explicit !== null && Number.isFinite(explicit) && explicit > 0) { + return Math.max(DEFAULT_KILL_TIMEOUT_MS, explicit + KILL_TIMEOUT_GRACE_MS) + } + return DEFAULT_KILL_TIMEOUT_MS +} + +export function buildHostCliEnv(args: { + hostEnv: NodeJS.ProcessEnv + remoteEnv: Record + userDataPath: string + remoteCwd: string +}): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { ...args.hostEnv } + for (const key of REMOTE_CONTEXT_ENV_VARS) { + const value = args.remoteEnv[key] + if (typeof value === 'string' && value.length > 0) { + env[key] = value + } + } + // Why: bind the subprocess to this app instance's runtime metadata (dev and + // parallel instances use non-default userData dirs). + env.ORCA_USER_DATA_PATH = args.userDataPath + // Why: the caller's working directory lives on the remote machine, so the + // subprocess cwd cannot be chdir'd there; ORCA_CLI_CWD carries it for + // cwd-based selectors like `--worktree active`. + env.ORCA_CLI_CWD = args.remoteCwd + // Why: same node-mode hygiene as the shipped CLI launchers — stash and clear + // NODE_OPTIONS so Electron's node bootstrap does not inherit them. + env.ORCA_NODE_OPTIONS = args.hostEnv.NODE_OPTIONS ?? '' + env.ORCA_NODE_REPL_EXTERNAL_MODULE = args.hostEnv.NODE_REPL_EXTERNAL_MODULE ?? '' + delete env.NODE_OPTIONS + delete env.NODE_REPL_EXTERNAL_MODULE + env.ELECTRON_RUN_AS_NODE = '1' + return env +} + +export async function runHostOrcaCliPassthrough( + request: RemoteOrcaCliRequest, + options: HostCliPassthroughOptions = {} +): Promise { + // Why: per-field lazy defaults keep the module testable — tests inject all + // three, so no Electron API is touched outside the production path. + const execPath = options.execPath ?? process.execPath + let cliEntryPath: string + let userDataPath: string + try { + cliEntryPath = + options.cliEntryPath ?? + resolveHostCliEntryPath({ + isPackaged: app.isPackaged, + resourcesPath: process.resourcesPath, + appPath: app.getAppPath() + }) + // Why: must match the userData dir the runtime RPC server writes metadata + // to (see index.ts OrcaRuntimeRpcServer wiring), or the CLI subprocess + // reports "Orca is not running" against a healthy app. + userDataPath = options.userDataPath ?? getCanonicalUserDataPath() + } catch (err) { + // Why: no Electron app context (or broken install paths) — degrade to the + // caller's legacy in-process fallback instead of failing the command. + throw new HostCliUnavailableError( + `Host CLI environment unavailable: ${err instanceof Error ? err.message : String(err)}` + ) + } + const hostEnv = options.hostEnv ?? process.env + const spawn = options.spawn ?? nodeSpawn + const entryExists = options.entryExists ?? existsSync + const killTimeoutMs = options.killTimeoutMs ?? resolveHostCliKillTimeoutMs(request.argv) + + if (!entryExists(cliEntryPath)) { + throw new HostCliUnavailableError(`Orca CLI entry not found at ${cliEntryPath}`) + } + + const env = buildHostCliEnv({ + hostEnv, + remoteEnv: request.env, + userDataPath, + remoteCwd: request.cwd + }) + + return await new Promise((resolve, reject) => { + let settled = false + const child = spawn(execPath, [cliEntryPath, ...request.argv], { + env, + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true + }) + + const stdout = new CappedOutputCollector(MAX_CAPTURED_OUTPUT_BYTES) + const stderr = new CappedOutputCollector(MAX_CAPTURED_OUTPUT_BYTES) + + const killTimer = setTimeout(() => { + if (settled) { + return + } + settled = true + try { + child.kill('SIGKILL') + } catch { + // best effort — process may already be gone + } + resolve({ + stdout: stdout.toString(), + stderr: `${stderr.toString()}Orca CLI bridge timed out after ${killTimeoutMs}ms on the host.\n`, + exitCode: 1 + }) + }, killTimeoutMs) + killTimer.unref?.() + + child.on('error', (err) => { + if (settled) { + return + } + settled = true + clearTimeout(killTimer) + // Why: failure to launch (ENOENT, EACCES) means the host CLI is not + // runnable at all — signal the caller to use the legacy fallback rather + // than reporting a confusing per-command failure. + reject( + new HostCliUnavailableError(`Failed to launch the Orca CLI on the host: ${err.message}`) + ) + }) + + child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk)) + child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk)) + + child.on('close', (code) => { + if (settled) { + return + } + settled = true + clearTimeout(killTimer) + resolve({ + stdout: stdout.toString(), + stderr: stderr.toString(), + exitCode: typeof code === 'number' ? code : 1 + }) + }) + + if (child.stdin) { + child.stdin.on('error', () => { + // Why: the CLI may exit without draining stdin; EPIPE here is routine. + }) + if (request.stdin !== undefined) { + child.stdin.end(request.stdin) + } else { + child.stdin.end() + } + } + }) +} + +class CappedOutputCollector { + private readonly chunks: Buffer[] = [] + private bytes = 0 + private truncated = false + + constructor(private readonly maxBytes: number) {} + + push(chunk: Buffer): void { + if (this.truncated) { + return + } + const remaining = this.maxBytes - this.bytes + if (chunk.length >= remaining) { + this.chunks.push(chunk.subarray(0, remaining)) + this.bytes = this.maxBytes + this.truncated = true + return + } + this.chunks.push(chunk) + this.bytes += chunk.length + } + + toString(): string { + const text = Buffer.concat(this.chunks).toString('utf8') + return this.truncated ? `${text}\n[orca ssh cli] output truncated\n` : text + } +} + +function parseTimeoutMsFlag(argv: string[]): number | null { + for (let i = 0; i < argv.length; i += 1) { + const token = argv[i] + if (token === '--timeout-ms') { + const next = argv[i + 1] + const parsed = next === undefined ? Number.NaN : Number(next) + return Number.isFinite(parsed) ? parsed : null + } + if (token.startsWith('--timeout-ms=')) { + const parsed = Number(token.slice('--timeout-ms='.length)) + return Number.isFinite(parsed) ? parsed : null + } + } + return null +} diff --git a/src/main/ssh/ssh-remote-orca-cli.test.ts b/src/main/ssh/ssh-remote-orca-cli.test.ts index c64443876dde..f54c2157c55f 100644 --- a/src/main/ssh/ssh-remote-orca-cli.test.ts +++ b/src/main/ssh/ssh-remote-orca-cli.test.ts @@ -1,7 +1,45 @@ +import { EventEmitter } from 'node:events' import { describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { + isPackaged: false, + getAppPath: () => '/host/app' + } +})) +vi.mock('../persistence', () => ({ + getCanonicalUserDataPath: () => '/host/user-data' +})) + import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { HostCliPassthroughOptions } from './ssh-remote-cli-host-passthrough' import { runRemoteOrcaCli } from './ssh-remote-orca-cli' +// Why: pointing the passthrough at a missing CLI entry forces the legacy +// in-process fallback, which is what these dispatch tests exercise. +const LEGACY_FALLBACK_OPTIONS: HostCliPassthroughOptions = { + execPath: '/host/electron', + cliEntryPath: '/host/app/out/cli/index.js', + userDataPath: '/host/user-data', + entryExists: () => false +} + +type FakeChild = EventEmitter & { + stdout: EventEmitter + stderr: EventEmitter + stdin: { end: ReturnType; on: ReturnType } + kill: ReturnType +} + +function createFakeChild(): FakeChild { + const child = new EventEmitter() as FakeChild + child.stdout = new EventEmitter() + child.stderr = new EventEmitter() + child.stdin = { end: vi.fn(), on: vi.fn() } + child.kill = vi.fn() + return child +} + describe('runRemoteOrcaCli', () => { function createRuntime() { const messages: { @@ -93,11 +131,15 @@ describe('runRemoteOrcaCli', () => { it('uses the remote ORCA_TERMINAL_HANDLE as orchestration sender identity', async () => { const { runtime, db } = createRuntime() - const result = await runRemoteOrcaCli(runtime, { - argv: ['orchestration', 'send', '--to', 'term_windows', '--subject', 'ping', '--json'], - cwd: '/home/alice/repo', - env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } - }) + const result = await runRemoteOrcaCli( + runtime, + { + argv: ['orchestration', 'send', '--to', 'term_windows', '--subject', 'ping', '--json'], + cwd: '/home/alice/repo', + env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } + }, + LEGACY_FALLBACK_OPTIONS + ) expect(result.exitCode).toBe(0) const payload = JSON.parse(result.stdout) as { ok: boolean } @@ -108,18 +150,22 @@ describe('runRemoteOrcaCli', () => { it('accepts equals-style orchestration flags in the remote shim', async () => { const { runtime, db } = createRuntime() - const result = await runRemoteOrcaCli(runtime, { - argv: [ - 'orchestration', - 'send', - '--to=term_windows', - '--subject=ping', - '--body=--literal-body', - '--json' - ], - cwd: '/home/alice/repo', - env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } - }) + const result = await runRemoteOrcaCli( + runtime, + { + argv: [ + 'orchestration', + 'send', + '--to=term_windows', + '--subject=ping', + '--body=--literal-body', + '--json' + ], + cwd: '/home/alice/repo', + env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } + }, + LEGACY_FALLBACK_OPTIONS + ) expect(result.exitCode).toBe(0) const payload = JSON.parse(result.stdout) as { ok: boolean } @@ -138,11 +184,15 @@ describe('runRemoteOrcaCli', () => { body: 'hello' }) - const result = await runRemoteOrcaCli(runtime, { - argv: ['orchestration', 'check', '--all', '--json'], - cwd: '/home/alice/repo', - env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } - }) + const result = await runRemoteOrcaCli( + runtime, + { + argv: ['orchestration', 'check', '--all', '--json'], + cwd: '/home/alice/repo', + env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } + }, + LEGACY_FALLBACK_OPTIONS + ) expect(result.exitCode).toBe(0) const payload = JSON.parse(result.stdout) as { @@ -153,4 +203,92 @@ describe('runRemoteOrcaCli', () => { expect(payload.result.count).toBe(1) expect(payload.result.messages[0]?.subject).toBe('pong') }) + + it('routes previously-unsupported commands through the full host CLI', async () => { + const { runtime } = createRuntime() + const child = createFakeChild() + const spawn = vi.fn(() => child) + + const resultPromise = runRemoteOrcaCli( + runtime, + { + argv: ['worktree', 'create', '--repo', 'orca', '--branch', 'fix/x', '--json'], + cwd: '/home/alice/repo', + env: { ORCA_TERMINAL_HANDLE: 'term_ssh' } + }, + { + execPath: '/host/electron', + cliEntryPath: '/host/app/out/cli/index.js', + userDataPath: '/host/user-data', + entryExists: () => true, + spawn: spawn as never + } + ) + + await Promise.resolve() + child.stdout.emit('data', Buffer.from('{"ok":true}\n')) + child.emit('close', 0) + + const result = await resultPromise + expect(result).toEqual({ stdout: '{"ok":true}\n', stderr: '', exitCode: 0 }) + const [, args] = spawn.mock.calls[0] as unknown as [string, string[]] + expect(args).toEqual([ + '/host/app/out/cli/index.js', + 'worktree', + 'create', + '--repo', + 'orca', + '--branch', + 'fix/x', + '--json' + ]) + }) + + it('rejects host-interactive commands with a targeted error instead of bridging them', async () => { + const { runtime } = createRuntime() + const spawn = vi.fn() + + const result = await runRemoteOrcaCli( + runtime, + { argv: ['serve'], cwd: '/home/alice', env: {} }, + { ...LEGACY_FALLBACK_OPTIONS, spawn: spawn as never } + ) + + expect(result.exitCode).toBe(1) + expect(result.stderr).toContain('orca serve') + expect(result.stderr).toContain('SSH relay bridge') + expect(spawn).not.toHaveBeenCalled() + }) + + it('reports host-interactive command errors as JSON envelopes with --json', async () => { + const { runtime } = createRuntime() + + const result = await runRemoteOrcaCli( + runtime, + { argv: ['serve', '--json'], cwd: '/home/alice', env: {} }, + LEGACY_FALLBACK_OPTIONS + ) + + expect(result.exitCode).toBe(1) + const payload = JSON.parse(result.stdout) as { + ok: boolean + error: { code: string } + } + expect(payload.ok).toBe(false) + expect(payload.error.code).toBe('unsupported_over_ssh') + }) + + it('explains the root cause when falling back and the command is not in the legacy switch', async () => { + const { runtime } = createRuntime() + + const result = await runRemoteOrcaCli( + runtime, + { argv: ['worktree', 'list'], cwd: '/home/alice', env: {} }, + LEGACY_FALLBACK_OPTIONS + ) + + expect(result.exitCode).toBe(1) + expect(result.stderr).toContain('Unsupported SSH Orca CLI command: worktree list') + expect(result.stderr).toContain('full Orca CLI bridge unavailable') + }) }) diff --git a/src/main/ssh/ssh-remote-orca-cli.ts b/src/main/ssh/ssh-remote-orca-cli.ts index d61fe4f25cf7..d555b5c2707b 100644 --- a/src/main/ssh/ssh-remote-orca-cli.ts +++ b/src/main/ssh/ssh-remote-orca-cli.ts @@ -3,30 +3,38 @@ import { RpcDispatcher } from '../runtime/rpc/dispatcher' import type { RpcResponse } from '../runtime/rpc/core' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { formatRemoteCli } from './ssh-remote-cli-format' +import { + HostCliUnavailableError, + runHostOrcaCliPassthrough, + type HostCliPassthroughOptions, + type RemoteOrcaCliRequest, + type RemoteOrcaCliResult +} from './ssh-remote-cli-host-passthrough' import { RemoteCliArgumentError, getRemoteLinearHelp, tryDispatchRemoteLinearCli } from './ssh-remote-linear-cli' -export type RemoteOrcaCliRequest = { - argv: string[] - cwd: string - env: Record - stdin?: string -} - -export type RemoteOrcaCliResult = { - stdout: string - stderr: string - exitCode: number -} +export type { RemoteOrcaCliRequest, RemoteOrcaCliResult } from './ssh-remote-cli-host-passthrough' type ParsedRemoteCli = { commandPath: string[] flags: Map } +// Why: these commands run a foreground/interactive process attached to the +// caller's TTY (or a local tmux pane), which a buffered one-shot relay bridge +// cannot host. Everything else routes through the full host CLI. +const HOST_INTERACTIVE_COMMANDS: Record = { + serve: + 'orca serve starts a foreground headless Orca server and cannot run through the SSH relay bridge. Run it directly on the machine that should host Orca.', + 'claude-teams': + 'orca claude-teams starts an interactive Claude Code session and cannot run through the SSH relay bridge. Run it in a terminal on the Orca host machine.', + 'agent-teams-tmux': + 'orca agent-teams-tmux is a tmux pane shim for the Orca host machine and cannot run through the SSH relay bridge.' +} + const REMOTE_BOOLEAN_FLAGS = new Set([ 'all', 'attachments', @@ -48,18 +56,60 @@ const REPEATABLE_REMOTE_STRING_FLAGS = new Set(['label']) export async function runRemoteOrcaCli( runtime: OrcaRuntimeService, - request: RemoteOrcaCliRequest + request: RemoteOrcaCliRequest, + passthroughOptions?: HostCliPassthroughOptions ): Promise { - const dispatcher = new RpcDispatcher({ runtime }) const parsed = parseRemoteCliArgs(request.argv) const json = parsed.flags.has('json') + + const interactiveMessage = HOST_INTERACTIVE_COMMANDS[parsed.commandPath[0] ?? ''] + if (interactiveMessage) { + if (json) { + return { + stdout: `${JSON.stringify(buildLocalError(interactiveMessage, 'unsupported_over_ssh'), null, 2)}\n`, + stderr: '', + exitCode: 1 + } + } + return { stdout: '', stderr: `${interactiveMessage}\n`, exitCode: 1 } + } + + let passthroughFailure: HostCliUnavailableError | null = null + try { + return await runHostOrcaCliPassthrough(request, passthroughOptions) + } catch (err) { + if (!(err instanceof HostCliUnavailableError)) { + throw err + } + // Why: fall back to the legacy in-process command switch below so the + // historical read-only/orchestration surface keeps working even when the + // bundled CLI entry cannot be launched on this install. + passthroughFailure = err + } + return await runLegacyRemoteOrcaCli(runtime, request, parsed, json, passthroughFailure) +} + +async function runLegacyRemoteOrcaCli( + runtime: OrcaRuntimeService, + request: RemoteOrcaCliRequest, + parsed: ParsedRemoteCli, + json: boolean, + passthroughFailure: HostCliUnavailableError +): Promise { + const dispatcher = new RpcDispatcher({ runtime }) const help = getRemoteLinearHelp(parsed) if (help) { return { stdout: `${help}\n`, stderr: '', exitCode: 0 } } try { - const response = await dispatchRemoteCli(dispatcher, parsed, request.env, request.stdin) + const response = await dispatchRemoteCli( + dispatcher, + parsed, + request.env, + request.stdin, + passthroughFailure.message + ) const formatted = json ? { stdout: `${JSON.stringify(response, null, 2)}\n`, stderr: '' } : formatRemoteCli(response) @@ -93,7 +143,8 @@ async function dispatchRemoteCli( dispatcher: RpcDispatcher, parsed: ParsedRemoteCli, env: Record, - stdin?: string + stdin: string | undefined, + passthroughFailureReason: string ): Promise { const command = parsed.commandPath.join(' ') const linearResponse = await tryDispatchRemoteLinearCli(dispatcher, parsed, env, stdin) @@ -156,7 +207,12 @@ async function dispatchRemoteCli( terminal: optionalString(parsed.flags, 'terminal') }) default: - throw new Error(`Unsupported SSH Orca CLI command: ${command}`) + // Why: only reachable when the full host CLI could not be launched; + // include that root cause so users can fix the install instead of + // assuming the command family is unsupported over SSH. + throw new Error( + `Unsupported SSH Orca CLI command: ${command} (full Orca CLI bridge unavailable: ${passthroughFailureReason})` + ) } } diff --git a/src/main/ssh/ssh-target-id-migration.test.ts b/src/main/ssh/ssh-target-id-migration.test.ts new file mode 100644 index 000000000000..fa6507d62606 --- /dev/null +++ b/src/main/ssh/ssh-target-id-migration.test.ts @@ -0,0 +1,139 @@ +import { describe, it, expect } from 'vitest' +import type { PersistedUIState, TerminalTab, WorkspaceSessionState } from '../../shared/types' +import { + migrateUiHostScopeSshTargetId, + migrateWorkspaceSessionSshTargetId +} from './ssh-target-id-migration' + +const OLD_ID = 'ssh-1783337351840-ohabf0' +const NEW_ID = 'ssh-1783400000000-fresh1' + +const makeTab = (overrides: Partial = {}): TerminalTab => ({ + id: 'tab1', + ptyId: null, + worktreeId: 'r1::/wt', + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1, + ...overrides +}) + +const makeSession = (overrides: Partial = {}): WorkspaceSessionState => ({ + activeRepoId: null, + activeWorktreeId: null, + activeTabId: null, + tabsByWorktree: {}, + terminalLayoutsByTabId: {}, + ...overrides +}) + +describe('migrateWorkspaceSessionSshTargetId', () => { + it('re-encodes SSH pty ids embedded in tabs, layouts, and remote session ids', () => { + const session = makeSession({ + tabsByWorktree: { + 'r1::/wt': [ + makeTab({ id: 'tab1', ptyId: `ssh:${OLD_ID}@@pty-3` }), + makeTab({ id: 'tab2', ptyId: 'local-pty-7' }), + makeTab({ id: 'tab3', ptyId: `ssh:other-target@@pty-1` }) + ] + }, + terminalLayoutsByTabId: { + tab1: { + root: { type: 'leaf', leafId: 'leaf-1' }, + activeLeafId: 'leaf-1', + expandedLeafId: null, + ptyIdsByLeafId: { 'leaf-1': `ssh:${OLD_ID}@@pty-3` } + } + }, + remoteSessionIdsByTabId: { + tab1: `ssh:${OLD_ID}@@pty-3`, + tab3: `ssh:other-target@@pty-1` + } + }) + + expect(migrateWorkspaceSessionSshTargetId(session, OLD_ID, NEW_ID)).toBe(true) + + const tabs = session.tabsByWorktree['r1::/wt'] + expect(tabs[0].ptyId).toBe(`ssh:${NEW_ID}@@pty-3`) + // Local and other-target pty ids must be untouched. + expect(tabs[1].ptyId).toBe('local-pty-7') + expect(tabs[2].ptyId).toBe(`ssh:other-target@@pty-1`) + expect(session.terminalLayoutsByTabId.tab1.ptyIdsByLeafId).toEqual({ + 'leaf-1': `ssh:${NEW_ID}@@pty-3` + }) + expect(session.remoteSessionIdsByTabId).toEqual({ + tab1: `ssh:${NEW_ID}@@pty-3`, + tab3: `ssh:other-target@@pty-1` + }) + }) + + it('replaces the old id in activeConnectionIdsAtShutdown and dedupes', () => { + const session = makeSession({ + activeConnectionIdsAtShutdown: [OLD_ID, NEW_ID, 'ssh-unrelated'] + }) + + expect(migrateWorkspaceSessionSshTargetId(session, OLD_ID, NEW_ID)).toBe(true) + expect(session.activeConnectionIdsAtShutdown).toEqual([NEW_ID, 'ssh-unrelated']) + }) + + it('re-points sleeping agent records pinned to the old connection', () => { + const session = makeSession({ + sleepingAgentSessionsByPaneKey: { + 'tab1:leaf-1': { + paneKey: 'tab1:leaf-1', + worktreeId: 'r1::/wt', + agent: 'claude', + providerSession: { key: 'session_id', id: 's-1' }, + prompt: 'p', + state: 'done', + capturedAt: 1, + updatedAt: 1, + connectionId: OLD_ID + } + } + }) + + expect(migrateWorkspaceSessionSshTargetId(session, OLD_ID, NEW_ID)).toBe(true) + expect(session.sleepingAgentSessionsByPaneKey?.['tab1:leaf-1'].connectionId).toBe(NEW_ID) + }) + + it('returns false when nothing references the old id', () => { + const session = makeSession({ + tabsByWorktree: { 'r1::/wt': [makeTab({ ptyId: 'local-pty' })] }, + activeConnectionIdsAtShutdown: ['ssh-unrelated'] + }) + + expect(migrateWorkspaceSessionSshTargetId(session, OLD_ID, NEW_ID)).toBe(false) + expect(session.activeConnectionIdsAtShutdown).toEqual(['ssh-unrelated']) + }) +}) + +describe('migrateUiHostScopeSshTargetId', () => { + const makeUi = (overrides: Partial): PersistedUIState => + ({ ...overrides }) as PersistedUIState + + it('re-points scope, visible hosts, and host order, deduping collisions', () => { + const ui = makeUi({ + workspaceHostScope: `ssh:${OLD_ID}`, + visibleWorkspaceHostIds: ['local', `ssh:${OLD_ID}`, `ssh:${NEW_ID}`], + workspaceHostOrder: [`ssh:${OLD_ID}`, 'local'] + }) + + expect(migrateUiHostScopeSshTargetId(ui, OLD_ID, NEW_ID)).toBe(true) + expect(ui.workspaceHostScope).toBe(`ssh:${NEW_ID}`) + expect(ui.visibleWorkspaceHostIds).toEqual(['local', `ssh:${NEW_ID}`]) + expect(ui.workspaceHostOrder).toEqual([`ssh:${NEW_ID}`, 'local']) + }) + + it('returns false when the old host id appears nowhere', () => { + const ui = makeUi({ + workspaceHostScope: 'all', + visibleWorkspaceHostIds: ['local'], + workspaceHostOrder: ['local'] + }) + + expect(migrateUiHostScopeSshTargetId(ui, OLD_ID, NEW_ID)).toBe(false) + }) +}) diff --git a/src/main/ssh/ssh-target-id-migration.ts b/src/main/ssh/ssh-target-id-migration.ts new file mode 100644 index 000000000000..a917c4393e9e --- /dev/null +++ b/src/main/ssh/ssh-target-id-migration.ts @@ -0,0 +1,116 @@ +import type { PersistedUIState, WorkspaceSessionState } from '../../shared/types' +import { parseAppSshPtyId, toAppSshPtyId } from '../../shared/ssh-pty-id' +import { toSshExecutionHostId } from '../../shared/execution-host' + +/** + * Carrier sweep for SSH target re-adoption (see ssh-target-readoption.ts). + * + * reassignSshTargetId re-points repos/worktree metas, but the removed target's + * id is also embedded in other persisted state: app-scoped SSH pty ids + * ("ssh:@@pty-N") inside the workspace session, the startup + * reconnect list, sleeping-agent resume records, and the sidebar host-scope + * arrays. Any survivor resurfaces later as `SSH target "" not found` at + * connect/reattach time (STA-1468), so every carrier must migrate together. + * + * All helpers mutate in place (matching how the Store edits this.state) and + * return whether anything changed so callers can gate scheduleSave. + */ + +function rewriteSshPtyId(ptyId: string, oldTargetId: string, newTargetId: string): string | null { + const parsed = parseAppSshPtyId(ptyId) + if (!parsed || parsed.connectionId !== oldTargetId) { + return null + } + return toAppSshPtyId(newTargetId, parsed.relayPtyId) +} + +function rewriteSshPtyIdRecordValues( + record: Record | undefined, + oldTargetId: string, + newTargetId: string +): boolean { + if (!record) { + return false + } + let changed = false + for (const [key, ptyId] of Object.entries(record)) { + const next = rewriteSshPtyId(ptyId, oldTargetId, newTargetId) + if (next) { + record[key] = next + changed = true + } + } + return changed +} + +/** Re-point every old-target-id carrier inside one workspace session partition. */ +export function migrateWorkspaceSessionSshTargetId( + session: WorkspaceSessionState, + oldTargetId: string, + newTargetId: string +): boolean { + let changed = false + for (const tabs of Object.values(session.tabsByWorktree ?? {})) { + for (const tab of tabs) { + if (!tab.ptyId) { + continue + } + const next = rewriteSshPtyId(tab.ptyId, oldTargetId, newTargetId) + if (next) { + tab.ptyId = next + changed = true + } + } + } + for (const layout of Object.values(session.terminalLayoutsByTabId ?? {})) { + if (rewriteSshPtyIdRecordValues(layout.ptyIdsByLeafId, oldTargetId, newTargetId)) { + changed = true + } + } + if (rewriteSshPtyIdRecordValues(session.remoteSessionIdsByTabId, oldTargetId, newTargetId)) { + changed = true + } + if (session.activeConnectionIdsAtShutdown?.includes(oldTargetId)) { + session.activeConnectionIdsAtShutdown = [ + ...new Set( + session.activeConnectionIdsAtShutdown.map((id) => (id === oldTargetId ? newTargetId : id)) + ) + ] + changed = true + } + for (const record of Object.values(session.sleepingAgentSessionsByPaneKey ?? {})) { + if (record.connectionId === oldTargetId) { + record.connectionId = newTargetId + changed = true + } + } + return changed +} + +/** Re-point the sidebar host-scope arrays pinned to the old SSH host id. */ +export function migrateUiHostScopeSshTargetId( + ui: PersistedUIState, + oldTargetId: string, + newTargetId: string +): boolean { + const oldHostId = toSshExecutionHostId(oldTargetId) + const newHostId = toSshExecutionHostId(newTargetId) + let changed = false + if (ui.workspaceHostScope === oldHostId) { + ui.workspaceHostScope = newHostId + changed = true + } + if (ui.visibleWorkspaceHostIds?.includes(oldHostId)) { + ui.visibleWorkspaceHostIds = [ + ...new Set(ui.visibleWorkspaceHostIds.map((id) => (id === oldHostId ? newHostId : id))) + ] + changed = true + } + if (ui.workspaceHostOrder?.includes(oldHostId)) { + ui.workspaceHostOrder = [ + ...new Set(ui.workspaceHostOrder.map((id) => (id === oldHostId ? newHostId : id))) + ] + changed = true + } + return changed +} diff --git a/src/main/ssh/ssh-target-readoption.test.ts b/src/main/ssh/ssh-target-readoption.test.ts new file mode 100644 index 000000000000..f263fe01d882 --- /dev/null +++ b/src/main/ssh/ssh-target-readoption.test.ts @@ -0,0 +1,198 @@ +import { describe, it, expect } from 'vitest' +import { + buildRemovedSshTargetTombstone, + readoptOrphanedWorkspacesForTarget +} from './ssh-target-readoption' +import type { Store } from '../persistence' +import type { RemovedSshTargetTombstone, SshTarget } from '../../shared/ssh-types' + +function makeTarget(overrides: Partial = {}): SshTarget { + return { + id: 'ssh-new', + label: 'Dev box', + host: 'dev.example.com', + port: 22, + username: 'tim', + ...overrides + } +} + +/** Minimal in-memory store exposing only what re-adoption touches. */ +function makeFakeStore(tombstones: RemovedSshTargetTombstone[]) { + const reassigned: { oldId: string; newId: string }[] = [] + let current = [...tombstones] + const store = { + getRemovedSshTargetTombstones: () => [...current], + removeRemovedSshTargetTombstone: (oldTargetId: string) => { + current = current.filter((t) => t.oldTargetId !== oldTargetId) + }, + reassignSshTargetId: (oldTargetId: string, newTargetId: string) => { + reassigned.push({ oldId: oldTargetId, newId: newTargetId }) + return 1 + } + } as unknown as Store + return { store, reassigned, remaining: () => current } +} + +const tombstone = ( + overrides: Partial = {} +): RemovedSshTargetTombstone => ({ + oldTargetId: 'ssh-old', + host: 'dev.example.com', + port: 22, + username: 'tim', + label: 'Dev box', + removedAt: 1, + ...overrides +}) + +describe('readoptOrphanedWorkspacesForTarget', () => { + it('re-adopts on matching configHost alias', () => { + const fake = makeFakeStore([tombstone({ configHost: 'devbox', host: 'changed.example.com' })]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ configHost: 'devbox', host: 'now.example.com' }) + ) + expect(count).toBe(1) + expect(fake.reassigned).toEqual([{ oldId: 'ssh-old', newId: 'ssh-new' }]) + expect(fake.remaining()).toHaveLength(0) // tombstone consumed + }) + + it('re-adopts on matching host+user+port when no alias', () => { + const fake = makeFakeStore([tombstone()]) + const count = readoptOrphanedWorkspacesForTarget(fake.store, makeTarget()) + expect(count).toBe(1) + expect(fake.reassigned).toEqual([{ oldId: 'ssh-old', newId: 'ssh-new' }]) + }) + + it('does not re-adopt when identity differs', () => { + const fake = makeFakeStore([tombstone({ host: 'other.example.com', username: 'root' })]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ host: 'dev.example.com', username: 'tim' }) + ) + expect(count).toBe(0) + expect(fake.reassigned).toEqual([]) + expect(fake.remaining()).toHaveLength(1) // tombstone left for a future match + }) + + it('matches host/user/port case-insensitively', () => { + const fake = makeFakeStore([tombstone({ host: 'Dev.Example.COM', username: 'Tim' })]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ host: 'dev.example.com', username: 'tim' }) + ) + expect(count).toBe(1) + }) + + it('does not match alias against a different host tuple', () => { + // Different alias AND different tuple => no match. + const fake = makeFakeStore([ + tombstone({ configHost: 'prod', host: 'prod.example.com', username: 'root' }) + ]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ configHost: 'devbox', host: 'dev.example.com', username: 'tim' }) + ) + expect(count).toBe(0) + }) + + it('is a no-op when there are no tombstones', () => { + const fake = makeFakeStore([]) + expect(readoptOrphanedWorkspacesForTarget(fake.store, makeTarget())).toBe(0) + }) + + it('does NOT re-adopt across two different aliases that share host+user+port', () => { + // prod-deploy removed; prod-admin re-added — same box, different alias. + // These are deliberately distinct targets and must not steal workspaces. + const fake = makeFakeStore([ + tombstone({ configHost: 'prod-deploy', host: 'prod.example.com', username: 'deploy' }) + ]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ configHost: 'prod-admin', host: 'prod.example.com', username: 'deploy' }) + ) + expect(count).toBe(0) + expect(fake.reassigned).toEqual([]) + expect(fake.remaining()).toHaveLength(1) // tombstone preserved + }) + + it('does NOT re-adopt a different account/port on the same host (implicit alias)', () => { + // Manual adds default configHost to host, so both carry configHost === host. + // That is NOT a real alias — matching on it alone would ignore port/username + // and reattach workspaces to the wrong SSH account on the same machine. + const fake = makeFakeStore([ + tombstone({ + configHost: 'dev.example.com', + host: 'dev.example.com', + port: 22, + username: 'alice' + }) + ]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ + configHost: 'dev.example.com', + host: 'dev.example.com', + port: 2222, + username: 'bob' + }) + ) + expect(count).toBe(0) + expect(fake.reassigned).toEqual([]) + }) + + it('re-adopts the same account/host/port even with implicit configHost === host', () => { + const fake = makeFakeStore([ + tombstone({ + configHost: 'dev.example.com', + host: 'dev.example.com', + port: 22, + username: 'alice' + }) + ]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ + configHost: 'dev.example.com', + host: 'dev.example.com', + port: 22, + username: 'alice' + }) + ) + expect(count).toBe(1) + }) + + it('still re-adopts via tuple when the re-added target has no alias', () => { + // Manual re-add (no configHost) of a host that was config-managed: fall back + // to the tuple since one side lacks an alias to distinguish it. + const fake = makeFakeStore([ + tombstone({ configHost: 'devbox', host: 'dev.example.com', username: 'tim' }) + ]) + const count = readoptOrphanedWorkspacesForTarget( + fake.store, + makeTarget({ configHost: undefined, host: 'dev.example.com', username: 'tim' }) + ) + expect(count).toBe(1) + }) +}) + +describe('buildRemovedSshTargetTombstone', () => { + it('captures identity fields and omits configHost when absent', () => { + const t = buildRemovedSshTargetTombstone(makeTarget(), 123) + expect(t).toEqual({ + oldTargetId: 'ssh-new', + host: 'dev.example.com', + port: 22, + username: 'tim', + label: 'Dev box', + removedAt: 123 + }) + expect('configHost' in t).toBe(false) + }) + + it('includes configHost when present', () => { + const t = buildRemovedSshTargetTombstone(makeTarget({ configHost: 'devbox' }), 1) + expect(t.configHost).toBe('devbox') + }) +}) diff --git a/src/main/ssh/ssh-target-readoption.ts b/src/main/ssh/ssh-target-readoption.ts new file mode 100644 index 000000000000..06b0cefd8ec0 --- /dev/null +++ b/src/main/ssh/ssh-target-readoption.ts @@ -0,0 +1,99 @@ +import type { Store } from '../persistence' +import type { RemovedSshTargetTombstone, SshTarget } from '../../shared/ssh-types' + +/** + * Re-adoption of workspaces orphaned when an SSH target was removed. + * + * Repos/worktrees store only the (random) target id, so removing a target + * strands them on a dead id. When the user re-adds the same host, a fresh id is + * minted and nothing links the old workspaces to it. We bridge that gap using + * removal-time tombstones ({ oldTargetId, configHost, host, username, port }): + * on add/import we match the new target's identity to a tombstone and re-point + * every repo/worktree from the old id to the new one. + * + * Matching is intentionally strict — configHost (alias) first, then the + * host+username+port tuple — so we only auto-reattach on a confident identity + * match and never mislink two genuinely different hosts. Anything that doesn't + * match cleanly stays a ghost, handled by the forget flow instead. + */ + +type IdentityFields = Pick + +function normalize(value: string | undefined): string { + return value?.trim().toLowerCase() ?? '' +} + +function tupleKey(fields: IdentityFields): string { + return `${normalize(fields.host)}|${fields.port}|${normalize(fields.username)}` +} + +// An alias only counts as a distinguishing identity when it differs from the +// host. addTarget defaults configHost to host, so a manual add with no real +// ssh-config alias has configHost === host — that's not an alias, it's just the +// hostname, and matching on it alone would ignore port/username. +function meaningfulAlias(fields: IdentityFields): string { + const alias = normalize(fields.configHost) + return alias && alias !== normalize(fields.host) ? alias : '' +} + +function tombstoneMatches(tombstone: RemovedSshTargetTombstone, target: IdentityFields): boolean { + const targetAlias = meaningfulAlias(target) + const tombstoneAlias = meaningfulAlias(tombstone) + // Primary: matching ssh-config alias. Stable across remove/re-import. + if (targetAlias && tombstoneAlias) { + // Both carry a real alias — the alias is the identity. Different aliases + // mean deliberately distinct targets (e.g. prod-deploy vs prod-admin on the + // same box with different identity files); do NOT fall through to the tuple, + // or a second alias for the same endpoint would steal the first's workspaces. + return targetAlias === tombstoneAlias + } + // Fallback: identical host+user+port. Used when either side has no real alias + // (manual adds default configHost to host), so a different account or port on + // the same host is correctly treated as a different target. + return tupleKey(tombstone) === tupleKey(target) +} + +/** + * Re-point orphaned repos/worktrees onto `newTarget` if a removed target with + * the same host identity is tombstoned. Consumes the matching tombstone(s). + * Returns the number of repos re-adopted (0 when there was nothing to adopt). + */ +export function readoptOrphanedWorkspacesForTarget(store: Store, newTarget: SshTarget): number { + const tombstones = store.getRemovedSshTargetTombstones() + if (tombstones.length === 0) { + return 0 + } + let readopted = 0 + for (const tombstone of tombstones) { + // Why: a re-added target can't share the id of one that still exists, but + // guard anyway so we never re-point a live target onto itself. + if (tombstone.oldTargetId === newTarget.id) { + store.removeRemovedSshTargetTombstone(tombstone.oldTargetId) + continue + } + if (!tombstoneMatches(tombstone, newTarget)) { + continue + } + readopted += store.reassignSshTargetId(tombstone.oldTargetId, newTarget.id) + // Consume the tombstone whether or not it re-pointed anything: the host has + // returned, so the record has served its purpose. + store.removeRemovedSshTargetTombstone(tombstone.oldTargetId) + } + return readopted +} + +/** Build a tombstone from a target about to be removed. */ +export function buildRemovedSshTargetTombstone( + target: SshTarget, + removedAt: number +): RemovedSshTargetTombstone { + return { + oldTargetId: target.id, + ...(target.configHost ? { configHost: target.configHost } : {}), + host: target.host, + port: target.port, + username: target.username, + label: target.label, + removedAt + } +} diff --git a/src/main/ssh/system-ssh-port-forward-provider.ts b/src/main/ssh/system-ssh-port-forward-provider.ts index 74227f67cfe8..e2b53abab7b8 100644 --- a/src/main/ssh/system-ssh-port-forward-provider.ts +++ b/src/main/ssh/system-ssh-port-forward-provider.ts @@ -33,9 +33,17 @@ export class SystemSshPortForwardProvider implements SshPortForwardProvider { ) await forward.waitForStartup() + // Why: this stderr stays attached for the forward's whole lifetime but is + // only used to build the exit-error detail, so keep a bounded tail — a chatty + // remote sshd could otherwise grow it unbounded on a long-lived forward + // (mirrors MAX_RELAY_STARTUP_BUFFER_BYTES in ssh-relay-deploy-helpers). + const MAX_STDERR_TAIL_BYTES = 64 * 1024 let stderr = '' const onStderr = (chunk: Buffer): void => { stderr += chunk.toString('utf-8') + if (stderr.length > MAX_STDERR_TAIL_BYTES) { + stderr = stderr.slice(-MAX_STDERR_TAIL_BYTES) + } } forward.process.stderr?.on('data', onStderr) diff --git a/src/main/synthetic-title-frame-routing.test.ts b/src/main/synthetic-title-frame-routing.test.ts new file mode 100644 index 000000000000..b4bbf35ecd2d --- /dev/null +++ b/src/main/synthetic-title-frame-routing.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { shouldCopySyntheticTitleFrameToPtyData } from './synthetic-title-frame-routing' + +describe('shouldCopySyntheticTitleFrameToPtyData', () => { + it('keeps the legacy pty:data copy only while the kill switch is off', () => { + // Authority off: renderer byte parsers are the sole synthetic-frame + // consumer, so the legacy copy must keep flowing. + expect(shouldCopySyntheticTitleFrameToPtyData({ terminalMainSideEffectAuthority: false })).toBe( + true + ) + }) + + it('skips the copy under main authority — tracker ingest is the only consumer', () => { + // Why: under authority the copy would only mint phantom renderer ACKs + // for fabricated bytes main never metered. + expect(shouldCopySyntheticTitleFrameToPtyData({ terminalMainSideEffectAuthority: true })).toBe( + false + ) + // Default-on: an unset switch means main authority. + expect(shouldCopySyntheticTitleFrameToPtyData({})).toBe(false) + expect(shouldCopySyntheticTitleFrameToPtyData(null)).toBe(false) + expect(shouldCopySyntheticTitleFrameToPtyData(undefined)).toBe(false) + }) +}) diff --git a/src/main/synthetic-title-frame-routing.ts b/src/main/synthetic-title-frame-routing.ts new file mode 100644 index 000000000000..3bb10a030fa9 --- /dev/null +++ b/src/main/synthetic-title-frame-routing.ts @@ -0,0 +1,14 @@ +import type { GlobalSettings } from '../shared/types' + +/** + * Why: with the side-effect kill switch off, renderer byte parsers are the + * ONLY consumer of main-fabricated OSC title frames, so they must still ride + * `pty:data`. With main authority on (the default), the tracker ingest is the + * sole consumer and the legacy copy would only mint phantom renderer ACKs for + * bytes main never metered. See terminal-side-effect-authority.md (slice 3). + */ +export function shouldCopySyntheticTitleFrameToPtyData( + settings: Pick | null | undefined +): boolean { + return settings?.terminalMainSideEffectAuthority === false +} diff --git a/src/main/system-resume-broadcast.test.ts b/src/main/system-resume-broadcast.test.ts new file mode 100644 index 000000000000..dc67ee27a8a6 --- /dev/null +++ b/src/main/system-resume-broadcast.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it, vi } from 'vitest' +import { registerSystemResumeBroadcast, SYSTEM_RESUMED_CHANNEL } from './system-resume-broadcast' + +vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: vi.fn(() => []) }, + powerMonitor: { on: vi.fn(), off: vi.fn() } +})) + +type ResumeListener = () => void + +function createResumeSource() { + const state: { listener: ResumeListener | null } = { listener: null } + const source = { + on: vi.fn((_event: 'resume', callback: ResumeListener) => { + state.listener = callback + }), + off: vi.fn((_event: 'resume', _callback: ResumeListener) => { + state.listener = null + }) + } + return { source, fireResume: () => state.listener?.() } +} + +function createWindow(destroyed = false): { + isDestroyed: () => boolean + webContents: { send: ReturnType void>> } +} { + return { + isDestroyed: () => destroyed, + webContents: { send: vi.fn<(channel: string) => void>() } + } +} + +describe('registerSystemResumeBroadcast', () => { + it('broadcasts the resume channel to every live window', () => { + const { source, fireResume } = createResumeSource() + const liveWindow = createWindow() + const destroyedWindow = createWindow(true) + registerSystemResumeBroadcast({ + resumeSource: source, + getWindows: () => [liveWindow, destroyedWindow] + }) + + fireResume() + + expect(liveWindow.webContents.send).toHaveBeenCalledWith(SYSTEM_RESUMED_CHANNEL) + expect(destroyedWindow.webContents.send).not.toHaveBeenCalled() + }) + + it('stops broadcasting after unsubscribe', () => { + const { source, fireResume } = createResumeSource() + const window = createWindow() + const unsubscribe = registerSystemResumeBroadcast({ + resumeSource: source, + getWindows: () => [window] + }) + + unsubscribe() + fireResume() + + expect(source.off).toHaveBeenCalledTimes(1) + expect(window.webContents.send).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/system-resume-broadcast.ts b/src/main/system-resume-broadcast.ts new file mode 100644 index 000000000000..990b8d2a66ca --- /dev/null +++ b/src/main/system-resume-broadcast.ts @@ -0,0 +1,39 @@ +import { BrowserWindow, powerMonitor } from 'electron' + +export const SYSTEM_RESUMED_CHANNEL = 'system:resumed' + +type ResumeEventSource = { + on(event: 'resume', listener: () => void): unknown + off(event: 'resume', listener: () => void): unknown +} + +type ResumeBroadcastWindow = { + isDestroyed(): boolean + webContents: { send(channel: string): void } +} + +type SystemResumeBroadcastOptions = { + resumeSource?: ResumeEventSource + getWindows?: () => ResumeBroadcastWindow[] +} + +// Why: renderers cannot observe OS sleep/wake directly, and Linux has no +// window-occlusion tracking so visibilitychange never fires around suspend. +// Wake-sensitive renderer recovery needs this explicit resume signal. +export function registerSystemResumeBroadcast( + options: SystemResumeBroadcastOptions = {} +): () => void { + const resumeSource = options.resumeSource ?? powerMonitor + const getWindows = options.getWindows ?? (() => BrowserWindow.getAllWindows()) + const onResume = (): void => { + for (const window of getWindows()) { + if (!window.isDestroyed()) { + window.webContents.send(SYSTEM_RESUMED_CHANNEL) + } + } + } + resumeSource.on('resume', onResume) + return () => { + resumeSource.off('resume', onResume) + } +} diff --git a/src/main/terminal-scrollback-snapshots.ts b/src/main/terminal-scrollback-snapshots.ts index 2dd41fad7d1f..3929288d588f 100644 --- a/src/main/terminal-scrollback-snapshots.ts +++ b/src/main/terminal-scrollback-snapshots.ts @@ -9,7 +9,7 @@ import { statSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import { app } from 'electron' import type { WorkspaceSessionState } from '../shared/types' import { @@ -20,20 +20,47 @@ import { const SNAPSHOT_DIR_NAME = 'terminal-scrollback' const REF_PREFIX = 'v1' -function getSnapshotRoot(): string { +export type TerminalScrollbackSnapshotStorage = { + snapshotRoot?: string + fallbackSnapshotRoot?: string | null +} + +function getLegacySnapshotRoot(): string { return join(app.getPath('userData'), SNAPSHOT_DIR_NAME) } +export function getProfileTerminalScrollbackSnapshotRoot(dataFile: string): string { + return join(dirname(dataFile), SNAPSHOT_DIR_NAME) +} + +function getSnapshotRoot(storage?: TerminalScrollbackSnapshotStorage): string { + return storage?.snapshotRoot ?? getLegacySnapshotRoot() +} + export function makeTerminalScrollbackSnapshotRef(tabId: string, leafId: string): string { const hash = createHash('sha256').update(`${tabId}\0${leafId}`).digest('hex').slice(0, 32) return `${REF_PREFIX}-${hash}` } -function snapshotPath(ref: string): string | null { +function snapshotPath(ref: string, snapshotRoot: string): string | null { if (!/^v1-[0-9a-f]{32}$/.test(ref)) { return null } - return join(getSnapshotRoot(), `${ref}.bin`) + return join(snapshotRoot, `${ref}.bin`) +} + +function snapshotReadPaths(ref: string, storage?: TerminalScrollbackSnapshotStorage): string[] { + const primaryRoot = getSnapshotRoot(storage) + const primaryPath = snapshotPath(ref, primaryRoot) + if (!primaryPath) { + return [] + } + const fallbackRoot = storage?.fallbackSnapshotRoot ?? null + if (!fallbackRoot || fallbackRoot === primaryRoot) { + return [primaryPath] + } + const fallbackPath = snapshotPath(ref, fallbackRoot) + return fallbackPath ? [primaryPath, fallbackPath] : [primaryPath] } function trailingUtf8Bytes(value: string, maxBytes: number): Buffer { @@ -72,17 +99,19 @@ export function writeTerminalScrollbackSnapshotSync(args: { tabId: string leafId: string buffer: string + storage?: TerminalScrollbackSnapshotStorage }): string | null { if (!args.buffer) { return null } const ref = makeTerminalScrollbackSnapshotRef(args.tabId, args.leafId) - const path = snapshotPath(ref) + const snapshotRoot = getSnapshotRoot(args.storage) + const path = snapshotPath(ref, snapshotRoot) if (!path) { return null } try { - mkdirSync(getSnapshotRoot(), { recursive: true, mode: 0o700 }) + mkdirSync(snapshotRoot, { recursive: true, mode: 0o700 }) const tmpPath = `${path}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp` const bytes = trailingUtf8Bytes(args.buffer, TERMINAL_SCROLLBACK_STORE_BYTE_LIMIT) let renamed = false @@ -104,27 +133,30 @@ export function writeTerminalScrollbackSnapshotSync(args: { } } -export function readTerminalScrollbackSnapshotSync(ref: string): string | null { - const path = snapshotPath(ref) - if (!path) { - return null - } - try { - return readTrailingUtf8(path, TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT) - } catch { - return null +export function readTerminalScrollbackSnapshotSync( + ref: string, + storage?: TerminalScrollbackSnapshotStorage +): string | null { + for (const path of snapshotReadPaths(ref, storage)) { + try { + return readTrailingUtf8(path, TERMINAL_SCROLLBACK_REPLAY_BYTE_LIMIT) + } catch { + // Try the legacy/global fallback when a profile-local snapshot is absent. + } } + return null } -export function deleteTerminalScrollbackSnapshotSync(ref: string): void { - const path = snapshotPath(ref) - if (!path) { - return - } - try { - rmSync(path, { force: true }) - } catch { - // Best-effort cleanup; stale refs are harmless and bounded by per-file caps. +export function deleteTerminalScrollbackSnapshotSync( + ref: string, + storage?: TerminalScrollbackSnapshotStorage +): void { + for (const path of snapshotReadPaths(ref, storage)) { + try { + rmSync(path, { force: true }) + } catch { + // Best-effort cleanup; stale refs are harmless and bounded by per-file caps. + } } } @@ -139,7 +171,8 @@ export function collectTerminalScrollbackSnapshotRefs(session: WorkspaceSessionS } export function migrateWorkspaceSessionTerminalScrollbackSnapshots( - session: WorkspaceSessionState + session: WorkspaceSessionState, + storage?: TerminalScrollbackSnapshotStorage ): { session: WorkspaceSessionState; changed: boolean } { let terminalLayoutsByTabId: WorkspaceSessionState['terminalLayoutsByTabId'] | null = null for (const [tabId, layout] of Object.entries(session.terminalLayoutsByTabId ?? {})) { @@ -151,7 +184,7 @@ export function migrateWorkspaceSessionTerminalScrollbackSnapshots( const remainingBuffers: Record = {} let layoutChanged = false for (const [leafId, buffer] of Object.entries(buffers)) { - const ref = writeTerminalScrollbackSnapshotSync({ tabId, leafId, buffer }) + const ref = writeTerminalScrollbackSnapshotSync({ tabId, leafId, buffer, storage }) if (ref) { refs[leafId] = ref layoutChanged = true diff --git a/src/main/tray/system-tray.test.ts b/src/main/tray/system-tray.test.ts index e269d9307b22..9f5ad72caade 100644 --- a/src/main/tray/system-tray.test.ts +++ b/src/main/tray/system-tray.test.ts @@ -1,21 +1,27 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as SystemTrayModule from './system-tray' -const { trayInstances, menuFromTemplateMock, createAppIconImageMock, resizedImage } = vi.hoisted( - () => { - const resizedImage = { resized: true } - return { - trayInstances: [] as FakeTray[], - menuFromTemplateMock: vi.fn((template: unknown) => ({ template })), - createAppIconImageMock: vi.fn(), - resizedImage - } +const { + trayInstances, + menuFromTemplateMock, + createAppIconImageMock, + composeAttentionMock, + resizedImage +} = vi.hoisted(() => { + const resizedImage = { resized: true } + return { + trayInstances: [] as FakeTray[], + menuFromTemplateMock: vi.fn((template: unknown) => ({ template })), + createAppIconImageMock: vi.fn(), + composeAttentionMock: vi.fn((image: unknown) => ({ dotted: image })), + resizedImage } -) +}) class FakeTray { setToolTip = vi.fn() setContextMenu = vi.fn() + setImage = vi.fn() on = vi.fn() destroy = vi.fn() isDestroyed = vi.fn(() => false) @@ -33,6 +39,10 @@ vi.mock('../app-icon', () => ({ createAppIconImage: createAppIconImageMock })) +vi.mock('./tray-attention-icon', () => ({ + composeTrayAttentionIcon: composeAttentionMock +})) + type TrayModule = typeof SystemTrayModule const originalPlatform = process.platform @@ -55,6 +65,7 @@ function builtMenuItems(): MenuItem[] { beforeEach(() => { trayInstances.length = 0 menuFromTemplateMock.mockClear() + composeAttentionMock.mockClear() createAppIconImageMock.mockReset() createAppIconImageMock.mockReturnValue({ resize: vi.fn(() => resizedImage) }) }) @@ -126,6 +137,57 @@ describe('createSystemTray', () => { }) }) +describe('setTrayAttention', () => { + it('swaps in the dotted icon when active and restores the base when cleared', async () => { + setPlatform('win32') + const { createSystemTray, setTrayAttention } = await loadModule() + createSystemTray({ appIcon: 'classic', onOpen: vi.fn(), onQuit: vi.fn() }) + const tray = trayInstances[0] + tray.setImage.mockClear() + + setTrayAttention(true) + expect(composeAttentionMock).toHaveBeenCalledWith(resizedImage) + expect(tray.setImage).toHaveBeenCalledWith({ dotted: resizedImage }) + + tray.setImage.mockClear() + setTrayAttention(false) + expect(tray.setImage).toHaveBeenCalledWith(resizedImage) + }) + + it('ignores repeated same-state calls', async () => { + setPlatform('win32') + const { createSystemTray, setTrayAttention } = await loadModule() + createSystemTray({ appIcon: 'classic', onOpen: vi.fn(), onQuit: vi.fn() }) + const tray = trayInstances[0] + tray.setImage.mockClear() + + setTrayAttention(true) + setTrayAttention(true) + + expect(tray.setImage).toHaveBeenCalledTimes(1) + }) + + it('reflects attention that was requested before the tray was created', async () => { + setPlatform('win32') + const { createSystemTray, setTrayAttention } = await loadModule() + + // Fire the event before the (deferred) tray exists. + setTrayAttention(true) + createSystemTray({ appIcon: 'classic', onOpen: vi.fn(), onQuit: vi.fn() }) + const tray = trayInstances[0] + + expect(tray.setImage).toHaveBeenCalledWith({ dotted: resizedImage }) + }) + + it('is a safe no-op on non-win32 platforms', async () => { + setPlatform('darwin') + const { setTrayAttention } = await loadModule() + + expect(() => setTrayAttention(true)).not.toThrow() + expect(composeAttentionMock).not.toHaveBeenCalled() + }) +}) + describe('destroySystemTray', () => { it('destroys an existing tray and is safe to call without one', async () => { setPlatform('win32') diff --git a/src/main/tray/system-tray.ts b/src/main/tray/system-tray.ts index d531d2c596b0..ada6f58c4e91 100644 --- a/src/main/tray/system-tray.ts +++ b/src/main/tray/system-tray.ts @@ -1,6 +1,7 @@ -import { Menu, Tray } from 'electron' +import { Menu, Tray, type NativeImage } from 'electron' import { createAppIconImage } from '../app-icon' import { translateMain } from '../i18n/main-i18n' +import { composeTrayAttentionIcon } from './tray-attention-icon' type SystemTrayOptions = { /** App icon id from settings; the tray reuses the app icon image. */ @@ -15,10 +16,28 @@ type SystemTrayOptions = { // reference is kept, so hold it at module scope for the app's lifetime. let tray: Tray | null = null +// Why: hold the plain (dot-free) icon so we can toggle the attention dot on and +// off with tray.setImage without rebuilding the icon from the app-icon PNG. +let baseTrayImage: NativeImage | null = null + +// Why: an attention event can fire while the tray is still being created +// (creation is deferred ~ready-to-show); remember the desired state so a +// freshly created tray reflects it immediately. +let attentionActive = false + // Why: on Windows the notification area expects a 16px icon; the app icon PNG // is larger, so downscale to avoid a cropped/blurry tray glyph. const TRAY_ICON_SIZE = 16 +// Why: centralize which image the tray shows so both creation and attention +// toggling stay in sync. No-ops safely when the tray or base image is missing. +function applyTrayImage(): void { + if (!tray || tray.isDestroyed() || !baseTrayImage) { + return + } + tray.setImage(attentionActive ? composeTrayAttentionIcon(baseTrayImage) : baseTrayImage) +} + /** * Creates the Windows system tray icon. No-op on macOS/Linux. Idempotent: a * second call while a tray is alive returns the existing one instead of @@ -31,11 +50,13 @@ export function createSystemTray(opts: SystemTrayOptions): Tray | null { if (tray && !tray.isDestroyed()) { return tray } - const image = createAppIconImage(opts.appIcon).resize({ + baseTrayImage = createAppIconImage(opts.appIcon).resize({ width: TRAY_ICON_SIZE, height: TRAY_ICON_SIZE }) - tray = new Tray(image) + tray = new Tray(baseTrayImage) + // Why: reflect any attention event that fired before the tray existed. + applyTrayImage() tray.setToolTip('Orca') const menu = Menu.buildFromTemplate([ { label: translateMain('tray.openOrca', 'Open Orca'), click: () => opts.onOpen() }, @@ -49,10 +70,26 @@ export function createSystemTray(opts: SystemTrayOptions): Tray | null { return tray } +/** + * Shows or hides a red/amber attention dot on the tray icon. Call with `true` + * when a terminal bell or agent completion fires while the window is + * minimized/hidden, and `false` once the window is shown again. No-op on + * macOS/Linux (no tray) and safe to call before the tray is created. + */ +export function setTrayAttention(active: boolean): void { + if (attentionActive === active) { + return + } + attentionActive = active + applyTrayImage() +} + /** Destroys the tray icon if present. Safe to call repeatedly or with no tray. */ export function destroySystemTray(): void { if (tray && !tray.isDestroyed()) { tray.destroy() } tray = null + baseTrayImage = null + attentionActive = false } diff --git a/src/main/tray/tray-attention-icon.test.ts b/src/main/tray/tray-attention-icon.test.ts new file mode 100644 index 000000000000..42d554417e06 --- /dev/null +++ b/src/main/tray/tray-attention-icon.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it, vi } from 'vitest' + +const createFromBitmapMock = vi.hoisted(() => + vi.fn((buffer: Buffer, options: { width: number; height: number }) => ({ + __image: true, + buffer, + ...options + })) +) + +vi.mock('electron', () => ({ + nativeImage: { createFromBitmap: createFromBitmapMock } +})) + +import { composeTrayAttentionIcon } from './tray-attention-icon' + +type FakeImage = { + getSize: () => { width: number; height: number } + toBitmap: () => Buffer +} + +function fakeBase(width: number, height: number): FakeImage { + // All-transparent base so any non-zero pixel in the result is the dot/ring. + return { + getSize: () => ({ width, height }), + toBitmap: () => Buffer.alloc(width * height * 4, 0) + } +} + +// The compositor receives BGRA. amber-500 = #f59e0b. +const AMBER = { b: 0x0b, g: 0x9e, r: 0xf5 } + +describe('composeTrayAttentionIcon', () => { + it('returns the base unchanged when it has no pixels', () => { + const base = { getSize: () => ({ width: 0, height: 0 }), toBitmap: () => Buffer.alloc(0) } + + expect(composeTrayAttentionIcon(base as never)).toBe(base) + expect(createFromBitmapMock).not.toHaveBeenCalled() + }) + + it('builds a new image of the same size', () => { + createFromBitmapMock.mockClear() + const result = composeTrayAttentionIcon(fakeBase(16, 16) as never) + + expect(createFromBitmapMock).toHaveBeenCalledTimes(1) + const [, options] = createFromBitmapMock.mock.calls[0] + expect(options).toEqual({ width: 16, height: 16 }) + expect(result).toMatchObject({ __image: true, width: 16, height: 16 }) + }) + + it('paints an amber dot in the top-right corner and leaves the rest untouched', () => { + createFromBitmapMock.mockClear() + const width = 16 + const height = 16 + composeTrayAttentionIcon(fakeBase(width, height) as never) + const bitmap = createFromBitmapMock.mock.calls[0][0] + + const pixel = (x: number, y: number): [number, number, number, number] => { + const o = (y * width + x) * 4 + return [bitmap[o], bitmap[o + 1], bitmap[o + 2], bitmap[o + 3]] + } + + // The dot must exist, be centered in the top-right, and never touch the + // opposite (bottom-left) corner where the app glyph is most visible. + let amberCount = 0 + let sumX = 0 + let sumY = 0 + let paintedInBottomLeft = 0 + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const [b, g, r, a] = pixel(x, y) + if (b === AMBER.b && g === AMBER.g && r === AMBER.r && a === 0xff) { + amberCount++ + sumX += x + sumY += y + } + if (a !== 0 && x < width / 2 && y >= height / 2) { + paintedInBottomLeft++ + } + } + } + + expect(amberCount).toBeGreaterThan(0) + expect(sumX / amberCount).toBeGreaterThan(width / 2) // centroid sits right of center + expect(sumY / amberCount).toBeLessThan(height / 2) // centroid sits above center + expect(paintedInBottomLeft).toBe(0) // the opposite corner is never touched + }) +}) diff --git a/src/main/tray/tray-attention-icon.ts b/src/main/tray/tray-attention-icon.ts new file mode 100644 index 000000000000..d9b042db37f1 --- /dev/null +++ b/src/main/tray/tray-attention-icon.ts @@ -0,0 +1,52 @@ +import { nativeImage, type NativeImage } from 'electron' + +// Why: amber-500 (#f59e0b) is Orca's "needs attention / unread" color, matching +// the renderer launcher dot and the tab-unread bell. Kept in sync with the +// bg-amber-500 used in FloatingTerminalToggleButton. +const DOT_RGB = { r: 0xf5, g: 0x9e, b: 0x0b } +// A near-white halo separates the dot from the icon glyph on any tray theme. +const RING_RGB = { r: 0xff, g: 0xff, b: 0xff } + +/** + * Returns a copy of `base` with a small amber attention dot composited into the + * top-right corner. Electron's NativeImage has no compositing API, so we merge + * the dot directly into the raw BGRA bitmap. Returns `base` unchanged if it has + * no pixels (e.g. a failed icon load) so the tray never shows a blank image. + */ +export function composeTrayAttentionIcon(base: NativeImage): NativeImage { + const { width, height } = base.getSize() + if (width <= 0 || height <= 0) { + return base + } + + // toBitmap()/createFromBitmap both use BGRA; the round-trip preserves format. + const bitmap = Buffer.from(base.toBitmap()) + const dotRadius = Math.max(2, Math.round(Math.min(width, height) * 0.2)) + const ringRadius = dotRadius + 1 + // Hug the top-right corner so the dot reads as a badge and leaves the app + // glyph (bottom-left) visible. The dot stays fully on-canvas; the outer ring + // may clip a pixel at the very corner, which is expected for a corner badge. + const centerX = width - 1 - dotRadius + const centerY = dotRadius + const dotRadiusSq = dotRadius * dotRadius + const ringRadiusSq = ringRadius * ringRadius + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const dx = x - centerX + const dy = y - centerY + const distSq = dx * dx + dy * dy + if (distSq > ringRadiusSq) { + continue + } + const offset = (y * width + x) * 4 + const color = distSq <= dotRadiusSq ? DOT_RGB : RING_RGB + bitmap[offset] = color.b + bitmap[offset + 1] = color.g + bitmap[offset + 2] = color.r + bitmap[offset + 3] = 0xff + } + } + + return nativeImage.createFromBitmap(bitmap, { width, height }) +} diff --git a/src/main/updater-events.ts b/src/main/updater-events.ts index 3b112ba31a66..27936f988ce7 100644 --- a/src/main/updater-events.ts +++ b/src/main/updater-events.ts @@ -11,6 +11,7 @@ import { import { compareVersions } from './updater-fallback' import { fetchChangelog } from './updater-changelog' import type { ElectronAutoUpdater } from './electron-updater-loader' +import { recordUpdaterLifecycle } from './updater-lifecycle-diagnostics' const AUTO_UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000 const AUTO_UPDATE_RETRY_INTERVAL_MS = 60 * 60 * 1000 @@ -27,6 +28,8 @@ type UpdaterHandlerContext = { getKnownReleaseUrl: () => string | undefined getPendingInstallVersion: () => string getUserInitiatedCheck: () => boolean + handleQuitAndInstallFailure: () => boolean + isQuitAndInstallHandoffActive: () => boolean hasNewerDownloadedVersion: () => boolean shouldHandleUpdaterErrorEvent: () => boolean clearUpdateAvailableEventPending: (attemptId: number | null) => void @@ -64,6 +67,8 @@ export function registerAutoUpdaterHandlers({ getKnownReleaseUrl, getPendingInstallVersion, getUserInitiatedCheck, + handleQuitAndInstallFailure, + isQuitAndInstallHandoffActive, hasNewerDownloadedVersion, shouldHandleUpdaterErrorEvent, clearUpdateAvailableEventPending, @@ -89,7 +94,8 @@ export function registerAutoUpdaterHandlers({ // Track Squirrel readiness so we don't show "ready to install" prematurely. if (process.platform === 'darwin') { nativeUpdater.on('update-downloaded', () => { - handleMacInstallerReady(hasNewerDownloadedVersion(), performQuitAndInstall, () => { + const hasNewerVersion = hasNewerDownloadedVersion() + handleMacInstallerReady(hasNewerVersion, performQuitAndInstall, () => { // If we were holding the 'downloaded' status, send it now — but only // when the staged version is actually newer than what's running. sendStatus({ @@ -102,7 +108,11 @@ export function registerAutoUpdaterHandlers({ } app.on('before-quit', (event) => { - if (consumeMacInstallGuardBypass() || isMacQuitAndInstallInFlight()) { + if (consumeMacInstallGuardBypass()) { + recordUpdaterLifecycle('macos_before_quit_guard_bypassed') + return + } + if (isMacQuitAndInstallInFlight()) { return } @@ -119,6 +129,9 @@ export function registerAutoUpdaterHandlers({ sendStatus ) ) { + recordUpdaterLifecycle('macos_before_quit_deferred', { + version: getPendingInstallVersion() + }) event.preventDefault() } }) @@ -255,12 +268,15 @@ export function registerAutoUpdaterHandlers({ sendStatus({ state: 'not-available' }) return } + const macInstallerReady = process.platform === 'darwin' ? isMacInstallerReady() : true + recordUpdaterLifecycle('update_downloaded', { version: info.version, macInstallerReady }) // On macOS, defer the 'downloaded' status until Squirrel.Mac has finished // processing the update via the localhost proxy. On other platforms, // the update is ready immediately after electron-updater downloads it. - if (process.platform === 'darwin' && !isMacInstallerReady()) { + if (process.platform === 'darwin' && !macInstallerReady) { // Squirrel is still processing. Keep the UI at 100% downloaded so the // user sees the handoff instead of a misleading "ready to install". + recordUpdaterLifecycle('macos_waiting_for_squirrel', { version: info.version }) sendStatus({ state: 'downloading', percent: 100, version: info.version }) return } @@ -269,6 +285,18 @@ export function registerAutoUpdaterHandlers({ autoUpdater.on('error', (err) => { const message = err?.message ?? 'Unknown error' + // Why: quitAndInstall reports the common "no staged update" failure through + // this event (often sync on Win/Linux, async on macOS/spawn). Recover + // quit-for-update flags before any suppression guard can early-return, but + // only after native invoke and only when install is not yet committed. + if (handleQuitAndInstallFailure()) { + return + } + // Why: handoff still owns the process (cleanup, native in-flight, or + // post-commit). Do not treat as check/download error or reset mac install. + if (isQuitAndInstallHandoffActive()) { + return + } // Why: primary/fallback promise handlers may already own this failure; do // not let their delayed paired error event consume fallback context. if (shouldSuppressMissingManifestPrereleaseFallbackEvent(message, err)) { diff --git a/src/main/updater-lifecycle-diagnostics.ts b/src/main/updater-lifecycle-diagnostics.ts new file mode 100644 index 000000000000..d5f0a10bfa87 --- /dev/null +++ b/src/main/updater-lifecycle-diagnostics.ts @@ -0,0 +1,12 @@ +import type { CrashReportBreadcrumbData } from '../shared/crash-reporting' +import { recordCrashBreadcrumb } from './crash-reporting/crash-breadcrumb-store' + +export function recordUpdaterLifecycle( + event: string, + data?: CrashReportBreadcrumbData, + options?: { level?: 'info' | 'warn' | 'error'; message?: string } +): void { + recordCrashBreadcrumb(`updater_${event}`, data) + const suffix = data && Object.keys(data).length > 0 ? ` ${JSON.stringify(data)}` : '' + console[options?.level ?? 'info'](`[updater] ${options?.message ?? event}${suffix}`) +} diff --git a/src/main/updater-mac-install.ts b/src/main/updater-mac-install.ts index 086e7d5fc6c2..8012f79d8fc3 100644 --- a/src/main/updater-mac-install.ts +++ b/src/main/updater-mac-install.ts @@ -1,5 +1,6 @@ import { app } from 'electron' import type { UpdateStatus } from '../shared/types' +import { recordUpdaterLifecycle } from './updater-lifecycle-diagnostics' const MAC_INSTALL_READY_TIMEOUT_MS = 15000 @@ -96,8 +97,13 @@ export function deferMacQuitUntilInstallerReady( return } - console.warn( - `[updater] macOS installer was not ready after ${MAC_INSTALL_READY_TIMEOUT_MS}ms; allowing quit without install` + recordUpdaterLifecycle( + 'macos_install_guard_timeout', + { timeoutMs: MAC_INSTALL_READY_TIMEOUT_MS }, + { + level: 'warn', + message: `macOS installer was not ready after ${MAC_INSTALL_READY_TIMEOUT_MS}ms; allowing quit without install` + } ) installRequestedAfterSquirrelReady = false // This is a safety valve. The updater path should wait for ShipIt so the @@ -117,14 +123,19 @@ export function handleMacInstallerReady( ): void { squirrelReady = true clearPendingInstallTimeout() + recordUpdaterLifecycle('macos_installer_ready', { + deferredInstallRequested: installRequestedAfterSquirrelReady, + hasNewerDownloadedVersion + }) if (installRequestedAfterSquirrelReady && hasNewerDownloadedVersion) { void Promise.resolve() .then(() => onReadyToInstall()) .catch((error) => { - console.warn( - '[updater] Deferred macOS install handoff failed:', - error instanceof Error ? error.name : typeof error + recordUpdaterLifecycle( + 'macos_deferred_install_handoff_failed', + { errorType: error instanceof Error ? error.name : typeof error }, + { level: 'warn', message: 'Deferred macOS install handoff failed' } ) }) return diff --git a/src/main/updater.mac-install.test.ts b/src/main/updater.mac-install.test.ts index 2026b354edcd..f48754afd4fa 100644 --- a/src/main/updater.mac-install.test.ts +++ b/src/main/updater.mac-install.test.ts @@ -258,9 +258,9 @@ describe('updater mac install handoff', () => { expect(reportDownloaded).not.toHaveBeenCalled() await vi.waitFor(() => { + // Why: recordUpdaterLifecycle packs metadata into one console line. expect(warn).toHaveBeenCalledWith( - '[updater] Deferred macOS install handoff failed:', - 'Error' + '[updater] Deferred macOS install handoff failed {"errorType":"Error"}' ) }) expect(JSON.stringify(warn.mock.calls)).not.toContain('handoff-secret') diff --git a/src/main/updater.test.ts b/src/main/updater.test.ts index b4c1a47c54be..f9905ae1824b 100644 --- a/src/main/updater.test.ts +++ b/src/main/updater.test.ts @@ -1177,7 +1177,7 @@ describe('updater', () => { expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledWith(false, true) }) - it('runs pre-quit cleanup before killing PTYs during update install', async () => { + it('runs pre-quit cleanup before local PTY cleanup during update install', async () => { vi.useFakeTimers() const onBeforeQuit = vi.fn() @@ -1240,6 +1240,145 @@ describe('updater', () => { expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1) }) + it('recovers quit-for-update state on sync quitAndInstall error event without killing PTYs', async () => { + vi.useFakeTimers() + + autoUpdaterMock.quitAndInstall.mockImplementation(() => { + // Why: BaseUpdater dispatches 'error' synchronously inside install() for + // the common "no staged update filepath" path. + autoUpdaterMock.emit( + 'error', + new Error("No update filepath provided, can't quit and install") + ) + }) + + const sendMock = vi.fn() + const mainWindow = { webContents: { send: sendMock } } + const { setupAutoUpdater, quitAndInstall, isQuittingForUpdate } = await import('./updater') + + setupAutoUpdater(mainWindow as never) + quitAndInstall() + + await vi.advanceTimersByTimeAsync(100) + + expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1) + expect(isQuittingForUpdate()).toBe(false) + // Why: destructive prep runs only after quitAndInstall returns still in + // progress; sync recovery clears flags first so PTYs stay alive. + expect(killAllPtyMock).not.toHaveBeenCalled() + expect(sendMock).toHaveBeenCalledWith( + 'updater:status', + expect.objectContaining({ + state: 'error', + message: 'Could not restart to install the update. Quit and reopen Orca, then try again.' + }) + ) + }) + + it('does not recover quit-for-update state from late errors after install commit', async () => { + const sendMock = vi.fn() + const mainWindow = { webContents: { send: sendMock } } + fetchNewerReleaseTagsMock.mockResolvedValue({ tags: ['v1.0.61'], state: 'ready' }) + autoUpdaterMock.checkForUpdates.mockImplementation(() => { + autoUpdaterMock.emit('checking-for-update') + queueMicrotask(() => { + autoUpdaterMock.emit('update-available', { version: '1.0.61' }) + }) + return Promise.resolve(undefined) + }) + + const { setupAutoUpdater, checkForUpdatesFromMenu, quitAndInstall, isQuittingForUpdate } = + await import('./updater') + + setupAutoUpdater(mainWindow as never, { getLastUpdateCheckAt: () => Date.now() }) + checkForUpdatesFromMenu() + + // Why: put status in downloaded so a naive error handler would otherwise + // treat a late post-commit error as a download/install UI failure. + await vi.waitFor(() => { + expect(sendMock).toHaveBeenCalledWith('updater:status', { + state: 'available', + version: '1.0.61', + changelog: null + }) + }) + + autoUpdaterMock.emit('update-downloaded', { version: '1.0.61' }) + + // Why: on macOS install is only "committed" once Squirrel is ready; mark + // it ready so this test covers the post-commit path on all platforms and + // the UI can leave the "waiting for Squirrel" downloading state. + if (process.platform === 'darwin') { + const nativeDownloadedHandler = nativeUpdaterMock.on.mock.calls.find( + ([eventName]) => eventName === 'update-downloaded' + )?.[1] as (() => void) | undefined + expect(nativeDownloadedHandler).toBeTypeOf('function') + nativeDownloadedHandler?.() + } + + await vi.waitFor(() => { + expect(sendMock).toHaveBeenCalledWith( + 'updater:status', + expect.objectContaining({ state: 'downloaded', version: '1.0.61' }) + ) + }) + + quitAndInstall() + await vi.waitFor(() => { + expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1) + }) + expect(killAllPtyMock).toHaveBeenCalledTimes(1) + expect(isQuittingForUpdate()).toBe(true) + + sendMock.mockClear() + autoUpdaterMock.emit('error', new Error('late post-commit install error')) + + expect(isQuittingForUpdate()).toBe(true) + // Why: handoff still owns the process after commit — no recovery message + // and no general check/download error status either. + expect(sendMock).not.toHaveBeenCalled() + }) + + it('does not treat pre-native autoUpdater errors as quitAndInstall recovery', async () => { + vi.useFakeTimers() + + let finishCleanup!: () => void + const onBeforeQuit = vi.fn( + () => + new Promise((resolve) => { + finishCleanup = resolve + }) + ) + const sendMock = vi.fn() + const mainWindow = { webContents: { send: sendMock } } + const { setupAutoUpdater, quitAndInstall, isQuittingForUpdate } = await import('./updater') + + setupAutoUpdater(mainWindow as never, { + onBeforeQuit, + getLastUpdateCheckAt: () => Date.now() + }) + quitAndInstall() + await vi.advanceTimersByTimeAsync(100) + + expect(onBeforeQuit).toHaveBeenCalledTimes(1) + expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() + expect(isQuittingForUpdate()).toBe(true) + + sendMock.mockClear() + // Why: an unrelated error during pre-quit cleanup must not clear + // quittingForUpdate or emit the install-recovery status (native not invoked). + autoUpdaterMock.emit('error', new Error('pre-native concurrent error')) + + expect(isQuittingForUpdate()).toBe(true) + expect(sendMock).not.toHaveBeenCalled() + + finishCleanup() + await vi.advanceTimersByTimeAsync(0) + + expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1) + expect(isQuittingForUpdate()).toBe(true) + }) + it('runs a startup check immediately when the last background check is stale', async () => { const mainWindow = { webContents: { send: vi.fn() } } const setLastUpdateCheckAt = vi.fn() @@ -1766,11 +1905,14 @@ describe('updater', () => { expect(setPendingUpdateNudgeId).toHaveBeenCalledWith(null) }) - // Why: issue #631 — the Windows auto-updater fails because installed - // versions signed with the wrong certificate have a stale publisherName - // in app-update.yml. verifyUpdateCodeSignature must be overridden on - // Windows so electron-updater skips Authenticode verification. - it('overrides verifyUpdateCodeSignature on Windows to skip signing verification', async () => { + // Why: the Windows auto-updater must keep electron-updater's built-in + // Authenticode verification, which checks the downloaded installer against + // the SignPath Foundation publisherName that electron-builder embeds in + // app-update.yml. A no-op verifyUpdateCodeSignature override would silently + // accept every installer, so setup must NOT install one. (The issue #631 + // stale-publisherName problem that once justified an override is resolved now + // that SignPath builds embed the correct publisherName.) + it('does not disable Windows Authenticode verification on win32', async () => { vi.stubGlobal('process', { ...process, platform: 'win32' }) const { setupAutoUpdater } = await import('./updater') @@ -1780,11 +1922,7 @@ describe('updater', () => { setupAutoUpdater(mainWindow as never) - // The override should be set on the autoUpdater mock - const override = (autoUpdaterMock as Record).verifyUpdateCodeSignature - expect(override).toBeTypeOf('function') - // Calling it should resolve to null (meaning "signature valid, skip check") - await expect((override as () => Promise)()).resolves.toBeNull() + expect((autoUpdaterMock as Record).verifyUpdateCodeSignature).toBeUndefined() }) it('does not override verifyUpdateCodeSignature on non-Windows platforms', async () => { diff --git a/src/main/updater.ts b/src/main/updater.ts index bc9c9d9b6f67..5bb2340fbf92 100644 --- a/src/main/updater.ts +++ b/src/main/updater.ts @@ -1,6 +1,5 @@ /* eslint-disable max-lines */ import { app, BrowserWindow, powerMonitor } from 'electron' -import type { NsisUpdater } from 'electron-updater' import { is } from '@electron-toolkit/utils' import type { UpdateCheckOptions, UpdateStatus } from '../shared/types' import { killAllPty } from './ipc/pty' @@ -10,9 +9,12 @@ import { writeMainThreadDiagnosticMarker } from './diagnostics/main-thread-churn import { beginMacUpdateDownload, deferMacQuitUntilInstallerReady, - markMacQuitAndInstallInFlight + isMacInstallerReady, + markMacQuitAndInstallInFlight, + resetMacInstallState } from './updater-mac-install' import { registerAutoUpdaterHandlers } from './updater-events' +import { recordUpdaterLifecycle } from './updater-lifecycle-diagnostics' import { compareVersions, isBenignCheckFailure, @@ -65,6 +67,14 @@ let autoUpdateCheckTimer: ReturnType | null = null let nudgeCheckTimer: ReturnType | null = null let pendingQuitAndInstallTimer: ReturnType | null = null let quitAndInstallInProgress = false +// Why: once quitAndInstall has committed (Win/Linux install, or macOS with +// Squirrel ready), late autoUpdater 'error' events must not clear +// quittingForUpdate — that would re-enable dock activate mid-installer. +let updateInstallCommitted = false +// Why: quit-and-install recovery must only run after the native +// quitAndInstall call. Pre-native cleanup-time autoUpdater errors must not +// clear quittingForUpdate or look like install recovery. +let quitAndInstallNativeInvoked = false let persistLastUpdateCheckAt: ((timestamp: number) => void) | null = null let _getLastUpdateCheckAt: (() => number | null) | null = null let backgroundCheckLaunchPending = false @@ -548,6 +558,7 @@ function clearPrereleaseFallbackContextIfSettled(): void { async function performQuitAndInstall(): Promise { if (quitAndInstallInProgress) { + recordUpdaterLifecycle('quit_and_install_ignored', { reason: 'already-in-progress' }) return } quitAndInstallInProgress = true @@ -567,14 +578,112 @@ async function performQuitAndInstall(): Promise { // either can't replace it or the user ends up on the old version. quittingForUpdate = true - await runBeforeUpdateQuitCleanup() - killAllPty() + const pendingVersion = getPendingInstallVersion() + try { + await withUpdaterSpan({ stage: 'install' }, async (span) => { + span.setAttribute('updater.version', pendingVersion || 'unknown') + span.setAttribute('updater.platform', process.platform) + span.setAttribute( + 'updater.macosInstallerReady', + process.platform === 'darwin' ? isMacInstallerReady() : true + ) + recordUpdaterLifecycle('quit_and_install_started', { + version: pendingVersion || null, + macInstallerReady: process.platform === 'darwin' ? isMacInstallerReady() : true + }) + span.addEvent('pre_quit_cleanup_start') + await runBeforeUpdateQuitCleanup() + span.addEvent('pre_quit_cleanup_done') + + recordUpdaterLifecycle('quit_and_install_invoking_native', { + version: pendingVersion || null + }) + // Why: defensive — state should stay in-progress until native invoke, but + // never call quitAndInstall if recovery/reset already cleared the handoff. + if (!quitAndInstallInProgress) { + return + } + // Why: mark before the call so a sync 'error' during quitAndInstall can + // recover; pre-native errors must not look like install failure. + quitAndInstallNativeInvoked = true + // Why: invoke quitAndInstall before killAllPty/remove close listeners so a + // sync 'error' (common "no filepath" path) recovers while windows and + // local PTYs are still intact. + getAutoUpdater().quitAndInstall(false, true) + span.addEvent('native_quit_and_install_invoked') + + // Why: handleQuitAndInstallFailure may clear quitAndInstallInProgress + // synchronously during quitAndInstall (Win/Linux dispatchError). Skip + // destructive prep if recovery already ran. + if (!quitAndInstallInProgress) { + return + } + + killAllPty() + span.addEvent('local_pty_kill_all') + + for (const win of BrowserWindow.getAllWindows()) { + win.removeAllListeners('close') + } + span.addEvent('window_close_listeners_removed', { + windowCount: BrowserWindow.getAllWindows().length + }) - for (const win of BrowserWindow.getAllWindows()) { - win.removeAllListeners('close') + // Why: committed installs must keep quittingForUpdate true so dock + // activate cannot reopen the old process mid-ShipIt/installer. macOS + // without Squirrel ready stays uncommitted so late native errors can + // still recover flags (PTYs may already be dead — residual OK). + if (process.platform !== 'darwin' || isMacInstallerReady()) { + updateInstallCommitted = true + } + }) + } catch (error) { + resetQuitForUpdateState() + recordUpdaterLifecycle( + 'quit_and_install_failed', + { errorType: error instanceof Error ? error.name : typeof error }, + { + level: 'warn', + message: 'Could not start update install' + } + ) + sendErrorStatus( + 'Could not restart to install the update. Quit and reopen Orca, then try again.' + ) } +} - getAutoUpdater().quitAndInstall(false, true) +function resetQuitForUpdateState(): void { + quitAndInstallInProgress = false + quittingForUpdate = false + updateInstallCommitted = false + quitAndInstallNativeInvoked = false + resetMacInstallState() +} + +// Why: electron-updater often reports quitAndInstall failures via the 'error' +// event. On Win/Linux this is frequently synchronous (dispatchError inside +// install()); on macOS/spawn it can be async. Recover only after native invoke +// and only when install has not been committed — after commit, clearing +// quittingForUpdate would allow dock activate to reopen the old process +// mid-installer. +function handleQuitAndInstallFailure(): boolean { + if (!quitAndInstallInProgress || !quitAndInstallNativeInvoked || updateInstallCommitted) { + return false + } + resetQuitForUpdateState() + recordUpdaterLifecycle('quit_and_install_failed_via_event', undefined, { + level: 'warn', + message: 'Update install could not start; recovered app state' + }) + sendErrorStatus('Could not restart to install the update. Quit and reopen Orca, then try again.') + return true +} + +// Why: while quit-and-install owns the process (pre-native cleanup through +// post-commit handoff), general check/download error UI must not run. +function isQuitAndInstallHandoffActive(): boolean { + return quitAndInstallInProgress } async function runBeforeUpdateQuitCleanup(): Promise { @@ -586,9 +695,13 @@ async function runBeforeUpdateQuitCleanup(): Promise { const cleanup = Promise.resolve() .then(() => onBeforeQuitCleanup?.()) .catch((error) => { - console.warn( - '[updater] Pre-quit cleanup failed; continuing update install:', - error instanceof Error ? error.name : typeof error + recordUpdaterLifecycle( + 'pre_quit_cleanup_failed', + { errorType: error instanceof Error ? error.name : typeof error }, + { + level: 'warn', + message: 'Pre-quit cleanup failed; continuing update install' + } ) }) const timeoutResult = new Promise<'timeout'>((resolve) => { @@ -597,8 +710,13 @@ async function runBeforeUpdateQuitCleanup(): Promise { const result = await Promise.race([cleanup.then(() => 'done' as const), timeoutResult]) if (result === 'timeout') { - console.warn( - `[updater] Pre-quit cleanup exceeded ${PRE_QUIT_CLEANUP_TIMEOUT_MS}ms; continuing update install` + recordUpdaterLifecycle( + 'pre_quit_cleanup_timeout', + { timeoutMs: PRE_QUIT_CLEANUP_TIMEOUT_MS }, + { + level: 'warn', + message: `Pre-quit cleanup exceeded ${PRE_QUIT_CLEANUP_TIMEOUT_MS}ms; continuing update install` + } ) return } @@ -1269,15 +1387,11 @@ export function setupAutoUpdater( debug: (m: unknown) => console.debug('[autoUpdater]', m) } as never - // Why: older Windows installs either have no publisherName or have the - // stale macOS Apple Developer ID publisherName from issue #631. Keep the - // migration path open while SignPath-signed builds roll out. - // - // TODO: re-enable after SignPath-signed builds with the explicit Windows - // publisherName have been the minimum supported updater source for a while. - if (process.platform === 'win32') { - ;(autoUpdater as NsisUpdater).verifyUpdateCodeSignature = () => Promise.resolve(null) - } + // Why: Windows update integrity is enforced by electron-updater's built-in + // Authenticode check against the `publisherName` (SignPath Foundation) that + // electron-builder embeds in app-update.yml. Do NOT re-add a + // `verifyUpdateCodeSignature` override — a no-op override silently accepts + // every downloaded installer, disabling signature verification entirely. // Use the generic provider with GitHub's /releases/latest/download/ URL as // the startup fallback so electron-updater can fetch the manifest @@ -1309,6 +1423,8 @@ export function setupAutoUpdater( getKnownReleaseUrl, getPendingInstallVersion, getUserInitiatedCheck: () => userInitiatedCheck, + handleQuitAndInstallFailure, + isQuitAndInstallHandoffActive, hasNewerDownloadedVersion, shouldHandleUpdaterErrorEvent, performQuitAndInstall, diff --git a/src/main/win32-utils.test.ts b/src/main/win32-utils.test.ts index d291198a0e0d..0a6d381d3c08 100644 --- a/src/main/win32-utils.test.ts +++ b/src/main/win32-utils.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { + getCmdExePath, getSpawnArgsForWindows, isPermissionError, isWindowsBatchScript, @@ -65,6 +66,26 @@ describe('getSpawnArgsForWindows', () => { } }) + it('preserves VS Code WSL remote arguments with spaces through .cmd launchers', () => { + withPlatform('win32', () => { + const { spawnCmd, spawnArgs } = getSpawnArgsForWindows('C:\\tools\\code.cmd', [ + '--remote', + 'wsl+Ubuntu Preview', + '/home/Ada Lovelace/project' + ]) + + expect(spawnCmd).toBe(getCmdExePath()) + expect(spawnArgs).toEqual([ + '/d', + '/c', + 'C:\\tools\\code.cmd', + '--remote', + 'wsl+Ubuntu Preview', + '/home/Ada Lovelace/project' + ]) + }) + }) + it('passes .exe through unchanged on win32', () => { withPlatform('win32', () => { const { spawnCmd, spawnArgs } = getSpawnArgsForWindows('C:\\tools\\codex.exe', ['login']) diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index 2d34a4c9fd05..cc03c40a904e 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -389,6 +389,7 @@ function registerRuntimeWindowLifecycle( }) as Promise, closeTerminal: (tabId, paneRuntimeId) => send('ui:closeTerminal', { tabId, paneRuntimeId }), sleepWorktree: (worktreeId) => send('ui:sleepWorktree', { worktreeId }), + resumeSleepingAgents: (worktreeId) => send('ui:resumeSleepingAgents', { worktreeId }), terminalFitOverrideChanged: (ptyId, mode, cols, rows) => send('runtime:terminalFitOverrideChanged', { ptyId, mode, cols, rows }), terminalDriverChanged: (ptyId, driver) => diff --git a/src/main/window/createMainWindow.test.ts b/src/main/window/createMainWindow.test.ts index 453487a18aa8..dc278cb1ffaa 100644 --- a/src/main/window/createMainWindow.test.ts +++ b/src/main/window/createMainWindow.test.ts @@ -9,6 +9,8 @@ const { menuPopupMock, notificationMock, notificationShowMock, + powerMonitorOnMock, + powerMonitorRemoveListenerMock, isMock } = vi.hoisted(() => { const menuPopupMock = vi.fn() @@ -23,6 +25,8 @@ const { return { show: notificationShowMock } }), notificationShowMock, + powerMonitorOnMock: vi.fn(), + powerMonitorRemoveListenerMock: vi.fn(), isMock: { dev: false } } }) @@ -34,6 +38,7 @@ vi.mock('electron', () => ({ Menu: { buildFromTemplate: buildFromTemplateMock }, Notification: notificationMock, nativeTheme: { shouldUseDarkColors: false }, + powerMonitor: { on: powerMonitorOnMock, removeListener: powerMonitorRemoveListenerMock }, screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 1440, height: 900 } }) }, @@ -77,6 +82,8 @@ describe('createMainWindow', () => { menuPopupMock.mockClear() notificationMock.mockClear() notificationShowMock.mockClear() + powerMonitorOnMock.mockReset() + powerMonitorRemoveListenerMock.mockReset() isMock.dev = false vi.mocked(ipcMain.on).mockReset() vi.mocked(ipcMain.removeListener).mockReset() @@ -2853,6 +2860,103 @@ describe('createMainWindow', () => { }) }) + describe('system resume relay', () => { + function setupResumeWindow() { + const windowHandlers: Record void> = {} + const webContents = { + on: vi.fn(), + setZoomLevel: vi.fn(), + setBackgroundThrottling: vi.fn(), + invalidate: vi.fn(), + setWindowOpenHandler: vi.fn(), + send: vi.fn(), + isDestroyed: vi.fn(() => false), + id: 1 + } + const instance = { + webContents, + on: vi.fn((event: string, handler: (...args: any[]) => void) => { + windowHandlers[event] = handler + }), + isDestroyed: vi.fn(() => false), + // Why: maximized keeps forceRepaint from scheduling its size-nudge timer. + isMaximized: vi.fn(() => true), + isFullScreen: vi.fn(() => false), + getSize: vi.fn(() => [1200, 800]), + setSize: vi.fn(), + maximize: vi.fn(), + show: vi.fn(), + loadFile: vi.fn(), + loadURL: vi.fn() + } + browserWindowMock.mockImplementation(function () { + return instance + }) + return { windowHandlers, webContents, instance } + } + + function getPowerResumeListener(): () => void { + const resumeCall = powerMonitorOnMock.mock.calls.find( + (call: unknown[]) => call[0] === 'resume' + ) + if (!resumeCall) { + throw new Error('missing powerMonitor resume listener') + } + return resumeCall[1] as () => void + } + + it('relays powerMonitor resume to the live window and forces a repaint', () => { + const { webContents } = setupResumeWindow() + createMainWindow(null) + const onResume = getPowerResumeListener() + webContents.send.mockClear() + webContents.invalidate.mockClear() + + onResume() + + expect(webContents.send).toHaveBeenCalledWith('system:resumed') + expect(webContents.invalidate).toHaveBeenCalledTimes(1) + }) + + it('does not send the resume event once the window is destroyed', () => { + const { webContents, instance } = setupResumeWindow() + createMainWindow(null) + const onResume = getPowerResumeListener() + instance.isDestroyed.mockReturnValue(true) + webContents.send.mockClear() + webContents.invalidate.mockClear() + + onResume() + + expect(webContents.send).not.toHaveBeenCalled() + expect(webContents.invalidate).not.toHaveBeenCalled() + }) + + it('does not send the resume event once webContents is destroyed', () => { + const { webContents } = setupResumeWindow() + createMainWindow(null) + const onResume = getPowerResumeListener() + webContents.isDestroyed.mockReturnValue(true) + webContents.send.mockClear() + webContents.invalidate.mockClear() + + onResume() + + expect(webContents.send).not.toHaveBeenCalled() + expect(webContents.invalidate).not.toHaveBeenCalled() + }) + + it('removes the powerMonitor resume listener when the window closes', () => { + const { windowHandlers } = setupResumeWindow() + createMainWindow(null) + const onResume = getPowerResumeListener() + + windowHandlers.closed() + + expect(powerMonitorRemoveListenerMock).toHaveBeenCalledWith('resume', onResume) + }) + }) + describe('minimize to tray on close (win32)', () => { const originalPlatform = process.platform diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index 44b246e89803..1a30178a4e2e 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -6,6 +6,7 @@ import { Menu, nativeTheme, Notification, + powerMonitor, screen, shell } from 'electron' @@ -313,6 +314,19 @@ export function createMainWindow( }) } + // Why: a focus-preserving system/display wake fires no window focus or + // visibility events in the renderer, so terminal wake recovery would never + // run. Relay powerMonitor resume explicitly (supported on mac/win/linux) + // and force a repaint so stale compositor surfaces recover too. + const onSystemResume = (): void => { + if (mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed?.() === true) { + return + } + forceRepaint(mainWindow) + mainWindow.webContents.send('system:resumed') + } + powerMonitor.on('resume', onSystemResume) + mainWindow.webContents.on('dom-ready', () => { const level = store?.getUI().uiZoomLevel ?? 0 mainWindow.webContents.setZoomLevel(level) @@ -1203,6 +1217,9 @@ export function createMainWindow( ipcMain.removeListener(terminalInputFocusChannel, onTerminalInputFocused) ipcMain.removeListener(floatingTerminalInputFocusChannel, onFloatingTerminalInputFocused) ipcMain.removeListener(shortcutRecorderFocusChannel, onShortcutRecorderFocused) + // Why: powerMonitor is app-global; without this the closed window's + // resume relay would leak and fire against a destroyed webContents. + powerMonitor.removeListener('resume', onSystemResume) clearTrustedUIRendererWebContentsId(rendererWebContentsId) // Why: on updater-triggered shutdown, BrowserWindow can emit `closed` // after its webContents has already been destroyed. The destroyed diff --git a/src/main/window/main-window-visibility.test.ts b/src/main/window/main-window-visibility.test.ts new file mode 100644 index 000000000000..335dc4a87d6e --- /dev/null +++ b/src/main/window/main-window-visibility.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' + +import { isMainWindowVisible } from './main-window-visibility' + +describe('main window visibility helpers', () => { + it('treats a minimal alive window double as visible', () => { + expect(isMainWindowVisible({ isDestroyed: () => false })).toBe(true) + }) + + it('parks work when the real window is hidden, minimized, destroyed, or missing', () => { + expect( + isMainWindowVisible({ + isDestroyed: () => false, + isVisible: () => false, + isMinimized: () => false + }) + ).toBe(false) + expect( + isMainWindowVisible({ + isDestroyed: () => false, + isVisible: () => true, + isMinimized: () => true + }) + ).toBe(false) + expect(isMainWindowVisible({ isDestroyed: () => true })).toBe(false) + expect(isMainWindowVisible(null)).toBe(false) + }) +}) diff --git a/src/main/window/main-window-visibility.ts b/src/main/window/main-window-visibility.ts new file mode 100644 index 000000000000..8b4ca4c4647f --- /dev/null +++ b/src/main/window/main-window-visibility.ts @@ -0,0 +1,38 @@ +// Why: BrowserWindow instances are recreated on macOS dock re-activation, so +// long-lived main-process services (e.g. the SSH port scanner) subscribe to +// this process-global signal instead of a specific window instance; index.ts +// re-wires each new window's show/restore events into notifyMainWindowBecameVisible. +type MainWindowBecameVisibleListener = () => void + +type MainWindowVisibilityState = { + isDestroyed: () => boolean + isVisible?: () => boolean + isMinimized?: () => boolean +} + +const listeners = new Set() + +export function notifyMainWindowBecameVisible(): void { + for (const listener of Array.from(listeners)) { + listener() + } +} + +export function onMainWindowBecameVisible(listener: MainWindowBecameVisibleListener): () => void { + listeners.add(listener) + return () => { + listeners.delete(listener) + } +} + +export function isMainWindowVisible(window: MainWindowVisibilityState | null): boolean { + if (window === null || window.isDestroyed()) { + return false + } + + // Why: production BrowserWindow exposes both APIs, but older main-process + // tests use minimal window doubles that should stay visible by default. + const isVisible = window.isVisible?.() ?? true + const isMinimized = window.isMinimized?.() ?? false + return isVisible && !isMinimized +} diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index a0e6c9bea81b..1001d14f9664 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -11,8 +11,35 @@ import type { import type { NativeFileDropPayload } from '../shared/native-file-drop' import type { ReadClipboardTextOptions } from '../shared/clipboard-text' import type { AppIdentity } from '../shared/app-identity' +import type { + CreateLocalOrcaProfileArgs, + CreateLocalOrcaProfileResult, + CreateCloudLinkedOrcaProfileArgs, + CreateCloudLinkedOrcaProfileResult, + ConnectCurrentOrcaProfileResult, + FindOrcaProfileProjectsByPathArgs, + FindOrcaProfileProjectsByPathResult, + OrcaProfileListResult, + OrcaProfileAuthStatus, + RefreshCurrentOrcaProfileAuthResult, + SelectOrcaProfileOrgArgs, + SelectOrcaProfileOrgResult, + SignOutCurrentOrcaProfileResult, + SwitchOrcaProfileArgs, + SwitchOrcaProfileResult, + TransferOrcaProfileProjectArgs, + TransferOrcaProfileProjectResult, + OrcaProfileOrgInviteRevokeArgs, + OrcaProfileOrgMemberChangeRoleArgs, + OrcaProfileOrgMemberInviteArgs, + OrcaProfileOrgMemberMutationResult, + OrcaProfileOrgMemberRemoveArgs, + OrcaProfileOrgMembersListArgs, + OrcaProfileOrgMembersListResult +} from '../shared/orca-profiles' import type { TerminalPaneSplitSource } from '../shared/feature-education-telemetry' import type { TaskSourceContext } from '../shared/task-source-context' +import type { LinearIssueAttributeFilter } from '../shared/linear-issue-attribute-filter' import type { ProjectExecutionRuntimeResolution } from '../shared/project-execution-runtime' import type { StartupCommandDelivery } from '../shared/codex-startup-delivery' import type { SleepingAgentLaunchConfig } from '../shared/agent-session-resume' @@ -94,6 +121,7 @@ import type { JiraIssue, JiraIssueFilter, JiraIssueType, + JiraProjectStatusOrder, JiraIssueUpdate, JiraPriority, JiraProject, @@ -126,6 +154,7 @@ import type { GetRateLimitResult, NotificationDispatchRequest, NotificationDispatchResult, + NotificationDeliveryProbeResult, NotificationDismissResult, NotificationPermissionStatusResult, NotificationSoundResult, @@ -177,22 +206,18 @@ import type { WorkspaceSessionPatch, WorkspaceSessionState } from '../shared/types' - -type GitLabRepoSelectorArgs = { - repoPath: string - repoId?: string | null - sourceContext?: TaskSourceContext | null -} - -type GitHubRepoSelectorArgs = { - repoPath: string - repoId?: string | null - sourceContext?: TaskSourceContext | null -} +import type { PtyModelRestoreNeededEvent } from '../shared/pty-model-restore-marker' +import type { + PtyRendererDeliveryHealthReply, + PtyRendererDeliveryStateReport +} from '../shared/pty-renderer-delivery-health' +import type { TerminalViewAttributes } from '../shared/terminal-view-attributes' +import type { PtyMainDeliveryDiagnostics } from '../shared/pty-delivery-diagnostics' import type { WarpThemeImportPreview, WarpThemeImportSource } from '../shared/terminal-custom-themes' + import type { SetupScriptImportCandidate } from '../shared/setup-script-imports' import type { GitHistoryOptions, GitHistoryResult } from '../shared/git-history' import type { PublicKnownRuntimeEnvironment } from '../shared/runtime-environments' @@ -263,6 +288,7 @@ import type { MigrationUnsupportedPtyEntry } from '../shared/agent-status-types' import type { AgentInterruptInferenceRequest } from '../shared/agent-interrupt-intent' +import type { TerminalSideEffectBatch } from '../shared/terminal-side-effect-facts' import type { RuntimeBrowserDriverState, RuntimeMobileSessionTabMove, @@ -324,6 +350,7 @@ import type { } from '../shared/claude-usage-types' import type { CodexRateLimitResetResult, + GrokAccountStatus, RateLimitRuntimeTarget, RateLimitState } from '../shared/rate-limit-types' @@ -374,7 +401,12 @@ import type { OpenCodeUsageSnapshot, OpenCodeUsageSummary } from '../shared/opencode-usage-types' -import type { AiVaultListArgs, AiVaultListResult } from '../shared/ai-vault-types' +import type { + AiVaultListArgs, + AiVaultListResult, + AiVaultSubagentListArgs, + AiVaultSubagentListResult +} from '../shared/ai-vault-types' import type { AgentType, NativeChatMessage } from '../shared/native-chat-types' import type { TelemetryConsentState } from '../shared/telemetry-consent-types' import type { AgentKind, LaunchSource, RequestKind } from '../shared/telemetry-events' @@ -410,6 +442,18 @@ import type { } from '../shared/workspace-cleanup' import type { KeybindingActionId, KeybindingFileSnapshot } from '../shared/keybindings' +type GitLabRepoSelectorArgs = { + repoPath: string + repoId?: string | null + sourceContext?: TaskSourceContext | null +} + +type GitHubRepoSelectorArgs = { + repoPath: string + repoId?: string | null + sourceContext?: TaskSourceContext | null +} + export type BrowserApi = { registerGuest: (args: { browserPageId: string @@ -752,6 +796,8 @@ export type OpenCodeUsageApi = { export type AiVaultApi = { listSessions: (args?: AiVaultListArgs) => Promise + /** Lists the Task subagent transcripts of one session, on demand. */ + listSubagentSessions: (args: AiVaultSubagentListArgs) => Promise /** Fires when any app window regains OS focus; returns an unsubscribe. */ onWindowFocused: (callback: () => void) => () => void } @@ -841,6 +887,40 @@ export type AppApi = { export type PreloadApi = { app: AppApi + orcaProfiles: { + list: () => Promise + authStatus: () => Promise + createLocal: (args?: CreateLocalOrcaProfileArgs) => Promise + createCloudLinked: ( + args?: CreateCloudLinkedOrcaProfileArgs + ) => Promise + switchProfile: (args: SwitchOrcaProfileArgs) => Promise + transferProject: ( + args: TransferOrcaProfileProjectArgs + ) => Promise + findProjectProfiles: ( + args: FindOrcaProfileProjectsByPathArgs + ) => Promise + connectCurrent: () => Promise + refreshAuth: () => Promise + signOutCurrent: () => Promise + selectOrg: (args: SelectOrcaProfileOrgArgs) => Promise + orgMembersList: ( + args: OrcaProfileOrgMembersListArgs + ) => Promise + orgMemberInvite: ( + args: OrcaProfileOrgMemberInviteArgs + ) => Promise + orgInviteRevoke: ( + args: OrcaProfileOrgInviteRevokeArgs + ) => Promise + orgMemberChangeRole: ( + args: OrcaProfileOrgMemberChangeRoleArgs + ) => Promise + orgMemberRemove: ( + args: OrcaProfileOrgMemberRemoveArgs + ) => Promise + } platform: { get: () => { platform: NodeJS.Platform @@ -859,6 +939,9 @@ export type PreloadApi = { kind?: 'git' | 'folder' }) => Promise<{ repo: Repo } | { error: string }> remove: (args: { repoId: string }) => Promise + // Forget a project on one execution host only, leaving the same repo id on + // other hosts (local or a re-added SSH target) intact. + removeForHost: (args: { repoId: string; hostId: string }) => Promise reorder: (args: { orderedIds: string[] }) => Promise<{ status: 'applied' | 'rejected' }> update: (args: { repoId: string @@ -1056,9 +1139,16 @@ export type PreloadApi = { > remove: (args: { worktreeId: string + hostId?: ExecutionHostId force?: boolean skipArchive?: boolean }) => Promise + // Forget a workspace from Orca only — no remote Git/filesystem work. Used + // for workspaces pinned to a removed/disconnected SSH host. + forgetLocal: (args: { + worktreeId: string + hostId?: ExecutionHostId + }) => Promise forceDeletePreservedBranch: (args: { worktreeId: string branchName: string @@ -1109,6 +1199,7 @@ export type PreloadApi = { cols: number rows: number cwd?: string + cwdFallback?: 'worktree' env?: Record command?: string launchConfig?: SleepingAgentLaunchConfig @@ -1124,6 +1215,10 @@ export type PreloadApi = { shellOverride?: string projectRuntime?: ProjectExecutionRuntimeResolution terminalColorQueryReplies?: { foreground?: string; background?: string } + // Why: hidden-at-spawn declaration — main marks the PTY hidden before + // its first byte so the delivery gate + model responder own spawn-time + // queries (terminal-query-authority.md §races). + initiallyHidden?: boolean // Why: closes the SIGKILL race documented in INVESTIGATION.md — main // sync-flushes the (worktreeId, tabId, leafId → ptyId) binding before // pty:spawn returns. Only the renderer's daemon-host path threads these. @@ -1136,6 +1231,7 @@ export type PreloadApi = { telemetry?: { agent_kind: AgentKind; launch_source: LaunchSource; request_kind: RequestKind } }) => Promise<{ id: string + launchAgent?: TuiAgent launchConfig?: SleepingAgentLaunchConfig snapshot?: string snapshotCols?: number @@ -1145,6 +1241,7 @@ export type PreloadApi = { replay?: string sessionExpired?: boolean coldRestore?: { scrollback: string; cwd: string } + startupCwdFallback?: { kind: 'worktree'; cwd: string } }> write: (id: string, data: string) => void writeAccepted: (id: string, data: string) => Promise @@ -1154,11 +1251,37 @@ export type PreloadApi = { clearBuffer: (id: string) => void kill: (id: string, opts?: { keepHistory?: boolean }) => Promise ackColdRestore: (id: string) => void - ackData: (id: string, charCount: number) => void + ackData: (id: string, charCount: number, processedChars?: number) => void + onDeliveryResyncRequest: (callback: (payload: { requestId: number }) => void) => () => void + respondDeliveryResync: (payload: { + requestId: number + processedCharsByPty: Record + }) => void + /** Renderer-initiated delivery health/heal lane over invoke — reaches main + * even when every main→renderer push channel is dead (field wedge). */ + reportRendererDeliveryState: ( + report: PtyRendererDeliveryStateReport + ) => Promise + /** Live pty:data listener count on the preload emitter (sync) — heal-time + * discriminator between a detached listener and a dead channel. */ + getPtyDataListenerCount: () => number + /** One-shot signal that this page's pty:data dispatcher is registered, so + * main can release sends held during the load/reload boot window. */ + rendererDispatcherReady: () => void setActiveRendererPty: (id: string, active: boolean) => void setRendererPtyVisible: (id: string, visible: boolean) => void + /** Hidden-delivery gate (Phase 4): hidden=true lets main drop renderer + * byte delivery after model ingestion; reveal restores from snapshots. */ + setHiddenRendererPty: (id: string, hidden: boolean) => void + /** Ref-counted-on-the-renderer delivery-interest signal that suppresses + * the hidden-delivery gate while any raw-byte consumer is registered. */ + setPtyDeliveryInterest: (id: string, interested: boolean) => void + /** View-attribute bridge (Phase 5 slice 2): app-global composed terminal + * appearance push backing main's hidden-PTY OSC/DSR color replies. */ + publishTerminalViewAttributes: (attributes: TerminalViewAttributes) => void hasChildProcesses: (id: string) => Promise getForegroundProcess: (id: string) => Promise + confirmForegroundProcess: (id: string) => Promise getCwd: (id: string) => Promise getSize: (id: string) => Promise<{ cols: number; rows: number } | null> listSessions: () => Promise<{ id: string; cwd: string; title: string }[]> @@ -1172,8 +1295,17 @@ export type PreloadApi = { rows: number cwd?: string | null seq?: number + /** Start of main's pending renderer-delivery queue at snapshot time + * (equals `seq` when empty) — bounds the renderer's post-restore + * duplicate window. */ + pendingDeliveryStartSeq?: number source?: 'headless' | 'renderer' alternateScreen?: boolean + /** Authoritative normal buffer paired with an alternate-screen frame. */ + scrollbackAnsi?: string + /** Trailing incomplete escape the emulator ingested; the restorer must + * write it after its post-replay resets, last before live chunks. */ + pendingEscapeTailAnsi?: string } | null> getRendererDeliveryDebugSnapshot: () => Promise<{ pendingPtyCount: number @@ -1189,6 +1321,18 @@ export type PreloadApi = { peakRendererInFlightChars: number peakMaxRendererInFlightCharsByPty: number ackGatedFlushSkipCount: number + hiddenDeliveryGatedPtyCount: number + hiddenDeliveryGatedVisiblePtyCount: number + hiddenDeliveryGatedActivePtyCount: number + deliveryInterestPtyCount: number + hiddenDeliveryDroppedChars: number + hiddenDeliveryDroppedChunks: number + pendingDroppedChars: number + diagnostics: PtyMainDeliveryDiagnostics + rendererLifecycleResetCount: number + lastLifecycleResetClearedChars: number + rendererPtyDispatcherReady: boolean + rendererDispatcherReadyForcedCount: number }> resetRendererDeliveryDebug: () => Promise onData: ( @@ -1198,10 +1342,19 @@ export type PreloadApi = { seq?: number rawLength?: number background?: boolean - droppedBacklog?: boolean + droppedOutput?: boolean }) => void ) => () => void onReplay: (callback: (data: { id: string; data: string }) => void) => () => void + /** Out-of-band main→renderer signal that renderer-bound bytes were + * dropped (hidden-delivery gate / pending cap); the pane restores from + * the model snapshot. Never delivered in-band on pty:data. */ + onModelRestoreNeeded: (callback: (event: PtyModelRestoreNeededEvent) => void) => () => void + /** Batched derived side-effect facts for PTYs whose bytes transit local + * main; see docs/reference/terminal-side-effect-authority.md. */ + onSideEffect: (callback: (batch: TerminalSideEffectBatch) => void) => () => void + /** Title-only replay snapshot for (re)attach; attention facts never replay. */ + getSideEffectSnapshot: (id: string) => Promise onExit: (callback: (data: { id: string; code: number }) => void) => () => void onSerializeBufferRequest: ( callback: (data: { @@ -1706,6 +1859,7 @@ export type PreloadApi = { filter?: 'assigned' | 'created' | 'all' | 'completed' limit?: number workspaceId?: LinearWorkspaceSelection + attributeFilter?: LinearIssueAttributeFilter }) => Promise> createIssue: (args: { teamId: string @@ -1844,6 +1998,10 @@ export type PreloadApi = { siteId?: string }) => Promise listTransitions: (args: { key: string; siteId?: string }) => Promise + getProjectStatusOrder: (args: { + projectKey: string + siteId?: string + }) => Promise } starNag: { onShow: ( @@ -1897,6 +2055,10 @@ export type PreloadApi = { telemetryAcknowledgeBanner: () => Promise settings: { get: () => Promise + /** Synchronous persisted-settings read for startup decisions that cannot + * wait for async hydration (terminal side-effect authority). Blocking + * IPC — call sparingly. */ + getSync: () => GlobalSettings | null set: (args: Partial) => Promise listFonts: () => Promise previewGhosttyImport: () => Promise @@ -1986,7 +2148,7 @@ export type PreloadApi = { dismiss: (ids: string[]) => Promise openSystemSettings: () => Promise getPermissionStatus: () => Promise - requestPermission: () => Promise + probeDelivery: (args?: { force?: boolean }) => Promise playSound: (options?: { force?: boolean; volume?: number }) => Promise } onboarding: { @@ -2039,7 +2201,7 @@ export type PreloadApi = { browser: BrowserApi emulator: EmulatorApi hooks: { - check: (args: { repoId: string }) => Promise<{ + check: (args: { repoId: string; hostId?: ExecutionHostId }) => Promise<{ status?: 'ok' | 'error' hasHooks: boolean hooks: OrcaHooks | null @@ -2240,7 +2402,9 @@ export type PreloadApi = { rootPath: string connectionId?: string excludePaths?: string[] + requestToken?: string }) => Promise + cancelListFiles: (args: { requestToken: string }) => Promise search: (args: SearchOptions & { connectionId?: string }) => Promise importExternalPaths: (args: { sourcePaths: string[] @@ -2678,7 +2842,9 @@ export type PreloadApi = { callback: (data: { tabId: string; paneRuntimeId?: number }) => void ) => () => void onSleepWorktree: (callback: (data: { worktreeId: string }) => void) => () => void + onResumeSleepingAgents: (callback: (data: { worktreeId: string }) => void) => () => void onTerminalZoom: (callback: (direction: 'in' | 'out' | 'reset') => void) => () => void + onSystemResumed: (callback: () => void) => () => void readClipboardText: (options?: ReadClipboardTextOptions) => Promise readSelectionClipboardText: (options?: ReadClipboardTextOptions) => Promise saveClipboardImageAsTempFile: (args?: { @@ -2800,6 +2966,7 @@ export type PreloadApi = { fetchInactiveClaudeAccounts: () => Promise fetchInactiveCodexAccounts: () => Promise refreshMiniMax: () => Promise + refreshGrok: () => Promise onUpdate: (callback: (state: RateLimitState) => void) => () => void } minimaxCredentials: { @@ -2807,8 +2974,14 @@ export type PreloadApi = { saveCookie: (cookie: string) => Promise<{ configured: boolean }> clearCookie: () => Promise<{ configured: boolean }> } + grokAccounts: { + getStatus: () => Promise + } ssh: { listTargets: () => Promise + // Removed-target id → last known label, for showing a friendly host name on + // workspaces still pinned to a target that no longer exists. + listRemovedTargetLabels: () => Promise> addTarget: (args: { target: Omit }) => Promise updateTarget: (args: { id: string diff --git a/src/preload/e2e-config.ts b/src/preload/e2e-config.ts index 079bdceb1812..f1cdf668ce3c 100644 --- a/src/preload/e2e-config.ts +++ b/src/preload/e2e-config.ts @@ -20,5 +20,8 @@ const exposeStore = preloadEnv?.MODE === 'e2e' || isEnvFlagEnabled(preloadEnv?.V export const preloadE2EConfig = createE2EConfig({ headless: process.env.ORCA_E2E_HEADLESS === '1', exposeStore, - userDataDir: process.env.ORCA_E2E_USER_DATA_DIR ?? null + userDataDir: process.env.ORCA_E2E_USER_DATA_DIR ?? null, + // Why: Number('') is 0 and Number(undefined) is NaN; both coerce to null so + // only a real positive override reaches the renderer parking policy. + terminalParkingDelayMs: Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || null }) diff --git a/src/preload/index.ts b/src/preload/index.ts index 727bee949bde..c1c8e7fe1545 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -25,6 +25,7 @@ import type { GitHubAssignableUser, GitHubCommentResult, GitHubWorkItem, + JiraProjectStatusOrder, GitPushTarget, GitStagingArea, GitForkSyncExpectedUpstream, @@ -36,6 +37,7 @@ import type { MemorySnapshot, NotificationDismissResult, NotificationDispatchResult, + NotificationDeliveryProbeResult, NotificationPermissionStatusResult, NotificationSoundDataResult, NotificationSoundPathResult, @@ -52,6 +54,13 @@ import type { WorktreeDefaultTabsLaunch, WorktreeRemoteBranchConflictEvent } from '../shared/types' +import type { PtyModelRestoreNeededEvent } from '../shared/pty-model-restore-marker' +import type { + PtyRendererDeliveryHealthReply, + PtyRendererDeliveryStateReport +} from '../shared/pty-renderer-delivery-health' +import type { TerminalViewAttributes } from '../shared/terminal-view-attributes' +import type { PtyMainDeliveryDiagnostics } from '../shared/pty-delivery-diagnostics' import type { WarpThemeImportPreview, WarpThemeImportSource @@ -78,6 +87,7 @@ import type { } from '../shared/mobile-markdown-document' import type { CodexRateLimitResetResult, + GrokAccountStatus, RateLimitRuntimeTarget, RateLimitState } from '../shared/rate-limit-types' @@ -128,6 +138,7 @@ import type { MigrationUnsupportedPtyEntry } from '../shared/agent-status-types' import type { AgentInterruptInferenceRequest } from '../shared/agent-interrupt-intent' +import type { TerminalSideEffectBatch } from '../shared/terminal-side-effect-facts' import type { SpeechErrorEvent, SpeechLifecycleEvent, @@ -139,6 +150,7 @@ import type { TelemetryConsentState } from '../shared/telemetry-consent-types' import type { PreflightRuntimeContext, RefreshAgentsResult } from './api-types' import type { AgentKind, LaunchSource, RequestKind } from '../shared/telemetry-events' import type { AppStarSource } from '../shared/gh-star-source' +import type { ExecutionHostId } from '../shared/execution-host' import type { Automation, AutomationCreateInput, @@ -155,7 +167,7 @@ import type { AutomationUpdateInput } from '../shared/automations-types' import type { KeybindingActionId, KeybindingFileSnapshot } from '../shared/keybindings' -import type { AiVaultListArgs } from '../shared/ai-vault-types' +import type { AiVaultListArgs, AiVaultSubagentListArgs } from '../shared/ai-vault-types' import type { AgentType } from '../shared/native-chat-types' import type { NativeChatAppendedMessages, @@ -481,6 +493,25 @@ const api = { ipcRenderer.invoke('app:pickFloatingWorkspaceDirectory') }, + orcaProfiles: { + list: () => ipcRenderer.invoke('orcaProfiles:list'), + authStatus: () => ipcRenderer.invoke('orcaProfiles:authStatus'), + createLocal: (args) => ipcRenderer.invoke('orcaProfiles:createLocal', args), + createCloudLinked: (args) => ipcRenderer.invoke('orcaProfiles:createCloudLinked', args), + switchProfile: (args) => ipcRenderer.invoke('orcaProfiles:switch', args), + transferProject: (args) => ipcRenderer.invoke('orcaProfiles:transferProject', args), + findProjectProfiles: (args) => ipcRenderer.invoke('orcaProfiles:findProjectProfiles', args), + connectCurrent: () => ipcRenderer.invoke('orcaProfiles:connectCurrent'), + refreshAuth: () => ipcRenderer.invoke('orcaProfiles:refreshAuth'), + signOutCurrent: () => ipcRenderer.invoke('orcaProfiles:signOutCurrent'), + selectOrg: (args) => ipcRenderer.invoke('orcaProfiles:selectOrg', args), + orgMembersList: (args) => ipcRenderer.invoke('orcaProfiles:orgMembersList', args), + orgMemberInvite: (args) => ipcRenderer.invoke('orcaProfiles:orgMemberInvite', args), + orgInviteRevoke: (args) => ipcRenderer.invoke('orcaProfiles:orgInviteRevoke', args), + orgMemberChangeRole: (args) => ipcRenderer.invoke('orcaProfiles:orgMemberChangeRole', args), + orgMemberRemove: (args) => ipcRenderer.invoke('orcaProfiles:orgMemberRemove', args) + } satisfies PreloadApi['orcaProfiles'], + platform: { get: () => ({ platform: process.platform, @@ -520,6 +551,8 @@ const api = { remove: (args) => ipcRenderer.invoke('repos:remove', args), + removeForHost: (args) => ipcRenderer.invoke('repos:removeForHost', args), + reorder: (args) => ipcRenderer.invoke('repos:reorder', args), update: (args) => ipcRenderer.invoke('repos:update', args), @@ -652,6 +685,8 @@ const api = { remove: (args) => ipcRenderer.invoke('worktrees:remove', args), + forgetLocal: (args) => ipcRenderer.invoke('worktrees:forgetLocal', args), + forceDeletePreservedBranch: (args) => ipcRenderer.invoke('worktrees:forceDeletePreservedBranch', args), @@ -752,6 +787,7 @@ const api = { cols: number rows: number cwd?: string + cwdFallback?: 'worktree' env?: Record command?: string launchConfig?: SleepingAgentLaunchConfig @@ -764,6 +800,10 @@ const api = { shellOverride?: string projectRuntime?: ProjectExecutionRuntimeResolution terminalColorQueryReplies?: { foreground?: string; background?: string } + // Why: hidden-at-spawn declaration — main marks the PTY hidden before + // its first byte so the delivery gate + model responder own spawn-time + // queries (terminal-query-authority.md §races). + initiallyHidden?: boolean // Why: closes the SIGKILL race documented in INVESTIGATION.md by // letting main patch + sync-flush the (worktreeId, tabId, leafId → // ptyId) binding before pty:spawn returns. Only the renderer's @@ -787,6 +827,7 @@ const api = { replay?: string sessionExpired?: boolean coldRestore?: { scrollback: string; cwd: string } + startupCwdFallback?: { kind: 'worktree'; cwd: string } }> => ipcRenderer.invoke('pty:spawn', opts), write: (id: string, data: string): void => { @@ -822,8 +863,41 @@ const api = { ackColdRestore: (id: string): void => { ipcRenderer.send('pty:ackColdRestore', { id }) }, - ackData: (id: string, charCount: number): void => { - ipcRenderer.send('pty:ackData', { id, charCount }) + /** charCount is the legacy per-chunk delta; processedChars is the + * cumulative per-pty total (self-healing under lost ACK messages). */ + ackData: (id: string, charCount: number, processedChars?: number): void => { + ipcRenderer.send('pty:ackData', { + id, + charCount, + ...(typeof processedChars === 'number' ? { processedChars } : {}) + }) + }, + /** Main asks for the renderer's cumulative processed totals when terminal + * delivery looks stuck on lost ACKs. */ + onDeliveryResyncRequest: (callback: (payload: { requestId: number }) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, payload: { requestId: number }) => + callback(payload) + ipcRenderer.on('pty:requestDeliveryResync', listener) + return () => ipcRenderer.removeListener('pty:requestDeliveryResync', listener) + }, + respondDeliveryResync: (payload: { + requestId: number + processedCharsByPty: Record + }): void => { + ipcRenderer.send('pty:deliveryResyncResponse', payload) + }, + /** Renderer-initiated delivery health/heal lane. Rides invoke because the + * field wedge (v1.4.121-rc.0 snapshot) kills main→renderer push events + * while invoke stays alive — push-initiated recovery can't reach it. */ + reportRendererDeliveryState: ( + report: PtyRendererDeliveryStateReport + ): Promise => + ipcRenderer.invoke('pty:reportRendererDeliveryState', report), + /** Sync count of live pty:data listeners on this preload's emitter — the + * watchdog's "listener detached" vs "channel dead" discriminator. */ + getPtyDataListenerCount: (): number => ipcRenderer.listenerCount('pty:data'), + rendererDispatcherReady: (): void => { + ipcRenderer.send('pty:rendererDispatcherReady') }, setActiveRendererPty: (id: string, active: boolean): void => { ipcRenderer.send('pty:setActiveRendererPty', { id, active }) @@ -831,6 +905,24 @@ const api = { setRendererPtyVisible: (id: string, visible: boolean): void => { ipcRenderer.send('pty:setRendererPtyVisible', { id, visible }) }, + /** Hidden-delivery gate (Phase 4): hidden=true lets main DROP renderer + * byte delivery after model ingestion; reveal restores from the model + * snapshot. Fire-and-forget like setActiveRendererPty. */ + setHiddenRendererPty: (id: string, hidden: boolean): void => { + ipcRenderer.send('pty:setHiddenRendererPty', { id, hidden }) + }, + /** Delivery-interest signal: any renderer party that needs raw bytes + * (dispatcher sidecars, eager pre-mount buffers) suppresses the + * hidden-delivery gate for that PTY while registered. */ + setPtyDeliveryInterest: (id: string, interested: boolean): void => { + ipcRenderer.send('pty:setPtyDeliveryInterest', { id, interested }) + }, + /** View-attribute bridge (Phase 5 slice 2): app-global composed terminal + * appearance push that lets main's model responder answer OSC 4/10/11/12 + * and DSR ?996n for hidden-gated PTYs with renderer-true values. */ + publishTerminalViewAttributes: (attributes: TerminalViewAttributes): void => { + ipcRenderer.send('pty:terminalViewAttributes', attributes) + }, kill: (id: string, opts?: { keepHistory?: boolean }): Promise => ipcRenderer.invoke('pty:kill', { id, keepHistory: opts?.keepHistory ?? false }), @@ -848,8 +940,11 @@ const api = { rows: number cwd?: string | null seq?: number + pendingDeliveryStartSeq?: number source?: 'headless' | 'renderer' alternateScreen?: boolean + scrollbackAnsi?: string + pendingEscapeTailAnsi?: string } | null> => ipcRenderer.invoke('pty:getMainBufferSnapshot', { id, opts }), getRendererDeliveryDebugSnapshot: (): Promise<{ @@ -866,6 +961,18 @@ const api = { peakRendererInFlightChars: number peakMaxRendererInFlightCharsByPty: number ackGatedFlushSkipCount: number + hiddenDeliveryGatedPtyCount: number + hiddenDeliveryGatedVisiblePtyCount: number + hiddenDeliveryGatedActivePtyCount: number + deliveryInterestPtyCount: number + hiddenDeliveryDroppedChars: number + hiddenDeliveryDroppedChunks: number + pendingDroppedChars: number + diagnostics: PtyMainDeliveryDiagnostics + rendererLifecycleResetCount: number + lastLifecycleResetClearedChars: number + rendererPtyDispatcherReady: boolean + rendererDispatcherReadyForcedCount: number }> => ipcRenderer.invoke('pty:getRendererDeliveryDebugSnapshot'), resetRendererDeliveryDebug: (): Promise => @@ -879,6 +986,8 @@ const api = { /** Return the PTY foreground process basename when available (e.g. "codex"). */ getForegroundProcess: (id: string): Promise => ipcRenderer.invoke('pty:getForegroundProcess', { id }), + confirmForegroundProcess: (id: string): Promise => + ipcRenderer.invoke('pty:confirmForegroundProcess', { id }), /** Resolve the live cwd of a PTY via `/proc` (Linux) or `lsof` (macOS). * Returns `''` when the id is unknown or the platform cannot resolve one. */ @@ -897,7 +1006,7 @@ const api = { seq?: number rawLength?: number background?: boolean - droppedBacklog?: boolean + droppedOutput?: boolean }) => void ): (() => void) => { const listener = ( @@ -908,7 +1017,7 @@ const api = { seq?: number rawLength?: number background?: boolean - droppedBacklog?: boolean + droppedOutput?: boolean } ) => callback(data) ipcRenderer.on('pty:data', listener) @@ -922,6 +1031,32 @@ const api = { return () => ipcRenderer.removeListener('pty:replay', listener) }, + /** Out-of-band signal that main dropped renderer-bound bytes for a PTY + * (hidden-delivery gate / pending cap) — the pane must restore from the + * model snapshot. Deliberately NOT on pty:data: an in-band marker is + * ambiguous with chunks fully stripped by OSC-9999 cleaning. */ + onModelRestoreNeeded: (callback: (event: PtyModelRestoreNeededEvent) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, event: PtyModelRestoreNeededEvent) => + callback(event) + ipcRenderer.on('pty:modelRestoreNeeded', listener) + return () => ipcRenderer.removeListener('pty:modelRestoreNeeded', listener) + }, + + /** Batched derived side-effect facts (title/bell/agent transitions) for + * PTYs whose bytes transit local main. Per-PTY in-order; deliberately not + * synchronized with pty:data (terminal-side-effect-authority.md). */ + onSideEffect: (callback: (batch: TerminalSideEffectBatch) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, batch: TerminalSideEffectBatch) => + callback(batch) + ipcRenderer.on('pty:sideEffect', listener) + return () => ipcRenderer.removeListener('pty:sideEffect', listener) + }, + + /** Title-only replay snapshot applied on (re)attach — attention facts + * (bells/completions) never replay. */ + getSideEffectSnapshot: (id: string): Promise => + ipcRenderer.invoke('pty:sideEffectSnapshot', { id }), + onExit: (callback: (data: { id: string; code: number }) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, data: { id: string; code: number }) => callback(data) @@ -1435,6 +1570,7 @@ const api = { filter?: 'assigned' | 'created' | 'all' | 'completed' limit?: number workspaceId?: string + attributeFilter?: unknown }): Promise => ipcRenderer.invoke('linear:listIssues', args), createIssue: (args: { @@ -1629,7 +1765,11 @@ const api = { }): Promise => ipcRenderer.invoke('jira:listAssignableUsers', args), listTransitions: (args: { key: string; siteId?: string }): Promise => - ipcRenderer.invoke('jira:listTransitions', args) + ipcRenderer.invoke('jira:listTransitions', args), + getProjectStatusOrder: (args: { + projectKey: string + siteId?: string + }): Promise => ipcRenderer.invoke('jira:getProjectStatusOrder', args) }, starNag: { @@ -1697,6 +1837,10 @@ const api = { settings: { get: (): Promise => ipcRenderer.invoke('settings:get'), + // Why: blocking read for the few startup decisions (terminal side-effect + // authority) that cannot wait for async hydration. Call sparingly. + getSync: (): unknown => ipcRenderer.sendSync('settings:get-sync'), + set: (args: Record): Promise => ipcRenderer.invoke('settings:set', args), @@ -1872,8 +2016,8 @@ const api = { openSystemSettings: (): Promise => ipcRenderer.invoke('notifications:openSystemSettings'), getPermissionStatus: (): Promise => ipcRenderer.invoke('notifications:getPermissionStatus'), - requestPermission: (): Promise => - ipcRenderer.invoke('notifications:requestPermission'), + probeDelivery: (args?: { force?: boolean }): Promise => + ipcRenderer.invoke('notifications:probeDelivery', args), playSound: async (options?: { force?: boolean volume?: number @@ -2437,6 +2581,7 @@ const api = { hooks: { check: (args: { repoId: string + hostId?: ExecutionHostId }): Promise<{ status?: 'ok' | 'error' hasHooks: boolean @@ -2643,7 +2788,10 @@ const api = { rootPath: string connectionId?: string excludePaths?: string[] + requestToken?: string }): Promise => ipcRenderer.invoke('fs:listFiles', args), + cancelListFiles: (args: { requestToken: string }): Promise => + ipcRenderer.invoke('fs:cancelListFiles', args), search: (args: { query: string rootPath: string @@ -3448,6 +3596,12 @@ const api = { ipcRenderer.on('ui:sleepWorktree', listener) return () => ipcRenderer.removeListener('ui:sleepWorktree', listener) }, + onResumeSleepingAgents: (callback: (data: { worktreeId: string }) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, data: { worktreeId: string }) => + callback(data) + ipcRenderer.on('ui:resumeSleepingAgents', listener) + return () => ipcRenderer.removeListener('ui:resumeSleepingAgents', listener) + }, onTerminalZoom: (callback: (direction: 'in' | 'out' | 'reset') => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, direction: 'in' | 'out' | 'reset') => callback(direction) @@ -3519,6 +3673,14 @@ const api = { ipcRenderer.on('window:fullscreen-changed', listener) return () => ipcRenderer.removeListener('window:fullscreen-changed', listener) }, + /** Fired when the OS resumes from sleep (main relays powerMonitor). A + * focus-preserving display wake fires no renderer focus/visibility + * events, so terminal wake recovery listens to this explicit signal. */ + onSystemResumed: (callback: () => void): (() => void) => { + const listener = () => callback() + ipcRenderer.on('system:resumed', listener) + return () => ipcRenderer.removeListener('system:resumed', listener) + }, /** Desktop custom titlebar only: minimize via renderer-drawn window controls. */ minimize: (): void => { ipcRenderer.send('window:minimize') @@ -3639,6 +3801,8 @@ const api = { aiVault: { listSessions: (args?: AiVaultListArgs): Promise => ipcRenderer.invoke('aiVault:listSessions', args), + listSubagentSessions: (args: AiVaultSubagentListArgs): Promise => + ipcRenderer.invoke('aiVault:listSubagentSessions', args), onWindowFocused: (callback: () => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent) => callback() ipcRenderer.on('aiVault:windowFocused', listener) @@ -3809,6 +3973,7 @@ const api = { fetchInactiveCodexAccounts: (): Promise => ipcRenderer.invoke('rateLimits:fetchInactiveCodexAccounts'), refreshMiniMax: (): Promise => ipcRenderer.invoke('rateLimits:refreshMiniMax'), + refreshGrok: (): Promise => ipcRenderer.invoke('rateLimits:refreshGrok'), onUpdate: (callback: (state: RateLimitState) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, state: RateLimitState) => callback(state) ipcRenderer.on('rateLimits:update', listener) @@ -3825,9 +3990,16 @@ const api = { ipcRenderer.invoke('minimaxCredentials:clearCookie') }, + grokAccounts: { + getStatus: (): Promise => ipcRenderer.invoke('grokAccounts:getStatus') + }, + ssh: { listTargets: (): Promise => ipcRenderer.invoke('ssh:listTargets'), + listRemovedTargetLabels: (): Promise> => + ipcRenderer.invoke('ssh:listRemovedTargetLabels'), + addTarget: (args: { target: Omit }): Promise => ipcRenderer.invoke('ssh:addTarget', args), diff --git a/src/relay/agent-hook-server.test.ts b/src/relay/agent-hook-server.test.ts index 33f630d9c478..4edb3dde4093 100644 --- a/src/relay/agent-hook-server.test.ts +++ b/src/relay/agent-hook-server.test.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import { endpointDirForRelaySocket, RelayAgentHookServer } from './agent-hook-server' import type { AgentHookRelayEnvelope } from '../shared/agent-hook-relay' import { makePaneKey } from '../shared/stable-pane-id' +import * as agentHookListener from '../shared/agent-hook-listener' const LEAF_ID = '11111111-1111-4111-8111-111111111111' const PANE_KEY = makePaneKey('tab-1', LEAF_ID) @@ -257,6 +258,8 @@ describe('RelayAgentHookServer', () => { }) expect(forward.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBeUndefined() + // Let the first 50ms retry miss so continuation across SessionEnd is proven. + await new Promise((resolve) => setTimeout(resolve, 70)) writeFileSync( transcriptPath, `${JSON.stringify({ @@ -331,4 +334,158 @@ describe('RelayAgentHookServer', () => { vi.unstubAllEnvs() } }) + + it('caps the replay cache at 256 panes, evicting the least-recently-updated', async () => { + // Mirrors the server's private MAX_CACHED_PANES. The WSL relay never gets a + // per-pane teardown signal, so the cache is recency-capped instead. + const CAP = 256 + const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() + const server = new RelayAgentHookServer({ endpointDir: dir, forward }) + await server.start() + try { + const { port, token } = server.getCoordinates() + const paneKeyFor = (i: number): string => makePaneKey(`tab-${i}`, LEAF_ID) + const postPane = (paneKey: string): Promise => + fetch(`http://127.0.0.1:${port}/hook/claude`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Orca-Agent-Hook-Token': token + }, + body: JSON.stringify({ + paneKey, + payload: { hook_event_name: 'UserPromptSubmit', prompt: 'p' } + }) + }) + + // Fill the cache to exactly the cap in insertion order 0..CAP-1. Sequential + // awaits pin Map order = update recency, which the eviction relies on. + for (let i = 0; i < CAP; i++) { + await postPane(paneKeyFor(i)) + } + // Refresh the OLDEST pane just before overflow, then push one more pane. + // Recency (not insertion) order must now evict pane 1, sparing pane 0. + await postPane(paneKeyFor(0)) + await postPane(paneKeyFor(CAP)) + + forward.mockClear() + const replayed = server.replayCachedPayloadsForPanes() + expect(replayed).toBe(CAP) + + const cachedPaneKeys = new Set(forward.mock.calls.map((call) => call[0].paneKey)) + expect(cachedPaneKeys.size).toBe(CAP) + expect(cachedPaneKeys.has(paneKeyFor(0))).toBe(true) + expect(cachedPaneKeys.has(paneKeyFor(CAP))).toBe(true) + expect(cachedPaneKeys.has(paneKeyFor(1))).toBe(false) + } finally { + server.stop() + } + }, 30_000) + + it('forwards a Grok result when discovery finishes after the old retry window', async () => { + let releaseDiscovery!: () => void + const discovery = new Promise((resolve) => { + releaseDiscovery = resolve + }) + vi.spyOn(agentHookListener, 'preparePendingGrokResultDiscovery').mockReturnValue(discovery) + const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() + const server = new RelayAgentHookServer({ endpointDir: dir, forward }) + const sessionId = '019e37f4-5135-7b63-a4ab-6d13aa6bf534' + const cwd = join(dir, 'workspace') + const sessionDir = join(dir, '.grok', 'sessions', encodeURIComponent(cwd), sessionId) + mkdirSync(sessionDir, { recursive: true }) + const history = join(sessionDir, 'chat_history.jsonl') + writeFileSync(history, '') + vi.stubEnv('HOME', dir) + vi.stubEnv('USERPROFILE', dir) + await server.start() + try { + const { port, token } = server.getCoordinates() + const post = (payload: Record): Promise => + fetch(`http://127.0.0.1:${port}/hook/grok`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Orca-Agent-Hook-Token': token + }, + body: JSON.stringify({ + paneKey: PANE_KEY, + tabId: 'tab-1', + env: 'remote', + version: '1', + payload + }) + }) + + await post({ hookEventName: 'UserPromptSubmit', prompt: 'delayed relay result' }) + await post({ hookEventName: 'Stop', sessionId, cwd }) + await new Promise((resolve) => setTimeout(resolve, 300)) + expect(forward.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBeUndefined() + + writeFileSync( + history, + `${JSON.stringify({ type: 'assistant', content: 'Relay found after discovery.' })}\n` + ) + releaseDiscovery() + + await vi.waitFor(() => { + expect(forward.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBe( + 'Relay found after discovery.' + ) + }) + } finally { + server.stop() + vi.unstubAllEnvs() + } + }) + + it('does not forward an old result over a newer same-text Grok turn', async () => { + let releaseDiscovery!: () => void + const discovery = new Promise((resolve) => { + releaseDiscovery = resolve + }) + vi.spyOn(agentHookListener, 'preparePendingGrokResultDiscovery').mockReturnValue(discovery) + const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>() + const server = new RelayAgentHookServer({ endpointDir: dir, forward }) + await server.start() + try { + const { port, token } = server.getCoordinates() + const post = (payload: Record): Promise => + fetch(`http://127.0.0.1:${port}/hook/grok`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Orca-Agent-Hook-Token': token + }, + body: JSON.stringify({ + paneKey: PANE_KEY, + tabId: 'tab-1', + env: 'remote', + version: '1', + payload + }) + }) + + await post({ hookEventName: 'UserPromptSubmit', prompt: 'repeat me' }) + await post({ + hookEventName: 'Stop', + sessionId: '019e37f4-5135-7b63-a4ab-6d13aa6bf535', + cwd: join(dir, 'workspace') + }) + await post({ hookEventName: 'UserPromptSubmit', prompt: 'repeat me' }) + const forwardsBeforeDiscovery = forward.mock.calls.length + + releaseDiscovery() + await new Promise((resolve) => setTimeout(resolve, 80)) + + expect(forward).toHaveBeenCalledTimes(forwardsBeforeDiscovery) + expect(forward.mock.calls.at(-1)?.[0].payload).toMatchObject({ + state: 'working', + prompt: 'repeat me', + agentType: 'grok' + }) + } finally { + server.stop() + } + }) }) diff --git a/src/relay/agent-hook-server.ts b/src/relay/agent-hook-server.ts index 769921f59c76..f5200a2b178f 100644 --- a/src/relay/agent-hook-server.ts +++ b/src/relay/agent-hook-server.ts @@ -25,6 +25,7 @@ import { hasPendingAgentResultText, HOOK_REQUEST_SLOWLORIS_MS, normalizeHookPayload, + preparePendingGrokResultDiscovery, readRequestBody, resolveHookSource, writeEndpointFile, @@ -54,6 +55,12 @@ const ASSISTANT_MESSAGE_RETRY_MS = 50 // '1'/'999'); anything longer is treated as absent. const MAX_HOOK_META_LEN = 64 +// Why: the WSL relay has no per-pane teardown signal (PTYs live on the +// Windows host, so nothing calls clearPaneState), and the replay cache would +// otherwise grow for the relay's lifetime. Recency-cap it; backstop for the +// SSH relay too. +const MAX_CACHED_PANES = 256 + function defaultEndpointDir(): string { return join(homedir(), RELAY_HOOKS_DIR_NAME, RELAY_HOOKS_SUBDIR) } @@ -84,6 +91,15 @@ export type RelayHookServerOptions = { /** Env tag forwarded into hook payloads. Defaults to "remote", a relay * location marker that main excludes from dev-vs-prod mismatch warnings. */ env?: string + /** Fixed auth token. The WSL relay passes the host-issued token that + * already crossed into guest env via WSLENV, so unmodified hook clients + * authenticate without any re-coordination. Defaults to a fresh UUID. */ + token?: string + /** Preferred bind port. The WSL relay passes the Windows listener's port — + * free inside the guest under NAT, so env-sourced client coords stay + * truthful. Occupied (e.g. mirrored networking) → fall back to :0 and rely + * on the endpoint file for re-coordination. Defaults to :0. */ + preferredPort?: number /** Called once per parsed payload. The relay wires this to * `dispatcher.notify('agent.hook', envelope)`. */ forward: RelayHookForward @@ -115,11 +131,16 @@ export class RelayAgentHookServer { > = new Map() private assistantMessageRetryTimers = new Map>() private forward: RelayHookForward + private fixedToken: string | undefined + private preferredPort: number + private portFallbackApplied = false constructor(options: RelayHookServerOptions) { this.env = options.env ?? REMOTE_AGENT_HOOK_ENV this.endpointDir = options.endpointDir ?? defaultEndpointDir() this.endpointFilePath = join(this.endpointDir, getEndpointFileName()) + this.fixedToken = options.token + this.preferredPort = options.preferredPort ?? 0 this.forward = options.forward } @@ -127,10 +148,37 @@ export class RelayAgentHookServer { if (this.server) { return } - this.token = randomUUID() + this.token = this.fixedToken ?? randomUUID() this.endpointFileWritten = false + this.portFallbackApplied = false + try { + await this.listenOn(this.preferredPort) + } catch (err) { + // Why: the preferred port is best-effort (WSL relay: the Windows + // listener's port — occupied under mirrored networking, or by an + // unrelated guest process). Fall back to an ephemeral port; clients + // re-coordinate through the endpoint file. + if (this.preferredPort > 0 && (err as NodeJS.ErrnoException)?.code === 'EADDRINUSE') { + this.portFallbackApplied = true + await this.listenOn(0) + } else { + throw err + } + } + if (options.publishEndpoint !== false) { + this.publishEndpointFile() + } + } + + /** True when the preferred port was occupied and the server fell back to + * an ephemeral bind — diagnostics for the host-side relay manager. */ + get usedPortFallback(): boolean { + return this.portFallbackApplied + } + + private listenOn(port: number): Promise { this.server = createServer((req, res) => this.handleRequest(req, res)) - await new Promise((resolve, reject) => { + return new Promise((resolve, reject) => { const onStartupError = (err: Error): void => { this.server?.off('listening', onListening) // Why: null the server reference on bind failure so a subsequent @@ -149,16 +197,12 @@ export class RelayAgentHookServer { if (address && typeof address === 'object') { this.port = address.port } - if (options.publishEndpoint !== false) { - this.publishEndpointFile() - } resolve() } this.server!.once('error', onStartupError) - // Why: bind 127.0.0.1:0 so the OS assigns a free port. Loopback only — - // the agent CLI inside the same remote box reaches us via curl - // 127.0.0.1:PORT; nobody outside the box can. - this.server!.listen(0, '127.0.0.1', onListening) + // Why: loopback only — the agent CLI inside the same remote box reaches + // us via curl 127.0.0.1:PORT; nobody outside the box can. + this.server!.listen(port, '127.0.0.1', onListening) }) } @@ -332,8 +376,19 @@ export class RelayAgentHookServer { if (event.payload.state !== 'done' || event.payload.lastAssistantMessage) { this.clearAssistantMessageRetry(event.paneKey) } + // Why: delete-then-set keeps Map insertion order equal to last-update + // recency, so the cache cap below always evicts the longest-idle pane. + this.state.lastStatusByPaneKey.delete(event.paneKey) this.state.lastStatusByPaneKey.set(event.paneKey, event) + this.lastEnvelopeMetaByPaneKey.delete(event.paneKey) this.lastEnvelopeMetaByPaneKey.set(event.paneKey, { source, env, version }) + while (this.state.lastStatusByPaneKey.size > MAX_CACHED_PANES) { + const oldest = this.state.lastStatusByPaneKey.keys().next().value + if (oldest === undefined) { + break + } + this.clearPaneState(oldest) + } this.forwardEvent(event, source, env, version) } @@ -352,7 +407,8 @@ export class RelayAgentHookServer { original: AgentHookEventPayload, env?: string, version?: string, - attempt = 1 + attempt = 1, + discoveryReady = false ): void { if ( original.payload.lastAssistantMessage || @@ -362,26 +418,37 @@ export class RelayAgentHookServer { return } this.clearAssistantMessageRetry(original.paneKey) + if (!discoveryReady) { + const discovery = preparePendingGrokResultDiscovery(source, body) + if (discovery) { + // Why: remote slug-group discovery can outlive the bounded transcript- + // flush timers, so completion itself drives the first retry. + void discovery + .then(() => { + if (this.server) { + this.applyAssistantMessageRetry(source, body, original, env, version, 1, true) + } + }) + .catch((err) => { + process.stderr.write( + `[relay-hook-server] Grok result discovery failed: ${err instanceof Error ? err.message : String(err)}\n` + ) + }) + return + } + } const timer = setTimeout(() => { try { this.assistantMessageRetryTimers.delete(original.paneKey) - const current = this.state.lastStatusByPaneKey.get(original.paneKey) - if ( - !current || - current.payload.agentType !== original.payload.agentType || - current.payload.prompt !== original.payload.prompt || - current.payload.lastAssistantMessage - ) { - return - } - const event = normalizeHookPayload(this.state, source, body, this.env) - if (!event?.payload.lastAssistantMessage) { - this.scheduleAssistantMessageRetry(source, body, original, env, version, attempt + 1) - return - } - // Why: the relay runs on SSH targets too; retry from a timer so a delayed - // transcript/chat-history write does not block the remote hook server. - this.applyEvent(event, source, env, version) + this.applyAssistantMessageRetry( + source, + body, + original, + env, + version, + attempt + 1, + discoveryReady + ) } catch (err) { process.stderr.write( `[relay-hook-server] assistant message retry failed: ${err instanceof Error ? err.message : String(err)}\n` @@ -394,6 +461,41 @@ export class RelayAgentHookServer { } } + private applyAssistantMessageRetry( + source: AgentHookSource, + body: unknown, + original: AgentHookEventPayload, + env: string | undefined, + version: string | undefined, + nextAttempt: number, + requireExactOriginal: boolean + ): void { + const current = this.state.lastStatusByPaneKey.get(original.paneKey) + if ( + !current || + (requireExactOriginal && current !== original) || + current.payload.agentType !== original.payload.agentType || + current.payload.prompt !== original.payload.prompt || + current.payload.lastAssistantMessage + ) { + return + } + const event = normalizeHookPayload(this.state, source, body, this.env) + if (!event?.payload.lastAssistantMessage) { + this.scheduleAssistantMessageRetry( + source, + body, + original, + env, + version, + nextAttempt, + requireExactOriginal + ) + return + } + this.applyEvent(event, source, env, version) + } + private bodyEnv(body: unknown): string | undefined { if (typeof body !== 'object' || body === null) { return undefined diff --git a/src/relay/dispatcher.test.ts b/src/relay/dispatcher.test.ts index 5ab997c9d210..0a9a39081721 100644 --- a/src/relay/dispatcher.test.ts +++ b/src/relay/dispatcher.test.ts @@ -396,6 +396,73 @@ describe('RelayDispatcher', () => { expect(listener).toHaveBeenCalledWith(1) }) + it('detaches the primary client when its write throws (frame lost, trigger reconnect)', () => { + // Regression: a primary-client write throw dropped the frame (possibly + // pty.data/pty.exit) with no resend AND without notifying detach, so the + // owning Orca's reconnect + PTY-reattach path never engaged until the ~20s + // keepalive timeout — output/pane-death were silently lost in the meantime. + let throwOnWrite = false + const detachDispatcher = new RelayDispatcher((data) => { + if (throwOnWrite) { + throw new Error('socket closed') + } + written.push(Buffer.from(data)) + }) + try { + const detachListener = vi.fn() + detachDispatcher.onClientDetached(detachListener) + + // A frame the owning Orca must not silently miss (e.g. a pane exit). + throwOnWrite = true + detachDispatcher.notify('pty.exit', { id: 'pty-1', code: 0 }) + + // Fix: the write failure detaches the primary so the reconnect/reattach + // machinery runs promptly instead of waiting for keepalive timeout. + expect(detachListener).toHaveBeenCalledWith(1) + + // Recovery: a reconnecting socket swaps the write via setWrite; the client + // is usable again and later frames flow to the new sink. + throwOnWrite = false + const recovered: Buffer[] = [] + detachDispatcher.setWrite((data) => { + recovered.push(Buffer.from(data)) + }) + detachDispatcher.notify('pty.data', { id: 'pty-1', data: 'x' }) + expect(recovered.length).toBeGreaterThan(0) + } finally { + detachDispatcher.dispose() + } + }) + + it('aborts in-flight primary requests when a client write throws', () => { + let throwOnWrite = false + const detachDispatcher = new RelayDispatcher(() => { + if (throwOnWrite) { + throw new Error('socket closed') + } + }) + let requestSignal: AbortSignal | undefined + try { + detachDispatcher.onRequest('slow.method', async (_params, context) => { + requestSignal = context.signal + await new Promise((resolve) => { + context.signal?.addEventListener('abort', () => resolve(), { once: true }) + }) + }) + detachDispatcher.feed( + encodeJsonRpcFrame({ jsonrpc: '2.0', id: 9, method: 'slow.method' }, 1, 0) + ) + + expect(requestSignal?.aborted).toBe(false) + throwOnWrite = true + detachDispatcher.notify('pty.exit', { id: 'pty-1', code: 0 }) + + expect(requestSignal?.aborted).toBe(true) + } finally { + detachDispatcher.dispose() + } + }) + describe('notifyBulk (bulk lane backpressure)', () => { it('resolves immediately when the sink accepts the frame', async () => { const frames: Buffer[] = [] diff --git a/src/relay/dispatcher.ts b/src/relay/dispatcher.ts index 427d90e6ac05..7dfdf5dc5f45 100644 --- a/src/relay/dispatcher.ts +++ b/src/relay/dispatcher.ts @@ -536,11 +536,21 @@ export class RelayDispatcher { } catch (err) { client.closed = true client.generation++ + this.requestAborts.abortClient(client.id) this.flushDrainWaiters(client) + // Why: a write throw means this frame (possibly pty.data or pty.exit) was + // lost with no resend — the framing carries seq/ack but no retransmit + // buffer. Detach so the owning Orca's reconnect + PTY-reattach path runs + // promptly (regenerating dropped pty.data from the replay buffer and pane + // death via reattach-not-found), instead of silently dropping frames until + // the ~20s keepalive timeout notices. The primary client stays in the map + // (its object is reused across setWrite reconnects) but detach listeners + // must still fire, exactly as invalidateClient() does for stdin/stdout + // death — this makes the socket-write-throw path consistent with those. if (client !== this.primaryClient) { this.clients.delete(client.id) - this.notifyClientDetached(client.id) } + this.notifyClientDetached(client.id) process.stderr.write( `[relay] Client write failed: ${err instanceof Error ? err.message : String(err)}\n` ) diff --git a/src/relay/fs-handler-git-fallback.ts b/src/relay/fs-handler-git-fallback.ts index da1f67c7ffaa..ae418f9e8814 100644 --- a/src/relay/fs-handler-git-fallback.ts +++ b/src/relay/fs-handler-git-fallback.ts @@ -7,9 +7,10 @@ * a git-focused app. */ import { spawn } from 'node:child_process' +import { fileListingCancellationError } from '../shared/file-listing-cancellation' import type { SearchOptions, SearchResult } from './fs-handler-utils' import { buildGitLsFilesArgsForQuickOpen } from '../shared/quick-open-filter' -import { expandQuickOpenGitFilesWithNestedRepos } from '../shared/quick-open-readdir-walk' +import { expandQuickOpenGitFileListing } from '../shared/quick-open-readdir-walk' import { buildGitGrepArgs, buildSubmatchRegex, @@ -18,7 +19,7 @@ import { ingestGitGrepLine, SEARCH_TIMEOUT_MS } from '../shared/text-search' -import { buildRelayCommandEnv } from './relay-command-env' +import { buildRelayGitEnv } from './relay-command-env' /** * List files using `git ls-files`. Fallback when rg is not installed. @@ -31,9 +32,15 @@ import { buildRelayCommandEnv } from './relay-command-env' */ export function listFilesWithGit( rootPath: string, - excludePathPrefixes: readonly string[] = [] + excludePathPrefixes: readonly string[] = [], + options: { signal?: AbortSignal } = {} ): Promise { + const { signal } = options + if (signal?.aborted) { + return Promise.reject(fileListingCancellationError(signal)) + } const gitPaths = new Set() + const directoryPaths = new Set() const { primary, ignoredPass } = buildGitLsFilesArgsForQuickOpen(excludePathPrefixes) const children: { child: ReturnType @@ -50,12 +57,16 @@ export function listFilesWithGit( if (!path) { return } - gitPaths.add(path) + if (path.endsWith('/')) { + directoryPaths.add(path) + } else { + gitPaths.add(path) + } } const child = spawn('git', ['ls-files', ...args], { cwd: rootPath, - env: buildRelayCommandEnv(), + env: buildRelayGitEnv(), stdio: ['ignore', 'pipe', 'pipe'] }) let timer: ReturnType | null = null @@ -145,7 +156,7 @@ export function listFilesWithGit( }) } - const killSurvivors = (): void => { + const killSurvivors = (reason: string): void => { // Why: Promise.all returns after the first failed pass, but the sibling // git process can keep streaming on SSH unless we cancel it explicitly. for (const entry of children) { @@ -155,22 +166,54 @@ export function listFilesWithGit( if (entry.child.exitCode === null && entry.child.signalCode === null) { entry.child.kill() } - entry.reject(new Error('git ls-files canceled after sibling failure')) + entry.reject(new Error(reason)) } } - return Promise.all([runGitLsFiles(primary), runGitLsFiles(ignoredPass)]) - .then(() => - expandQuickOpenGitFilesWithNestedRepos({ + // Why: a cancelled scan (workspace switch, superseded request) must stop + // its git children right away instead of streaming a huge tree the caller + // has already abandoned over the shared SSH channel. + const onAbort = (): void => killSurvivors('git ls-files cancelled') + signal?.addEventListener('abort', onAbort, { once: true }) + + return Promise.all([ + runGitLsFiles(primary), + // Why: ignored files are supplementary — a failed or timed-out ignored + // pass must not discard the primary listing the user actually needs + // (#7719 root cause: the all-or-nothing failure showed zero files). + // Entries streamed before the failure are kept; a cancelled scan still + // rejects via the primary pass or the expansion's cancellation check. + runGitLsFiles(ignoredPass).catch((err: Error) => { + if (!signal?.aborted) { + console.warn( + '[relay quick-open] git ignored-file pass failed; keeping primary results:', + err + ) + } + }) + ]) + .then(async () => { + const files = await expandQuickOpenGitFileListing({ rootPath, gitPaths, - excludePathPrefixes + directoryPaths, + excludePathPrefixes, + signal }) - ) + // Why: directory placeholders are expanded after Git exits; restore + // Git's path order for empty queries and fuzzy-score ties over SSH. + return files.sort() + }) .catch((err) => { - killSurvivors() + killSurvivors('git ls-files canceled after sibling failure') + if (signal?.aborted) { + throw fileListingCancellationError(signal) + } throw err }) + .finally(() => { + signal?.removeEventListener('abort', onAbort) + }) } /** @@ -190,7 +233,7 @@ export function searchWithGitGrep( const child = spawn('git', gitArgs, { cwd: rootPath, - env: buildRelayCommandEnv(), + env: buildRelayGitEnv(), stdio: ['ignore', 'pipe', 'pipe'] }) let killTimeout: ReturnType diff --git a/src/relay/fs-handler-list-files-cancel.test.ts b/src/relay/fs-handler-list-files-cancel.test.ts new file mode 100644 index 000000000000..02cd8da6afc1 --- /dev/null +++ b/src/relay/fs-handler-list-files-cancel.test.ts @@ -0,0 +1,127 @@ +/** + * Cancellation behavior of the relay file-list scanners (#7721): an aborted + * scan must kill its child processes immediately and reject with a + * cancellation error instead of streaming an abandoned tree to completion. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { spawnMock } = vi.hoisted(() => ({ + spawnMock: vi.fn() +})) + +vi.mock('child_process', () => ({ + spawn: spawnMock +})) + +import { EventEmitter } from 'node:events' +import type { ChildProcess } from 'node:child_process' +import { listFilesWithRg } from './fs-handler-list-files' +import { listFilesWithGit } from './fs-handler-git-fallback' +import { isFileListingCancellation } from '../shared/file-listing-cancellation' + +function createMockProcess(): ChildProcess { + const p = new EventEmitter() as unknown as ChildProcess + ;(p as unknown as Record).stdout = new EventEmitter() + ;( + (p as unknown as Record).stdout as EventEmitter & { + setEncoding: () => void + } + ).setEncoding = vi.fn() + ;(p as unknown as Record).stderr = new EventEmitter() + ;(p as unknown as Record).kill = vi.fn() + ;(p as unknown as Record).exitCode = null + ;(p as unknown as Record).signalCode = null + return p +} + +describe('relay list-files cancellation', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('listFilesWithRg kills both rg passes and rejects when aborted mid-flight', async () => { + const primaryProc = createMockProcess() + const ignoredProc = createMockProcess() + spawnMock.mockImplementation((_cmd: string, args: string[]) => + args.includes('--no-ignore-vcs') ? ignoredProc : primaryProc + ) + + const controller = new AbortController() + const promise = listFilesWithRg('/remote/root', [], { signal: controller.signal }) + + // Partial output before the abort — must be discarded, not resolved. + ;(primaryProc.stdout as unknown as EventEmitter).emit('data', 'src/index.ts\n') + controller.abort() + + await expect(promise).rejects.toSatisfy(isFileListingCancellation) + expect(primaryProc.kill).toHaveBeenCalled() + expect(ignoredProc.kill).toHaveBeenCalled() + + // Late close events after cancellation must not fire anything. + primaryProc.emit('close', null, 'SIGTERM') + ignoredProc.emit('close', null, 'SIGTERM') + }) + + it('listFilesWithRg rejects without spawning when the signal is already aborted', async () => { + const controller = new AbortController() + controller.abort() + + await expect( + listFilesWithRg('/remote/root', [], { signal: controller.signal }) + ).rejects.toSatisfy(isFileListingCancellation) + expect(spawnMock).not.toHaveBeenCalled() + }) + + it('listFilesWithRg still resolves normally when a signal is provided but never aborted', async () => { + const primaryProc = createMockProcess() + const ignoredProc = createMockProcess() + spawnMock.mockImplementation((_cmd: string, args: string[]) => + args.includes('--no-ignore-vcs') ? ignoredProc : primaryProc + ) + + const controller = new AbortController() + const promise = listFilesWithRg('/remote/root', [], { signal: controller.signal }) + + setTimeout(() => { + ;(primaryProc.stdout as unknown as EventEmitter).emit('data', 'src/index.ts\n') + primaryProc.emit('close', 0, null) + ;(ignoredProc.stdout as unknown as EventEmitter).emit('data', 'dist/out.js\n') + ignoredProc.emit('close', 0, null) + }, 5) + + await expect(promise).resolves.toEqual(['src/index.ts', 'dist/out.js']) + }) + + it('listFilesWithGit kills both git passes and rejects when aborted mid-flight', async () => { + const procs: ChildProcess[] = [] + spawnMock.mockImplementation(() => { + const proc = createMockProcess() + procs.push(proc) + return proc + }) + + const controller = new AbortController() + const promise = listFilesWithGit('/remote/root', [], { signal: controller.signal }) + + expect(procs).toHaveLength(2) + controller.abort() + + await expect(promise).rejects.toSatisfy(isFileListingCancellation) + expect(procs[0].kill).toHaveBeenCalled() + expect(procs[1].kill).toHaveBeenCalled() + }) + + it('listFilesWithGit rejects without spawning when the signal is already aborted', async () => { + const controller = new AbortController() + controller.abort() + + await expect( + listFilesWithGit('/remote/root', [], { signal: controller.signal }) + ).rejects.toSatisfy(isFileListingCancellation) + expect(spawnMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/relay/fs-handler-list-files-ignored.test.ts b/src/relay/fs-handler-list-files-ignored.test.ts index 753ce02fddc8..d76fe40b5178 100644 --- a/src/relay/fs-handler-list-files-ignored.test.ts +++ b/src/relay/fs-handler-list-files-ignored.test.ts @@ -98,6 +98,8 @@ describe('relay quick open ignored file listing', () => { }) it('git fallback ignored pass includes ignored non-env files', async () => { + const root = await makeTempRoot() + await writeRel(root, 'dist/generated.js') const primaryProc = createMockProcess() const ignoredProc = createMockProcess() let callIndex = 0 @@ -107,7 +109,7 @@ describe('relay quick open ignored file listing', () => { return callIndex === 1 ? primaryProc : ignoredProc }) - const promise = listFilesWithGit('/remote/root', ['packages/other']) + const promise = listFilesWithGit(root, ['packages/other']) setTimeout(() => { ;(primaryProc.stdout as unknown as EventEmitter).emit( @@ -120,26 +122,28 @@ describe('relay quick open ignored file listing', () => { ) primaryProc.emit('close', 0, null) - ;(ignoredProc.stdout as unknown as EventEmitter).emit('data', 'dist/generated.js\0') + ;(ignoredProc.stdout as unknown as EventEmitter).emit('data', 'dist/\0') ;(ignoredProc.stdout as unknown as EventEmitter).emit('data', 'packages/other/src/x.ts\0') ignoredProc.emit('close', 0, null) }, 10) - await expect(promise).resolves.toEqual(['src/index.ts', 'tab\tfile.txt', 'dist/generated.js']) + await expect(promise).resolves.toEqual(['dist/generated.js', 'src/index.ts', 'tab\tfile.txt']) const ignoredArgs = spawnMock.mock.calls[1][1] as string[] - expect(ignoredArgs).toEqual([ + expect(ignoredArgs.slice(0, 6)).toEqual([ 'ls-files', '-z', '-s', '--others', '--ignored', - '--exclude-standard', - '--', - '.', - ':(exclude,glob)packages/other', - ':(exclude,glob)packages/other/**' + '--exclude-standard' ]) + expect(ignoredArgs).toContain('--') + expect(ignoredArgs).toContain('.') + expect(ignoredArgs).toContain('--directory') + expect(ignoredArgs).toContain('--no-empty-directory') + expect(ignoredArgs).toContain(':(exclude,glob)packages/other') + expect(ignoredArgs).toContain(':(exclude,glob)packages/other/**') }) it('git fallback fills nested git repos returned as root-relative placeholders', async () => { @@ -178,7 +182,65 @@ describe('relay quick open ignored file listing', () => { ]) }) - it('git fallback rejects signal exits instead of returning partial results', async () => { + it('git fallback keeps primary results when the ignored pass is killed', async () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const primaryProc = createMockProcess() + const ignoredProc = createMockProcess() + let callIndex = 0 + + spawnMock.mockImplementation(() => { + callIndex++ + return callIndex === 1 ? primaryProc : ignoredProc + }) + + const promise = listFilesWithGit('/remote/root') + + setTimeout(() => { + ;(primaryProc.stdout as unknown as EventEmitter).emit('data', 'src/index.ts\0') + primaryProc.emit('close', 0, null) + + // Entries streamed before the kill are kept alongside the primary pass. + ;(ignoredProc.stdout as unknown as EventEmitter).emit('data', 'dist/generated.js\0') + ignoredProc.emit('close', null, 'SIGTERM') + }, 10) + + await expect(promise).resolves.toEqual(['dist/generated.js', 'src/index.ts']) + expect(warnSpy).toHaveBeenCalled() + } finally { + warnSpy.mockRestore() + } + }) + + it('git fallback keeps primary results when the ignored pass exits non-zero', async () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const primaryProc = createMockProcess() + const ignoredProc = createMockProcess() + let callIndex = 0 + + spawnMock.mockImplementation(() => { + callIndex++ + return callIndex === 1 ? primaryProc : ignoredProc + }) + + const promise = listFilesWithGit('/remote/root') + + setTimeout(() => { + ;(primaryProc.stdout as unknown as EventEmitter).emit('data', 'src/index.ts\0') + primaryProc.emit('close', 0, null) + + ignoredProc.emit('close', 128, null) + }, 10) + + await expect(promise).resolves.toEqual(['src/index.ts']) + expect(warnSpy).toHaveBeenCalled() + } finally { + warnSpy.mockRestore() + } + }) + + it('git fallback rejects when the primary pass is killed', async () => { const primaryProc = createMockProcess() const ignoredProc = createMockProcess() let callIndex = 0 @@ -192,16 +254,16 @@ describe('relay quick open ignored file listing', () => { setTimeout(() => { ;(primaryProc.stdout as unknown as EventEmitter).emit('data', 'src/index.ts\0') - primaryProc.emit('close', 0, null) + primaryProc.emit('close', null, 'SIGTERM') ;(ignoredProc.stdout as unknown as EventEmitter).emit('data', 'dist/generated.js\0') - ignoredProc.emit('close', null, 'SIGTERM') + ignoredProc.emit('close', 0, null) }, 10) await expect(promise).rejects.toThrow('git ls-files killed by SIGTERM') }) - it('git fallback rejects non-zero exits instead of expanding a partial result set', async () => { + it('git fallback rejects when the primary pass exits non-zero', async () => { const primaryProc = createMockProcess() const ignoredProc = createMockProcess() let callIndex = 0 @@ -214,10 +276,10 @@ describe('relay quick open ignored file listing', () => { const promise = listFilesWithGit('/remote/root') setTimeout(() => { - ;(primaryProc.stdout as unknown as EventEmitter).emit('data', 'src/index.ts\0') - primaryProc.emit('close', 0, null) + primaryProc.emit('close', 128, null) - ignoredProc.emit('close', 128, null) + ;(ignoredProc.stdout as unknown as EventEmitter).emit('data', 'dist/generated.js\0') + ignoredProc.emit('close', 0, null) }, 10) await expect(promise).rejects.toThrow('git ls-files exited with code 128') diff --git a/src/relay/fs-handler-list-files.ts b/src/relay/fs-handler-list-files.ts index 99e3eb97ff9b..bbe7912ee61c 100644 --- a/src/relay/fs-handler-list-files.ts +++ b/src/relay/fs-handler-list-files.ts @@ -16,6 +16,7 @@ * denied on a single subdir is expected on home-dir roots) */ import { spawn, type ChildProcess } from 'node:child_process' +import { fileListingCancellationError } from '../shared/file-listing-cancellation' import { buildRgArgsForQuickOpen, normalizeQuickOpenRgLine, @@ -27,8 +28,13 @@ export const LIST_FILES_TIMEOUT_MS = 25_000 export function listFilesWithRg( rootPath: string, - excludePathPrefixes: readonly string[] = [] + excludePathPrefixes: readonly string[] = [], + options: { signal?: AbortSignal } = {} ): Promise { + const { signal } = options + if (signal?.aborted) { + return Promise.reject(fileListingCancellationError(signal)) + } return new Promise((resolve, reject) => { const files = new Set() let done = false @@ -177,7 +183,7 @@ export function listFilesWithRg( child.once('close', handleClose) }) - const killSurvivors = (): void => { + const killSurvivors = (reason: string): void => { // Why: when one pass rejects, Promise.all surfaces the error immediately // but the sibling rg keeps running up to LIST_FILES_TIMEOUT_MS. Kill it // so repeated Quick Open opens don't pile up orphan rg processes on the @@ -189,16 +195,30 @@ export function listFilesWithRg( if (entry.child.exitCode === null && entry.child.signalCode === null) { entry.child.kill() } - entry.reject(new Error('rg list canceled after sibling failure')) + entry.reject(new Error(reason)) } } + // Why: a cancelled scan (workspace switch, superseded request) must stop + // its rg children immediately instead of letting them walk the tree to + // completion and flood the relay with stdout it will only discard. + const onAbort = (): void => { + if (done) { + return + } + done = true + killSurvivors('rg list cancelled') + reject(fileListingCancellationError(signal)) + } + signal?.addEventListener('abort', onAbort, { once: true }) + Promise.all([runPass(primary), runPass(ignoredPass)]) .then(() => { if (done) { return } done = true + signal?.removeEventListener('abort', onAbort) resolve(Array.from(files)) }) .catch((err) => { @@ -206,7 +226,8 @@ export function listFilesWithRg( return } done = true - killSurvivors() + signal?.removeEventListener('abort', onAbort) + killSurvivors('rg list canceled after sibling failure') reject(err instanceof Error ? err : new Error(String(err))) }) }) diff --git a/src/relay/fs-handler-readdir-fallback.ts b/src/relay/fs-handler-readdir-fallback.ts index e49609996d1c..d7c9172183b3 100644 --- a/src/relay/fs-handler-readdir-fallback.ts +++ b/src/relay/fs-handler-readdir-fallback.ts @@ -23,10 +23,12 @@ import { */ export async function listFilesWithReaddir( rootPath: string, - excludePathPrefixes: readonly string[] = [] + excludePathPrefixes: readonly string[] = [], + options: { signal?: AbortSignal } = {} ): Promise { return listQuickOpenFilesWithReaddir(rootPath, { excludePathPrefixes, - budget: createQuickOpenReaddirBudget() + budget: createQuickOpenReaddirBudget(), + signal: options.signal }) } diff --git a/src/relay/fs-handler.ts b/src/relay/fs-handler.ts index c6564c51fbed..6074fad2e2b7 100644 --- a/src/relay/fs-handler.ts +++ b/src/relay/fs-handler.ts @@ -17,6 +17,11 @@ import { } from './fs-handler-utils' import { listFilesWithGit, searchWithGitGrep } from './fs-handler-git-fallback' import { listFilesWithReaddir } from './fs-handler-readdir-fallback' +import { ListFilesScanCoordinator } from './fs-list-files-scan-coordinator' +import { + isFileListingCancellation, + throwIfFileListingCancelled +} from '../shared/file-listing-cancellation' import { isQuickOpenReaddirBudgetError } from '../shared/quick-open-readdir-walk' import { buildExcludePathPrefixes } from '../shared/quick-open-filter' import { buildInstallRgMessage } from './fs-handler-install-rg' @@ -31,7 +36,7 @@ import { buildRelayCommandEnv } from './relay-command-env' import { assertNoClobberRenameDestinationAvailable } from '../shared/filesystem-rename-collision' import { WATCHER_IGNORE_DIRS, - buildParcelWatcherIgnoreOption + buildParcelWatcherIgnoreOptions } from '../main/ipc/filesystem-watcher-ignore' type WatchState = { @@ -82,6 +87,7 @@ export class FsHandler { private dispatcher: RelayDispatcher private watches = new Map() private streamRegistry = new RelayStreamRegistry() + private listFilesScans = new ListFilesScanCoordinator() constructor(dispatcher: RelayDispatcher, _context: RelayContext) { this.dispatcher = dispatcher @@ -114,7 +120,7 @@ export class FsHandler { this.dispatcher.onRequest('fs.copy', (p) => this.copy(p)) this.dispatcher.onRequest('fs.realpath', (p) => this.realpath(p)) this.dispatcher.onRequest('fs.search', (p) => this.search(p)) - this.dispatcher.onRequest('fs.listFiles', (p) => this.listFiles(p)) + this.dispatcher.onRequest('fs.listFiles', (p, c) => this.listFiles(p, c)) this.dispatcher.onRequest('fs.workspaceSpaceScan', (p, c) => this.workspaceSpaceScan(p, c)) this.dispatcher.onRequest('fs.watch', (p, context) => this.watch(p, context)) this.dispatcher.onNotification('fs.unwatch', (p, context) => this.unwatch(p, context)) @@ -331,16 +337,33 @@ export class FsHandler { }) } - private async listFiles(params: Record): Promise { + private listFiles(params: Record, context?: RequestContext): Promise { const rootPath = expandTilde(params.rootPath as string) // Why: the main-to-relay RPC adds excludePaths so nested linked worktrees // don't get double-scanned. The shared helper validates the shape and // normalizes into root-relative prefixes; malformed input yields [] so // the request still succeeds (older apps omit the field entirely). const excludePathPrefixes = buildExcludePathPrefixes(rootPath, params.excludePaths) + // Why #7721: full-tree scans are the relay's most expensive request; the + // coordinator caps them at one per client, coalescing duplicates and + // aborting a stale scan when the workspace changes or the host cancels. + return this.listFilesScans.run({ + clientId: context?.clientId ?? 0, + key: JSON.stringify([rootPath, excludePathPrefixes]), + signal: context?.signal, + start: (signal) => this.runListFilesScan(rootPath, excludePathPrefixes, signal) + }) + } + + private async runListFilesScan( + rootPath: string, + excludePathPrefixes: string[], + signal: AbortSignal + ): Promise { const rgAvailable = await checkRgAvailable() + throwIfFileListingCancelled(signal) if (rgAvailable) { - return listFilesWithRg(rootPath, excludePathPrefixes) + return listFilesWithRg(rootPath, excludePathPrefixes, { signal }) } // Why: git ls-files only works inside git repos. Use rev-parse to detect // git ancestry — unlike checking for a local .git entry, this works from @@ -361,7 +384,7 @@ export class FsHandler { // budget errors into install-rg guidance; genuine git failures keep // their own messages. try { - return await listFilesWithGit(rootPath, excludePathPrefixes) + return await listFilesWithGit(rootPath, excludePathPrefixes, { signal }) } catch (err) { if (isQuickOpenReaddirBudgetError(err)) { throw new Error(await buildInstallRgMessage(err)) @@ -375,8 +398,13 @@ export class FsHandler { // problem, so translate the opaque cap error into actionable guidance // the user can act on directly from the error toast. try { - return await listFilesWithReaddir(rootPath, excludePathPrefixes) + return await listFilesWithReaddir(rootPath, excludePathPrefixes, { signal }) } catch (err) { + // Why: a cancelled scan is not an rg-availability problem; wrapping it + // in install-rg guidance would surface bogus advice on the client. + if (isFileListingCancellation(err)) { + throw err + } throw new Error(await buildInstallRgMessage(err)) } } @@ -433,9 +461,9 @@ export class FsHandler { })) this.dispatcher.notify('fs.changed', { events: mapped }) }, - // Why: align remote-Linux watchers with the shared nested-glob exclusion - // so nested node_modules/.git don't exhaust inotify on large codebases. - { ignore: buildParcelWatcherIgnoreOption(WATCHER_IGNORE_DIRS) } + // Why: align remote watchers with the shared nested exclusion so + // generated trees neither exhaust inotify nor trigger slow glob regexes. + buildParcelWatcherIgnoreOptions(WATCHER_IGNORE_DIRS) ) watchState.unwatchFn = () => { void subscription.unsubscribe() diff --git a/src/relay/fs-list-files-cancel.integration.test.ts b/src/relay/fs-list-files-cancel.integration.test.ts new file mode 100644 index 000000000000..588ddb5fe519 --- /dev/null +++ b/src/relay/fs-list-files-cancel.integration.test.ts @@ -0,0 +1,209 @@ +/** + * End-to-end in-process regression tests for #7721: cancellable fs.listFiles. + * + * Wires the client-side SshChannelMultiplexer to the relay-side + * RelayDispatcher + FsHandler through an in-memory pipe (no SSH). The scan + * body is a controllable fake so the tests are deterministic: + * - aborting the client request sends rpc.cancel and stops the relay scan, + * - interactive fs.readDir is served while a scan is in flight, + * - a scan for a different workspace supersedes the previous one, + * - identical concurrent requests coalesce into one scan. + */ +import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest' +import { mkdtempSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import * as path from 'node:path' +import { tmpdir } from 'node:os' + +const { fakeListFiles } = vi.hoisted(() => { + type ScanRecord = { + rootPath: string + signal: AbortSignal | undefined + resolve: (files: string[]) => void + } + const scans: ScanRecord[] = [] + const fakeListFiles = Object.assign( + vi.fn( + ( + rootPath: string, + _excludes: readonly string[] = [], + options: { signal?: AbortSignal } = {} + ) => + new Promise((resolve, reject) => { + scans.push({ rootPath, signal: options.signal, resolve }) + options.signal?.addEventListener( + 'abort', + () => + // Mirror the real scanners: surface the abort reason (e.g. the + // "superseded" error) so the dispatcher reports it to the host. + reject( + options.signal?.reason instanceof Error + ? options.signal.reason + : new Error('File listing cancelled') + ), + { once: true } + ) + }) + ), + { scans } + ) + return { fakeListFiles } +}) + +vi.mock('./fs-handler-utils', async (importOriginal) => { + const original = (await importOriginal()) as Record + return { + ...original, + checkRgAvailable: () => Promise.resolve(true), + listFilesWithRg: fakeListFiles + } +}) + +import { + SshChannelMultiplexer, + type MultiplexerTransport +} from '../main/ssh/ssh-channel-multiplexer' +import { RelayDispatcher } from './dispatcher' +import { RelayContext } from './context' +import { FsHandler } from './fs-handler' +import { LIST_FILES_SUPERSEDED_MESSAGE } from './fs-list-files-scan-coordinator' + +async function flushPipe(): Promise { + // The in-memory pipe defers each hop with setImmediate; a few macrotask + // turns guarantee request/notification frames have crossed both directions. + for (let i = 0; i < 10; i++) { + await new Promise((resolve) => setImmediate(resolve)) + } +} + +describe('Integration: cancellable fs.listFiles (#7721)', () => { + let tmpDir: string + let mux: SshChannelMultiplexer + let dispatcher: RelayDispatcher + let fsHandler: FsHandler + + beforeEach(() => { + fakeListFiles.mockClear() + fakeListFiles.scans.length = 0 + tmpDir = mkdtempSync(path.join(tmpdir(), 'relay-listfiles-cancel-')) + + let relayFeedFn: (data: Buffer) => void + const clientDataCallbacks: ((data: Buffer) => void)[] = [] + const clientTransport: MultiplexerTransport = { + write: (data: Buffer) => { + setImmediate(() => relayFeedFn?.(data)) + }, + onData: (cb) => { + clientDataCallbacks.push(cb) + }, + onClose: () => {} + } + dispatcher = new RelayDispatcher((data: Buffer) => { + setImmediate(() => { + for (const cb of clientDataCallbacks) { + cb(data) + } + }) + }) + relayFeedFn = (data: Buffer) => dispatcher.feed(data) + fsHandler = new FsHandler(dispatcher, new RelayContext()) + mux = new SshChannelMultiplexer(clientTransport) + }) + + afterEach(async () => { + mux.dispose() + dispatcher.dispose() + fsHandler.dispose() + await rm(tmpDir, { recursive: true, force: true }) + }) + + it('serves fs.readDir while a full-tree scan is in flight', async () => { + writeFileSync(path.join(tmpDir, 'a.txt'), 'a') + + const scanPromise = mux.request('fs.listFiles', { rootPath: '/big/workspace' }) + await flushPipe() + expect(fakeListFiles.scans).toHaveLength(1) + + // The interactive request must complete while the scan is still pending. + const entries = (await mux.request('fs.readDir', { dirPath: tmpDir })) as { name: string }[] + expect(entries.map((e) => e.name)).toEqual(['a.txt']) + + fakeListFiles.scans[0].resolve(['src/index.ts']) + await expect(scanPromise).resolves.toEqual(['src/index.ts']) + }) + + it('client abort sends rpc.cancel and stops the relay-side scan', async () => { + const controller = new AbortController() + const scanPromise = mux.request( + 'fs.listFiles', + { rootPath: '/big/workspace' }, + { signal: controller.signal } + ) + await flushPipe() + expect(fakeListFiles.scans).toHaveLength(1) + expect(fakeListFiles.scans[0].signal?.aborted).toBe(false) + + controller.abort() + await expect(scanPromise).rejects.toThrow('was cancelled') + await flushPipe() + + // The rpc.cancel notification must have aborted the scan on the relay. + expect(fakeListFiles.scans[0].signal?.aborted).toBe(true) + }) + + it('a scan for a different workspace supersedes the previous scan', async () => { + const first = mux.request('fs.listFiles', { rootPath: '/workspace/a' }) + // Attach the rejection handler up front: the error response arrives on a + // macrotask inside flushPipe, before any later `await expect` could. + const firstOutcome = first.then( + () => null, + (err: Error) => err + ) + await flushPipe() + expect(fakeListFiles.scans).toHaveLength(1) + + const second = mux.request('fs.listFiles', { rootPath: '/workspace/b' }) + await flushPipe() + expect(fakeListFiles.scans).toHaveLength(2) + + // The stale scan is aborted and its request fails fast — it does not run + // to completion behind the new one and does not hit the 30s timeout. + expect(fakeListFiles.scans[0].signal?.aborted).toBe(true) + const firstError = await firstOutcome + expect(firstError?.message).toContain(LIST_FILES_SUPERSEDED_MESSAGE) + + fakeListFiles.scans[1].resolve(['b.ts']) + await expect(second).resolves.toEqual(['b.ts']) + }) + + it('identical concurrent requests coalesce into a single scan', async () => { + const first = mux.request('fs.listFiles', { rootPath: '/workspace/a' }) + const second = mux.request('fs.listFiles', { rootPath: '/workspace/a' }) + await flushPipe() + + expect(fakeListFiles.scans).toHaveLength(1) + fakeListFiles.scans[0].resolve(['shared.ts']) + await expect(first).resolves.toEqual(['shared.ts']) + await expect(second).resolves.toEqual(['shared.ts']) + }) + + it('cancelling one coalesced requester keeps the scan alive for the other', async () => { + const controller = new AbortController() + const first = mux.request( + 'fs.listFiles', + { rootPath: '/workspace/a' }, + { signal: controller.signal } + ) + const second = mux.request('fs.listFiles', { rootPath: '/workspace/a' }) + await flushPipe() + expect(fakeListFiles.scans).toHaveLength(1) + + controller.abort() + await expect(first).rejects.toThrow('was cancelled') + await flushPipe() + expect(fakeListFiles.scans[0].signal?.aborted).toBe(false) + + fakeListFiles.scans[0].resolve(['still.ts']) + await expect(second).resolves.toEqual(['still.ts']) + }) +}) diff --git a/src/relay/fs-list-files-scan-coordinator.test.ts b/src/relay/fs-list-files-scan-coordinator.test.ts new file mode 100644 index 000000000000..a142c120cdbc --- /dev/null +++ b/src/relay/fs-list-files-scan-coordinator.test.ts @@ -0,0 +1,222 @@ +import { describe, expect, it, vi } from 'vitest' +import { + LIST_FILES_SUPERSEDED_MESSAGE, + ListFilesScanCoordinator +} from './fs-list-files-scan-coordinator' +import { + FileListingCancelledError, + isFileListingCancellation +} from '../shared/file-listing-cancellation' + +type Deferred = { + promise: Promise + resolve: (files: string[]) => void + reject: (error: Error) => void +} + +function deferred(): Deferred { + let resolve!: (files: string[]) => void + let reject!: (error: Error) => void + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} + +/** Scan runner that resolves/rejects on demand and rejects when aborted. */ +function controllableScan(): { + start: (signal: AbortSignal) => Promise + starts: AbortSignal[] + finish: (files: string[]) => void +} { + const starts: AbortSignal[] = [] + let current: Deferred | null = null + return { + starts, + start: (signal: AbortSignal) => { + starts.push(signal) + const scan = deferred() + current = scan + signal.addEventListener( + 'abort', + () => { + scan.reject( + signal.reason instanceof Error ? signal.reason : new FileListingCancelledError() + ) + }, + { once: true } + ) + return scan.promise + }, + finish: (files: string[]) => current?.resolve(files) + } +} + +describe('ListFilesScanCoordinator', () => { + it('coalesces same-key concurrent requests into one scan', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + + const first = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + const second = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + + expect(scan.starts).toHaveLength(1) + scan.finish(['x.ts']) + await expect(first).resolves.toEqual(['x.ts']) + await expect(second).resolves.toEqual(['x.ts']) + }) + + it('supersedes a different-key scan: aborts the old one and rejects it fast', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + + const first = coordinator.run({ clientId: 1, key: 'workspace-a', start: scan.start }) + const second = coordinator.run({ clientId: 1, key: 'workspace-b', start: scan.start }) + + expect(scan.starts).toHaveLength(2) + expect(scan.starts[0].aborted).toBe(true) + await expect(first).rejects.toThrow(LIST_FILES_SUPERSEDED_MESSAGE) + await first.catch((err) => expect(isFileListingCancellation(err)).toBe(true)) + + expect(scan.starts[1].aborted).toBe(false) + scan.finish(['b.ts']) + await expect(second).resolves.toEqual(['b.ts']) + }) + + it('keeps scans from different clients independent', async () => { + const coordinator = new ListFilesScanCoordinator() + const scanA = controllableScan() + const scanB = controllableScan() + + const first = coordinator.run({ clientId: 1, key: 'workspace-a', start: scanA.start }) + const second = coordinator.run({ clientId: 2, key: 'workspace-b', start: scanB.start }) + + expect(scanA.starts[0].aborted).toBe(false) + scanA.finish(['a.ts']) + scanB.finish(['b.ts']) + await expect(first).resolves.toEqual(['a.ts']) + await expect(second).resolves.toEqual(['b.ts']) + }) + + it('aborts the scan when its only requester cancels', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + const requester = new AbortController() + + const result = coordinator.run({ + clientId: 1, + key: 'a', + signal: requester.signal, + start: scan.start + }) + + requester.abort() + expect(scan.starts[0].aborted).toBe(true) + await expect(result).rejects.toSatisfy(isFileListingCancellation) + }) + + it('keeps a coalesced scan alive while another requester still waits', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + const first = new AbortController() + const second = new AbortController() + + const firstResult = coordinator.run({ + clientId: 1, + key: 'a', + signal: first.signal, + start: scan.start + }) + const secondResult = coordinator.run({ + clientId: 1, + key: 'a', + signal: second.signal, + start: scan.start + }) + + first.abort() + expect(scan.starts[0].aborted).toBe(false) + // The aborting requester observes its own cancellation immediately, + // while the shared scan keeps running for the sibling. + await expect(firstResult).rejects.toSatisfy(isFileListingCancellation) + + second.abort() + expect(scan.starts[0].aborted).toBe(true) + await expect(secondResult).rejects.toSatisfy(isFileListingCancellation) + }) + + it('rejects an aborted coalesced requester while the sibling still resolves', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + const first = new AbortController() + + const firstResult = coordinator.run({ + clientId: 1, + key: 'a', + signal: first.signal, + start: scan.start + }) + const secondResult = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + + first.abort() + scan.finish(['kept.ts']) + + await expect(firstResult).rejects.toSatisfy(isFileListingCancellation) + await expect(secondResult).resolves.toEqual(['kept.ts']) + }) + + it('rejects immediately when the requester is already cancelled', async () => { + const coordinator = new ListFilesScanCoordinator() + const start = vi.fn() + const requester = new AbortController() + requester.abort() + + await expect( + coordinator.run({ + clientId: 1, + key: 'a', + signal: requester.signal, + start: start as unknown as (signal: AbortSignal) => Promise + }) + ).rejects.toSatisfy(isFileListingCancellation) + expect(start).not.toHaveBeenCalled() + }) + + it('starts a fresh scan for the same key after the previous one settled', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + + const first = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + scan.finish(['old.ts']) + await expect(first).resolves.toEqual(['old.ts']) + + const second = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + expect(scan.starts).toHaveLength(2) + scan.finish(['new.ts']) + await expect(second).resolves.toEqual(['new.ts']) + }) + + it('does not join a scan that is already aborted; starts a replacement', async () => { + const coordinator = new ListFilesScanCoordinator() + const scan = controllableScan() + const requester = new AbortController() + + const first = coordinator.run({ + clientId: 1, + key: 'a', + signal: requester.signal, + start: scan.start + }) + requester.abort() + await expect(first).rejects.toSatisfy(isFileListingCancellation) + + // The aborted entry may still be in the map until its promise settles; + // a new same-key request must get a live scan, not the dead one. + const second = coordinator.run({ clientId: 1, key: 'a', start: scan.start }) + expect(scan.starts).toHaveLength(2) + expect(scan.starts[1].aborted).toBe(false) + scan.finish(['fresh.ts']) + await expect(second).resolves.toEqual(['fresh.ts']) + }) +}) diff --git a/src/relay/fs-list-files-scan-coordinator.ts b/src/relay/fs-list-files-scan-coordinator.ts new file mode 100644 index 000000000000..6e6e30c5f0df --- /dev/null +++ b/src/relay/fs-list-files-scan-coordinator.ts @@ -0,0 +1,104 @@ +/** + * Single-flight coordinator for fs.listFiles full-tree scans (#7721). + * + * Why: rapid workspace switching used to stack N concurrent full-tree scans + * on the single-threaded relay and its one SSH channel, starving small + * interactive fs.readDir/fs.stat requests past their 30s timeout. This + * coordinator guarantees at most one scan in flight per client: + * - a request for the same root/excludes joins the in-flight scan + * (Quick Open + file-explorer filter share one scan), + * - a request for a different root supersedes it — the old scan is aborted + * and its request fails fast instead of running to completion (this also + * protects against older Orca clients that never send rpc.cancel), + * - when every joined requester cancels (rpc.cancel / client detach), the + * scan is aborted so abandoned work stops immediately. + */ +import { + FileListingCancelledError, + fileListingCancellationError +} from '../shared/file-listing-cancellation' + +export const LIST_FILES_SUPERSEDED_MESSAGE = 'File listing superseded by a newer request' + +type ScanEntry = { + key: string + controller: AbortController + promise: Promise + attachedCount: number +} + +export class ListFilesScanCoordinator { + private readonly scansByClient = new Map() + + run(opts: { + clientId: number + key: string + signal?: AbortSignal + start: (signal: AbortSignal) => Promise + }): Promise { + const { clientId, key, signal, start } = opts + if (signal?.aborted) { + return Promise.reject(fileListingCancellationError(signal)) + } + + const existing = this.scansByClient.get(clientId) + if (existing && existing.key === key && !existing.controller.signal.aborted) { + return this.attach(existing, signal) + } + if (existing) { + existing.controller.abort(new FileListingCancelledError(LIST_FILES_SUPERSEDED_MESSAGE)) + } + + const controller = new AbortController() + const entry: ScanEntry = { + key, + controller, + promise: Promise.resolve([]), + attachedCount: 0 + } + this.scansByClient.set(clientId, entry) + entry.promise = start(controller.signal).finally(() => { + if (this.scansByClient.get(clientId) === entry) { + this.scansByClient.delete(clientId) + } + }) + return this.attach(entry, signal) + } + + private attach(entry: ScanEntry, signal?: AbortSignal): Promise { + entry.attachedCount++ + if (!signal) { + return entry.promise + } + // Why: an aborting requester must see its own cancellation even though + // the shared scan keeps running (and may later resolve) for coalesced + // siblings — so each attachment gets its own promise. + return new Promise((resolve, reject) => { + let settled = false + const settle = (complete: () => void): void => { + if (settled) { + return + } + settled = true + signal.removeEventListener('abort', onAbort) + complete() + } + const onAbort = (): void => + settle(() => { + entry.attachedCount-- + const cancellation = fileListingCancellationError(signal) + // Why: only stop the shared scan when nobody is left waiting on it — + // one requester cancelling must not break a coalesced sibling. + if (entry.attachedCount <= 0) { + entry.controller.abort(cancellation) + } + reject(cancellation) + }) + signal.addEventListener('abort', onAbort, { once: true }) + entry.promise.then( + (files) => settle(() => resolve(files)), + (error) => settle(() => reject(error)) + ) + }) + } +} diff --git a/src/relay/git-handler-branch-cleanup.test.ts b/src/relay/git-handler-branch-cleanup.test.ts index cf84b54d5919..8058d55ae29d 100644 --- a/src/relay/git-handler-branch-cleanup.test.ts +++ b/src/relay/git-handler-branch-cleanup.test.ts @@ -1,9 +1,17 @@ import { describe, expect, it, vi } from 'vitest' import * as path from 'node:path' +import { GitCapabilityCache } from '../shared/git-capability-cache' import type { GitExec } from './git-handler-ops' import { removeWorktreeOp } from './git-handler-worktree-ops' import { forceDeletePreservedRelayBranch } from './git-handler-branch-cleanup' +function removeWorktreeWithCapabilityCache( + git: GitExec, + params: Parameters[1] +) { + return removeWorktreeOp(git, params, new GitCapabilityCache()) +} + function worktreeList(...entries: { path: string; branch?: string }[]): string { return entries .map((entry, index) => @@ -192,7 +200,9 @@ describe('removeWorktreeOp branch cleanup', () => { return { stdout: '', stderr: '' } }) - await expect(removeWorktreeOp(git, { worktreePath: '/repo-feature' })).resolves.toEqual({}) + await expect( + removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature' }) + ).resolves.toEqual({}) expect(git).toHaveBeenCalledWith(['branch', '-d', '--', 'feature/test'], expect.any(String)) expect(git).toHaveBeenCalledWith( @@ -279,7 +289,9 @@ describe('removeWorktreeOp branch cleanup', () => { return { stdout: '', stderr: '' } }) - await expect(removeWorktreeOp(git, { worktreePath: '/repo-feature' })).resolves.toEqual({}) + await expect( + removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature' }) + ).resolves.toEqual({}) expect(git).toHaveBeenCalledWith( ['update-ref', '-d', 'refs/heads/feature/test', '1'], @@ -341,7 +353,9 @@ describe('removeWorktreeOp branch cleanup', () => { return { stdout: '', stderr: '' } }) - await expect(removeWorktreeOp(git, { worktreePath: '/repo-feature' })).resolves.toEqual({}) + await expect( + removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature' }) + ).resolves.toEqual({}) const commandIndex = (expectedArgs: string[]) => calls.findIndex(({ args }) => JSON.stringify(args) === JSON.stringify(expectedArgs)) @@ -404,7 +418,9 @@ describe('removeWorktreeOp branch cleanup', () => { return { stdout: '', stderr: '' } }) - await expect(removeWorktreeOp(git, { worktreePath: '/repo-feature' })).resolves.toEqual({ + await expect( + removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature' }) + ).resolves.toEqual({ preservedBranch: { branchName: 'feature/test', head: '1' } }) diff --git a/src/relay/git-handler-branch-cleanup.ts b/src/relay/git-handler-branch-cleanup.ts index 1454334db251..51aa0be521aa 100644 --- a/src/relay/git-handler-branch-cleanup.ts +++ b/src/relay/git-handler-branch-cleanup.ts @@ -3,6 +3,7 @@ import { getBranchCleanupTargetRefs, refreshBranchCleanupTargetRefs } from '../shared/git-branch-cleanup' +import type { GitCapabilityCache } from '../shared/git-capability-cache' import type { GitExec } from './git-handler-ops' import { parseWorktreeList } from './git-handler-utils' @@ -10,7 +11,8 @@ export async function deleteAlreadyMergedRelayBranchAfterSafeDeleteFailure( git: GitExec, repoPath: string, branchName: string, - branchHead: string + branchHead: string, + capabilities: GitCapabilityCache ): Promise { const runGit = (args: string[], options?: { stdin?: string }) => options ? git(args, repoPath, options) : git(args, repoPath) @@ -19,7 +21,9 @@ export async function deleteAlreadyMergedRelayBranchAfterSafeDeleteFailure( // Why: SSH worktrees hit the same squash-merge shape as local worktrees. // Git's no-op merge proof lets us clean up only branches whose changes // already exist on the saved base ref. - if (!(await branchHasNoUnmergedChangesOnAnyTarget(runGit, branchName, targetRefs))) { + if ( + !(await branchHasNoUnmergedChangesOnAnyTarget(runGit, branchName, targetRefs, capabilities)) + ) { return false } await deleteRelayBranchAtExpectedHead(git, repoPath, branchName, branchHead) diff --git a/src/relay/git-handler-check-ignore.test.ts b/src/relay/git-handler-check-ignore.test.ts new file mode 100644 index 000000000000..678798bf7483 --- /dev/null +++ b/src/relay/git-handler-check-ignore.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it, vi } from 'vitest' +import type { GitExec } from './git-handler-ops' +import { checkIgnoredPathsOp } from './git-handler-check-ignore' +import { GIT_CHECK_IGNORE_TIMEOUT_MS } from '../shared/git-check-ignore-stdio' + +describe('checkIgnoredPathsOp', () => { + it('passes exact paths over one bounded NUL-delimited stdin invocation', async () => { + const git = vi.fn().mockResolvedValue({ + stdout: 'dist/bundle.js\0line\nbreak.txt\0', + stderr: '' + }) + + await expect( + checkIgnoredPathsOp(git, { + worktreePath: '/repo', + paths: ['dist/bundle.js', 'line\nbreak.txt', 'src/index.ts'] + }) + ).resolves.toEqual(['dist/bundle.js', 'line\nbreak.txt']) + + expect(git).toHaveBeenCalledWith( + ['-c', 'core.quotePath=false', 'check-ignore', '-z', '--stdin'], + '/repo', + { + stdin: 'dist/bundle.js\0line\nbreak.txt\0src/index.ts\0', + timeout: GIT_CHECK_IGNORE_TIMEOUT_MS + } + ) + }) + + it('treats git exit code 1 as no ignored paths', async () => { + const noMatches = Object.assign(new Error('no ignored paths'), { + code: 1, + stdout: '' + }) + const git = vi.fn().mockRejectedValue(noMatches) + + await expect( + checkIgnoredPathsOp(git, { + worktreePath: '/repo', + paths: ['src/index.ts'] + }) + ).resolves.toEqual([]) + }) +}) diff --git a/src/relay/git-handler-check-ignore.ts b/src/relay/git-handler-check-ignore.ts new file mode 100644 index 000000000000..e458aba7af6d --- /dev/null +++ b/src/relay/git-handler-check-ignore.ts @@ -0,0 +1,35 @@ +import type { GitExec } from './git-handler-ops' +import { + encodeGitCheckIgnorePaths, + GIT_CHECK_IGNORE_STDIN_ARGS, + GIT_CHECK_IGNORE_TIMEOUT_MS, + parseGitCheckIgnorePaths, + splitGitCheckIgnorePathsByStdinBytes +} from '../shared/git-check-ignore-stdio' + +export async function checkIgnoredPathsOp( + git: GitExec, + params: Record +): Promise { + const worktreePath = params.worktreePath as string + const paths = Array.isArray(params.paths) + ? params.paths.filter((path): path is string => typeof path === 'string' && path.length > 0) + : [] + const ignored: string[] = [] + for (const chunk of splitGitCheckIgnorePathsByStdinBytes(paths)) { + try { + const { stdout } = await git([...GIT_CHECK_IGNORE_STDIN_ARGS], worktreePath, { + stdin: encodeGitCheckIgnorePaths(chunk), + timeout: GIT_CHECK_IGNORE_TIMEOUT_MS + }) + ignored.push(...parseGitCheckIgnorePaths(stdout)) + } catch (error) { + const gitError = error as Error & { code?: number | string; stdout?: string } + if (gitError.code !== 1) { + throw error + } + ignored.push(...parseGitCheckIgnorePaths(gitError.stdout ?? '')) + } + } + return ignored +} diff --git a/src/relay/git-handler-local-base-ref-refresh.ts b/src/relay/git-handler-local-base-ref-refresh.ts index 2ff1967a7d3f..299780799f0b 100644 --- a/src/relay/git-handler-local-base-ref-refresh.ts +++ b/src/relay/git-handler-local-base-ref-refresh.ts @@ -1,9 +1,11 @@ import type { GitExec } from './git-handler-ops' import { areRelayWorktreePathsEqual, readRelayWorktreeList } from './git-handler-worktree-ops' +import type { GitCapabilityCache } from '../shared/git-capability-cache' export async function refreshLocalBaseRefForWorktreeCreateOp( git: GitExec, - params: Record + params: Record, + capabilities: GitCapabilityCache ): Promise { const repoPath = params.repoPath as string const fullRef = params.fullRef as string @@ -42,7 +44,7 @@ export async function refreshLocalBaseRefForWorktreeCreateOp( throw new Error('Local base ref is not a fast-forward update.') } - const worktrees = await readRelayWorktreeList(git, repoPath) + const worktrees = await readRelayWorktreeList(git, repoPath, capabilities) const ownerWorktree = worktrees.find((worktree) => worktree.branch === fullRef) if (ownerWorktree) { if (ownerWorktreePath && !areRelayWorktreePathsEqual(ownerWorktree.path, ownerWorktreePath)) { diff --git a/src/relay/git-handler-ops.ts b/src/relay/git-handler-ops.ts index 1ff93a4a23ac..0bb862fbcea2 100644 --- a/src/relay/git-handler-ops.ts +++ b/src/relay/git-handler-ops.ts @@ -16,7 +16,7 @@ import { readWorkingDiffFile } from './git-working-file-read' export type GitExec = ( args: string[], cwd: string, - opts?: { maxBuffer?: number; disableOptionalLocks?: boolean; stdin?: string } + opts?: { maxBuffer?: number; disableOptionalLocks?: boolean; stdin?: string; timeout?: number } ) => Promise<{ stdout: string; stderr: string }> export type GitBufferExec = (args: string[], cwd: string) => Promise diff --git a/src/relay/git-handler-status-ops.ts b/src/relay/git-handler-status-ops.ts index 34e96b906adb..4f48ec9b6da4 100644 --- a/src/relay/git-handler-status-ops.ts +++ b/src/relay/git-handler-status-ops.ts @@ -249,34 +249,3 @@ function shouldProbeEffectiveUpstreamStatus( const parsed = splitRemoteBranchName(upstreamName) return parsed?.remoteName === 'origin' && parsed.branchName !== branchName } - -function parseCheckIgnoreOutput(stdout: string): string[] { - return stdout.split(/\r?\n/).filter(Boolean) -} - -export async function checkIgnoredPathsOp( - git: GitExec, - params: Record -): Promise { - const worktreePath = params.worktreePath as string - const paths = Array.isArray(params.paths) - ? params.paths.filter((path): path is string => typeof path === 'string' && path.length > 0) - : [] - if (paths.length === 0) { - return [] - } - - try { - const { stdout } = await git( - ['-c', 'core.quotePath=false', 'check-ignore', '--', ...paths], - worktreePath - ) - return parseCheckIgnoreOutput(stdout) - } catch (error) { - const gitError = error as Error & { code?: number | string; stdout?: string } - if (gitError.code === 1) { - return parseCheckIgnoreOutput(gitError.stdout ?? '') - } - throw error - } -} diff --git a/src/relay/git-handler-utils.test.ts b/src/relay/git-handler-utils.test.ts index 03d0fe14aedd..211e4b205f44 100644 --- a/src/relay/git-handler-utils.test.ts +++ b/src/relay/git-handler-utils.test.ts @@ -1,6 +1,49 @@ import { describe, expect, it } from 'vitest' import { parseStatusOutput } from './git-status-output-parser' -import { isUnsupportedWorktreeListZError } from './git-handler-utils' +import { isUnsupportedWorktreeListZError, parseWorktreeList } from './git-handler-utils' + +describe('parseWorktreeList', () => { + it('preserves SSH worktree lock metadata from porcelain output', () => { + expect( + parseWorktreeList( + 'worktree /repo\nHEAD abc\nbranch refs/heads/main\n\nworktree /locked\nHEAD def\nbranch refs/heads/feature\nlocked remote session\n' + )[1] + ).toMatchObject({ + path: '/locked', + locked: true, + lockReason: 'remote session' + }) + }) + + it('decodes C-quoted lock reasons from legacy line porcelain output', () => { + const output = + 'worktree /repo\nHEAD abc\nbranch refs/heads/main\n\nworktree /locked\nHEAD def\nbranch refs/heads/feature\nlocked "first line\\nsecond line \\303\\251"\n' + + expect(parseWorktreeList(output)[1]).toMatchObject({ + locked: true, + lockReason: 'first line\nsecond line é' + }) + }) + + it('keeps NUL-delimited lock reasons raw', () => { + const output = [ + 'worktree /repo', + 'HEAD abc', + 'branch refs/heads/main', + '', + 'worktree /locked', + 'HEAD def', + 'branch refs/heads/feature', + 'locked "literal\\nquote"', + '' + ].join('\0') + + expect(parseWorktreeList(output, { nulDelimited: true })[1]).toMatchObject({ + locked: true, + lockReason: '"literal\\nquote"' + }) + }) +}) describe('isUnsupportedWorktreeListZError', () => { it('detects an unknown-switch usage error from stderr when the exit code is absent', () => { diff --git a/src/relay/git-handler-utils.ts b/src/relay/git-handler-utils.ts index f0a395da27ba..6fbb8ec4a7df 100644 --- a/src/relay/git-handler-utils.ts +++ b/src/relay/git-handler-utils.ts @@ -7,8 +7,10 @@ */ import { existsSync } from 'node:fs' import * as path from 'node:path' +import { decodeGitCQuotedPath } from '../shared/git-cquoted-path' import { isBinaryBuffer } from '../shared/binary-buffer' import type { GitLineStats } from '../shared/git-uncommitted-line-stats' +export { isUnsupportedWorktreeListZError } from '../shared/git-worktree-command-capabilities' export function parseBranchStatusChar(char: string): string { switch (char) { @@ -133,36 +135,6 @@ export function parseBranchDiff( // ─── Worktree parsing ──────────────────────────────────────────────── -function getErrorText(error: unknown): string { - if (typeof error === 'object' && error !== null) { - const parts: string[] = [] - if ('message' in error && typeof error.message === 'string') { - parts.push(error.message) - } - if ('stderr' in error && typeof error.stderr === 'string') { - parts.push(error.stderr) - } - return parts.join('\n') - } - return String(error) -} - -function getErrorCode(error: unknown): string | undefined { - return typeof error === 'object' && error !== null && 'code' in error - ? String((error as { code?: unknown }).code) - : undefined -} - -export function isUnsupportedWorktreeListZError(error: unknown): boolean { - // `-z` is this command's only flag older Git (<2.36) lacks, so its usage exit - // 129 signals the rejection in any locale; key for SSH remotes on old Git. - if (getErrorCode(error) === '129') { - return true - } - - return /(?:unknown|invalid|unrecognized) (?:switch|option).*`?-?z'?/i.test(getErrorText(error)) -} - export function parseWorktreeList( output: string, options: { nulDelimited?: boolean } = {} @@ -178,6 +150,8 @@ export function parseWorktreeList( let head = '' let branch = '' let isBare = false + let locked = false + let lockReason = '' for (const line of lines) { if (line.startsWith('worktree ')) { @@ -188,6 +162,10 @@ export function parseWorktreeList( branch = line.slice('branch '.length) } else if (line === 'bare') { isBare = true + } else if (line === 'locked' || line.startsWith('locked ')) { + locked = true + const rawReason = line.slice('locked'.length).trim() + lockReason = options.nulDelimited ? rawReason : decodeGitCQuotedPath(rawReason) } } @@ -197,6 +175,8 @@ export function parseWorktreeList( head, branch, isBare, + ...(locked ? { locked: true } : {}), + ...(lockReason ? { lockReason } : {}), isMainWorktree: worktrees.length === 0 }) } diff --git a/src/relay/git-handler-worktree-git-capabilities.test.ts b/src/relay/git-handler-worktree-git-capabilities.test.ts new file mode 100644 index 000000000000..6d58a9993935 --- /dev/null +++ b/src/relay/git-handler-worktree-git-capabilities.test.ts @@ -0,0 +1,115 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { RelayContext } from './context' +import { GitHandler } from './git-handler' +import { + createMockDispatcher, + type MockDispatcher, + type RelayDispatcher +} from './git-handler-test-setup' + +type GitSpyTarget = { + git(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> +} + +const WORKTREE_LIST_OUTPUT = `worktree /repo +HEAD abc123 +branch refs/heads/main +` + +describe('relay worktree Git capabilities', () => { + let dispatcher: MockDispatcher + let handler: GitHandler + + beforeEach(() => { + dispatcher = createMockDispatcher() + handler = new GitHandler(dispatcher as unknown as RelayDispatcher, new RelayContext()) + }) + + it('does not repeat a known-unsupported -z probe on later scans', async () => { + const gitSpy = vi + .spyOn(handler as unknown as GitSpyTarget, 'git') + .mockImplementation((args: string[]) => { + if (args.includes('-z')) { + return Promise.reject( + Object.assign(new Error('git usage error'), { + code: 129, + stderr: 'usage: git worktree list []\n' + }) + ) + } + return Promise.resolve({ stdout: WORKTREE_LIST_OUTPUT, stderr: '' }) + }) + + await dispatcher.callRequest('git.listWorktrees', { repoPath: '/repo' }) + await dispatcher.callRequest('git.listWorktrees', { repoPath: '/repo' }) + + expect(gitSpy.mock.calls.map(([args]) => args)).toEqual([ + ['worktree', 'list', '--porcelain', '-z'], + ['worktree', 'list', '--porcelain'], + ['worktree', 'list', '--porcelain'] + ]) + }) + + it('re-probes after a relay handler is replaced', async () => { + const mockOldGit = (target: GitHandler) => + vi.spyOn(target as unknown as GitSpyTarget, 'git').mockImplementation((args: string[]) => { + if (args.includes('-z')) { + return Promise.reject( + Object.assign(new Error('git usage error'), { + code: 129, + stderr: 'usage: git worktree list []\n' + }) + ) + } + return Promise.resolve({ stdout: WORKTREE_LIST_OUTPUT, stderr: '' }) + }) + const firstGit = mockOldGit(handler) + const replacementDispatcher = createMockDispatcher() + const replacementHandler = new GitHandler( + replacementDispatcher as unknown as RelayDispatcher, + new RelayContext() + ) + const replacementGit = mockOldGit(replacementHandler) + + await dispatcher.callRequest('git.listWorktrees', { repoPath: '/repo' }) + await dispatcher.callRequest('git.listWorktrees', { repoPath: '/repo' }) + await replacementDispatcher.callRequest('git.listWorktrees', { repoPath: '/repo' }) + + expect(firstGit.mock.calls.filter(([args]) => args.includes('-z'))).toHaveLength(1) + expect(replacementGit.mock.calls.filter(([args]) => args.includes('-z'))).toHaveLength(1) + }) + + it('does not repeat a known-unsupported rev-parse --path-format probe', async () => { + const gitSpy = vi + .spyOn(handler as unknown as GitSpyTarget, 'git') + .mockImplementation((args: string[]) => { + if (args[0] === 'worktree') { + return Promise.resolve({ + stdout: 'worktree /git-store/project.git\nHEAD abc123\nbranch refs/heads/main\n', + stderr: '' + }) + } + if (args.includes('--path-format=absolute')) { + return Promise.reject( + Object.assign(new Error('unknown option: --path-format=absolute'), { + stderr: 'error: unknown option `path-format=absolute`\n' + }) + ) + } + return Promise.resolve({ + stdout: '/repo\n/git-store/project.git\n', + stderr: '' + }) + }) + + await dispatcher.callRequest('git.listWorktrees', { repoPath: '/repo' }) + await dispatcher.callRequest('git.listWorktrees', { repoPath: '/repo' }) + + const revParseCalls = gitSpy.mock.calls.filter(([args]) => args[0] === 'rev-parse') + expect(revParseCalls.map(([args]) => args)).toEqual([ + ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'], + ['rev-parse', '--show-toplevel', '--git-common-dir'], + ['rev-parse', '--show-toplevel', '--git-common-dir'] + ]) + }) +}) diff --git a/src/relay/git-handler-worktree-list.ts b/src/relay/git-handler-worktree-list.ts new file mode 100644 index 000000000000..72bec899ad3b --- /dev/null +++ b/src/relay/git-handler-worktree-list.ts @@ -0,0 +1,43 @@ +import type { GitCapabilityCache } from '../shared/git-capability-cache' +import type { GitExec } from './git-handler-ops' +import { isUnsupportedWorktreeListZError, parseWorktreeList } from './git-handler-utils' + +export type RelayWorktreeInfo = { + path: string + branch?: string + head?: string + locked?: boolean + lockReason?: string +} + +export async function readRelayWorktreeList( + git: GitExec, + repoPath: string, + capabilities: GitCapabilityCache +): Promise { + return capabilities.runWithFallback( + 'worktree-list-z', + async () => { + const { stdout } = await git(['worktree', 'list', '--porcelain', '-z'], repoPath) + return normalizeRelayWorktrees(parseWorktreeList(stdout, { nulDelimited: true })) + }, + async () => { + // Why: `-z` preserves newlines; fallback keeps Git <2.36 compatible. + const { stdout } = await git(['worktree', 'list', '--porcelain'], repoPath) + return normalizeRelayWorktrees(parseWorktreeList(stdout)) + }, + isUnsupportedWorktreeListZError + ) +} + +function normalizeRelayWorktrees(worktrees: Record[]): RelayWorktreeInfo[] { + return worktrees + .map((worktree) => ({ + path: typeof worktree.path === 'string' ? worktree.path : '', + head: typeof worktree.head === 'string' ? worktree.head : undefined, + branch: typeof worktree.branch === 'string' ? worktree.branch : undefined, + locked: worktree.locked === true ? true : undefined, + lockReason: typeof worktree.lockReason === 'string' ? worktree.lockReason : undefined + })) + .filter((worktree) => worktree.path.length > 0) +} diff --git a/src/relay/git-handler-worktree-ops.test.ts b/src/relay/git-handler-worktree-ops.test.ts index 52cc1236054b..ed252df6a467 100644 --- a/src/relay/git-handler-worktree-ops.test.ts +++ b/src/relay/git-handler-worktree-ops.test.ts @@ -1,8 +1,16 @@ import { describe, expect, it, vi } from 'vitest' import * as path from 'node:path' +import { GitCapabilityCache } from '../shared/git-capability-cache' import type { GitExec } from './git-handler-ops' import { addWorktreeOp, removeWorktreeOp } from './git-handler-worktree-ops' +function removeWorktreeWithCapabilityCache( + git: GitExec, + params: Parameters[1] +) { + return removeWorktreeOp(git, params, new GitCapabilityCache()) +} + function worktreeList(...entries: { path: string; branch?: string }[]): string { return entries .map((entry, index) => @@ -128,6 +136,32 @@ describe('addWorktreeOp', () => { }) describe('removeWorktreeOp', () => { + it('rejects a locked SSH worktree before invoking remove', async () => { + const git = vi.fn(async (args) => { + if (args[0] === 'rev-parse') { + return { stdout: '/repo/.git\n', stderr: '' } + } + if (args[0] === 'worktree' && args[1] === 'list') { + return { + stdout: `${worktreeList( + { path: '/repo', branch: 'main' }, + { path: '/repo-feature', branch: 'feature/test' } + )}\nlocked remote agent`, + stderr: '' + } + } + return { stdout: '', stderr: '' } + }) + + await expect( + removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature' }) + ).rejects.toThrow('Worktree is locked by Git. Lock reason: remote agent.') + expect(git).not.toHaveBeenCalledWith( + ['worktree', 'remove', '/repo-feature'], + expect.any(String) + ) + }) + it('deletes the now-unused branch after removing an SSH worktree', async () => { const calls: string[] = [] let listCount = 0 @@ -152,7 +186,7 @@ describe('removeWorktreeOp', () => { return { stdout: '', stderr: '' } }) - await removeWorktreeOp(git, { worktreePath: '/repo-feature' }) + await removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature' }) expect(calls).toEqual([ '/repo-feature$ rev-parse --git-common-dir', @@ -188,7 +222,9 @@ describe('removeWorktreeOp', () => { }) // The unmerged-branch refusal must be surfaced without failing workspace removal. - await expect(removeWorktreeOp(git, { worktreePath: '/repo-feature' })).resolves.toEqual({ + await expect( + removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature' }) + ).resolves.toEqual({ preservedBranch: { branchName: 'feature/test', head: '1' } }) @@ -218,16 +254,47 @@ describe('removeWorktreeOp', () => { return { stdout: '', stderr: '' } }) - await removeWorktreeOp(git, { + await removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature', force: true, forceBranchDelete: true }) + expect(git).toHaveBeenCalledWith( + ['worktree', 'remove', '--force', '/repo-feature'], + expect.any(String) + ) expect(git).toHaveBeenCalledWith(['branch', '-D', '--', 'feature/test'], expect.any(String)) expect(git).not.toHaveBeenCalledWith(['branch', '-d', '--', 'feature/test'], expect.any(String)) }) + it('does not let force override a locked SSH worktree', async () => { + const git = vi.fn(async (args) => { + if (args[0] === 'rev-parse') { + return { stdout: '/repo/.git\n', stderr: '' } + } + if (args[0] === 'worktree' && args[1] === 'list') { + return { + stdout: `${worktreeList( + { path: '/repo', branch: 'main' }, + { path: '/repo-feature', branch: 'feature/test' } + )}\nlocked remote agent`, + stderr: '' + } + } + return { stdout: '', stderr: '' } + }) + + await expect( + removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature', force: true }) + ).rejects.toThrow('Worktree is locked by Git. Lock reason: remote agent') + + expect(git).not.toHaveBeenCalledWith( + ['worktree', 'remove', '--force', '/repo-feature'], + expect.any(String) + ) + }) + it('skips branch deletion entirely when deleteBranch is false', async () => { const calls: string[] = [] const git = vi.fn(async (args, cwd) => { @@ -247,7 +314,10 @@ describe('removeWorktreeOp', () => { return { stdout: '', stderr: '' } }) - await removeWorktreeOp(git, { worktreePath: '/repo-feature', deleteBranch: false }) + await removeWorktreeWithCapabilityCache(git, { + worktreePath: '/repo-feature', + deleteBranch: false + }) expect(calls).toEqual([ '/repo-feature$ rev-parse --git-common-dir', @@ -286,7 +356,7 @@ describe('removeWorktreeOp', () => { return { stdout: '', stderr: '' } }) - await removeWorktreeOp(git, { worktreePath: '/repo-feature' }) + await removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature' }) expect(git).toHaveBeenCalledWith(['branch', '-d', '--', 'feature/test'], expect.any(String)) expect(git).toHaveBeenCalledWith(['worktree', 'prune'], expect.any(String)) diff --git a/src/relay/git-handler-worktree-ops.ts b/src/relay/git-handler-worktree-ops.ts index a1fc319446a1..487fabd76882 100644 --- a/src/relay/git-handler-worktree-ops.ts +++ b/src/relay/git-handler-worktree-ops.ts @@ -1,8 +1,8 @@ import * as path from 'node:path' import { resolveWorktreeAddBaseRef } from '../shared/worktree-base-ref' import type { GitExec } from './git-handler-ops' -import { isUnsupportedWorktreeListZError, parseWorktreeList } from './git-handler-utils' export { removeWorktreeOp } from './git-handler-worktree-remove' +export { readRelayWorktreeList } from './git-handler-worktree-list' async function persistRelayWorktreeCreationBase( git: GitExec, @@ -111,40 +111,6 @@ export async function addWorktreeOp(git: GitExec, params: Record { - try { - const { stdout } = await git(['worktree', 'list', '--porcelain', '-z'], repoPath) - return normalizeRelayWorktrees(parseWorktreeList(stdout, { nulDelimited: true })) - } catch (error) { - if (!isUnsupportedWorktreeListZError(error)) { - throw error - } - } - - // Why: `-z` preserves newlines; fallback keeps Git <2.36 compatible. - const { stdout } = await git(['worktree', 'list', '--porcelain'], repoPath) - return normalizeRelayWorktrees(parseWorktreeList(stdout)) -} - -function normalizeRelayWorktrees(worktrees: Record[]): RelayWorktreeInfo[] { - return worktrees - .map((worktree) => ({ - path: typeof worktree.path === 'string' ? worktree.path : '', - head: typeof worktree.head === 'string' ? worktree.head : undefined, - branch: typeof worktree.branch === 'string' ? worktree.branch : undefined - })) - .filter((worktree) => worktree.path.length > 0) -} - function isPosixAbsolutePath(value: string): boolean { return value.startsWith('/') } diff --git a/src/relay/git-handler-worktree-paths.test.ts b/src/relay/git-handler-worktree-paths.test.ts index 7bdb08265610..d5f7a7755cb3 100644 --- a/src/relay/git-handler-worktree-paths.test.ts +++ b/src/relay/git-handler-worktree-paths.test.ts @@ -1,8 +1,16 @@ import { describe, expect, it, vi } from 'vitest' import * as path from 'node:path' +import { GitCapabilityCache } from '../shared/git-capability-cache' import type { GitExec } from './git-handler-ops' import { removeWorktreeOp } from './git-handler-worktree-ops' +function removeWorktreeWithCapabilityCache( + git: GitExec, + params: Parameters[1] +) { + return removeWorktreeOp(git, params, new GitCapabilityCache()) +} + function lineWorktreeList(...entries: { path: string; branch?: string }[]): string { return entries .map((entry, index) => @@ -56,7 +64,7 @@ describe('relay worktree path parsing', () => { return { stdout: '', stderr: '' } }) - await removeWorktreeOp(git, { worktreePath }) + await removeWorktreeWithCapabilityCache(git, { worktreePath }) expect(git).toHaveBeenCalledWith(['branch', '-d', '--', 'feature/newline'], resolvedRepoPath()) }) @@ -90,7 +98,7 @@ describe('relay worktree path parsing', () => { return { stdout: '', stderr: '' } }) - await removeWorktreeOp(git, { worktreePath: '/repo-feature' }) + await removeWorktreeWithCapabilityCache(git, { worktreePath: '/repo-feature' }) expect(calls).toEqual([ '/repo-feature$ rev-parse --git-common-dir', diff --git a/src/relay/git-handler-worktree-remove.ts b/src/relay/git-handler-worktree-remove.ts index edd3932ef3bc..2c2ce54a8cca 100644 --- a/src/relay/git-handler-worktree-remove.ts +++ b/src/relay/git-handler-worktree-remove.ts @@ -1,14 +1,10 @@ import * as path from 'node:path' import type { RemoveWorktreeResult } from '../shared/types' +import { assertWorktreeUnlockedForRemoval } from '../shared/worktree-removal' import { deleteAlreadyMergedRelayBranchAfterSafeDeleteFailure } from './git-handler-branch-cleanup' import type { GitExec } from './git-handler-ops' -import { isUnsupportedWorktreeListZError, parseWorktreeList } from './git-handler-utils' - -type RelayWorktreeInfo = { - path: string - branch?: string - head?: string -} +import type { GitCapabilityCache } from '../shared/git-capability-cache' +import { readRelayWorktreeList } from './git-handler-worktree-list' function getErrorText(error: unknown): string { if (typeof error === 'object' && error !== null) { @@ -74,34 +70,13 @@ function areRelayWorktreePathsEqual(leftPath: string, rightPath: string): boolea return compareCaseInsensitive ? left.toLowerCase() === right.toLowerCase() : left === right } -function normalizeRelayWorktrees(worktrees: Record[]): RelayWorktreeInfo[] { - return worktrees - .map((worktree) => ({ - path: typeof worktree.path === 'string' ? worktree.path : '', - head: typeof worktree.head === 'string' ? worktree.head : undefined, - branch: typeof worktree.branch === 'string' ? worktree.branch : undefined - })) - .filter((worktree) => worktree.path.length > 0) -} - -async function readRelayWorktreeList(git: GitExec, repoPath: string): Promise { - try { - const { stdout } = await git(['worktree', 'list', '--porcelain', '-z'], repoPath) - return normalizeRelayWorktrees(parseWorktreeList(stdout, { nulDelimited: true })) - } catch (error) { - if (!isUnsupportedWorktreeListZError(error)) { - throw error - } - } - - // Why: `-z` preserves newlines; fallback keeps Git <2.36 compatible. - const { stdout } = await git(['worktree', 'list', '--porcelain'], repoPath) - return normalizeRelayWorktrees(parseWorktreeList(stdout)) -} - -async function listRelayWorktreesForRemoval(git: GitExec, repoPath: string) { +async function listRelayWorktreesForRemoval( + git: GitExec, + repoPath: string, + capabilities: GitCapabilityCache +) { try { - return await readRelayWorktreeList(git, repoPath) + return await readRelayWorktreeList(git, repoPath, capabilities) } catch { return [] } @@ -148,7 +123,8 @@ async function deleteRelayBranchAfterWorktreeRemoval( export async function removeWorktreeOp( git: GitExec, - params: Record + params: Record, + capabilities: GitCapabilityCache ): Promise { const worktreePath = params.worktreePath as string const force = params.force as boolean | undefined @@ -166,13 +142,15 @@ export async function removeWorktreeOp( // fall through with worktreePath as repo } - const worktreesBeforeRemoval = await listRelayWorktreesForRemoval(git, repoPath) + const worktreesBeforeRemoval = await listRelayWorktreesForRemoval(git, repoPath, capabilities) const removedWorktree = worktreesBeforeRemoval.find((worktree) => areRelayWorktreePathsEqual(worktree.path, worktreePath) ) const branchName = normalizeLocalBranchRef(removedWorktree?.branch ?? '') const branchHead = removedWorktree?.head ?? '' + assertWorktreeUnlockedForRemoval(removedWorktree) + const args = ['worktree', 'remove'] if (force) { args.push('--force') @@ -210,7 +188,8 @@ export async function removeWorktreeOp( git, repoPath, branchName, - branchHead + branchHead, + capabilities ) ) { return {} diff --git a/src/relay/git-handler.test.ts b/src/relay/git-handler.test.ts index 0847c2ae8e77..ba8f631d8157 100644 --- a/src/relay/git-handler.test.ts +++ b/src/relay/git-handler.test.ts @@ -24,7 +24,11 @@ type GitBufferSpyTarget = { } type GitSpyTarget = { - git(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> + git( + args: string[], + cwd: string, + opts?: { signal?: AbortSignal } + ): Promise<{ stdout: string; stderr: string }> } function deferredRelayBuffer(content: string): { @@ -1218,7 +1222,8 @@ describe('GitHandler', () => { worktreePath: tmpDir, remote: 'origin', branch: 'main', - ref: 'refs/remotes/origin/main' + ref: 'refs/remotes/origin/main', + skipAutoMaintenance: true }) const second = dispatcher.callRequest('git.diff', { @@ -1234,7 +1239,18 @@ describe('GitHandler', () => { expect(gitBufferSpy).toHaveBeenCalledTimes(2) expect(gitSpy).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main'], + [ + '-c', + 'maintenance.auto=false', + '-c', + 'maintenance.commit-graph.auto=0', + '-c', + 'gc.auto=0', + 'fetch', + '--no-tags', + 'origin', + '+refs/heads/main:refs/remotes/origin/main' + ], tmpDir ) }) @@ -1882,6 +1898,24 @@ describe('GitHandler', () => { expect(result[0].isMainWorktree).toBe(true) }) + it('passes request cancellation to the git worktree list subprocess', async () => { + const controller = new AbortController() + const gitSpy = vi + .spyOn(handler as unknown as GitSpyTarget, 'git') + .mockRejectedValue(new Error('aborted')) + + const result = await dispatcher.callRequest( + 'git.listWorktrees', + { repoPath: tmpDir }, + { isStale: () => false, signal: controller.signal } + ) + + expect(result).toEqual([]) + expect(gitSpy).toHaveBeenCalledWith(['worktree', 'list', '--porcelain', '-z'], tmpDir, { + signal: controller.signal + }) + }) + it.skipIf(process.platform === 'win32')( 'normalizes the main worktree path for a separate-git-dir repo', async () => { diff --git a/src/relay/git-handler.ts b/src/relay/git-handler.ts index 746dbffd803c..67e78821d9a7 100644 --- a/src/relay/git-handler.ts +++ b/src/relay/git-handler.ts @@ -39,7 +39,8 @@ import { } from './git-handler-worktree-ops' import { forceDeletePreservedRelayBranch } from './git-handler-branch-cleanup' import { refreshLocalBaseRefForWorktreeCreateOp } from './git-handler-local-base-ref-refresh' -import { checkIgnoredPathsOp, detectConflictOperation, getStatusOp } from './git-handler-status-ops' +import { detectConflictOperation, getStatusOp } from './git-handler-status-ops' +import { checkIgnoredPathsOp } from './git-handler-check-ignore' import { resolveRelayPushTarget } from './git-handler-push-target' import { isNoUpstreamError, normalizeGitErrorMessage } from '../shared/git-remote-error' import { upstreamOnlyCommitsArePatchEquivalent } from '../shared/git-upstream-status' @@ -52,7 +53,7 @@ import { resolveEffectiveGitUpstream } from '../shared/git-effective-upstream' import { loadGitHistoryFromExecutor } from '../shared/git-history' -import { buildRelayCommandEnv } from './relay-command-env' +import { buildRelayGitEnv } from './relay-command-env' import { removeSafeUntrackedDiscardTarget, removeSafeUntrackedDiscardTargets @@ -60,6 +61,15 @@ import { import { getGitCloneFailureMessage } from '../shared/git-clone-failure-message' import { syncForkDefaultBranch, validateGitForkSyncExpectedUpstream } from '../shared/git-fork-sync' import { InFlightPromiseDedupe, stableInFlightKey } from '../shared/in-flight-promise-dedupe' +import { GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS } from '../shared/git-fetch-auto-maintenance' +import { GitCapabilityCache } from '../shared/git-capability-cache' +import { + hasUnsupportedRevParsePathFormatEcho, + isUnsupportedRevParsePathFormatError +} from '../shared/git-worktree-command-capabilities' +import { GitResponseStreamRegistry } from './git-response-stream' +import { GIT_RESPONSE_STREAM_THRESHOLD } from './protocol' +import { endSubprocessStdin } from '../shared/subprocess-stdin-write' const execFileAsync = promisify(execFile) const MAX_GIT_BUFFER = 10 * 1024 * 1024 @@ -74,26 +84,6 @@ function resolveSubmoduleStatusArea( return 'unstaged' } -function getErrorText(error: unknown): string { - if (typeof error === 'object' && error !== null) { - const parts: string[] = [] - if ('message' in error && typeof error.message === 'string') { - parts.push(error.message) - } - if ('stderr' in error && typeof error.stderr === 'string') { - parts.push(error.stderr) - } - return parts.join('\n') - } - return String(error) -} - -function isUnsupportedRevParsePathFormatError(error: unknown): boolean { - return /(?:unknown|invalid|unrecognized).*(?:--path-format|path-format)/i.test( - getErrorText(error) - ) -} - function isWindowsAbsolutePath(value: string): boolean { return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith('\\\\') } @@ -163,13 +153,17 @@ function execFileWithStdin( finish(null, stdout, stderr) }) child.once('error', (error) => finish(error)) - child.stdin?.end(stdin) + endSubprocessStdin(child.stdin, stdin) }) } export class GitHandler { private dispatcher: RelayDispatcher private readonly gitDiffReadDedupe = new InFlightPromiseDedupe() + private readonly gitCapabilities = new GitCapabilityCache() + // Why: large diff/exec responses are chunked onto the bulk lane so they do + // not head-of-line-block interactive pty.data echo on the shared SSH channel. + private readonly responseStreams = new GitResponseStreamRegistry() // Why: configured submodule paths change rarely; an instance-level TTL cache // avoids re-reading `.gitmodules` on every diff click over SSH, and being @@ -181,6 +175,13 @@ export class GitHandler { constructor(dispatcher: RelayDispatcher, _context: RelayContext) { this.dispatcher = dispatcher this.registerHandlers() + // Why: a detached client's git.responseAck frames will never arrive; wake + // any pump parked on the ack window so it re-checks staleness and exits. + this.dispatcher.onClientDetached?.(() => this.responseStreams.wakeAll()) + } + + dispose(): void { + this.responseStreams.disposeAll() } private registerHandlers(): void { @@ -189,7 +190,7 @@ export class GitHandler { this.dispatcher.onRequest('git.checkIgnored', (p) => this.checkIgnored(p)) this.dispatcher.onRequest('git.history', (p) => this.history(p)) this.dispatcher.onRequest('git.commit', (p) => this.commit(p)) - this.dispatcher.onRequest('git.diff', (p) => this.getDiff(p)) + this.dispatcher.onRequest('git.diff', (p, context) => this.getDiff(p, context)) this.dispatcher.onRequest('git.stage', (p) => this.stage(p)) this.dispatcher.onRequest('git.unstage', (p) => this.unstage(p)) this.dispatcher.onRequest('git.bulkStage', (p) => this.bulkStage(p)) @@ -214,9 +215,9 @@ export class GitHandler { this.dispatcher.onRequest('git.pull', (p) => this.pull(p)) this.dispatcher.onRequest('git.fastForward', (p) => this.fastForward(p)) this.dispatcher.onRequest('git.rebaseFromBase', (p) => this.rebaseFromBase(p)) - this.dispatcher.onRequest('git.branchDiff', (p) => this.branchDiff(p)) - this.dispatcher.onRequest('git.commitDiff', (p) => this.commitDiff(p)) - this.dispatcher.onRequest('git.listWorktrees', (p) => this.listWorktrees(p)) + this.dispatcher.onRequest('git.branchDiff', (p, context) => this.branchDiff(p, context)) + this.dispatcher.onRequest('git.commitDiff', (p, context) => this.commitDiff(p, context)) + this.dispatcher.onRequest('git.listWorktrees', (p, context) => this.listWorktrees(p, context)) this.dispatcher.onRequest('git.addWorktree', (p) => this.addWorktree(p)) this.dispatcher.onRequest('git.removeWorktree', (p) => this.removeWorktree(p)) this.dispatcher.onRequest('git.worktreeIsClean', (p) => this.worktreeIsClean(p)) @@ -230,6 +231,45 @@ export class GitHandler { this.dispatcher.onRequest('git.exec', (p, context) => this.exec(p, context)) this.dispatcher.onRequest('git.clone', (p, context) => this.clone(p, context)) this.dispatcher.onRequest('git.isGitRepo', (p) => this.isGitRepo(p)) + this.dispatcher.onNotification('git.responseAck', (p, context) => this.responseAck(p, context)) + this.dispatcher.onNotification('git.cancelResponseStream', (p, context) => + this.cancelResponseStream(p, context) + ) + } + + private responseAck(params: Record, context: RequestContext): void { + const streamId = params.streamId + const seq = params.seq + if (typeof streamId === 'number' && typeof seq === 'number') { + this.responseStreams.recordAck(streamId, seq, context.clientId) + } + } + + private cancelResponseStream(params: Record, context: RequestContext): void { + const streamId = params.streamId + if (typeof streamId === 'number') { + this.responseStreams.abort(streamId, context.clientId) + } + } + + // Why: when the client opted into response streaming and the serialized result + // exceeds the threshold, chunk it onto the bulk lane and return a small + // sentinel as the RPC result. Old clients omit the flag (single-frame, as + // today); old relays never call this, so a new client falls back to the plain + // result they return. + private maybeStreamResponse( + result: unknown, + params: Record, + context: RequestContext | undefined + ): unknown { + if (params.__streamResponse !== true || !context) { + return result + } + const payload = Buffer.from(JSON.stringify(result ?? null), 'utf-8') + if (payload.length <= GIT_RESPONSE_STREAM_THRESHOLD) { + return result + } + return this.responseStreams.startStream(payload, this.dispatcher, context) } private async runWithDiffDedupeClear(run: () => Promise): Promise { @@ -252,9 +292,10 @@ export class GitHandler { signal?: AbortSignal nonInteractive?: boolean stdin?: string + timeout?: number } ): Promise<{ stdout: string; stderr: string }> { - const env = buildRelayCommandEnv() + const env = buildRelayGitEnv() if (opts?.disableOptionalLocks) { env.GIT_OPTIONAL_LOCKS = '0' } @@ -269,6 +310,7 @@ export class GitHandler { env, encoding: 'utf-8', maxBuffer: opts?.maxBuffer ?? MAX_GIT_BUFFER, + timeout: opts?.timeout, signal: opts?.signal } satisfies ExecFileOptions if (opts?.stdin !== undefined) { @@ -281,7 +323,7 @@ export class GitHandler { private async gitBuffer(args: string[], cwd: string): Promise { const { stdout } = (await execFileAsync('git', args, { cwd, - env: buildRelayCommandEnv(), + env: buildRelayGitEnv(), encoding: 'buffer', maxBuffer: MAX_GIT_BUFFER })) as { stdout: Buffer } @@ -351,7 +393,7 @@ export class GitHandler { }) } - private async getDiff(params: Record) { + private async getDiff(params: Record, context?: RequestContext) { const worktreePath = params.worktreePath as string const filePath = params.filePath as string // Why: filePath is relative to worktreePath and used in readWorkingFile via @@ -365,7 +407,7 @@ export class GitHandler { const compareAgainstHead = params.compareAgainstHead as boolean | undefined // Why: register the in-flight dedupe synchronously (before any await) so // concurrent identical reads coalesce; submodule routing happens inside. - return this.gitDiffReadDedupe.run( + const result = await this.gitDiffReadDedupe.run( stableInFlightKey(['diff', worktreePath, filePath, staged, compareAgainstHead]), async () => { // Why: gitlink paths can't be read as blobs and submodule working dirs @@ -430,6 +472,7 @@ export class GitHandler { ) } ) + return this.maybeStreamResponse(result, params, context) } private async stage(params: Record) { @@ -844,10 +887,14 @@ export class GitHandler { const remote = params.remote const branch = params.branch const ref = params.ref + const skipAutoMaintenance = params.skipAutoMaintenance try { if (typeof remote !== 'string' || typeof branch !== 'string' || typeof ref !== 'string') { throw new Error('Invalid remote-tracking fetch request.') } + if (skipAutoMaintenance !== undefined && typeof skipAutoMaintenance !== 'boolean') { + throw new Error('Invalid remote-tracking fetch maintenance option.') + } if (remote.startsWith('-') || branch.startsWith('-')) { throw new Error('Remote-tracking fetch inputs must not start with "-".') } @@ -866,7 +913,16 @@ export class GitHandler { } await this.git(['check-ref-format', `refs/heads/${branch}`], worktreePath) await this.git(['check-ref-format', ref], worktreePath) - await this.git(['fetch', '--no-tags', remote, `+refs/heads/${branch}:${ref}`], worktreePath) + await this.git( + [ + ...(skipAutoMaintenance ? GIT_FETCH_SKIP_AUTO_MAINTENANCE_CONFIG_ARGS : []), + 'fetch', + '--no-tags', + remote, + `+refs/heads/${branch}:${ref}` + ], + worktreePath + ) } catch (error) { // Why: create-worktree needs a write-capable fetch, but generic git.exec // intentionally rejects fetch. This narrow RPC keeps the relay allowlist @@ -1013,7 +1069,7 @@ export class GitHandler { } } - private async branchDiff(params: Record) { + private async branchDiff(params: Record, context?: RequestContext) { const worktreePath = params.worktreePath as string const baseRef = params.baseRef as string if (baseRef.startsWith('-')) { @@ -1024,7 +1080,7 @@ export class GitHandler { filePath: params.filePath as string | undefined, oldPath: params.oldPath as string | undefined } - return this.gitDiffReadDedupe.run( + const result = await this.gitDiffReadDedupe.run( stableInFlightKey([ 'branchDiff', worktreePath, @@ -1042,9 +1098,10 @@ export class GitHandler { options ) ) + return this.maybeStreamResponse(result, params, context) } - private async commitDiff(params: Record) { + private async commitDiff(params: Record, context?: RequestContext) { const worktreePath = params.worktreePath as string const args = { commitOid: params.commitOid as string, @@ -1052,7 +1109,7 @@ export class GitHandler { filePath: params.filePath as string, oldPath: params.oldPath as string | undefined } - return this.gitDiffReadDedupe.run( + const result = await this.gitDiffReadDedupe.run( stableInFlightKey([ 'commitDiff', worktreePath, @@ -1063,6 +1120,7 @@ export class GitHandler { ]), () => commitDiffEntry(this.gitBuffer.bind(this), worktreePath, args) ) + return this.maybeStreamResponse(result, params, context) } private async exec(params: Record, context?: RequestContext) { @@ -1071,7 +1129,7 @@ export class GitHandler { validateGitExecArgs(args) const { stdout, stderr } = await this.git(args, cwd, { signal: context?.signal }) - return { stdout, stderr } + return this.maybeStreamResponse({ stdout, stderr }, params, context) } private async clone(params: Record, context?: RequestContext) { @@ -1097,7 +1155,7 @@ export class GitHandler { return await new Promise((resolve, reject) => { const child = spawn('git', args, { cwd: expandTilde(cwd), - env: buildRelayCommandEnv(), + env: buildRelayGitEnv(), stdio: ['ignore', 'pipe', 'pipe'] }) let stdout = '' @@ -1209,23 +1267,29 @@ export class GitHandler { private async readRepoLocation(repoPath: string): Promise { try { - const { stdout } = await this.git( - ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'], - repoPath - ) - return parseRelayRepoLocation(repoPath, stdout) - } catch (error) { - if (!isUnsupportedRevParsePathFormatError(error)) { - return undefined - } - } - - try { - const { stdout } = await this.git( - ['rev-parse', '--show-toplevel', '--git-common-dir'], - repoPath + return await this.gitCapabilities.runWithFallback( + 'rev-parse-path-format', + async () => { + const { stdout } = await this.git( + ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'], + repoPath + ) + if (hasUnsupportedRevParsePathFormatEcho(stdout)) { + // Why: some old Git versions echo the unknown option and exit zero; + // remember that signal even though the trailing paths remain usable. + this.gitCapabilities.rememberUnsupported('rev-parse-path-format') + } + return parseRelayRepoLocation(repoPath, stdout) + }, + async () => { + const { stdout } = await this.git( + ['rev-parse', '--show-toplevel', '--git-common-dir'], + repoPath + ) + return parseRelayRepoLocation(repoPath, stdout) + }, + isUnsupportedRevParsePathFormatError ) - return parseRelayRepoLocation(repoPath, stdout) } catch { return undefined } @@ -1263,28 +1327,35 @@ export class GitHandler { return normalized } - private async listWorktrees(params: Record) { + private async listWorktrees(params: Record, context?: RequestContext) { const repoPath = params.repoPath as string - try { - const { stdout } = await this.git(['worktree', 'list', '--porcelain', '-z'], repoPath) - return this.normalizeMainWorktreePath( - repoPath, - parseWorktreeList(stdout, { nulDelimited: true }) + return this.gitCapabilities + .runWithFallback( + 'worktree-list-z', + async () => { + const { stdout } = await this.git(['worktree', 'list', '--porcelain', '-z'], repoPath, { + signal: context?.signal + }) + return this.normalizeMainWorktreePath( + repoPath, + parseWorktreeList(stdout, { nulDelimited: true }) + ) + }, + async () => { + // Why: `-z` keeps newline-containing SSH worktree paths intact, but + // Git <2.36 requires the line-block parser. + try { + const { stdout } = await this.git(['worktree', 'list', '--porcelain'], repoPath, { + signal: context?.signal + }) + return this.normalizeMainWorktreePath(repoPath, parseWorktreeList(stdout)) + } catch { + return [] + } + }, + isUnsupportedWorktreeListZError ) - } catch (error) { - if (!isUnsupportedWorktreeListZError(error)) { - return [] - } - } - - // Why: `-z` keeps newline-containing SSH worktree paths intact, but older - // Git rejects it. Fall back to the original line-block parser there. - try { - const { stdout } = await this.git(['worktree', 'list', '--porcelain'], repoPath) - return this.normalizeMainWorktreePath(repoPath, parseWorktreeList(stdout)) - } catch { - return [] - } + .catch(() => []) } private async addWorktree(params: Record) { @@ -1292,7 +1363,9 @@ export class GitHandler { } private async removeWorktree(params: Record) { - return this.runWithDiffDedupeClear(() => removeWorktreeOp(this.git.bind(this), params)) + return this.runWithDiffDedupeClear(() => + removeWorktreeOp(this.git.bind(this), params, this.gitCapabilities) + ) } private async worktreeIsClean(params: Record) { @@ -1301,7 +1374,7 @@ export class GitHandler { private async refreshLocalBaseRefForWorktreeCreate(params: Record) { return this.runWithDiffDedupeClear(() => - refreshLocalBaseRefForWorktreeCreateOp(this.git.bind(this), params) + refreshLocalBaseRefForWorktreeCreateOp(this.git.bind(this), params, this.gitCapabilities) ) } } diff --git a/src/relay/git-response-pty-echo-backpressure.integration.test.ts b/src/relay/git-response-pty-echo-backpressure.integration.test.ts new file mode 100644 index 000000000000..09e6bf381928 --- /dev/null +++ b/src/relay/git-response-pty-echo-backpressure.integration.test.ts @@ -0,0 +1,309 @@ +/** + * Regression: SSH typing latency under large git responses. + * + * The relay and the client share ONE ordered SSH channel. A large git diff/exec + * response sent as a single JSON-RPC frame queues megabytes into the outbound + * pipe at once; an interactive pty.data echo emitted mid-response then sits + * behind all of it and typing feels seconds-slow. + * + * These tests model the SSH channel as a congestible in-memory pipe and assert + * deterministic byte bounds instead of wall-clock latency: + * - WITHOUT the fix (client does not opt in), the whole response queues ahead + * of a pty echo; + * - WITH the fix (client opts in), the response streams on the bulk lane and + * at most ~1 chunk frame sits ahead of the echo; + * - both paths reassemble the identical git result. + */ +import { describe, expect, it, beforeEach, afterEach } from 'vitest' +import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import { execFileSync } from 'node:child_process' +import * as path from 'node:path' +import { tmpdir } from 'node:os' + +import { + SshChannelMultiplexer, + type MultiplexerTransport +} from '../main/ssh/ssh-channel-multiplexer' +import { requestGitStreamable } from '../main/ssh/ssh-git-response-stream-reader' + +import { RelayDispatcher } from './dispatcher' +import { RelayContext } from './context' +import { GitHandler } from './git-handler' +import { GIT_RESPONSE_CHUNK_SIZE } from './protocol' + +// One framed git.responseChunk: base64 (4/3) + JSON envelope + header slack. +const FRAMED_CHUNK_BYTES = Math.ceil((GIT_RESPONSE_CHUNK_SIZE * 4) / 3) + 512 +const SINK_HIGH_WATER_MARK = 64 * 1024 + +async function waitUntil( + predicate: () => boolean, + what: string, + timeoutMs = 10_000 +): Promise { + const deadline = Date.now() + timeoutMs + while (!predicate()) { + if (Date.now() > deadline) { + throw new Error(`waitUntil timed out: ${what}`) + } + await new Promise((r) => setImmediate(r)) + } +} + +async function waitUntilSettled(read: () => number, stableTurns = 25): Promise { + let last = read() + let stable = 0 + while (stable < stableTurns) { + await new Promise((r) => setImmediate(r)) + const current = read() + if (current === last) { + stable += 1 + } else { + stable = 0 + last = current + } + } +} + +type Harness = { + mux: SshChannelMultiplexer + dispatcher: RelayDispatcher + gitHandler: GitHandler + queuedBytes: () => number + deliverAll: () => void + startAutoDeliver: () => void + dispose: () => void +} + +function createHarness(opts: { congested: boolean }): Harness { + let relayFeed: ((data: Buffer) => void) | null = null + const clientDataCallbacks: ((data: Buffer) => void)[] = [] + + const clientTransport: MultiplexerTransport = { + write: (data: Buffer) => { + // Client → relay (keystrokes, acks) is the opposite duplex direction and + // is not blocked by relay→client congestion. + setImmediate(() => relayFeed?.(data)) + }, + onData: (cb) => { + clientDataCallbacks.push(cb) + }, + onClose: () => {} + } + + const outQueue: Buffer[] = [] + let queuedBytes = 0 + const drainWaiters = new Set<() => void>() + const fireDrainIfIdle = (): void => { + if (queuedBytes > 0) { + return + } + for (const cb of Array.from(drainWaiters)) { + drainWaiters.delete(cb) + cb() + } + } + + const dispatcher = new RelayDispatcher( + (data: Buffer) => { + outQueue.push(data) + queuedBytes += data.length + if (!opts.congested) { + return true + } + return queuedBytes < SINK_HIGH_WATER_MARK + }, + { + waitWriteDrain: (cb: () => void) => { + drainWaiters.add(cb) + fireDrainIfIdle() + } + } + ) + relayFeed = (data: Buffer) => dispatcher.feed(data) + + const deliverAll = (): void => { + while (outQueue.length > 0) { + const buf = outQueue.shift()! + queuedBytes -= buf.length + for (const cb of clientDataCallbacks) { + cb(buf) + } + } + fireDrainIfIdle() + } + + let autoDeliverTimer: ReturnType | null = null + const startAutoDeliver = (): void => { + if (autoDeliverTimer) { + return + } + autoDeliverTimer = setInterval(deliverAll, 1) + } + + const context = new RelayContext() + const gitHandler = new GitHandler(dispatcher, context) + const mux = new SshChannelMultiplexer(clientTransport) + + return { + mux, + dispatcher, + gitHandler, + queuedBytes: () => queuedBytes, + deliverAll, + startAutoDeliver, + dispose: () => { + if (autoDeliverTimer) { + clearInterval(autoDeliverTimer) + } + mux.dispose() + dispatcher.dispose() + gitHandler.dispose() + } + } +} + +// Build a repo whose staged diff for `big.txt` is several MB so git.diff +// returns a payload well over the stream threshold. +function makeRepoWithLargeStagedDiff(dir: string): void { + const env = { ...process.env } + const run = (args: string[]): void => { + execFileSync('git', args, { cwd: dir, stdio: 'pipe', env }) + } + run(['init']) + run(['config', 'user.email', 'test@test.com']) + run(['config', 'user.name', 'Test']) + // Distinct non-repeating lines keep the diff from compressing to nothing. + // Stay under the render limits (120k lines / 6M chars) so the diff result + // carries the full ~4MB content and exceeds the stream threshold. + const lines: string[] = [] + for (let i = 0; i < 12_000; i += 1) { + lines.push(`line ${i} ${'x'.repeat(100)}`) + } + writeFileSync(path.join(dir, 'big.txt'), lines.join('\n')) + run(['add', 'big.txt']) +} + +describe('large git response vs pty.data echo head-of-line blocking', () => { + let tmpDir: string + let repoDir: string + + beforeEach(() => { + tmpDir = mkdtempSync(path.join(tmpdir(), 'relay-git-hol-')) + repoDir = path.join(tmpDir, 'repo') + mkdirSync(repoDir, { recursive: true }) + makeRepoWithLargeStagedDiff(repoDir) + }) + + afterEach(async () => { + await rm(tmpDir, { recursive: true, force: true }) + }) + + it('WITHOUT opt-in: the whole diff queues ahead of a pty echo (single-frame HOL)', async () => { + const harness = createHarness({ congested: true }) + try { + let queuedBytesAheadOfEcho = -1 + harness.dispatcher.onNotification('pty.data', (params) => { + queuedBytesAheadOfEcho = harness.queuedBytes() + harness.dispatcher.notify('pty.data', { id: params.id, data: params.data }) + }) + + // Plain request WITHOUT __streamResponse: single-frame response, as today. + const diffPromise = harness.mux.request('git.diff', { + worktreePath: repoDir, + filePath: 'big.txt', + staged: true + }) + // Let the whole single JSON-RPC frame land in the congested pipe. + await waitUntil(() => harness.queuedBytes() > SINK_HIGH_WATER_MARK, 'diff frame queued') + await waitUntilSettled(() => harness.queuedBytes()) + + harness.mux.notify('pty.data', { id: 'pty-1', data: 'x' }) + await waitUntil(() => queuedBytesAheadOfEcho >= 0, 'echo emitted by relay') + + // The echo sits behind the entire (multi-hundred-KB) diff frame — far + // more than a single bulk chunk would be. + expect(queuedBytesAheadOfEcho).toBeGreaterThan(512 * 1024) + + harness.startAutoDeliver() + const result = (await diffPromise) as { diff?: string } + expect(typeof result).toBe('object') + } finally { + harness.dispose() + } + }, 30_000) + + it('WITH opt-in: the diff streams on the bulk lane and the echo stays bounded', async () => { + const harness = createHarness({ congested: true }) + try { + let queuedBytesAheadOfEcho = -1 + harness.dispatcher.onNotification('pty.data', (params) => { + queuedBytesAheadOfEcho = harness.queuedBytes() + harness.dispatcher.notify('pty.data', { id: params.id, data: params.data }) + }) + + const diffPromise = requestGitStreamable(harness.mux, 'git.diff', { + worktreePath: repoDir, + filePath: 'big.txt', + staged: true + }) + // Deliver the sentinel response, then let the pump run into congestion. + await waitUntil(() => harness.queuedBytes() > 0, 'sentinel queued') + harness.deliverAll() + await waitUntil(() => harness.queuedBytes() > 0, 'first chunk queued') + await waitUntilSettled(() => harness.queuedBytes()) + + harness.mux.notify('pty.data', { id: 'pty-1', data: 'x' }) + await waitUntil(() => queuedBytesAheadOfEcho >= 0, 'echo emitted by relay') + + // At most one in-flight bulk frame (the write that saturated the sink) + // plus slack sits ahead of the echo. + expect(queuedBytesAheadOfEcho).toBeLessThan(2 * FRAMED_CHUNK_BYTES) + + harness.startAutoDeliver() + const streamed = (await diffPromise) as Record + expect(typeof streamed).toBe('object') + expect(streamed).not.toHaveProperty('__orcaGitResponseStream') + } finally { + harness.dispose() + } + }, 30_000) + + it('streamed result equals the single-frame result', async () => { + const harness = createHarness({ congested: false }) + try { + harness.startAutoDeliver() + const params = { worktreePath: repoDir, filePath: 'big.txt', staged: true } + // Why: request both concurrently so the shared 1ms delivery pump drives + // the plain frame and the streamed chunk/ack round-trips without either + // starving the other on a slow CI event loop. + const [plain, streamed] = await Promise.all([ + harness.mux.request('git.diff', params), + requestGitStreamable(harness.mux, 'git.diff', params) + ]) + expect(streamed).toEqual(plain) + } finally { + harness.dispose() + } + }, 30_000) + + it('rejects with an inactivity timeout when the stream stalls after the sentinel', async () => { + const harness = createHarness({ congested: false }) + try { + // Deliver the sentinel so reassembly begins, then stop delivering chunks + // to model a relay pump that wedged while the channel stayed up. Without + // the client-side inactivity deadline this promise would hang forever. + const streamedPromise = requestGitStreamable( + harness.mux, + 'git.diff', + { worktreePath: repoDir, filePath: 'big.txt', staged: true }, + { inactivityTimeoutMs: 250 } + ) + await waitUntil(() => harness.queuedBytes() > 0, 'sentinel queued') + harness.deliverAll() // sentinel only; chunks stay undelivered + await expect(streamedPromise).rejects.toThrow(/stalled/) + } finally { + harness.dispose() + } + }, 30_000) +}) diff --git a/src/relay/git-response-stream-ownership.test.ts b/src/relay/git-response-stream-ownership.test.ts new file mode 100644 index 000000000000..c6340265238b --- /dev/null +++ b/src/relay/git-response-stream-ownership.test.ts @@ -0,0 +1,68 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { RelayDispatcher, RequestContext } from './dispatcher' +import { GitResponseStreamRegistry } from './git-response-stream' +import { GIT_RESPONSE_CHUNK_SIZE, STREAM_ACK_WINDOW_CHUNKS } from './protocol' + +async function flushPump(): Promise { + await new Promise((resolve) => setImmediate(resolve)) +} + +describe('GitResponseStreamRegistry client ownership', () => { + const registries: GitResponseStreamRegistry[] = [] + + afterEach(() => { + for (const registry of registries) { + registry.disposeAll() + } + registries.length = 0 + }) + + it('ignores acknowledgements and cancellation from a different relay client', async () => { + const ownerClientId = 7 + const notifyBulk = vi.fn().mockResolvedValue(undefined) + const dispatcher = { + notifyBulk, + notify: vi.fn() + } as unknown as RelayDispatcher + const context: RequestContext = { + clientId: ownerClientId, + isStale: () => false + } + const registry = new GitResponseStreamRegistry() + registries.push(registry) + const payload = Buffer.alloc(GIT_RESPONSE_CHUNK_SIZE * (STREAM_ACK_WINDOW_CHUNKS * 3)) + const marker = registry.startStream(payload, dispatcher, context) + const streamId = marker.__orcaGitResponseStream.streamId + + await flushPump() + expect(notifyBulk).toHaveBeenCalledTimes(STREAM_ACK_WINDOW_CHUNKS) + + registry.recordAck(streamId, 10_000, ownerClientId + 1) + await flushPump() + expect(notifyBulk).toHaveBeenCalledTimes(STREAM_ACK_WINDOW_CHUNKS) + + registry.abort(streamId, ownerClientId + 1) + registry.recordAck(streamId, STREAM_ACK_WINDOW_CHUNKS - 1, ownerClientId) + await flushPump() + expect(notifyBulk.mock.calls.length).toBeGreaterThan(STREAM_ACK_WINDOW_CHUNKS) + }) + + it('contains a secondary failure while reporting a stream error', async () => { + const notifyBulk = vi.fn().mockRejectedValue(new Error('socket closed')) + const dispatcher = { notifyBulk, notify: vi.fn() } as unknown as RelayDispatcher + const registry = new GitResponseStreamRegistry() + registries.push(registry) + + registry.startStream(Buffer.from('payload'), dispatcher, { + clientId: 7, + isStale: () => false + }) + + await flushPump() + await flushPump() + + expect(notifyBulk).toHaveBeenCalledTimes(2) + expect(notifyBulk.mock.calls[0]?.[0]).toBe('git.responseChunk') + expect(notifyBulk.mock.calls[1]?.[0]).toBe('git.responseError') + }) +}) diff --git a/src/relay/git-response-stream.ts b/src/relay/git-response-stream.ts new file mode 100644 index 000000000000..bced3b47e466 --- /dev/null +++ b/src/relay/git-response-stream.ts @@ -0,0 +1,211 @@ +// Streams large git RPC responses (diff family + exec) onto the bulk lane in +// chunks instead of one JSON-RPC frame, so a big diff cannot head-of-line-block +// interactive pty.data echo on the shared SSH channel. Mirrors the fs +// read-stream credit-window pattern (see fs-handler-file-read.ts) but the +// payload is an in-memory serialized string rather than a file handle. +import type { RelayDispatcher, RequestContext } from './dispatcher' +import { + GIT_RESPONSE_CHUNK_SIZE, + STREAM_ACK_WINDOW_CHUNKS, + STREAM_ACK_STALL_RECHECK_MS, + type GitResponseStreamMarker +} from './protocol' + +type GitResponseStreamEntry = { + ownerClientId: number + aborted: boolean + /** Highest chunk seq the client acknowledged (in-order; -1 = none yet). */ + ackedThroughSeq: number + ackWaiters: Set<() => void> +} + +/** Serialized git responses are chunked as base64 so multi-byte UTF-8 + * sequences never split across a chunk boundary (the client concatenates the + * decoded bytes and parses once). */ +function encodeChunks(payload: Buffer): string[] { + const chunks: string[] = [] + for (let offset = 0; offset < payload.length; offset += GIT_RESPONSE_CHUNK_SIZE) { + chunks.push(payload.subarray(offset, offset + GIT_RESPONSE_CHUNK_SIZE).toString('base64')) + } + return chunks +} + +export class GitResponseStreamRegistry { + private streams = new Map() + private nextId = 1 + + private register(ownerClientId: number): number { + const streamId = this.nextId++ + this.streams.set(streamId, { + ownerClientId, + aborted: false, + ackedThroughSeq: -1, + ackWaiters: new Set() + }) + return streamId + } + + recordAck(streamId: number, seq: number, clientId: number): void { + const entry = this.streams.get(streamId) + if ( + !entry || + entry.ownerClientId !== clientId || + typeof seq !== 'number' || + !Number.isFinite(seq) + ) { + return + } + if (seq > entry.ackedThroughSeq) { + entry.ackedThroughSeq = seq + } + this.wake(entry) + } + + abort(streamId: number, clientId: number): void { + const entry = this.streams.get(streamId) + if (entry?.ownerClientId === clientId) { + entry.aborted = true + this.wake(entry) + } + } + + /** Wake every parked pump so it re-checks staleness — used when a client + * detaches and its acks will never arrive. */ + wakeAll(): void { + for (const entry of this.streams.values()) { + this.wake(entry) + } + } + + private wake(entry: GitResponseStreamEntry): void { + for (const waiter of Array.from(entry.ackWaiters)) { + waiter() + } + } + + private waitForAck(streamId: number): Promise { + const entry = this.streams.get(streamId) + if (!entry || entry.aborted) { + return Promise.resolve() + } + return new Promise((resolve) => { + let settled = false + const finish = (): void => { + if (settled) { + return + } + settled = true + clearTimeout(timer) + entry.ackWaiters.delete(finish) + resolve() + } + const timer = setTimeout(finish, STREAM_ACK_STALL_RECHECK_MS) + timer.unref?.() + entry.ackWaiters.add(finish) + }) + } + + /** + * Register a stream for `payload`, kick off the bulk-lane pump on a later + * task (so the sentinel response reaches the client first), and return the + * sentinel marker to send as the RPC result. + */ + startStream( + payload: Buffer, + dispatcher: RelayDispatcher, + context: RequestContext + ): GitResponseStreamMarker { + const streamId = this.register(context.clientId) + const chunks = encodeChunks(payload) + // Why: kick the pump off the response task so the client sees the sentinel + // (and can subscribe/reassemble) before the first chunk frame arrives. + setImmediate(() => { + void this.pump(streamId, chunks, dispatcher, context) + }) + return { + __orcaGitResponseStream: { streamId, totalBytes: payload.length, chunkCount: chunks.length } + } + } + + private async pump( + streamId: number, + chunks: string[], + dispatcher: RelayDispatcher, + context: RequestContext + ): Promise { + const entry = this.streams.get(streamId) + if (!entry) { + return + } + const clientId = context.clientId + let seq = 0 + let endReason: 'end' | 'aborted' | 'stale' = 'end' + try { + for (seq = 0; seq < chunks.length; seq += 1) { + if (context.isStale()) { + endReason = 'stale' + break + } + if (entry.aborted) { + endReason = 'aborted' + break + } + // Why: credit window — the client acks each chunk, bounding how many + // bulk bytes a keystroke echo can queue behind on the shared channel. + while ( + seq - entry.ackedThroughSeq > STREAM_ACK_WINDOW_CHUNKS && + !context.isStale() && + !entry.aborted + ) { + await this.waitForAck(streamId) + } + if (context.isStale()) { + endReason = 'stale' + break + } + if (entry.aborted) { + endReason = 'aborted' + break + } + // Why: notifyBulk waits out sink saturation so chunk frames never pile + // up in the outbound pipe ahead of interactive pty.data frames. + await dispatcher.notifyBulk( + 'git.responseChunk', + { streamId, seq, data: chunks[seq] }, + { + clientId + } + ) + } + if (endReason === 'end') { + await dispatcher.notifyBulk('git.responseEnd', { streamId }, { clientId }) + } + } catch (err) { + if (!context.isStale() && !entry.aborted) { + try { + await dispatcher.notifyBulk( + 'git.responseError', + { + streamId, + message: err instanceof Error ? err.message : String(err) + }, + { clientId } + ) + } catch { + // Why: the original failure may be the owning channel closing; a + // second send failure must not escape this detached pump. + } + } + } finally { + this.streams.delete(streamId) + } + } + + disposeAll(): void { + for (const entry of this.streams.values()) { + entry.aborted = true + this.wake(entry) + } + this.streams.clear() + } +} diff --git a/src/relay/preflight-handler.test.ts b/src/relay/preflight-handler.test.ts index 668354b03db2..80bc2ba490a0 100644 --- a/src/relay/preflight-handler.test.ts +++ b/src/relay/preflight-handler.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { buildPosixCommandPathLookupScript } from '../shared/posix-command-path-lookup' const { execFileAsyncMock } = vi.hoisted(() => ({ execFileAsyncMock: vi.fn() @@ -38,7 +39,8 @@ function lookupArgs(command: string, mode: '-lc' | '-ilc' = '-lc'): string[] { return [ mode, [ - `if resolved=$(command -v ${command} 2>/dev/null); then`, + buildPosixCommandPathLookupScript({ kind: 'literal', value: command }), + 'if [ -n "$resolved" ]; then', 'printf \'__ORCA_AGENT_PATH__%s\\n\' "$resolved"', 'fi' ].join('\n') @@ -77,14 +79,14 @@ describe('buildCommandLookupSpec', () => { it('falls back to sh for POSIX probes without a configured shell', () => { expect(buildCommandLookupSpec('codex', 'linux', {}, null)).toEqual({ file: '/bin/sh', - args: lookupArgs("'codex'") + args: lookupArgs('codex') }) }) it('uses the configured remote shell for POSIX probes', () => { expect(buildCommandLookupSpec('codex', 'linux', { SHELL: '/bin/zsh' }, '/bin/zsh')).toEqual({ file: '/bin/zsh', - args: lookupArgs("'codex'", '-ilc') + args: lookupArgs('codex', '-ilc') }) }) @@ -93,7 +95,7 @@ describe('buildCommandLookupSpec', () => { buildCommandLookupSpec("agent'cli", 'linux', { SHELL: '/bin/bash' }, '/bin/bash') ).toEqual({ file: '/bin/bash', - args: lookupArgs("'agent'\\''cli'", '-ilc') + args: lookupArgs("agent'cli", '-ilc') }) }) }) @@ -101,8 +103,8 @@ describe('buildCommandLookupSpec', () => { describe('buildCommandLookupSpecs', () => { it('falls back to inherited PATH after a trusted configured POSIX shell', () => { expect(buildCommandLookupSpecs('codex', 'linux', { SHELL: '/bin/zsh' }, '/bin/zsh')).toEqual([ - { file: '/bin/zsh', args: lookupArgs("'codex'", '-ilc') }, - { file: '/bin/sh', args: lookupArgs("'codex'") } + { file: '/bin/zsh', args: lookupArgs('codex', '-ilc') }, + { file: '/bin/sh', args: lookupArgs('codex') } ]) }) @@ -115,15 +117,15 @@ describe('buildCommandLookupSpecs', () => { '/opt/homebrew/bin/zsh' ) ).toEqual([ - { file: '/opt/homebrew/bin/zsh', args: lookupArgs("'codex'", '-ilc') }, - { file: '/bin/sh', args: lookupArgs("'codex'") } + { file: '/opt/homebrew/bin/zsh', args: lookupArgs('codex', '-ilc') }, + { file: '/bin/sh', args: lookupArgs('codex') } ]) }) it('allows conservative system shell paths when account lookup is unavailable', () => { expect(buildCommandLookupSpecs('codex', 'linux', { SHELL: '/usr/bin/bash' }, null)[0]).toEqual({ file: '/usr/bin/bash', - args: lookupArgs("'codex'", '-ilc') + args: lookupArgs('codex', '-ilc') }) }) @@ -136,14 +138,14 @@ describe('buildCommandLookupSpecs', () => { it('ignores untrusted temp shell paths even when the basename is supported', () => { expect(buildCommandLookupSpecs('codex', 'linux', { SHELL: '/tmp/zsh' }, '/bin/bash')).toEqual([ - { file: '/bin/sh', args: lookupArgs("'codex'") } + { file: '/bin/sh', args: lookupArgs('codex') } ]) }) it('ignores untrusted home-bin shell paths even when the basename is supported', () => { expect( buildCommandLookupSpecs('codex', 'linux', { SHELL: '/home/test/bin/bash' }, '/bin/bash') - ).toEqual([{ file: '/bin/sh', args: lookupArgs("'codex'") }]) + ).toEqual([{ file: '/bin/sh', args: lookupArgs('codex') }]) }) }) @@ -160,17 +162,12 @@ describe('isCommandOnPathForRelay', () => { accountLoginShell: '/bin/zsh' }) ).resolves.toBe(true) - expect(execFileAsyncMock).toHaveBeenNthCalledWith( - 1, - '/bin/zsh', - lookupArgs("'codex'", '-ilc'), - { - encoding: 'utf-8', - env: expect.objectContaining({ SHELL: '/bin/zsh' }), - timeout: 5000 - } - ) - expect(execFileAsyncMock).toHaveBeenNthCalledWith(2, '/bin/sh', lookupArgs("'codex'"), { + expect(execFileAsyncMock).toHaveBeenNthCalledWith(1, '/bin/zsh', lookupArgs('codex', '-ilc'), { + encoding: 'utf-8', + env: expect.objectContaining({ SHELL: '/bin/zsh' }), + timeout: 5000 + }) + expect(execFileAsyncMock).toHaveBeenNthCalledWith(2, '/bin/sh', lookupArgs('codex'), { encoding: 'utf-8', env: expect.objectContaining({ SHELL: '/bin/zsh' }), timeout: 5000 @@ -203,7 +200,7 @@ describe('isCommandOnPathForRelay', () => { }) ).resolves.toBe(true) expect(execFileAsyncMock).toHaveBeenCalledTimes(1) - expect(execFileAsyncMock).toHaveBeenCalledWith('/bin/sh', lookupArgs("'codex'"), { + expect(execFileAsyncMock).toHaveBeenCalledWith('/bin/sh', lookupArgs('codex'), { encoding: 'utf-8', env: expect.objectContaining({ SHELL: '/tmp/zsh' }), timeout: 5000 @@ -236,6 +233,86 @@ describe('hasAbsoluteCommandPath', () => { }) describe('PreflightHandler', () => { + it('honors required commands when reporting detected agents', async () => { + execFileAsyncMock.mockImplementation(async (_file, args) => { + const script = String(args[1]) + if (script.includes("'orca'")) { + return { stdout: '__ORCA_AGENT_PATH__/relay/path/orca\n' } + } + throw new Error('not found') + }) + const requestHandlers = new Map) => Promise>() + const dispatcher = { + onRequest: vi.fn( + (method: string, handler: (params: Record) => Promise) => { + requestHandlers.set(method, handler) + } + ) + } + + new PreflightHandler(dispatcher as never) + + const handler = requestHandlers.get('preflight.detectAgents') + expect(handler).toBeDefined() + await expect( + handler!({ + commands: [ + { id: 'claude-agent-teams', cmd: 'orca', requiredCommands: ['claude'] }, + { id: 'claude', cmd: 'claude' } + ] + }) + ).resolves.toEqual({ agents: [] }) + }) + + it('does not report platform-unsupported agents on native Windows SSH hosts', async () => { + const originalPlatform = process.platform + Object.defineProperty(process, 'platform', { + configurable: true, + value: 'win32' + }) + execFileAsyncMock.mockImplementation(async (_file, args) => { + if (String(args[0]) === 'claude') { + return { stdout: 'C:\\Users\\test\\AppData\\Roaming\\npm\\claude.cmd\r\n' } + } + if (String(args[0]) === 'orca') { + return { stdout: 'C:\\Program Files\\Orca\\orca.cmd\r\n' } + } + throw new Error('not found') + }) + const requestHandlers = new Map) => Promise>() + const dispatcher = { + onRequest: vi.fn( + (method: string, handler: (params: Record) => Promise) => { + requestHandlers.set(method, handler) + } + ) + } + + try { + new PreflightHandler(dispatcher as never) + const handler = requestHandlers.get('preflight.detectAgents') + expect(handler).toBeDefined() + await expect( + handler!({ + commands: [ + { + id: 'claude-agent-teams', + cmd: 'orca', + requiredCommands: ['claude'], + unsupportedRuntimes: ['win32'] + }, + { id: 'claude', cmd: 'claude' } + ] + }) + ).resolves.toEqual({ agents: ['claude'] }) + } finally { + Object.defineProperty(process, 'platform', { + configurable: true, + value: originalPlatform + }) + } + }) + it('reports remote Windows shell capabilities through the SSH preflight path', async () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { diff --git a/src/relay/preflight-handler.ts b/src/relay/preflight-handler.ts index 3eff81213682..101c796137c4 100644 --- a/src/relay/preflight-handler.ts +++ b/src/relay/preflight-handler.ts @@ -7,6 +7,7 @@ import { buildRelayCommandEnv } from './relay-command-env' import { isPwshAvailable } from '../main/pwsh' import { isWslAvailable, listWslDistros } from '../main/wsl' import { isGitBashAvailable } from '../main/git-bash' +import { buildPosixCommandPathLookupScript } from '../shared/posix-command-path-lookup' const execFileAsync = promisify(execFile) @@ -22,6 +23,15 @@ type RelayCommandLookupOptions = { accountLoginShell?: string | null } +type AgentDetectionRuntime = NodeJS.Platform | 'wsl' + +type AgentDetectionCommand = { + id: string + cmd: string + requiredCommands?: readonly string[] + unsupportedRuntimes?: readonly AgentDetectionRuntime[] +} + const SUPPORTED_POSIX_SHELLS = new Set(['sh', 'dash', 'bash', 'zsh', 'fish']) const CONSERVATIVE_SYSTEM_SHELL_DIRS = new Set(['/bin', '/usr/bin']) const AGENT_PATH_PREFIX = '__ORCA_AGENT_PATH__' @@ -45,19 +55,42 @@ export class PreflightHandler { // on the relay side. This keeps the relay bundle minimal and makes the protocol // self-describing — the relay doesn't need to know the agent catalog. private async detectAgents(params: Record): Promise<{ agents: string[] }> { - const commands = params.commands as { id: string; cmd: string }[] + const commands = params.commands as AgentDetectionCommand[] if (!Array.isArray(commands)) { return { agents: [] } } + const probeCommands = [ + ...new Set( + commands + .filter((command) => !isDetectionUnsupportedInRuntime(command, process.platform)) + .flatMap((command) => [command.cmd, ...(command.requiredCommands ?? [])]) + ) + ] const results = await Promise.all( - commands.map(async ({ id, cmd }) => ({ - id, + probeCommands.map(async (cmd) => ({ + cmd, installed: await this.isCommandOnPath(cmd) })) ) + const foundCommands = new Set( + results.filter((result) => result.installed).map(({ cmd }) => cmd) + ) - return { agents: [...new Set(results.filter((r) => r.installed).map((r) => r.id))] } + return { + agents: [ + ...new Set( + commands + .filter( + (command) => + !isDetectionUnsupportedInRuntime(command, process.platform) && + foundCommands.has(command.cmd) && + (command.requiredCommands ?? []).every((required) => foundCommands.has(required)) + ) + .map(({ id }) => id) + ) + ] + } } private async detectWindowsTerminalCapabilities(): Promise<{ @@ -91,6 +124,13 @@ export class PreflightHandler { } } +function isDetectionUnsupportedInRuntime( + command: AgentDetectionCommand, + runtime: AgentDetectionRuntime +): boolean { + return command.unsupportedRuntimes?.includes(runtime) === true +} + export function buildCommandLookupSpec( command: string, platform: NodeJS.Platform, @@ -180,9 +220,10 @@ function buildPosixCommandLookupSpec(command: string, shell: string): CommandLoo } function buildShCommandLookupScript(command: string): string { - const quotedCommand = shellQuote(command) + // Why: login shells may define aliases or functions that mask the PATH executable. return [ - `if resolved=$(command -v ${quotedCommand} 2>/dev/null); then`, + buildPosixCommandPathLookupScript({ kind: 'literal', value: command }), + 'if [ -n "$resolved" ]; then', `printf '${AGENT_PATH_PREFIX}%s\\n' "$resolved"`, 'fi' ].join('\n') diff --git a/src/relay/protocol.ts b/src/relay/protocol.ts index 267f6ef480f3..4df0f7bd9b55 100644 --- a/src/relay/protocol.ts +++ b/src/relay/protocol.ts @@ -59,6 +59,27 @@ export const STREAM_ACK_WINDOW_CHUNKS = 4 * (and its open file handle) forever. */ export const STREAM_ACK_STALL_RECHECK_MS = 1_000 +// ── Git response streaming (see docs/relay-git-response-stream-design.md) ── + +/** Serialized-JSON size above which a streamable git response (diff family + + * exec) is chunked onto the bulk lane instead of one JSON-RPC frame, so a large + * diff cannot head-of-line-block interactive pty.data echo on the shared SSH + * channel. Below this, single-frame is cheaper and avoids stream overhead. */ +export const GIT_RESPONSE_STREAM_THRESHOLD = 256 * 1024 + +/** Per-chunk size (UTF-8 bytes of the serialized result) for git response + * streaming. Independent from STREAM_CHUNK_SIZE — this offset math is not + * shared with fs streams, so tuning it here is cross-version safe as long as + * the client reassembles by concatenation (it does not depend on chunk size). */ +export const GIT_RESPONSE_CHUNK_SIZE = 128 * 1024 + +/** Sentinel result returned in place of a large git response: the real payload + * follows as git.responseChunk frames on the bulk lane. Old relays never emit + * this, so a new client falls back to the plain result they return. */ +export type GitResponseStreamMarker = { + __orcaGitResponseStream: { streamId: number; totalBytes: number; chunkCount: number } +} + export const RelayErrorCode = { TooManyStreams: -33006, StreamProtocolError: -33007 diff --git a/src/relay/pty-handler.test.ts b/src/relay/pty-handler.test.ts index aa35e99571a2..332828408bdd 100644 --- a/src/relay/pty-handler.test.ts +++ b/src/relay/pty-handler.test.ts @@ -14,7 +14,10 @@ import { const { mockPtySpawn, mockPtyInstance } = vi.hoisted(() => ({ mockPtySpawn: vi.fn(), mockPtyInstance: { - pid: 12345, + // Why: attach now proves the backing pid is alive before replaying, so the + // default managed PTY must report a live pid. Reuse the test runner's own + // pid — always alive — so unrelated attach tests are not seen as dead. + pid: process.pid, onData: vi.fn(), onExit: vi.fn(), write: vi.fn(), @@ -609,6 +612,71 @@ describe('PtyHandler', () => { } ) + it('reports not-found and reaps a reattach whose backing shell is dead', async () => { + // Why: a lingering managed entry whose child died without an onExit would + // otherwise attach-succeed with an empty replay and strand the pane on a + // black shell. A provably-dead pid must surface as not-found so the SSH + // provider maps it to SSH_SESSION_EXPIRED and the pane respawns fresh. + let onExitCb: ((evt: { exitCode: number }) => void) | undefined + mockPtySpawn.mockReturnValue({ + ...mockPtyInstance, + onData: vi.fn(), + onExit: vi.fn((cb: (evt: { exitCode: number }) => void) => { + onExitCb = cb + }) + }) + const exits: { id: string; paneKey?: string }[] = [] + handler.setExitListener((evt) => exits.push(evt)) + + await dispatcher.callRequest('pty.spawn', { env: { ORCA_PANE_KEY: 'tab-dead:0' } }) + expect(handler.activePtyCount).toBe(1) + expect(onExitCb).toBeDefined() + + const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(false) + try { + await expect( + dispatcher.callRequest('pty.attach', { id: 'pty-1', suppressReplayNotification: true }) + ).rejects.toThrow('PTY "pty-1" not found') + } finally { + aliveSpy.mockRestore() + } + + // The stale entry is reaped: cache-eviction observers fire and the map slot + // is freed so a later attach also cleanly reports not-found. + expect(exits).toEqual([{ id: 'pty-1', paneKey: 'tab-dead:0' }]) + expect(handler.activePtyCount).toBe(0) + await expect( + dispatcher.callRequest('pty.attach', { id: 'pty-1', suppressReplayNotification: true }) + ).rejects.toThrow('PTY "pty-1" not found') + }) + + it('replays for a reattach whose backing shell is still alive', async () => { + // Guard the other direction: a live pid must never be reaped, so a quiet + // but live session still returns its buffered replay on reattach. + let dataCallback: ((data: string) => void) | undefined + mockPtySpawn.mockReturnValue({ + ...mockPtyInstance, + onData: vi.fn((cb: (data: string) => void) => { + dataCallback = cb + }), + onExit: vi.fn() + }) + await dispatcher.callRequest('pty.spawn', {}) + dataCallback?.('prompt$ ') + + const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(true) + try { + const result = await dispatcher.callRequest('pty.attach', { + id: 'pty-1', + suppressReplayNotification: true + }) + expect(result).toEqual({ replay: 'prompt$ ' }) + } finally { + aliveSpy.mockRestore() + } + expect(handler.activePtyCount).toBe(1) + }) + it('terminates spawned PTY when request becomes stale before response', async () => { const killSpy = vi.fn() const term = { ...mockPtyInstance, kill: killSpy, onData: vi.fn(), onExit: vi.fn() } @@ -1222,11 +1290,78 @@ describe('PtyHandler', () => { } } - const spawnEnv = mockPtySpawn.mock.calls[0][2] as { env: Record } + const spawnEnv = mockPtySpawn.mock.calls[0][2] as { + name: string + env: Record + } + expect(spawnEnv.name).toBe('xterm-256color') expect(spawnEnv.env.SEEN_OPENCODE_CONFIG_DIR).toBe('/remote/renderer-opencode') expect(spawnEnv.env.SEEN_PI_CODING_AGENT_DIR).toBe('/remote/pi') }) + it('applies identity defaults, then deletions, while preserving explicit TERM', async () => { + handler.addEnvAugmenter(() => ({ + TERM: 'augmenter-term', + TERM_PROGRAM: 'augmenter-terminal', + ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/augmenter-attribution' + })) + + await dispatcher.callRequest('pty.spawn', { + env: { + TERM: 'screen-256color', + TERM_PROGRAM: 'renderer-terminal', + ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/renderer-attribution' + }, + envToDelete: ['TERM_PROGRAM', 'ORCA_ATTRIBUTION_SHIM_DIR'] + }) + + const spawnEnv = mockPtySpawn.mock.calls[0][2] as { + name: string + env: Record + } + expect(spawnEnv.name).toBe('screen-256color') + expect(spawnEnv.env.TERM).toBe('screen-256color') + expect(spawnEnv.env.COLORTERM).toBe('truecolor') + expect(spawnEnv.env.FORCE_HYPERLINK).toBe('1') + expect(spawnEnv.env.TERM_PROGRAM).toBeUndefined() + expect(spawnEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined() + }) + + it('replaces an ambient TERM=dumb when no explicit TERM is supplied', async () => { + const previousTerm = process.env.TERM + process.env.TERM = 'dumb' + try { + await dispatcher.callRequest('pty.spawn', {}) + } finally { + if (previousTerm === undefined) { + delete process.env.TERM + } else { + process.env.TERM = previousTerm + } + } + + const spawnEnv = mockPtySpawn.mock.calls[0][2] as { + name: string + env: Record + } + expect(spawnEnv.name).toBe('xterm-256color') + expect(spawnEnv.env.TERM).toBe('xterm-256color') + expect(spawnEnv.env.TERM_PROGRAM).toBe('Orca') + }) + + it('uses the safe terminal default when TERM is deleted without a custom value', async () => { + await dispatcher.callRequest('pty.spawn', { + envToDelete: ['TERM'] + }) + + const spawnEnv = mockPtySpawn.mock.calls[0][2] as { + name: string + env: Record + } + expect(spawnEnv.name).toBe('xterm-256color') + expect(spawnEnv.env.TERM).toBe('xterm-256color') + }) + it('lets relay env augmenters resolve the original sequenced startup command hint', async () => { handler.addEnvAugmenter((ctx) => ({ SEEN_LAUNCH_COMMAND_HINT: resolveSetupAgentSequenceLaunchCommand(ctx.env, ctx.command) ?? '' @@ -1334,6 +1469,172 @@ describe('PtyHandler', () => { expect(callArgs.env.ORCA_WORKTREE_ID).toBe('wt-5') expect(callArgs.env.ORCA_AGENT_HOOK_PORT).toBe('12345') expect(callArgs.env.ORCA_AGENT_HOOK_TOKEN).toBe('abc-uuid') + expect(callArgs.env.TERM).toBe('xterm-256color') + expect(callArgs.env.TERM_PROGRAM).toBe('Orca') + }) + + it('normalizes an explicit empty TERM and preserves sanitized env deletions on revive', async () => { + await dispatcher.callRequest('pty.spawn', { + env: { TERM: '' }, + envToDelete: ['ORCA_ATTRIBUTION_SHIM_DIR', '', 42] + }) + + const initialEnv = mockPtySpawn.mock.calls[0][2] as { + name: string + env: Record + } + expect(initialEnv.name).toBe('xterm-256color') + expect(initialEnv.env.TERM).toBe('xterm-256color') + + const state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + const [serialized] = JSON.parse(state) as { + explicitTerm?: string + envToDelete?: string[] + }[] + expect(serialized.explicitTerm).toBeUndefined() + expect(serialized.envToDelete).toEqual(['ORCA_ATTRIBUTION_SHIM_DIR']) + + handler.dispose() + mockPtySpawn.mockClear() + dispatcher = createMockDispatcher() + handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler.addEnvAugmenter(() => ({ + ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/revived-attribution' + })) + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) + try { + await dispatcher.callRequest('pty.revive', { state }) + } finally { + killSpy.mockRestore() + } + + const revivedEnv = mockPtySpawn.mock.calls[0][2] as { + name: string + env: Record + } + expect(revivedEnv.name).toBe('xterm-256color') + expect(revivedEnv.env.TERM).toBe('xterm-256color') + expect(revivedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined() + }) + + it('drops legacy empty explicit TERM metadata after revive', async () => { + const state = JSON.stringify([ + { + id: 'pty-8', + pid: process.pid, + cols: 80, + rows: 24, + cwd: process.cwd(), + explicitTerm: '', + envToDelete: ['ORCA_ATTRIBUTION_SHIM_DIR'] + } + ]) + handler.addEnvAugmenter(() => ({ + ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/legacy-empty-attribution' + })) + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) + try { + await dispatcher.callRequest('pty.revive', { state }) + } finally { + killSpy.mockRestore() + } + + const revivedEnv = mockPtySpawn.mock.calls[0][2] as { + name: string + env: Record + } + expect(revivedEnv.name).toBe('xterm-256color') + expect(revivedEnv.env.TERM).toBe('xterm-256color') + expect(revivedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined() + + const serializedState = (await dispatcher.callRequest('pty.serialize', { + ids: ['pty-8'] + })) as string + const [serialized] = JSON.parse(serializedState) as { + explicitTerm?: string + envToDelete?: string[] + }[] + expect(serialized.explicitTerm).toBeUndefined() + expect(serialized.envToDelete).toEqual(['ORCA_ATTRIBUTION_SHIM_DIR']) + }) + + it('preserves explicit TERM and env deletions through repeated revive cycles', async () => { + await dispatcher.callRequest('pty.spawn', { + env: { TERM: 'screen-256color' }, + envToDelete: ['ORCA_ATTRIBUTION_SHIM_DIR'] + }) + let state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) + try { + handler.dispose() + mockPtySpawn.mockClear() + dispatcher = createMockDispatcher() + handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler.addEnvAugmenter(() => ({ + ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/first-revive' + })) + await dispatcher.callRequest('pty.revive', { state }) + + const firstRevivedEnv = mockPtySpawn.mock.calls[0][2] as { + name: string + env: Record + } + expect(firstRevivedEnv.name).toBe('screen-256color') + expect(firstRevivedEnv.env.TERM).toBe('screen-256color') + expect(firstRevivedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined() + state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string + expect(JSON.parse(state)).toMatchObject([ + { + explicitTerm: 'screen-256color', + envToDelete: ['ORCA_ATTRIBUTION_SHIM_DIR'] + } + ]) + + handler.dispose() + mockPtySpawn.mockClear() + dispatcher = createMockDispatcher() + handler = new PtyHandler(dispatcher as unknown as RelayDispatcher) + handler.addEnvAugmenter(() => ({ + ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/second-revive' + })) + await dispatcher.callRequest('pty.revive', { state }) + } finally { + killSpy.mockRestore() + } + + const secondRevivedEnv = mockPtySpawn.mock.calls[0][2] as { + name: string + env: Record + } + expect(secondRevivedEnv.name).toBe('screen-256color') + expect(secondRevivedEnv.env.TERM).toBe('screen-256color') + expect(secondRevivedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined() + }) + + it('revives legacy serialized entries with default TERM and no env deletions', async () => { + handler.addEnvAugmenter(() => ({ + ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/legacy-attribution' + })) + const state = JSON.stringify([ + { + id: 'pty-7', + pid: process.pid, + cols: 80, + rows: 24, + cwd: process.cwd() + } + ]) + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) + try { + await dispatcher.callRequest('pty.revive', { state }) + } finally { + killSpy.mockRestore() + } + + const revivedEnv = mockPtySpawn.mock.calls[0][2] as { env: Record } + expect(revivedEnv.env.TERM).toBe('xterm-256color') + expect(revivedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBe('/tmp/legacy-attribution') }) it('revive preserves attach identity metadata without exporting hook identity env', async () => { diff --git a/src/relay/pty-handler.ts b/src/relay/pty-handler.ts index 7e94eb9a74fa..965d8cbdc303 100644 --- a/src/relay/pty-handler.ts +++ b/src/relay/pty-handler.ts @@ -10,6 +10,7 @@ import { resolveProcessCwd, processHasChildren, getForegroundProcessName, + isProcessAlive, listShellProfiles } from './pty-shell-utils' import { getRelayShellLaunchConfig } from './pty-shell-launch' @@ -67,6 +68,8 @@ type ManagedPty = { attachIdentity?: PtyIdentity worktreeId?: string terminalHandle?: string + explicitTerm?: string + envToDelete: string[] startupCommand?: ManagedStartupCommand } @@ -179,6 +182,16 @@ type SerializedPtyEntry = { attachIdentity?: PtyIdentity worktreeId?: string terminalHandle?: string + explicitTerm?: string + envToDelete?: string[] +} + +function sanitizeEnvToDelete(value: unknown): string[] { + return Array.isArray(value) + ? value + .filter((key): key is string => typeof key === 'string' && key.length > 0) + .slice(0, 1_024) + : [] } export type PtyExitListener = (event: { id: string; paneKey?: string }) => void @@ -282,9 +295,19 @@ export class PtyHandler { * otherwise agent-status over SSH silently breaks on every revive. */ private buildSpawnEnv( rendererEnv: Record | undefined, - ctx: { id: string; paneKey?: string; shell: string; command?: string } + ctx: { id: string; paneKey?: string; shell: string; command?: string }, + envToDelete: readonly string[] = [] ): Record { - const baseEnv = { ...process.env, ...rendererEnv } as Record + const baseEnv = { + ...process.env, + TERM: 'xterm-256color', + COLORTERM: 'truecolor', + TERM_PROGRAM: 'Orca', + TERM_PROGRAM_VERSION: + rendererEnv?.ORCA_APP_VERSION || process.env.ORCA_APP_VERSION || '0.0.0-dev', + FORCE_HYPERLINK: '1', + ...rendererEnv + } as Record const augmented: Record = {} for (const augmenter of this.envAugmenters) { try { @@ -295,7 +318,25 @@ export class PtyHandler { ) } } - return { ...baseEnv, ...augmented } + const result = { ...baseEnv, ...augmented } + // Why: match local/daemon precedence so relay defaults and augmenters + // cannot resurrect attribution or identity values explicitly removed. + for (const key of envToDelete) { + delete result[key] + } + if ( + !envToDelete.includes('TERM') && + rendererEnv && + Object.prototype.hasOwnProperty.call(rendererEnv, 'TERM') + ) { + result.TERM = rendererEnv.TERM + } + // Why: node-pty treats missing/empty TERM as its own platform-specific + // default. Normalize here so POSIX and Windows relay children agree. + if (!result.TERM) { + result.TERM = 'xterm-256color' + } + return result } private clearStartupCommandTimer(managed: ManagedPty): void { @@ -561,6 +602,15 @@ export class PtyHandler { const rows = (params.rows as number) || 24 const cwd = (params.cwd as string) || resolveDefaultCwd() const env = params.env as Record | undefined + const envToDelete = sanitizeEnvToDelete(params.envToDelete) + const explicitTerm = + !envToDelete.includes('TERM') && + env && + Object.prototype.hasOwnProperty.call(env, 'TERM') && + typeof env.TERM === 'string' && + env.TERM.length > 0 + ? env.TERM + : undefined const shellOverride = typeof params.shellOverride === 'string' ? params.shellOverride.trim() : '' const resolvedShellOverride = resolvePtyShellOverride(shellOverride) @@ -584,7 +634,7 @@ export class PtyHandler { typeof params.terminalWindowsWslDistro === 'string' ? params.terminalWindowsWslDistro : null const commandDelivery = params.commandDelivery === 'provider' ? 'provider' : 'renderer' const shouldProviderDeliverCommand = commandDelivery === 'provider' && command !== undefined - const spawnEnv = this.buildSpawnEnv(env, { id, paneKey, shell, command }) + const spawnEnv = this.buildSpawnEnv(env, { id, paneKey, shell, command }, envToDelete) const launchCommandHint = resolveSetupAgentSequenceLaunchCommand(spawnEnv, command) const shouldEmitShellReadyMarker = launchCommandHint !== undefined && @@ -606,7 +656,9 @@ export class PtyHandler { // When overlays are injected, the launch wrapper keeps those paths after // user startup files re-export their defaults. const term = pty.spawn(shell, shellLaunch.args, { - name: 'xterm-256color', + // Why: node-pty overwrites env.TERM with `name`; keep caller-selected + // terminal identities instead of losing them at the final spawn boundary. + name: spawnEnv.TERM ?? 'xterm-256color', cols, rows, cwd, @@ -634,6 +686,8 @@ export class PtyHandler { tabId, ...(attachIdentity.paneKey || attachIdentity.tabId ? { attachIdentity } : {}), worktreeId, + ...(explicitTerm !== undefined ? { explicitTerm } : {}), + envToDelete, ...(terminalHandle ? { terminalHandle } : {}), ...(shouldProviderDeliverCommand ? { @@ -692,6 +746,22 @@ export class PtyHandler { throw new Error(`PTY "${id}" not found`) } + // Why: a reattach can arrive for a relay PTY whose backing shell already + // died without node-pty delivering onExit (e.g. the child was reaped out of + // band while the SSH channel was down). The map entry lingers, so attach + // would otherwise "succeed" with an empty replay and strand the reattached + // pane on a black, unresponsive shell. Prove liveness here; if the pid is + // provably gone, reap the stale entry and report not-found so the caller + // drops the dead lease and spawns fresh — the same recovery path an expired + // grace window already takes. + if (managed.pty.pid && !isProcessAlive(managed.pty.pid)) { + this.notifyExitListener(managed) + disposeManagedPty(managed) + this.ptys.delete(id) + this.clearPtyFlowState(id) + throw new Error(`PTY "${id}" not found`) + } + // Why: PTY ids are a per-relay-process counter (pty-1, pty-2, …). When the // relay changes generation — an app update deploys a new content-hashed // relay dir, or a grace-expired relay restarts — the counter resets, so an @@ -918,6 +988,8 @@ export class PtyHandler { tabId: managed.tabId, attachIdentity: managed.attachIdentity, worktreeId: managed.worktreeId, + ...(managed.explicitTerm !== undefined ? { explicitTerm: managed.explicitTerm } : {}), + envToDelete: managed.envToDelete, ...(managed.terminalHandle ? { terminalHandle: managed.terminalHandle } : {}) }) } @@ -959,6 +1031,16 @@ export class PtyHandler { if (entry.terminalHandle) { revivedEnv.ORCA_TERMINAL_HANDLE = entry.terminalHandle } + const explicitTerm = + typeof entry.explicitTerm === 'string' && entry.explicitTerm.length > 0 + ? entry.explicitTerm + : undefined + if (explicitTerm !== undefined) { + revivedEnv.TERM = explicitTerm + } + // Why: serialized state can come from an older or untrusted client, so + // revive reapplies the same bounds as a fresh spawn before retaining it. + const envToDelete = sanitizeEnvToDelete(entry.envToDelete) const shell = resolveDefaultShell() // Why: `command` is intentionally absent from this revive path because // SerializedPtyEntry (see line 99) does not persist it — ManagedPty @@ -967,14 +1049,19 @@ export class PtyHandler { // undefined` for revived PTYs and prepares the Pi default plus OMP's // typed-command wrapper. Plumbing `command` through serialization is a // separate, larger change. - const spawnEnv = this.buildSpawnEnv(revivedEnv, { - id: entry.id, - paneKey: entry.paneKey, - shell - }) + const spawnEnv = this.buildSpawnEnv( + revivedEnv, + { + id: entry.id, + paneKey: entry.paneKey, + shell + }, + envToDelete + ) const shellLaunch = getRelayShellLaunchConfig(shell, spawnEnv) const term = ptyMod.spawn(shell, shellLaunch.args, { - name: 'xterm-256color', + // Why: revive must preserve the same terminal identity as fresh spawn. + name: spawnEnv.TERM ?? 'xterm-256color', cols: entry.cols, rows: entry.rows, cwd: entry.cwd, @@ -991,6 +1078,8 @@ export class PtyHandler { tabId: entry.tabId, attachIdentity: entry.attachIdentity, worktreeId: entry.worktreeId, + ...(explicitTerm !== undefined ? { explicitTerm } : {}), + envToDelete, ...(entry.terminalHandle ? { terminalHandle: entry.terminalHandle } : {}) }) diff --git a/src/relay/pty-shell-utils.test.ts b/src/relay/pty-shell-utils.test.ts index e2b7adcadd05..544e1509c12a 100644 --- a/src/relay/pty-shell-utils.test.ts +++ b/src/relay/pty-shell-utils.test.ts @@ -11,6 +11,7 @@ vi.mock('child_process', () => ({ import { resetProcessTableSnapshotForTests } from '../shared/process-table-snapshot' import { getForegroundProcessName, + isProcessAlive, resolveDefaultCwd, resolveWindowsDefaultShell } from './pty-shell-utils' @@ -51,6 +52,40 @@ beforeEach(() => { resetProcessTableSnapshotForTests() }) +describe('isProcessAlive', () => { + it('reports the test runner process as alive', () => { + expect(isProcessAlive(process.pid)).toBe(true) + }) + + it('reports a process as dead ONLY on ESRCH', () => { + // Why: attach() reaps a lingering managed PTY based on this, so a false + // positive would kill a live remote shell. Only "no such process" counts. + const spy = vi.spyOn(process, 'kill').mockImplementation(() => { + const err = new Error('no such process') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + }) + try { + expect(isProcessAlive(2147483646)).toBe(false) + } finally { + spy.mockRestore() + } + }) + + it('treats an unsignalable process (EPERM) as alive', () => { + const spy = vi.spyOn(process, 'kill').mockImplementation(() => { + const err = new Error('operation not permitted') as NodeJS.ErrnoException + err.code = 'EPERM' + throw err + }) + try { + expect(isProcessAlive(1)).toBe(true) + } finally { + spy.mockRestore() + } + }) +}) + describe('resolveWindowsDefaultShell', () => { it('uses an existing SHELL override when one is provided', () => { expect( diff --git a/src/relay/pty-shell-utils.ts b/src/relay/pty-shell-utils.ts index 6a9c4507372e..87035c9510dc 100644 --- a/src/relay/pty-shell-utils.ts +++ b/src/relay/pty-shell-utils.ts @@ -147,6 +147,19 @@ export async function processHasChildren(pid: number): Promise { } } +// Why: signal 0 probes existence without delivering a signal. Only ESRCH ("no +// such process") proves the pid is gone; EPERM means it exists but is +// unsignalable, so treat every non-ESRCH outcome as alive. Kept conservative so +// a liveness check can only ever declare a *provably* dead process dead. +export function isProcessAlive(pid: number): boolean { + try { + process.kill(pid, 0) + return true + } catch (err) { + return (err as NodeJS.ErrnoException).code !== 'ESRCH' + } +} + function collectDescendants( rows: ProcessTableRow[], rootPid: number diff --git a/src/relay/relay-command-env.test.ts b/src/relay/relay-command-env.test.ts index f2120c177cf5..e9164fb86f7d 100644 --- a/src/relay/relay-command-env.test.ts +++ b/src/relay/relay-command-env.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { homedir } from 'node:os' -import { buildRelayCommandEnv } from './relay-command-env' +import { buildRelayCommandEnv, buildRelayGitEnv } from './relay-command-env' // homedir() is the fallback when the relay env carries no HOME; mock it so the // fallback path is deterministic and the "no resolvable home" branch is reachable. @@ -228,3 +228,20 @@ describe('buildRelayCommandEnv', () => { expect(env.PATH?.split(':')).toContain('/home/fallback/.local/bin') }) }) + +describe('buildRelayGitEnv', () => { + it('pins an untranslated locale on top of the command env (issue #7808)', () => { + // Relay git stderr/progress is machine-parsed; a non-English host locale + // with a gettext git would translate it and break the parsers. + const env = buildRelayGitEnv( + { HOME: '/home/me', PATH: '/usr/bin', LC_ALL: 'de_DE.UTF-8' }, + 'linux' + ) + + expect(env.LC_ALL).toBe('en_US.UTF-8') + expect(env.LANG).toBe('en_US.UTF-8') + expect(env.LANGUAGE).toBe('en') + // PATH fallback behavior is unchanged. + expect(env.PATH?.split(':')).toEqual(expect.arrayContaining(['/usr/bin', '/usr/local/bin'])) + }) +}) diff --git a/src/relay/relay-command-env.ts b/src/relay/relay-command-env.ts index ad64703207d0..3d4c22f7f30d 100644 --- a/src/relay/relay-command-env.ts +++ b/src/relay/relay-command-env.ts @@ -1,5 +1,6 @@ import { homedir } from 'node:os' import { posix, win32 } from 'node:path' +import { UNTRANSLATED_GIT_OUTPUT_ENV } from '../shared/git-output-locale' const POSIX_RELAY_PATH_FALLBACKS = ['/usr/local/bin', '/opt/homebrew/bin', '/usr/bin', '/bin'] const WINDOWS_RELAY_PATH_FALLBACKS = [ @@ -154,3 +155,16 @@ export function buildRelayCommandEnv( [key]: [...segments].join(delimiter) } } + +/** + * Env for relay-spawned git specifically: the PATH fallbacks above plus a + * pinned English UTF-8 locale, because relay git output is machine-parsed + * (stderr phrase matching, progress regexes) and a gettext-enabled git under + * a non-English host locale translates it (issue #7808). + */ +export function buildRelayGitEnv( + baseEnv: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform +): NodeJS.ProcessEnv { + return { ...buildRelayCommandEnv(baseEnv, platform), ...UNTRANSLATED_GIT_OUTPUT_ENV } +} diff --git a/src/relay/relay-diagnostic-log.test.ts b/src/relay/relay-diagnostic-log.test.ts new file mode 100644 index 000000000000..38adbcb76697 --- /dev/null +++ b/src/relay/relay-diagnostic-log.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it, vi } from 'vitest' +import { relayLogLine } from './relay-diagnostic-log' + +describe('relayLogLine', () => { + it('prefixes each log line with an ISO timestamp', () => { + const writeSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true) + try { + relayLogLine('[relay] Grace started (stdin ended)') + + expect(writeSpy).toHaveBeenCalledTimes(1) + const line = writeSpy.mock.calls[0][0] as string + // Why: relay.log correlation depends on a grep-stable + // " " shape (#7773). + expect(line).toMatch( + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z \[relay\] Grace started \(stdin ended\)\n$/ + ) + } finally { + writeSpy.mockRestore() + } + }) +}) diff --git a/src/relay/relay-diagnostic-log.ts b/src/relay/relay-diagnostic-log.ts new file mode 100644 index 000000000000..a42106101d9c --- /dev/null +++ b/src/relay/relay-diagnostic-log.ts @@ -0,0 +1,7 @@ +// Why: the relay daemon's stderr is redirected to relay.log on the remote +// host. Without timestamps, reconnect flaps in that log cannot be correlated +// with user activity or sleep/wake windows during diagnosis (#7773). Keep the +// format grep-stable: ISO timestamp, single space, then the original line. +export function relayLogLine(message: string): void { + process.stderr.write(`${new Date().toISOString()} ${message}\n`) +} diff --git a/src/relay/relay-handshake.ts b/src/relay/relay-handshake.ts index 6db263bcc929..fb64c57ec160 100644 --- a/src/relay/relay-handshake.ts +++ b/src/relay/relay-handshake.ts @@ -17,6 +17,7 @@ import { parseHandshakeMessage, type DecodedFrame } from './protocol' +import { relayLogLine } from './relay-diagnostic-log' // Why: a unique exit code reserved for the wire-level version-mismatch terminal // condition. The client (waitForSentinel + ssh.ts) maps this exit code to a @@ -132,22 +133,18 @@ function handleDaemonHandshakeFrame( try { msg = parseHandshakeMessage(frame.payload) } catch (err) { - process.stderr.write( - `[relay] Could not parse handshake: ${(err as Error).message}; closing socket\n` - ) + relayLogLine(`[relay] Could not parse handshake: ${(err as Error).message}; closing socket`) sock.destroy() return false } if (msg.type !== 'orca-relay-handshake') { - process.stderr.write( - `[relay] Unexpected handshake type from client: ${msg.type}; closing socket\n` - ) + relayLogLine(`[relay] Unexpected handshake type from client: ${msg.type}; closing socket`) sock.destroy() return false } if (msg.version !== launchVersion) { - process.stderr.write( - `[relay] Handshake mismatch: own=${launchVersion}, client=${msg.version}; closing socket\n` + relayLogLine( + `[relay] Handshake mismatch: own=${launchVersion}, client=${msg.version}; closing socket` ) try { sock.write( diff --git a/src/relay/relay.ts b/src/relay/relay.ts index 99225227903e..d47c20195829 100644 --- a/src/relay/relay.ts +++ b/src/relay/relay.ts @@ -37,6 +37,7 @@ import { RelayDispatcher } from './dispatcher' import { RelayContext } from './context' import { PtyHandler } from './pty-handler' import { FsHandler } from './fs-handler' +import { installRelayLogRotation } from './rotating-log-writer' import { GitHandler } from './git-handler' import { PreflightHandler } from './preflight-handler' import { ExternalAutomationsHandler } from './external-automations-handler' @@ -59,6 +60,7 @@ import { resolveOpenCodeSourceConfigDir, resolvePiSourceAgentDir } from './plugi import { detectPiAgentKindFromCommand } from '../shared/pi-agent-kind' import { resolveSetupAgentSequenceLaunchCommand } from '../shared/setup-agent-sequencing' import { pickRemoteCliEnv } from './remote-cli-env' +import { relayLogLine } from './relay-diagnostic-log' import { remoteCliRequestTimeoutMs } from './remote-cli-timeout' import { shouldReadRemoteCliStdin } from './remote-cli-stdin' @@ -113,6 +115,7 @@ function parseArgs(argv: string[]): { cliMode: boolean sockPath: string endpointDir?: string + logFile?: string } { let graceTimeMs = DEFAULT_GRACE_MS let connectMode = false @@ -120,6 +123,7 @@ function parseArgs(argv: string[]): { let cliMode = false let sockPath = '' let endpointDir: string | undefined + let logFile: string | undefined for (let i = 2; i < argv.length; i++) { if (argv[i] === '--grace-time' && argv[i + 1]) { const parsed = Number.parseInt(argv[i + 1], 10) @@ -142,12 +146,15 @@ function parseArgs(argv: string[]): { } else if (argv[i] === '--endpoint-dir' && argv[i + 1]) { endpointDir = argv[i + 1] i++ + } else if (argv[i] === '--log-file' && argv[i + 1]) { + logFile = argv[i + 1] + i++ } } if (!sockPath) { sockPath = join(process.cwd(), SOCK_NAME) } - return { graceTimeMs, connectMode, detached, cliMode, sockPath, endpointDir } + return { graceTimeMs, connectMode, detached, cliMode, sockPath, endpointDir, logFile } } // ── Connect mode ───────────────────────────────────────────────────── @@ -317,7 +324,7 @@ async function readOrcaCliStdin(): Promise { // ── Normal mode ────────────────────────────────────────────────────── async function main(): Promise { - const { graceTimeMs, connectMode, detached, cliMode, sockPath, endpointDir } = parseArgs( + const { graceTimeMs, connectMode, detached, cliMode, sockPath, endpointDir, logFile } = parseArgs( process.argv ) @@ -331,6 +338,13 @@ async function main(): Promise { return } + // Why: only the long-lived detached daemon accumulates relay.log; --connect + // bridges and --orca-cli are short-lived and already returned above. Route all + // relay logging through a size-capped rotator so relay.log can't grow forever. + if (detached && logFile) { + installRelayLogRotation(logFile) + } + let ownsSocketPath = false let ownedSocketIdentity: SocketIdentity | null = null const ownsCurrentSocketPath = (): boolean => { @@ -358,13 +372,13 @@ async function main(): Promise { // would risk silent data corruption or zombie PTYs. We log for diagnostics // and then exit so the client can detect the disconnect and reconnect cleanly. process.on('uncaughtException', (err) => { - process.stderr.write(`[relay] Uncaught exception: ${err.message}\n${err.stack}\n`) + relayLogLine(`[relay] Uncaught exception: ${err.message}\n${err.stack}`) cleanupOwnedSocket() process.exit(1) }) process.on('unhandledRejection', (reason) => { - process.stderr.write(`[relay] Unhandled rejection: ${reason}\n`) + relayLogLine(`[relay] Unhandled rejection: ${reason}`) }) // Why: stdoutAlive tracks whether process.stdout is still writable. @@ -453,10 +467,7 @@ async function main(): Promise { const ptyHandler = new PtyHandler(dispatcher, graceTimeMs) const fsHandler = new FsHandler(dispatcher, context) - // Why: GitHandler registers its own request handlers on construction, - // so we hold the reference only for potential future disposal. - const _gitHandler = new GitHandler(dispatcher, context) - void _gitHandler + const gitHandler = new GitHandler(dispatcher, context) const _preflightHandler = new PreflightHandler(dispatcher) const _externalAutomationsHandler = new ExternalAutomationsHandler(dispatcher) @@ -529,8 +540,8 @@ async function main(): Promise { try { await hookServer.start({ publishEndpoint: false }) } catch (err) { - process.stderr.write( - `[relay] agent-hook server failed to start: ${err instanceof Error ? err.message : String(err)}\n` + relayLogLine( + `[relay] agent-hook server failed to start: ${err instanceof Error ? err.message : String(err)}` ) } @@ -688,7 +699,7 @@ async function main(): Promise { function cancelGrace(reason: string): void { if (ptyHandler.graceTimerActive) { - process.stderr.write(`[relay] Grace canceled: ${reason}\n`) + relayLogLine(`[relay] Grace canceled: ${reason}`) } graceDeadlineAt = null graceReason = null @@ -704,8 +715,8 @@ async function main(): Promise { hasAcceptedSocketClient = true acceptedSocketConnections++ - process.stderr.write( - `[relay] Socket client accepted (clients=${socketClients.size + 1}, accepted=${acceptedSocketConnections})\n` + relayLogLine( + `[relay] Socket client accepted (clients=${socketClients.size + 1}, accepted=${acceptedSocketConnections})` ) cancelGrace('socket client accepted') @@ -779,7 +790,7 @@ async function main(): Promise { if (clientId !== undefined) { dispatcher.detachClient(clientId) } - process.stderr.write(`[relay] Socket client closed (clients=${socketClients.size})\n`) + relayLogLine(`[relay] Socket client closed (clients=${socketClients.size})`) if (!stdoutAlive && socketClients.size === 0) { startGrace('socket client closed') } @@ -821,9 +832,9 @@ async function main(): Promise { ownsSocketPath = true ownedSocketIdentity = readSocketIdentity(sockPath) server.on('error', (err) => { - process.stderr.write(`[relay] Socket server error: ${err.message}\n`) + relayLogLine(`[relay] Socket server error: ${err.message}`) }) - process.stderr.write(`[relay] Socket server listening: ${sockPath}\n`) + relayLogLine(`[relay] Socket server listening: ${sockPath}`) resolve() } @@ -831,11 +842,11 @@ async function main(): Promise { removeStartupListeners() restoreUmask() if (err.code === 'EADDRINUSE') { - process.stderr.write( - `[relay] Socket path already in use: ${sockPath}; another relay is likely active. Use --connect instead of starting a new daemon.\n` + relayLogLine( + `[relay] Socket path already in use: ${sockPath}; another relay is likely active. Use --connect instead of starting a new daemon.` ) } else { - process.stderr.write(`[relay] Socket server error before listen: ${err.message}\n`) + relayLogLine(`[relay] Socket server error before listen: ${err.message}`) } reject(err) } @@ -903,9 +914,7 @@ async function main(): Promise { failInitial(err) return } - process.stderr.write( - `[relay] Removed stale socket at ${sockPath} and retrying listen\n` - ) + relayLogLine(`[relay] Removed stale socket at ${sockPath} and retrying listen`) removeStartupListeners() listenForStartupError(failInitial) }) @@ -958,11 +967,11 @@ async function main(): Promise { : graceTimeMs graceDeadlineAt = timeoutMs === 0 ? null : Date.now() + timeoutMs graceReason = reason - process.stderr.write( - `[relay] Grace started (${reason}): timeoutMs=${timeoutMs}, startupEmptyDetached=${startupEmptyDetached}, ptys=${ptyHandler.activePtyCount}, clients=${socketClients.size}\n` + relayLogLine( + `[relay] Grace started (${reason}): timeoutMs=${timeoutMs}, startupEmptyDetached=${startupEmptyDetached}, ptys=${ptyHandler.activePtyCount}, clients=${socketClients.size}` ) ptyHandler.startGraceTimer(() => { - process.stderr.write(`[relay] Grace expired (${reason}); shutting down\n`) + relayLogLine(`[relay] Grace expired (${reason}); shutting down`) shutdown() }, timeoutMs) } @@ -1006,14 +1015,15 @@ async function main(): Promise { } function shutdown(): void { - process.stderr.write( - `[relay] Shutdown: ptys=${ptyHandler.activePtyCount}, clients=${socketClients.size}, ownsSocket=${ownsSocketPath}\n` + relayLogLine( + `[relay] Shutdown: ptys=${ptyHandler.activePtyCount}, clients=${socketClients.size}, ownsSocket=${ownsSocketPath}` ) graceDeadlineAt = null graceReason = null dispatcher.dispose() ptyHandler.dispose() fsHandler.dispose() + gitHandler.dispose() hookServer.stop() // Why: Node's Unix server.close() can unlink the listen path. If the path // was externally removed and rebound by a newer relay, closing this older @@ -1034,10 +1044,10 @@ async function main(): Promise { // window — a reconnecting client can then bridge to the live relay via // --connect and reattach to the still-running PTY sessions. process.on('SIGHUP', () => { - process.stderr.write('[relay] Received SIGHUP (SSH session dropped), ignoring\n') + relayLogLine('[relay] Received SIGHUP (SSH session dropped), ignoring') }) process.on('exit', (code) => { - process.stderr.write(`[relay] Process exiting with code ${code}\n`) + relayLogLine(`[relay] Process exiting with code ${code}`) }) // Signal readiness to the client — the client watches for this exact @@ -1059,8 +1069,8 @@ function cleanupSocket(sockPath: string): void { } void main().catch((err) => { - process.stderr.write( - `[relay] Fatal startup error: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n` + relayLogLine( + `[relay] Fatal startup error: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}` ) process.exit(1) }) diff --git a/src/relay/remote-cli-env.test.ts b/src/relay/remote-cli-env.test.ts index 844055a832c1..1546230a5dd3 100644 --- a/src/relay/remote-cli-env.test.ts +++ b/src/relay/remote-cli-env.test.ts @@ -7,6 +7,8 @@ describe('pickRemoteCliEnv', () => { pickRemoteCliEnv({ ORCA_TERMINAL_HANDLE: 'term_ssh', ORCA_WORKTREE_ID: 'repo::remote', + ORCA_PANE_KEY: 'pane-1', + ORCA_WORKSPACE_ID: 'workspace-1', ORCA_USER_DATA_PATH: '/tmp/orca', PATH: '/usr/bin', SECRET_TOKEN: 'nope' @@ -14,6 +16,8 @@ describe('pickRemoteCliEnv', () => { ).toEqual({ ORCA_TERMINAL_HANDLE: 'term_ssh', ORCA_WORKTREE_ID: 'repo::remote', + ORCA_PANE_KEY: 'pane-1', + ORCA_WORKSPACE_ID: 'workspace-1', ORCA_USER_DATA_PATH: '/tmp/orca', PATH: '/usr/bin' }) diff --git a/src/relay/remote-cli-env.ts b/src/relay/remote-cli-env.ts index 360b6074b9a8..d8bc800c6602 100644 --- a/src/relay/remote-cli-env.ts +++ b/src/relay/remote-cli-env.ts @@ -3,6 +3,8 @@ export function pickRemoteCliEnv(env: NodeJS.ProcessEnv): Record for (const key of [ 'ORCA_TERMINAL_HANDLE', 'ORCA_WORKTREE_ID', + 'ORCA_PANE_KEY', + 'ORCA_WORKSPACE_ID', 'ORCA_USER_DATA_PATH', 'PATH', 'Path' diff --git a/src/relay/remote-cli-stdin.test.ts b/src/relay/remote-cli-stdin.test.ts index 62fde790a2f9..494ad94e5d5b 100644 --- a/src/relay/remote-cli-stdin.test.ts +++ b/src/relay/remote-cli-stdin.test.ts @@ -15,4 +15,16 @@ describe('shouldReadRemoteCliStdin', () => { false ) }) + + it('reads stdin for *-stdin payload flags bridged to the full host CLI', () => { + expect(shouldReadRemoteCliStdin(['computer', 'action', '--app', 'Notes', '--text-stdin'])).toBe( + true + ) + expect(shouldReadRemoteCliStdin(['computer', 'action', '--app', 'Notes', '--text', 'hi'])).toBe( + false + ) + expect( + shouldReadRemoteCliStdin(['computer', 'action', '--app', 'Notes', '--text-stdin', '--help']) + ).toBe(false) + }) }) diff --git a/src/relay/remote-cli-stdin.ts b/src/relay/remote-cli-stdin.ts index 23ca208978ea..f9ab8c56da87 100644 --- a/src/relay/remote-cli-stdin.ts +++ b/src/relay/remote-cli-stdin.ts @@ -2,6 +2,12 @@ export function shouldReadRemoteCliStdin(argv: string[]): boolean { if (argv.includes('--help') || argv.includes('-h')) { return false } + // Why: computer-use style flags (`--text-stdin`, ...) declare a stdin + // payload directly in the flag name; the full-CLI bridge (#7716) must + // forward stdin for them the same way local shells provide it. + if (argv.some((part) => /^--[a-z0-9][a-z0-9-]*-stdin(?:=|$)/.test(part))) { + return true + } const commandPath = parseRemoteCliCommandPath(argv) if (!isLinearBodyWriteCommand(commandPath)) { return false diff --git a/src/relay/remote-cli-timeout.test.ts b/src/relay/remote-cli-timeout.test.ts index 58a62ac5a190..c09a0ccfeaaf 100644 --- a/src/relay/remote-cli-timeout.test.ts +++ b/src/relay/remote-cli-timeout.test.ts @@ -2,58 +2,64 @@ import { describe, expect, it } from 'vitest' import { remoteCliRequestTimeoutMs } from './remote-cli-timeout' describe('remoteCliRequestTimeoutMs', () => { - it('extends SSH remote CLI timeout for Linear issue context reads', () => { + it('gives Linear issue context reads the general CLI budget', () => { expect( remoteCliRequestTimeoutMs({ argv: ['linear', 'issue', 'ENG-123', '--json'] }) - ).toBe(120_000) + ).toBe(300_000) }) - it('extends the timeout when global flags appear before the Linear command', () => { + it('gives ordinary remote CLI requests the general CLI budget instead of the 30s relay default', () => { + // Why: mutation commands bridged through the full host CLI (worktree + // create, orchestration dispatch, ...) can legitimately exceed 30s. + expect(remoteCliRequestTimeoutMs({ argv: ['status'] })).toBe(300_000) + expect(remoteCliRequestTimeoutMs({ argv: ['worktree', 'create', '--repo', 'r'] })).toBe(300_000) + }) + + it('extends the timeout for wait-style commands', () => { + expect(remoteCliRequestTimeoutMs({ argv: ['terminal', 'wait', '--for', 'exit'] })).toBe(600_000) expect( remoteCliRequestTimeoutMs({ - argv: ['--json', 'linear', 'issue', 'ENG-123', '--workspace', 'workspace-1', '--full'] + argv: ['orchestration', 'check', '--wait', '--json'] }) - ).toBe(120_000) - }) - - it('extends SSH remote CLI timeout for Linear search', () => { + ).toBe(600_000) expect( remoteCliRequestTimeoutMs({ - argv: ['linear', 'search', 'auth', '--limit', '1'] + argv: ['orchestration', 'ask', '--to', 'term_x', '--question', 'ok?'] }) - ).toBe(120_000) + ).toBe(600_000) }) - it('extends the timeout when boolean flags appear between Linear and search', () => { + it('extends past an explicit --timeout-ms waiter budget', () => { + expect( + remoteCliRequestTimeoutMs({ + argv: ['terminal', 'wait', '--for', 'exit', '--timeout-ms', '1800000'] + }) + ).toBe(1_860_000) expect( remoteCliRequestTimeoutMs({ - argv: ['linear', '--json', 'search', 'auth', '--limit', '1'] + argv: ['orchestration', 'check', '--wait', '--timeout-ms=1800000'] }) - ).toBe(120_000) + ).toBe(1_860_000) }) - it('extends the timeout when boolean flags appear between Linear and issue', () => { + it('keeps the wait base budget when --timeout-ms is small', () => { expect( remoteCliRequestTimeoutMs({ - argv: ['linear', '--json', 'issue', 'ENG-123', '--full'] + argv: ['terminal', 'wait', '--for', 'exit', '--timeout-ms', '5000'] }) - ).toBe(120_000) + ).toBe(600_000) }) - it('extends SSH remote CLI timeout for Linear writes', () => { - for (const argv of [ - ['linear', 'status', 'set', 'ENG-123', '--to', 'Done'], - ['linear', 'comment', 'add', 'ENG-123', '--body', 'Done'], - ['linear', 'attach', 'ENG-123', '--url', 'https://example.invalid/review'], - ['linear', 'create', '--team', 'ENG', '--title', 'Follow up'] - ]) { - expect(remoteCliRequestTimeoutMs({ argv })).toBe(120_000) - } + it('does not treat a flag value named wait as a command path element', () => { + expect(remoteCliRequestTimeoutMs({ argv: ['terminal', 'read', '--terminal', 'wait'] })).toBe( + 300_000 + ) }) - it('keeps ordinary remote CLI requests on the relay default timeout', () => { - expect(remoteCliRequestTimeoutMs({ argv: ['status'] })).toBeUndefined() + it('falls back to the relay default for malformed argv', () => { + expect(remoteCliRequestTimeoutMs({ argv: 'status' })).toBeUndefined() + expect(remoteCliRequestTimeoutMs({})).toBeUndefined() }) }) diff --git a/src/relay/remote-cli-timeout.ts b/src/relay/remote-cli-timeout.ts index a7f73e0bf6c8..b28ef0ee313d 100644 --- a/src/relay/remote-cli-timeout.ts +++ b/src/relay/remote-cli-timeout.ts @@ -1,4 +1,13 @@ -const LINEAR_ISSUE_CONTEXT_TIMEOUT_MS = 120_000 +// Why: the host bridges the full Orca CLI over the relay (#7716), so mutation +// commands (worktree create, orchestration dispatch, Linear writes, ...) can +// legitimately outlive the relay's 30 s default request timeout. Long-poll +// commands carry their waiter budget in --timeout-ms; extend past it so the +// host-side CLI produces its proper timeout error instead of the relay +// cutting the request short. +const REMOTE_CLI_DEFAULT_TIMEOUT_MS = 5 * 60_000 +const REMOTE_CLI_WAIT_TIMEOUT_MS = 10 * 60_000 +const REMOTE_CLI_TIMEOUT_GRACE_MS = 60_000 + const REMOTE_TIMEOUT_BOOLEAN_FLAGS = new Set([ 'all', 'attachments', @@ -15,30 +24,54 @@ const REMOTE_TIMEOUT_BOOLEAN_FLAGS = new Set([ ]) export function remoteCliRequestTimeoutMs(params: Record): number | undefined { - return isLinearCliRequest(params) ? LINEAR_ISSUE_CONTEXT_TIMEOUT_MS : undefined + const argv = getStringArgv(params) + if (!argv) { + return undefined + } + const base = isWaitStyleCliRequest(argv) + ? REMOTE_CLI_WAIT_TIMEOUT_MS + : REMOTE_CLI_DEFAULT_TIMEOUT_MS + const explicit = parseTimeoutMsFlag(argv) + if (explicit !== null && explicit > 0) { + return Math.max(base, explicit + REMOTE_CLI_TIMEOUT_GRACE_MS) + } + return base } -function isLinearCliRequest(params: Record): boolean { - const argv = params.argv - if (!Array.isArray(argv) || !argv.every((part) => typeof part === 'string')) { - return false +function isWaitStyleCliRequest(argv: string[]): boolean { + if (argv.includes('--wait')) { + return true } const commandPath = parseRemoteCommandPath(argv) - return commandPath.some( - (part, index) => - part === 'linear' && isExtendedLinearCliCommand(commandPath.slice(index + 1, index + 4)) + return ( + (commandPath[0] === 'terminal' && commandPath[1] === 'wait') || + (commandPath[0] === 'orchestration' && commandPath[1] === 'ask') ) } -function isExtendedLinearCliCommand(command: string[]): boolean { - const [first, second] = command - if (first === 'issue' || first === 'search' || first === 'attach' || first === 'create') { - return true +function parseTimeoutMsFlag(argv: string[]): number | null { + for (let index = 0; index < argv.length; index += 1) { + const token = argv[index] + let raw: string | undefined + if (token === '--timeout-ms') { + raw = argv[index + 1] + } else if (token.startsWith('--timeout-ms=')) { + raw = token.slice('--timeout-ms='.length) + } else { + continue + } + const parsed = raw === undefined ? Number.NaN : Number(raw) + return Number.isFinite(parsed) ? parsed : null } - if (first === 'status' && second === 'set') { - return true + return null +} + +function getStringArgv(params: Record): string[] | null { + const argv = params.argv + if (!Array.isArray(argv) || !argv.every((part) => typeof part === 'string')) { + return null } - return first === 'comment' && second === 'add' + return argv } function parseRemoteCommandPath(argv: string[]): string[] { diff --git a/src/relay/rotating-log-writer.test.ts b/src/relay/rotating-log-writer.test.ts new file mode 100644 index 000000000000..61c988766bb8 --- /dev/null +++ b/src/relay/rotating-log-writer.test.ts @@ -0,0 +1,161 @@ +/** + * Regression: relay.log grows unbounded on long-lived relays. + * + * The relay is launched detached with `> relay.log 2>&1`, which truncates only + * at relaunch; a relay that stays up for days accumulates per-stream stderr + * lines forever. These tests assert the in-process rotator caps size, keeps one + * archived generation, and always leaves the CURRENT log at relay.log so the + * `tail -100 relay.log` diagnostics workflow keeps working. + */ +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' +import { mkdtempSync, mkdirSync, readFileSync, existsSync, statSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import * as path from 'node:path' +import { tmpdir } from 'node:os' + +import { RotatingLogWriter, installRelayLogRotation } from './rotating-log-writer' + +describe('RotatingLogWriter', () => { + let dir: string + let logPath: string + + beforeEach(() => { + dir = mkdtempSync(path.join(tmpdir(), 'relay-log-rot-')) + logPath = path.join(dir, 'relay.log') + }) + + afterEach(async () => { + await rm(dir, { recursive: true, force: true }) + }) + + it('rotates relay.log -> relay.log.1 at the cap and keeps the current log tail-able', () => { + const cap = 4 * 1024 + const writer = new RotatingLogWriter(logPath, cap) + try { + const line = `${'a'.repeat(200)}\n` + // Write well past the cap so at least one rotation happens. + for (let i = 0; i < 60; i += 1) { + writer.write(line) + } + + // Current log exists at relay.log (tail target) and is under the cap. + expect(existsSync(logPath)).toBe(true) + expect(statSync(logPath).size).toBeLessThanOrEqual(cap) + // Exactly one archived generation. + expect(existsSync(`${logPath}.1`)).toBe(true) + expect(existsSync(`${logPath}.2`)).toBe(false) + + // The most recent lines are in the current log (tail-ability). + writer.write('MARKER-LAST\n') + expect(readFileSync(logPath, 'utf-8')).toContain('MARKER-LAST') + } finally { + writer.dispose() + } + }) + + it('preserves pre-existing boot output already in relay.log (append, not truncate)', () => { + writeFileSync(logPath, 'BOOT-LINE-FROM-SHELL-REDIRECT\n') + const writer = new RotatingLogWriter(logPath, 1024 * 1024) + try { + writer.write('runtime line\n') + const contents = readFileSync(logPath, 'utf-8') + expect(contents).toContain('BOOT-LINE-FROM-SHELL-REDIRECT') + expect(contents).toContain('runtime line') + } finally { + writer.dispose() + } + }) + + it('bounds a single oversized log write and keeps its newest tail', () => { + const cap = 1024 + const writer = new RotatingLogWriter(logPath, cap) + try { + writer.write(`${'old'.repeat(1000)}LATEST-CONTEXT`) + expect(statSync(logPath).size).toBeLessThanOrEqual(cap) + expect(readFileSync(logPath, 'utf-8')).toContain('LATEST-CONTEXT') + } finally { + writer.dispose() + } + }) + + it('caps total footprint to ~2x maxBytes (current + one archive)', () => { + const cap = 8 * 1024 + const writer = new RotatingLogWriter(logPath, cap) + try { + const line = `${'z'.repeat(256)}\n` + for (let i = 0; i < 500; i += 1) { + writer.write(line) + } + const currentSize = statSync(logPath).size + const archiveSize = existsSync(`${logPath}.1`) ? statSync(`${logPath}.1`).size : 0 + // Never more than the current file + a single archived generation. + expect(currentSize).toBeLessThanOrEqual(cap) + expect(archiveSize).toBeLessThanOrEqual(cap) + expect(existsSync(`${logPath}.2`)).toBe(false) + } finally { + writer.dispose() + } + }) + + it('caps size via truncate-in-place when rename cannot succeed (Windows shell-handle case)', () => { + // Model the platform where renameSync fails (e.g. Windows, where the launch + // shell's own `1>relay.log` handle blocks renaming the live file): make the + // archive path a directory so renameSync(logPath, `${logPath}.1`) throws. + mkdirSync(`${logPath}.1`, { recursive: true }) + const cap = 4 * 1024 + const writer = new RotatingLogWriter(logPath, cap) + try { + const line = `${'q'.repeat(200)}\n` + for (let i = 0; i < 100; i += 1) { + writer.write(line) + } + // The cap still holds via truncate-in-place even though no archive was made. + expect(statSync(logPath).size).toBeLessThanOrEqual(cap) + writer.write('MARKER-LAST\n') + expect(readFileSync(logPath, 'utf-8')).toContain('MARKER-LAST') + } finally { + writer.dispose() + } + }) + + it('installRelayLogRotation routes stdout/stderr through the rotator and restores', () => { + const cap = 2 * 1024 + const { restore } = installRelayLogRotation(logPath, cap) + try { + process.stderr.write('via-stderr-line\n') + process.stdout.write('via-stdout-line\n') + expect(readFileSync(logPath, 'utf-8')).toContain('via-stderr-line') + expect(readFileSync(logPath, 'utf-8')).toContain('via-stdout-line') + } finally { + restore() + } + // After restore, process.stderr no longer targets the rotator file. Spy so + // the assertion write does not leak to the real test-runner stderr. + const sizeAfterRestore = statSync(logPath).size + const spy = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + try { + process.stderr.write('should-not-be-in-relay-log\n') + } finally { + spy.mockRestore() + } + expect(statSync(logPath).size).toBe(sizeAfterRestore) + }) + + it('leaves the original streams active when the log cannot be opened', () => { + mkdirSync(logPath) + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + try { + const { writer, restore } = installRelayLogRotation(logPath) + expect(writer.active).toBe(false) + process.stdout.write('stdout fallback\n') + process.stderr.write('stderr fallback\n') + expect(stdout).toHaveBeenCalledWith('stdout fallback\n') + expect(stderr).toHaveBeenCalledWith('stderr fallback\n') + restore() + } finally { + stdout.mockRestore() + stderr.mockRestore() + } + }) +}) diff --git a/src/relay/rotating-log-writer.ts b/src/relay/rotating-log-writer.ts new file mode 100644 index 000000000000..e685e6fd520e --- /dev/null +++ b/src/relay/rotating-log-writer.ts @@ -0,0 +1,174 @@ +// Size-capped, crash-safe rotation for the relay's diagnostic log. +// +// Why: the relay is launched detached with `> relay.log 2>&1`, which only +// truncates at relaunch — a long-lived relay's relay.log grows unbounded +// (per-stream stderr lines, reconnect flaps, etc.). Rotation must live in the +// relay process because it owns its own stderr; the shell redirect cannot cap +// size. Constraints honored: +// - keeps working when the launch fd is a pipe/redirect on Linux/macOS/Windows +// (append-only, no fd tricks; a rotation failure falls back to the prior fd); +// - the diagnostics tail (`tail -100 ~/.orca-remote/relay-*/relay.log`) keeps +// working because the CURRENT log is always at relay.log; +// - crash-safe: writes and rotation are guarded so logging never throws, and +// rotation renames (never deletes the live file) so no window loses logging. +import { closeSync, openSync, renameSync, statSync, writeSync } from 'node:fs' + +/** Default size cap before rotating relay.log → relay.log.1. 10 MB balances + * keeping enough history for diagnosis against bounding disk use on small + * remote hosts (e.g. a Raspberry Pi); one archived generation is kept. */ +export const DEFAULT_RELAY_LOG_MAX_BYTES = 10 * 1024 * 1024 + +type StreamWrite = typeof process.stderr.write + +export class RotatingLogWriter { + private readonly logPath: string + private readonly rotatedPath: string + private readonly maxBytes: number + private fd: number | null = null + private currentBytes = 0 + private failed = false + + constructor(logPath: string, maxBytes: number = DEFAULT_RELAY_LOG_MAX_BYTES) { + this.logPath = logPath + this.rotatedPath = `${logPath}.1` + this.maxBytes = maxBytes + this.open() + } + + private open(mode: 'a' | 'w' = 'a'): void { + try { + // 'a' preserves pre-JS boot output already in relay.log and keeps + // concurrent appends atomic; 'w' truncates in place (used as the rotation + // fallback when a rename cannot succeed — e.g. Windows, where the launch + // shell's own redirect handle blocks renaming the live file). + this.fd = openSync(this.logPath, mode) + try { + this.currentBytes = mode === 'w' ? 0 : statSync(this.logPath).size + } catch { + this.currentBytes = 0 + } + } catch { + // Cannot open the log file (permission/full disk): disable rotation and + // let callers fall back to the original stream. + this.failed = true + this.fd = null + } + } + + /** True when the writer is usable; false means fall back to raw stderr. */ + get active(): boolean { + return !this.failed && this.fd !== null + } + + write(chunk: string | Uint8Array): void { + if (!this.active || this.fd === null) { + return + } + const encoded = typeof chunk === 'string' ? Buffer.from(chunk, 'utf-8') : Buffer.from(chunk) + // Why: one pathological log write must not bypass the disk cap. Preserve + // the newest tail because it carries the most useful failure context. + const buf = + encoded.length > this.maxBytes ? encoded.subarray(encoded.length - this.maxBytes) : encoded + try { + // Rotate BEFORE writing when the incoming write would cross the cap, so a + // single large line still lands wholly in the fresh file. + if (this.currentBytes > 0 && this.currentBytes + buf.length > this.maxBytes) { + this.rotate() + } + writeSync(this.fd, buf) + this.currentBytes += buf.length + } catch { + // A write failure must never crash the relay; disable and fall back. + this.failed = true + this.closeQuietly() + } + } + + private rotate(): void { + if (this.fd !== null) { + closeSync(this.fd) + this.fd = null + } + let renamed = false + try { + // Preferred path: archive one generation. rename() replaces any existing + // relay.log.1 atomically on POSIX; the live file is renamed (never + // deleted) so no log window is lost, then we reopen a fresh relay.log. + renameSync(this.logPath, this.rotatedPath) + renamed = true + } catch { + // Why: on Windows the launch shell holds its own `1>relay.log` handle + // WITHOUT FILE_SHARE_DELETE, so renaming the live file fails (EPERM/EBUSY) + // — and a cross-device relay.log.1 would fail too. Fall back to truncating + // relay.log in place ('w') so the size cap STILL holds and we don't churn a + // failing rename on every subsequent line. The shell's fd keeps appending + // at its own offset, but the truncation bounds total growth. Trade-off: no + // archived generation on this platform/path. + } + // Successful rename → fresh append file (size 0). Failed rename → truncate. + this.open(renamed ? 'a' : 'w') + } + + private closeQuietly(): void { + if (this.fd !== null) { + try { + closeSync(this.fd) + } catch { + // best-effort + } + this.fd = null + } + } + + dispose(): void { + this.closeQuietly() + } +} + +/** + * Route process.stdout/stderr writes through a RotatingLogWriter that owns + * `logPath`. Returns a restore function. If the writer cannot open the file, + * the original streams are left untouched (logging still works, just uncapped). + */ +export function installRelayLogRotation( + logPath: string, + maxBytes: number = DEFAULT_RELAY_LOG_MAX_BYTES +): { writer: RotatingLogWriter; restore: () => void } { + const writer = new RotatingLogWriter(logPath, maxBytes) + const originalStdout = process.stdout.write.bind(process.stdout) + const originalStderr = process.stderr.write.bind(process.stderr) + + if (!writer.active) { + return { writer, restore: () => {} } + } + + const wrap = + (original: StreamWrite): StreamWrite => + (chunk: string | Uint8Array, encodingOrCb?: unknown, cb?: unknown): boolean => { + writer.write(chunk) + // Why: preserve the Writable.write callback contract so callers awaiting + // the write (rare, but e.g. flush-before-exit) are not left hanging. + const callback = typeof encodingOrCb === 'function' ? encodingOrCb : cb + if (typeof callback === 'function') { + ;(callback as (err?: Error | null) => void)(null) + } + // If the writer went inactive mid-run (write failure), fall back so logs + // are not silently dropped for the rest of the session. + if (!writer.active) { + return (original as (c: string | Uint8Array) => boolean)(chunk) + } + return true + } + + process.stdout.write = wrap(originalStdout as StreamWrite) as typeof process.stdout.write + process.stderr.write = wrap(originalStderr as StreamWrite) as typeof process.stderr.write + + return { + writer, + restore: () => { + process.stdout.write = originalStdout as typeof process.stdout.write + process.stderr.write = originalStderr as typeof process.stderr.write + writer.dispose() + } + } +} diff --git a/src/relay/wsl-agent-hook-relay.test.ts b/src/relay/wsl-agent-hook-relay.test.ts new file mode 100644 index 000000000000..c72f21462c88 --- /dev/null +++ b/src/relay/wsl-agent-hook-relay.test.ts @@ -0,0 +1,195 @@ +// Guest-side WSL hook relay pieces: host-given port/token binding with +// ephemeral fallback, and the shared endpoint-path contract. +import { createServer } from 'node:net' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { RelayAgentHookServer } from './agent-hook-server' +import { makePaneKey } from '../shared/stable-pane-id' +import { + sanitizeWslHookInstanceKey, + wslHookRelayEndpointDir, + wslHookRelayEndpointFilePath +} from '../shared/wsl-hook-relay-contract' + +const LEAF_ID = '22222222-2222-4222-8222-222222222222' +const PANE_KEY = makePaneKey('tab-2', LEAF_ID) + +// Parse an endpoint file tolerantly across platforms: POSIX writes `KEY=value`, +// Windows writes `set KEY=value`. Strips the optional `set ` prefix. +function parseEndpointFile(contents: string): Record { + const env: Record = {} + for (const rawLine of contents.split(/\r?\n/)) { + const line = rawLine.replace(/^set /, '') + const eq = line.indexOf('=') + if (eq > 0) { + env[line.slice(0, eq)] = line.slice(eq + 1) + } + } + return env +} + +describe('RelayAgentHookServer host-given coordinates (WSL relay)', () => { + let tmpDir: string + let server: RelayAgentHookServer | null + + beforeEach(() => { + tmpDir = mkdtempSync(join(tmpdir(), 'wsl-hook-relay-')) + server = null + }) + + afterEach(() => { + server?.stop() + rmSync(tmpDir, { recursive: true, force: true }) + }) + + it('binds the preferred port with the fixed token when the port is free', async () => { + const probe = createServer() + const freePort = await new Promise((resolve) => { + probe.listen(0, '127.0.0.1', () => { + const address = probe.address() + resolve(typeof address === 'object' && address ? address.port : 0) + }) + }) + await new Promise((resolve) => probe.close(() => resolve())) + + server = new RelayAgentHookServer({ + endpointDir: tmpDir, + token: 'host-issued-token', + preferredPort: freePort, + forward: () => {} + }) + await server.start() + + expect(server.getCoordinates().port).toBe(freePort) + expect(server.getCoordinates().token).toBe('host-issued-token') + expect(server.usedPortFallback).toBe(false) + }) + + it('falls back to an ephemeral port when the preferred port is occupied', async () => { + const occupant = createServer() + const occupiedPort = await new Promise((resolve) => { + occupant.listen(0, '127.0.0.1', () => { + const address = occupant.address() + resolve(typeof address === 'object' && address ? address.port : 0) + }) + }) + try { + server = new RelayAgentHookServer({ + endpointDir: tmpDir, + token: 'host-issued-token', + preferredPort: occupiedPort, + forward: () => {} + }) + await server.start() + + expect(server.usedPortFallback).toBe(true) + const bound = server.getCoordinates().port + expect(bound).toBeGreaterThan(0) + expect(bound).not.toBe(occupiedPort) + // Fallback still authenticates with the host-issued token. + expect(server.getCoordinates().token).toBe('host-issued-token') + } finally { + await new Promise((resolve) => occupant.close(() => resolve())) + } + }) + + it('keeps random-token ephemeral behavior when no coordinates are given (SSH shape)', async () => { + server = new RelayAgentHookServer({ endpointDir: tmpDir, forward: () => {} }) + await server.start() + expect(server.getCoordinates().port).toBeGreaterThan(0) + expect(server.getCoordinates().token).toMatch(/^[0-9a-f-]{36}$/) + expect(server.usedPortFallback).toBe(false) + }) + + it('rejects a wrong token but authenticates the host-issued fixed token', async () => { + const forward = vi.fn() + server = new RelayAgentHookServer({ endpointDir: tmpDir, token: 'host-issued-token', forward }) + await server.start() + const { port } = server.getCoordinates() + + const rejected = await fetch(`http://127.0.0.1:${port}/hook/claude`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-Orca-Agent-Hook-Token': 'wrong-token' }, + body: '{}' + }) + expect(rejected.status).toBe(403) + expect(forward).not.toHaveBeenCalled() + + const accepted = await fetch(`http://127.0.0.1:${port}/hook/claude`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Orca-Agent-Hook-Token': 'host-issued-token' + }, + body: JSON.stringify({ + paneKey: PANE_KEY, + payload: { hook_event_name: 'UserPromptSubmit', prompt: 'hi' } + }) + }) + expect(accepted.status).toBe(204) + expect(forward).toHaveBeenCalledTimes(1) + expect(forward.mock.calls[0][0].paneKey).toBe(PANE_KEY) + }) + + it('publishes the fallback port + fixed token into the endpoint file after EADDRINUSE', async () => { + const occupant = createServer() + const occupiedPort = await new Promise((resolve) => { + occupant.listen(0, '127.0.0.1', () => { + const address = occupant.address() + resolve(typeof address === 'object' && address ? address.port : 0) + }) + }) + try { + server = new RelayAgentHookServer({ + endpointDir: tmpDir, + token: 'host-issued-token', + preferredPort: occupiedPort, + forward: () => {} + }) + await server.start() + + expect(server.usedPortFallback).toBe(true) + const { port, token, endpointFilePath } = server.getCoordinates() + expect(port).not.toBe(occupiedPort) + + // The endpoint file is the client re-coordination contract: surviving + // agents re-source it and MUST see the actual fallback port, not the + // occupied preferred port. + const published = parseEndpointFile(readFileSync(endpointFilePath, 'utf8')) + expect(published.ORCA_AGENT_HOOK_PORT).toBe(String(port)) + expect(published.ORCA_AGENT_HOOK_PORT).not.toBe(String(occupiedPort)) + expect(published.ORCA_AGENT_HOOK_TOKEN).toBe(token) + expect(published.ORCA_AGENT_HOOK_TOKEN).toBe('host-issued-token') + } finally { + await new Promise((resolve) => occupant.close(() => resolve())) + } + }) +}) + +describe('wsl hook relay endpoint contract', () => { + it('derives the endpoint dir from guest home and the restart-stable instance key', () => { + expect(wslHookRelayEndpointDir('/home/u', 'abc123')).toBe( + '/home/u/.orca-wsl/agent-hooks/instance-abc123' + ) + expect(wslHookRelayEndpointDir('/home/u/', 'abc123')).toBe( + '/home/u/.orca-wsl/agent-hooks/instance-abc123' + ) + }) + + it('names the guest endpoint file endpoint.env regardless of host platform', () => { + expect(wslHookRelayEndpointFilePath('/home/u', 'k1')).toBe( + '/home/u/.orca-wsl/agent-hooks/instance-k1/endpoint.env' + ) + }) + + it('sanitizes instance keys to a shell/path-inert alphabet', () => { + expect(sanitizeWslHookInstanceKey('ABCdef012')).toBe('abcdef012') + expect(sanitizeWslHookInstanceKey(' a-1 ')).toBe('a-1') + expect(sanitizeWslHookInstanceKey('bad key$')).toBeNull() + expect(sanitizeWslHookInstanceKey('')).toBeNull() + expect(sanitizeWslHookInstanceKey(undefined)).toBeNull() + }) +}) diff --git a/src/relay/wsl-agent-hook-relay.ts b/src/relay/wsl-agent-hook-relay.ts new file mode 100644 index 000000000000..3411cb690e6d --- /dev/null +++ b/src/relay/wsl-agent-hook-relay.ts @@ -0,0 +1,114 @@ +#!/usr/bin/env node +// Guest-resident WSL agent-hook relay (STA-1515). Runs inside a WSL distro, +// binds a loopback hook receiver on the very port the Windows host issued +// (free under NAT — that port only exists Windows-side), and forwards every +// parsed hook envelope to Orca over this process's own stdin/stdout using the +// framed JSON-RPC protocol the SSH relay already speaks. Also hosts the +// home-scoped fs bridge the host uses to install hook configs into the guest. +// +// Lifecycle: dies when stdin closes. A lingering guest listener would let +// WSL's Windows→WSL forwarder grab the freed Windows-side port and blackhole +// stale Windows-side hook posts — so unlike the SSH relay there is no grace +// period and no daemon socket. +import { homedir } from 'node:os' + +import { RELAY_SENTINEL } from './protocol' +import { RelayDispatcher } from './dispatcher' +import { RelayAgentHookServer } from './agent-hook-server' +import { registerWslHookFsHandlers } from './wsl-hook-fs-bridge' +import { + AGENT_HOOK_NOTIFICATION_METHOD, + AGENT_HOOK_REQUEST_REPLAY_METHOD +} from '../shared/agent-hook-relay' +import { + sanitizeWslHookInstanceKey, + WSL_HOOK_RELAY_INSTANCE_ENV, + wslHookRelayEndpointDir +} from '../shared/wsl-hook-relay-contract' + +async function main(): Promise { + const windowsPort = Number(process.env.ORCA_AGENT_HOOK_PORT ?? '') + const token = process.env.ORCA_AGENT_HOOK_TOKEN ?? '' + if (!Number.isInteger(windowsPort) || windowsPort <= 0 || token.length === 0) { + process.stderr.write('[wsl-hook-relay] missing ORCA_AGENT_HOOK_PORT/TOKEN in env\n') + process.exit(1) + } + + let stdoutAlive = true + const dispatcher = new RelayDispatcher((data) => { + if (!stdoutAlive) { + return + } + return process.stdout.write(data) + }) + + // Why: restart-stable instance key keeps the endpoint file at one path + // across app restarts so surviving agents re-coordinate off its rewrite. + const instanceKey = + sanitizeWslHookInstanceKey(process.env[WSL_HOOK_RELAY_INSTANCE_ENV]) ?? `port${windowsPort}` + const hookServer = new RelayAgentHookServer({ + endpointDir: wslHookRelayEndpointDir(homedir(), instanceKey), + token, + preferredPort: windowsPort, + forward: (envelope) => + dispatcher.notify( + AGENT_HOOK_NOTIFICATION_METHOD, + envelope as unknown as Record + ) + }) + + dispatcher.onRequest(AGENT_HOOK_REQUEST_REPLAY_METHOD, async () => ({ + replayed: hookServer.replayCachedPayloadsForPanes() + })) + registerWslHookFsHandlers(dispatcher, homedir(), () => ({ + portFallback: hookServer.usedPortFallback, + boundPort: hookServer.getCoordinates().port + })) + + try { + await hookServer.start() + } catch (err) { + process.stderr.write( + `[wsl-hook-relay] hook server bind failed: ${err instanceof Error ? err.message : String(err)}\n` + ) + process.exit(1) + } + if (hookServer.usedPortFallback) { + // Why: diagnosable breadcrumb — hook clients are fail-open silent, the + // relay must not be. Fallback is expected under mirrored networking. + process.stderr.write( + `[wsl-hook-relay] port ${windowsPort} occupied; bound ${hookServer.getCoordinates().port} (endpoint-file re-coordination)\n` + ) + } + + const shutdown = (): void => { + stdoutAlive = false + dispatcher.dispose() + hookServer.stop() + process.exit(0) + } + + process.stdin.on('data', (chunk: Buffer) => dispatcher.feed(chunk)) + process.stdin.on('end', shutdown) + process.stdin.on('error', shutdown) + process.stdout.on('error', shutdown) + process.on('SIGTERM', shutdown) + process.on('SIGINT', shutdown) + // Why: same posture as the SSH relay — an uncaught exception may leave + // broken invariants, so exit and let the host manager respawn a clean + // relay; a stray rejection is logged and survived (hook delivery must not + // die for a non-fatal async error). + process.on('uncaughtException', (err) => { + process.stderr.write(`[wsl-hook-relay] uncaught exception: ${err.message}\n`) + process.exit(1) + }) + process.on('unhandledRejection', (reason) => { + process.stderr.write(`[wsl-hook-relay] unhandled rejection: ${String(reason)}\n`) + }) + + // Signal readiness — the host watches for this exact string before + // sending framed data (same contract as the SSH relay). + process.stdout.write(RELAY_SENTINEL) +} + +void main() diff --git a/src/relay/wsl-hook-fs-bridge.test.ts b/src/relay/wsl-hook-fs-bridge.test.ts new file mode 100644 index 000000000000..f656b4aa3bdb --- /dev/null +++ b/src/relay/wsl-hook-fs-bridge.test.ts @@ -0,0 +1,143 @@ +// Why: the fs bridge is POSIX-by-design — it resolves every path with +// `posix.resolve` against a POSIX guest home. On win32 `posix.resolve` of a +// Windows tmpdir yields an invalid path, so the whole suite is skipped there +// (the bridge only ever runs inside a Linux WSL guest). +import { mkdtempSync, rmSync, statSync } from 'node:fs' +import { posix } from 'node:path' +import { tmpdir } from 'node:os' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +import { registerWslHookFsHandlers } from './wsl-hook-fs-bridge' +import type { MethodHandler, RelayDispatcher, RequestContext } from './dispatcher' +import { WSL_HOOK_FS_METHODS, type WslFsResult } from '../shared/wsl-hook-relay-contract' + +describe.skipIf(process.platform === 'win32')('registerWslHookFsHandlers (WSL fs bridge)', () => { + let home: string + let handlers: Map + const context: RequestContext = { clientId: 1, isStale: () => false } + + const call = async >( + method: string, + params: Record = {} + ): Promise> => { + const handler = handlers.get(method) + if (!handler) { + throw new Error(`no handler registered for ${method}`) + } + return (await handler(params, context)) as WslFsResult + } + + beforeEach(() => { + home = mkdtempSync(posix.join(tmpdir(), 'wsl-fs-home-')) + handlers = new Map() + // Capture handlers from a minimal fake dispatcher — registration only ever + // calls onRequest, so a real RelayDispatcher is unnecessary. + const dispatcher = { + onRequest: (method: string, handler: MethodHandler) => { + handlers.set(method, handler) + } + } as unknown as RelayDispatcher + registerWslHookFsHandlers(dispatcher, home, () => ({ fallbackPort: 4321 })) + }) + + afterEach(() => { + rmSync(home, { recursive: true, force: true }) + }) + + it('returns the resolved home and merges linkStatus extras', async () => { + const result = await call<{ home: string; fallbackPort: number }>(WSL_HOOK_FS_METHODS.home) + expect(result).toMatchObject({ ok: true, home: posix.resolve(home), fallbackPort: 4321 }) + }) + + it('round-trips writeFile + readFile inside home', async () => { + const path = posix.join(home, 'note.txt') + const write = await call(WSL_HOOK_FS_METHODS.writeFile, { path, content: 'hello guest' }) + expect(write.ok).toBe(true) + const read = await call<{ content: string }>(WSL_HOOK_FS_METHODS.readFile, { path }) + expect(read).toEqual({ ok: true, content: 'hello guest' }) + }) + + it('refuses writeFile to an absolute path outside home', async () => { + const result = await call(WSL_HOOK_FS_METHODS.writeFile, { + path: '/etc/orca-evil.txt', + content: 'x' + }) + expect(result).toMatchObject({ ok: false, errno: 'EACCES' }) + }) + + it('refuses a `..` traversal that escapes home', async () => { + const result = await call(WSL_HOOK_FS_METHODS.writeFile, { + path: `${home}/../escape.txt`, + content: 'x' + }) + expect(result).toMatchObject({ ok: false, errno: 'EACCES' }) + }) + + it('refuses a sibling dir that shares home as a string prefix', async () => { + // `${home}-evil/x` starts with homeRoot but not with `${homeRoot}/`. + const result = await call(WSL_HOOK_FS_METHODS.writeFile, { + path: `${home}-evil/x.txt`, + content: 'x' + }) + expect(result).toMatchObject({ ok: false, errno: 'EACCES' }) + }) + + it('reports ENOENT for a missing file inside home', async () => { + const result = await call(WSL_HOOK_FS_METHODS.readFile, { + path: posix.join(home, 'does-not-exist.txt') + }) + expect(result).toMatchObject({ ok: false, errno: 'ENOENT' }) + }) + + it('allows readdir existence probes on an ancestor of home and on /', async () => { + const ancestor = await call<{ entries: { filename: string }[] }>(WSL_HOOK_FS_METHODS.readdir, { + path: posix.dirname(home) + }) + expect(ancestor.ok).toBe(true) + const root = await call<{ entries: { filename: string }[] }>(WSL_HOOK_FS_METHODS.readdir, { + path: '/' + }) + expect(root.ok).toBe(true) + }) + + it('refuses readdir on a non-ancestor dir outside home', async () => { + const result = await call(WSL_HOOK_FS_METHODS.readdir, { path: '/etc' }) + expect(result).toMatchObject({ ok: false, errno: 'EACCES' }) + }) + + it('refuses rename crossing the home boundary in either direction', async () => { + const inside = posix.join(home, 'src.txt') + await call(WSL_HOOK_FS_METHODS.writeFile, { path: inside, content: 'x' }) + const outbound = await call(WSL_HOOK_FS_METHODS.rename, { + src: inside, + dst: '/etc/orca-evil.txt' + }) + expect(outbound).toMatchObject({ ok: false, errno: 'EACCES' }) + const inbound = await call(WSL_HOOK_FS_METHODS.rename, { + src: '/etc/passwd', + dst: posix.join(home, 'stolen.txt') + }) + expect(inbound).toMatchObject({ ok: false, errno: 'EACCES' }) + }) + + it('refuses a relative path (resolved against cwd, which lands outside home)', async () => { + const result = await call(WSL_HOOK_FS_METHODS.readFile, { path: 'foo.txt' }) + expect(result).toMatchObject({ ok: false, errno: 'EACCES' }) + }) + + it('refuses mkdir outside home and creates a dir inside home', async () => { + const outside = await call(WSL_HOOK_FS_METHODS.mkdir, { path: '/etc/orca-evil-dir' }) + expect(outside).toMatchObject({ ok: false, errno: 'EACCES' }) + const dir = posix.join(home, 'newdir') + const inside = await call(WSL_HOOK_FS_METHODS.mkdir, { path: dir }) + expect(inside.ok).toBe(true) + expect(statSync(dir).isDirectory()).toBe(true) + }) + + it('fails without crashing when chmod gets a non-numeric mode', async () => { + const path = posix.join(home, 'perm.txt') + await call(WSL_HOOK_FS_METHODS.writeFile, { path, content: 'x' }) + const result = await call(WSL_HOOK_FS_METHODS.chmod, { path, mode: 'not-a-number' }) + expect(result.ok).toBe(false) + }) +}) diff --git a/src/relay/wsl-hook-fs-bridge.ts b/src/relay/wsl-hook-fs-bridge.ts new file mode 100644 index 000000000000..3ebb6047b1be --- /dev/null +++ b/src/relay/wsl-hook-fs-bridge.ts @@ -0,0 +1,153 @@ +// Guest-side fs bridge for the WSL agent-hook relay. Exposes the handful of +// home-scoped file operations the shared remote hook installers need, as +// JSON-RPC request handlers over the relay's stdio channel — so the host +// installs hook configs/scripts into the distro without per-file wsl.exe +// spawns (load-sensitive, see docs/agent-status-over-wsl.md). +import { promises as fs } from 'node:fs' +import { posix } from 'node:path' + +import type { RelayDispatcher } from './dispatcher' +import { + WSL_HOOK_FS_METHODS, + type WslFsFailure, + type WslFsResult +} from '../shared/wsl-hook-relay-contract' + +function failure(err: unknown): WslFsFailure { + const e = err as NodeJS.ErrnoException + return { ok: false, errno: e?.code ?? 'EUNKNOWN', message: e?.message ?? String(err) } +} + +export function registerWslHookFsHandlers( + dispatcher: RelayDispatcher, + home: string, + // Why: the home request doubles as the connect handshake; link diagnostics + // (port fallback) ride it so the host can breadcrumb them. + linkStatus?: () => Record +): void { + // Why: the bridge exists solely to write agent hook configs into the guest + // user's home. Refusing paths outside it bounds the blast radius of a + // compromised host-side caller to what hook installation touches anyway. + // The bound is lexical (symlinks inside home are followed) — acceptable + // because the only caller is the host-owned stdio channel, never an + // agent-reachable surface. + const homeRoot = posix.resolve(home) + const resolveRaw = (rawPath: unknown): string => { + if (typeof rawPath !== 'string' || rawPath.length === 0) { + throw Object.assign(new Error('invalid path'), { code: 'EINVAL' }) + } + return posix.resolve(rawPath) + } + const scoped = (rawPath: unknown): string => { + const resolved = resolveRaw(rawPath) + if (resolved !== homeRoot && !resolved.startsWith(`${homeRoot}/`)) { + throw Object.assign(new Error(`path outside home: ${resolved}`), { code: 'EACCES' }) + } + return resolved + } + // Why: the installers' mkdir-p walks top-down from `/`, probing every + // ancestor of home with readdir before it ever creates a dir. Allow + // read-only existence probes on those ancestors; everything else stays + // home-scoped. + const scopedProbe = (rawPath: unknown): string => { + const resolved = resolveRaw(rawPath) + if (resolved === '/' || homeRoot === resolved || homeRoot.startsWith(`${resolved}/`)) { + return resolved + } + return scoped(rawPath) + } + + dispatcher.onRequest( + WSL_HOOK_FS_METHODS.home, + async (): Promise> => { + return { ok: true, home: homeRoot, ...linkStatus?.() } + } + ) + + dispatcher.onRequest( + WSL_HOOK_FS_METHODS.readFile, + async (params): Promise> => { + try { + const content = await fs.readFile(scoped(params.path), 'utf8') + return { ok: true, content } + } catch (err) { + return failure(err) + } + } + ) + + dispatcher.onRequest(WSL_HOOK_FS_METHODS.writeFile, async (params): Promise => { + try { + const mode = typeof params.mode === 'number' ? params.mode : undefined + await fs.writeFile(scoped(params.path), String(params.content ?? ''), { + encoding: 'utf8', + mode + }) + return { ok: true } + } catch (err) { + return failure(err) + } + }) + + dispatcher.onRequest( + WSL_HOOK_FS_METHODS.stat, + async (params): Promise> => { + try { + const stats = await fs.stat(scoped(params.path)) + return { ok: true, mode: stats.mode } + } catch (err) { + return failure(err) + } + } + ) + + dispatcher.onRequest(WSL_HOOK_FS_METHODS.rename, async (params): Promise => { + try { + // Why: POSIX rename overwrites atomically — exactly the OpenSSH + // overwrite-rename semantics the installers prefer. + await fs.rename(scoped(params.src), scoped(params.dst)) + return { ok: true } + } catch (err) { + return failure(err) + } + }) + + dispatcher.onRequest(WSL_HOOK_FS_METHODS.unlink, async (params): Promise => { + try { + await fs.unlink(scoped(params.path)) + return { ok: true } + } catch (err) { + return failure(err) + } + }) + + dispatcher.onRequest(WSL_HOOK_FS_METHODS.chmod, async (params): Promise => { + try { + await fs.chmod(scoped(params.path), Number(params.mode)) + return { ok: true } + } catch (err) { + return failure(err) + } + }) + + dispatcher.onRequest( + WSL_HOOK_FS_METHODS.readdir, + async (params): Promise> => { + try { + const names = await fs.readdir(scopedProbe(params.path)) + return { ok: true, entries: names.map((filename) => ({ filename })) } + } catch (err) { + return failure(err) + } + } + ) + + dispatcher.onRequest(WSL_HOOK_FS_METHODS.mkdir, async (params): Promise => { + try { + await fs.mkdir(scoped(params.path)) + return { ok: true } + } catch (err) { + return failure(err) + } + }) +} diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index cb881ea97d95..eeaff50abb56 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -7,6 +7,7 @@ import { useMemo, useRef, useState, + useSyncExternalStore, type SetStateAction } from 'react' import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' @@ -64,6 +65,7 @@ import { onOnboardingReopened } from './components/onboarding/show-onboarding-ev import { shouldShowOnboarding } from './components/onboarding/should-show-onboarding' import { MarkdownTemplatePicker } from './components/editor/MarkdownTemplatePicker' import { FloatingTerminalToggleButton } from './components/floating-terminal/FloatingTerminalToggleButton' +import { OrcaProfileSwitcher } from './components/orca-profiles/OrcaProfileSwitcher' import { TOGGLE_FLOATING_TERMINAL_EVENT, requestFloatingTerminalOpenMaximized @@ -128,6 +130,8 @@ import { } from './startup/startup-diagnostics' import { shouldRenderPetOverlay } from './components/pet/pet-overlay-visibility' import { applyDocumentTheme } from './lib/document-theme' +import { getSystemPrefersDark } from './lib/terminal-theme' +import { publishTerminalViewAttributesAtAppStart } from './components/terminal-pane/terminal-appearance' import { isEditableTarget } from './lib/editable-target' import { getSelectedTextForFileSearch } from './lib/file-search-selection' import { useShortcutLabel } from './hooks/useShortcutLabel' @@ -169,6 +173,15 @@ import { showTerminalShortcutCaptureNotification } from '@/lib/terminal-shortcut import { resolveMountedLazyModalIds, type LazyModalId } from './lazy-modal-mount-state' import { translate } from '@/i18n/i18n' import PinnedTabCloseDialog from './components/terminal-pane/PinnedTabCloseDialog' +import { + hasRequestedBackgroundTerminalWorktreeMount, + subscribeBackgroundTerminalWorktreeMountRequests +} from './components/terminal/background-terminal-worktree-mount' + +// Why: agents alive during a hard kill (crash, forced update install) need a +// reasonably fresh resume record on disk; one minute bounds the lost window +// without measurable per-tick cost (the capture skips unchanged records). +const SLEEPING_AGENT_RESUME_CAPTURE_INTERVAL_MS = 60_000 const isMac = navigator.userAgent.includes('Mac') const isWindows = !isMac && navigator.userAgent.includes('Windows') @@ -418,6 +431,7 @@ function App(): React.JSX.Element { fetchFolderWorkspacesForAllHosts: s.fetchFolderWorkspacesForAllHosts, fetchAllWorktrees: s.fetchAllWorktrees, fetchWorktreeLineage: s.fetchWorktreeLineage, + fetchOrcaProfiles: s.fetchOrcaProfiles, fetchSettings: s.fetchSettings, fetchKeybindings: s.fetchKeybindings, initGitHubCache: s.initGitHubCache, @@ -479,6 +493,11 @@ function App(): React.JSX.Element { const worktreeSidebarScrollAnchorRef = useRef(null) const floatingVisibleTabCount = useAppStore(selectFloatingVisibleTabCount) const workspaceSessionReady = useAppStore((s) => s.workspaceSessionReady) + const backgroundTerminalMountRequested = useSyncExternalStore( + subscribeBackgroundTerminalWorktreeMountRequests, + hasRequestedBackgroundTerminalWorktreeMount, + hasRequestedBackgroundTerminalWorktreeMount + ) const keybindings = useAppStore((s) => s.keybindings) const updateStatus = useAppStore((s) => s.updateStatus) const activeContextualTourId = useAppStore((s) => s.activeContextualTourId) @@ -495,14 +514,16 @@ function App(): React.JSX.Element { floatingTerminalEnabled && (floatingTerminalTriggerLocation === 'floating-button' || !statusBarVisible) const hasMountedTerminalWorkbenchRef = useRef(false) - if (activeWorktreeId !== null) { + if (activeWorktreeId !== null || backgroundTerminalMountRequested) { hasMountedTerminalWorkbenchRef.current = true } // Why: skip the terminal bundle on the no-workspace landing path, but once a // workspace has mounted, keep Terminal-owned hidden panes alive through sleep // and shutdown transitions where activeWorktreeId can briefly become null. const shouldMountTerminalWorkbench = - activeWorktreeId !== null || hasMountedTerminalWorkbenchRef.current + activeWorktreeId !== null || + backgroundTerminalMountRequested || + hasMountedTerminalWorkbenchRef.current // Why: visible worktree creation owns its faux tab strip from start to finish; // the previous workspace must stay mounted for retention without rendering // real chrome. @@ -864,10 +885,22 @@ function App(): React.JSX.Element { const startupStartedAt = performance.now() logRendererStartupDiagnostic('startup-chain-start') try { + // Why: profile state only feeds the switcher and the add-project + // advisory — nothing in the hydration chain reads it synchronously, + // so it must not add a serial IPC round-trip before fetchSettings. + void actions.fetchOrcaProfiles() // Why: repo/worktree hydration routes through settings.activeRuntimeEnvironmentId. // Load settings first so a persisted remote runtime does not boot against // the local filesystem and then hydrate stale local workspace state. await timeRendererStartupStep('fetch-settings', () => actions.fetchSettings()) + // Why here: hidden-at-launch PTYs (background terminal reconnects, + // agent sessions) can query OSC 10/11 before any terminal pane mounts + // and main's responder is silent-until-first-push. Publish composed + // view attributes as soon as settings exist, before any spawn below. + publishTerminalViewAttributesAtAppStart( + useAppStore.getState().settings, + getSystemPrefersDark() + ) // Why: keybindings + onboarding are main-side reads with no dependency // on the catalog/session steps below, so start them now and await them // at their original positions — the round-trips overlap the local @@ -1347,6 +1380,22 @@ function App(): React.JSX.Element { return () => window.removeEventListener('beforeunload', captureAndFlush) }, []) + // Why: beforeunload never fires on a hard kill (crash, forced update + // install, TerminateProcess), so agents alive at that moment would leave no + // resume record. This periodic capture stores only agent session ids — not + // scrollback, see the no-periodic-scrollback note below — and the store + // action skips unchanged records, so idle ticks write nothing; real changes + // flow through the debounced session-write subscriber. + useEffect(() => { + const timer = window.setInterval(() => { + if (!shouldPersistWorkspaceSession(useAppStore.getState())) { + return + } + useAppStore.getState().captureAllSleepingAgentSessions() + }, SLEEPING_AGENT_RESUME_CAPTURE_INTERVAL_MS) + return () => window.clearInterval(timer) + }, []) + // Own the single window-close-request subscription at the always-mounted App // root. Why: the rich confirmation flow lives in Terminal, which is not // mounted on the no-workspace landing page (and is lazy-loaded elsewhere), so @@ -1494,6 +1543,8 @@ function App(): React.JSX.Element { // Why: suppress right sidebar controls on full-page navigation surfaces // since those surfaces intentionally own the full content area. const showRightSidebarControls = !creationLayoutActive && canShowRightSidebarForView(activeView) + const showProfileSwitcherInSidebarFooter = showSidebar && sidebarOpen + const showProfileSwitcherInTopRight = !showProfileSwitcherInSidebarFooter const handleToggleExpand = (): void => { if (!effectiveActiveTabId) { @@ -2135,6 +2186,7 @@ function App(): React.JSX.Element { )} + {showProfileSwitcherInTopRight ? : null} {/* Why: when the right sidebar is open, its own header renders an identical close button — hide this copy so only one is visible at a time. */} @@ -2144,6 +2196,25 @@ function App(): React.JSX.Element { {hasCustomTitleBar &&
    } ) + const workspaceProfileSwitcher = + showProfileSwitcherInTopRight && + workspaceChromeActive && + leftTitlebarChromeLayout.shouldMount && + !stackedSidebarOpen ? ( +
    + +
    + ) : null return (
    )} + {workspaceProfileSwitcher}
    {shouldMountTerminalWorkbench ? (
    { expect(source).not.toContain("from './components/Terminal'") expect(source).toContain('const hasMountedTerminalWorkbenchRef = useRef(false)') expect(source).toContain('hasMountedTerminalWorkbenchRef.current = true') - expect(source).toContain('activeWorktreeId !== null || hasMountedTerminalWorkbenchRef.current') + expect(source).toContain('activeWorktreeId !== null || backgroundTerminalMountRequested') + expect(source).toContain('backgroundTerminalMountRequested ||') + expect(source).toContain('hasMountedTerminalWorkbenchRef.current') expect(source).toContain('shouldMountTerminalWorkbench ?') }) diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index f028b6413845..56841b77245c 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -101,6 +101,8 @@ --color-status-success: var(--status-success); --color-status-success-background: var(--status-success-background); --color-status-success-border: var(--status-success-border); + --color-tab-group-split-divider: var(--tab-group-split-divider); + --color-tab-group-split-divider-strong: var(--tab-group-split-divider-strong); --color-git-graph-ref: var(--git-graph-ref); --color-git-graph-remote-ref: var(--git-graph-remote-ref); --color-git-graph-base-ref: var(--git-graph-base-ref); @@ -202,6 +204,11 @@ --git-graph-lane-4: #40b0a6; --git-graph-lane-5: #b66dff; --annotation-highlight: #f59e0b; + /* Why: tab-group splits use a dedicated divider — `--border` is too faint on + card/editor surfaces when panes are side-by-side or stacked. Default must + meet >=3:1 against `--card`, not only the hover/drag strong state. */ + --tab-group-split-divider: #868690; + --tab-group-split-divider-strong: #71717a; } /* ── Dark Mode ───────────────────────────────────────── */ @@ -285,6 +292,9 @@ --git-graph-lane-4: #40b0a6; --git-graph-lane-5: #b66dff; --annotation-highlight: #fbbf24; + /* Brighter than terminal defaults so the always-visible line clears 3:1 on `--card`. */ + --tab-group-split-divider: #71717a; + --tab-group-split-divider-strong: #a1a1aa; } .linear-priority-bars { @@ -463,12 +473,12 @@ scrollbar-color: color-mix(in srgb, var(--muted-foreground, #737373) 48%, transparent) transparent; } -/* Keep the sidebar gutter reserved; only the thumb fades in on hover. */ +/* Why: no reserved `scrollbar-gutter` — paired with `overflow-y: auto`, a list + that fits shows no scrollbar (and no Windows scrollbar arrow buttons), so its + rows stay flush with the fixed header controls, matching macOS. The gutter is + only taken while actually scrolling. Thumb still fades in on hover. */ .worktree-sidebar-scrollbar { - /* Why: the scrollbar gutter is paint-only in Chromium; this keeps card - surfaces clear of Orca's resize handle and right-edge sidebar chrome. */ padding-right: 4px; - scrollbar-gutter: stable; scrollbar-color: transparent transparent; } @@ -519,27 +529,32 @@ /* ── Editor-style scrollbar (matches Monaco) ────────── */ -.scrollbar-editor { +.scrollbar-editor, +.xterm .xterm-viewport { scrollbar-width: thin; scrollbar-color: rgba(121, 121, 121, 0.4) transparent; } -.scrollbar-editor::-webkit-scrollbar { +.scrollbar-editor::-webkit-scrollbar, +.xterm .xterm-viewport::-webkit-scrollbar { width: 14px; } -.scrollbar-editor::-webkit-scrollbar-track { +.scrollbar-editor::-webkit-scrollbar-track, +.xterm .xterm-viewport::-webkit-scrollbar-track { background: transparent; } -.scrollbar-editor::-webkit-scrollbar-thumb { +.scrollbar-editor::-webkit-scrollbar-thumb, +.xterm .xterm-viewport::-webkit-scrollbar-thumb { background: rgba(121, 121, 121, 0.4); border: 3px solid transparent; border-radius: 7px; background-clip: padding-box; } -.scrollbar-editor::-webkit-scrollbar-thumb:hover { +.scrollbar-editor::-webkit-scrollbar-thumb:hover, +.xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background: rgba(121, 121, 121, 0.7); border: 3px solid transparent; background-clip: padding-box; @@ -618,6 +633,52 @@ overflow: hidden; } +/* Tab-group split resize handle — wide hit area, visible center line. */ +.tab-group-split-resize-handle { + flex-shrink: 0; + position: relative; + background: transparent; +} + +.tab-group-split-resize-handle.is-vertical { + width: 6px; + cursor: col-resize; +} + +.tab-group-split-resize-handle.is-horizontal { + height: 6px; + cursor: row-resize; +} + +.tab-group-split-resize-handle::after { + content: ''; + position: absolute; + border-radius: 1px; + background: var(--tab-group-split-divider); + transition: background 100ms ease; +} + +.tab-group-split-resize-handle.is-vertical::after { + top: 0; + bottom: 0; + left: 50%; + width: 3px; + transform: translateX(-50%); +} + +.tab-group-split-resize-handle.is-horizontal::after { + left: 0; + right: 0; + top: 50%; + height: 3px; + transform: translateY(-50%); +} + +.tab-group-split-resize-handle:hover::after, +.tab-group-split-resize-handle.is-dragging::after { + background: var(--tab-group-split-divider-strong); +} + /* ── Titlebar ────────────────────────────────────────── */ /* Why: Radix portals (dropdowns, popovers, dialogs, sheets) render at the @@ -901,6 +962,11 @@ color: var(--muted-foreground); } +.titlebar-profile-switcher { + -webkit-app-region: no-drag; + flex-shrink: 0; +} + .editor-header { display: flex; align-items: center; @@ -1915,6 +1981,16 @@ pointer-events: auto; } +/* Why: Monaco leaves the peek preview container `inline-block` and only sizes the + editor child, so the container shrink-wraps the child in BOTH axes while the + inherited automaticLayout ResizeObserver measures the container — a feedback + loop that ratchets the preview to blank at fractional zoom/DPI (issue #7405). + Pinning both dimensions to the splitview slot severs the loop. */ +.monaco-editor .reference-zone-widget .preview.inline { + height: 100%; + width: 100%; +} + /* ── Git conflict decorations ───────────────────────────────────── */ .monaco-editor .orca-conflict-marker-line { @@ -2357,7 +2433,7 @@ } /* Brief one-shot pulse when the Codex limits popover swaps accounts and the - "100% left" label flashes from red to green. */ + "0% used" label flashes from red to green. */ @keyframes feature-wall-meta-pulse { 0% { color: rgb(220 38 38); diff --git a/src/renderer/src/assets/rich-markdown-editor.css b/src/renderer/src/assets/rich-markdown-editor.css index 395b18131a7b..ccf79ad36385 100644 --- a/src/renderer/src/assets/rich-markdown-editor.css +++ b/src/renderer/src/assets/rich-markdown-editor.css @@ -1381,8 +1381,9 @@ /* ── Link Bubble ──────────────────────────────────────── */ .rich-markdown-link-bubble { - position: absolute; - z-index: 30; + position: fixed; + z-index: 60; + -webkit-app-region: no-drag; display: flex; align-items: center; gap: 2px; diff --git a/src/renderer/src/assets/terminal-scrollbar-style.test.ts b/src/renderer/src/assets/terminal-scrollbar-style.test.ts new file mode 100644 index 000000000000..642678e264cf --- /dev/null +++ b/src/renderer/src/assets/terminal-scrollbar-style.test.ts @@ -0,0 +1,17 @@ +import fs from 'node:fs' +import { describe, expect, it } from 'vitest' + +const terminalCss = fs.readFileSync(new URL('./terminal.css', import.meta.url), 'utf8') +const mainCss = fs.readFileSync(new URL('./main.css', import.meta.url), 'utf8') + +describe('terminal scrollbar styling', () => { + it('reuses the canonical editor scrollbar with a transparent gutter', () => { + expect(mainCss).toMatch( + /\.scrollbar-editor,\s*\.xterm \.xterm-viewport\s*{[^}]*scrollbar-color:\s*rgba\(121, 121, 121, 0\.4\) transparent/s + ) + expect(mainCss).toMatch( + /\.scrollbar-editor::-webkit-scrollbar-track,\s*\.xterm \.xterm-viewport::-webkit-scrollbar-track\s*{[^}]*background:\s*transparent/s + ) + expect(terminalCss).not.toContain('--xterm-scrollbar-thumb') + }) +}) diff --git a/src/renderer/src/assets/terminal.css b/src/renderer/src/assets/terminal.css index d9763b3e3417..31c2d142e431 100644 --- a/src/renderer/src/assets/terminal.css +++ b/src/renderer/src/assets/terminal.css @@ -36,8 +36,8 @@ the install terminals inside centered setup modals), that black layer anti-aliases into a faint 1px line above/below the themed .xterm. Match xterm's own selector so this also covers terminals mounted outside the pane - manager, and let the themed .xterm background show through; our scrollbar is - already custom-styled below. */ + manager, and let the themed .xterm background show through; the viewport + reuses the canonical editor scrollbar rules in main.css. */ .xterm:not(.allow-transparency) .xterm-viewport { background-color: transparent; } diff --git a/src/renderer/src/components/AgentStateDot.tsx b/src/renderer/src/components/AgentStateDot.tsx index f3d801dc2616..951e3be36f1f 100644 --- a/src/renderer/src/components/AgentStateDot.tsx +++ b/src/renderer/src/components/AgentStateDot.tsx @@ -18,6 +18,9 @@ export type AgentDotState = | 'blocked' | 'waiting' | 'interrupted' + // Why: AI Vault subagent rows report a transcript-derived failure, which is + // an outcome (like 'done'), not a live attention state like 'blocked'. + | 'failed' | 'done' | 'idle' // Why: the sidebar's title-based status flow (StatusIndicator/WorktreeCard) @@ -37,6 +40,8 @@ export function agentStateLabel(state: AgentDotState): string { return 'Waiting for input' case 'interrupted': return 'Interrupted' + case 'failed': + return 'Failed' case 'done': return 'Done' case 'idle': @@ -105,7 +110,7 @@ export const AgentStateDot = React.memo(function AgentStateDot({ inner, state === 'permission' || state === 'waiting' ? 'bg-amber-500' - : state === 'blocked' || state === 'interrupted' + : state === 'blocked' || state === 'interrupted' || state === 'failed' ? 'bg-red-500' : 'bg-neutral-500/40' )} diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index 5d45f1f78ea0..ff76246a24c8 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -166,6 +166,7 @@ import { import { lookupGitHubWorkItemDetailsForSource } from '@/lib/github-work-item-source-lookup' import { canUseGitHubRepoContext, + getGitHubMutationRoutingSettings, getGitHubRuntimeRepoId, getGitHubSourceRuntimeHost } from '@/lib/github-source-runtime-context' @@ -3848,21 +3849,11 @@ function PRActionsPanel({ const actionItem = { ...item, state: localState } const mergePresentation = presentGitHubPRMergeState(actionItem) const mergeMethods = resolveGitHubPRMergeMethods(actionItem.mergeMethodSettings) - const repoOwnerSettings = useAppStore( - useShallow((s) => getSettingsForRepoRuntimeOwner(s, repoId ?? item.repoId ?? null)) + const sourceSettings = useAppStore( + useShallow((s) => + getGitHubMutationRoutingSettings(s, item.repoId ?? repoId ?? null, sourceContext) + ) ) - const sourceSettings = useMemo(() => { - if (sourceContext?.provider !== 'github') { - return repoOwnerSettings - } - const sourceRuntimeSettings = getTaskSourceRuntimeSettings(sourceContext) - return sourceRuntimeSettings.activeRuntimeEnvironmentId - ? ({ - ...repoOwnerSettings, - ...sourceRuntimeSettings - } as typeof repoOwnerSettings) - : repoOwnerSettings - }, [repoOwnerSettings, sourceContext]) const mergeTarget = getActiveRuntimeTarget(sourceSettings) const canMutateWithRepoContext = !!repoPath || !!projectOrigin || mergeTarget.kind === 'environment' @@ -5465,32 +5456,36 @@ async function runPullRequestStateUpdate(args: { } return } - const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) - if (!args.repoPath && !runtimeHost) { + // Why: close/reopen must route by the repo owner host like merge (#6957). + const target = getActiveRuntimeTarget( + getGitHubMutationRoutingSettings(useAppStore.getState(), args.repoId, args.sourceContext) + ) + if (!args.repoPath && target.kind !== 'environment') { throw new Error('No repo context available for this pull request.') } - const res = runtimeHost - ? await callRuntimeRpc>>( - { kind: 'environment', environmentId: runtimeHost.environmentId }, - 'github.updatePRState', - { - repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? ''), + const res = + target.kind === 'environment' + ? await callRuntimeRpc>>( + target, + 'github.updatePRState', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? ''), + prNumber: args.number, + updates: args.updates + }, + { timeoutMs: 30_000 } + ) + : await window.api.gh.updatePRState({ + repoPath: args.repoPath ?? '', + repoId: args.repoId ?? undefined, + sourceContext: args.sourceContext, prNumber: args.number, updates: args.updates - }, - { timeoutMs: 30_000 } - ) - : await window.api.gh.updatePRState({ - repoPath: args.repoPath ?? '', - repoId: args.repoId ?? undefined, - sourceContext: args.sourceContext, - prNumber: args.number, - updates: args.updates - }) + }) if (!res.ok) { throw new Error(res.error) } - if (runtimeHost) { + if (target.kind === 'environment') { notifyWorkItemDetailsMutation( { repoPath: args.repoPath ?? '', @@ -5571,10 +5566,10 @@ function GHEditSection({ onUse: (item: GitHubWorkItem) => void onOpenOrUse?: (item: GitHubWorkItem) => void attachedWorkspaceLabel?: string | null - /** `'horizontal'` is the legacy strip rendered above the conversation; the - * `'sidebar'` layout matches the GitHub issue page's right rail with each - * metadata row stacked under a section heading. */ - layout?: 'horizontal' | 'sidebar' + /** Two surfaces only: compact pill strip for the non-issue drawer/header + * (`horizontal`), and labeled property columns above the issue page body + * (`top-columns`). */ + layout?: 'horizontal' | 'top-columns' }): React.JSX.Element | null { const [labelPopoverOpen, setLabelPopoverOpen] = useState(false) const [assigneePopoverOpen, setAssigneePopoverOpen] = useState(false) @@ -6155,11 +6150,13 @@ function GHEditSection({ ) - if (layout === 'sidebar') { + if (layout === 'top-columns') { + // Why: issue page body should match the header width — property fields sit + // as top columns so the description is not squeezed by a right rail. return ( -
    -
    - ) - })} -
    +

    - {activeLinearIssueContextLabel - ? translate( + {(() => { + const emptyKind = resolveLinearIssueEmptyKind({ + hasContextLabel: Boolean(activeLinearIssueContextLabel), + searchActive: linearSearchActive, + attributeFilter: linearAttributeFilter, + serverIssueCount: activeLinearIssues.length, + filteredIssueCount: filteredLinearIssues.length + }) + if (emptyKind === 'context') { + return translate( 'auto.components.TaskPage.25ff84769a', 'No issues match this Linear context.' ) - : linearSearchInput - ? translate( - 'auto.components.TaskPage.2bdefbcac3', - 'Try a different search query.' - ) - : translate( - 'auto.components.TaskPage.d079be2dc8', - 'No assigned issues. Try searching for something.' - )} + } + if (emptyKind === 'search') { + return translate( + 'auto.components.TaskPage.2bdefbcac3', + 'Try a different search query.' + ) + } + if (emptyKind === 'server-attribute-filter') { + return translate( + 'auto.components.TaskPage.linearEmptyAttributeFilter', + 'No issues match the selected filters. Clear a filter or try different criteria.' + ) + } + return translate( + 'auto.components.TaskPage.linearEmptyUnfilteredScope', + 'No issues in this workspace scope. Try searching or adjusting teams.' + ) + })()}

    ) : null} @@ -10489,6 +10668,27 @@ export default function TaskPage(): React.JSX.Element { 'Try selecting more teams or refreshing; team filters apply to the current fetched issue set.' )}

    + {shouldOfferLinearIssueFetchMore({ + emptyKind: 'client-team', + serverHasMore: linearIssuesHasMore + }) ? ( + + ) : null} ) : null} @@ -11057,7 +11257,15 @@ export default function TaskPage(): React.JSX.Element { onNameChange(event.target.value)} + placeholder={translate( + 'auto.components.orca.profiles.switcher.f322e1f4d6', + 'Profile name' + )} + maxLength={80} + /> + + + + + + + ) +} diff --git a/src/renderer/src/components/orca-profiles/OrcaProfileManagementDialog.tsx b/src/renderer/src/components/orca-profiles/OrcaProfileManagementDialog.tsx new file mode 100644 index 000000000000..8f1577c79989 --- /dev/null +++ b/src/renderer/src/components/orca-profiles/OrcaProfileManagementDialog.tsx @@ -0,0 +1,272 @@ +import { useMemo, useState } from 'react' +import { ArrowRightLeft, Copy, FolderGit2, Loader2, MoveRight } from 'lucide-react' +import { toast } from 'sonner' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { ScrollArea } from '@/components/ui/scroll-area' +import { translate } from '@/i18n/i18n' +import { useAppStore } from '@/store' +import type { + OrcaProfileSummary, + TransferOrcaProfileProjectMode +} from '../../../../shared/orca-profiles' +import type { Repo } from '../../../../shared/types' +import { OrcaProfileAvatar } from './OrcaProfileAvatar' +import { + OrcaProfileProjectTransferConfirmDialog, + type PendingProjectTransfer +} from './OrcaProfileProjectTransferConfirmDialog' +import { getOrcaProfileProjectLiveWorkSummary } from './orca-profile-switch-liveness' + +type PendingTransfer = { + repoId: string + targetProfileId: string + mode: TransferOrcaProfileProjectMode +} + +function pendingKey(value: PendingTransfer): string { + return `${value.mode}:${value.repoId}:${value.targetProfileId}` +} + +function getRepoPath(repo: Repo): string { + return repo.path || repo.displayName +} + +function ProjectTransferMenu({ + repo, + sourceProfileId, + targetProfiles, + pending, + onTransfer +}: { + repo: Repo + sourceProfileId: string + targetProfiles: OrcaProfileSummary[] + pending: PendingTransfer | null + onTransfer: ( + repo: Repo, + targetProfile: OrcaProfileSummary, + mode: TransferOrcaProfileProjectMode + ) => void +}): React.JSX.Element { + const disabled = targetProfiles.length === 0 || Boolean(pending) + const repoPending = pending?.repoId === repo.id + const renderTargetItems = (mode: TransferOrcaProfileProjectMode): React.JSX.Element[] => + targetProfiles.map((profile) => { + const targetPending = + pending && + pendingKey(pending) === pendingKey({ repoId: repo.id, targetProfileId: profile.id, mode }) + return ( + onTransfer(repo, profile, mode)} + > + {mode === 'move' ? : } + + {profile.name} + {targetPending ? : null} + + ) + }) + + return ( + + + + + + + {translate('auto.components.orca.profiles.management.128c7dfe64', 'Copy to')} + + {renderTargetItems('copy')} + + + {translate('auto.components.orca.profiles.management.df8b7d876b', 'Move to')} + + {renderTargetItems('move')} + + + ) +} + +export function OrcaProfileManagementDialog({ + open, + onOpenChange, + activeProfile, + profiles +}: { + open: boolean + onOpenChange: (open: boolean) => void + activeProfile: OrcaProfileSummary + profiles: OrcaProfileSummary[] +}): React.JSX.Element { + const repos = useAppStore((s) => s.repos) + const transferProject = useAppStore((s) => s.transferOrcaProfileProject) + const [pending, setPending] = useState(null) + const [pendingConfirmation, setPendingConfirmation] = useState( + null + ) + const targetProfiles = useMemo( + () => profiles.filter((profile) => profile.id !== activeProfile.id), + [activeProfile.id, profiles] + ) + + const runTransfer = async ( + repo: Repo, + targetProfile: OrcaProfileSummary, + mode: TransferOrcaProfileProjectMode + ): Promise => { + if (pending) { + return + } + const nextPending = { repoId: repo.id, targetProfileId: targetProfile.id, mode } + setPending(nextPending) + const result = await transferProject({ + sourceProfileId: activeProfile.id, + targetProfileId: targetProfile.id, + repoId: repo.id, + mode + }) + setPending(null) + if (result?.status === 'transferred') { + toast.success( + mode === 'move' + ? translate('auto.components.orca.profiles.management.9aa26347b3', 'Project moved') + : translate('auto.components.orca.profiles.management.816ce624b6', 'Project copied'), + { + description: targetProfile.name + } + ) + } + } + + const handleTransfer = ( + repo: Repo, + targetProfile: OrcaProfileSummary, + mode: TransferOrcaProfileProjectMode + ): void => { + if (pending) { + return + } + const liveWorkSummary = getOrcaProfileProjectLiveWorkSummary(useAppStore.getState(), repo.id) + if (mode === 'move' || liveWorkSummary.hasLiveWork) { + setPendingConfirmation({ repo, targetProfile, mode, liveWorkSummary }) + return + } + void runTransfer(repo, targetProfile, mode) + } + + const confirmTransfer = async (): Promise => { + if (!pendingConfirmation) { + return + } + const next = pendingConfirmation + await runTransfer(next.repo, next.targetProfile, next.mode) + setPendingConfirmation(null) + } + + return ( + + + + + {translate('auto.components.orca.profiles.management.2c45bda8d3', 'Manage profiles')} + + + {translate( + 'auto.components.orca.profiles.management.2db945e4a0', + 'Copy or move projects from the active profile to another local profile.' + )} + + + +
    +
    + +
    +
    {activeProfile.name}
    +
    + {translate( + repos.length === 1 + ? 'auto.components.orca.profiles.management.projectCountSingular' + : 'auto.components.orca.profiles.management.projectCountPlural', + repos.length === 1 ? '{{count}} project' : '{{count}} projects', + { count: repos.length } + )} +
    +
    +
    + + {repos.length === 0 ? ( +
    + {translate( + 'auto.components.orca.profiles.management.8668cb2946', + 'No projects in this profile.' + )} +
    + ) : ( +
    + {repos.map((repo) => ( +
    + +
    +
    {repo.displayName}
    +
    + {getRepoPath(repo)} +
    +
    + { + handleTransfer(selectedRepo, targetProfile, mode) + }} + /> +
    + ))} +
    + )} +
    +
    + + {targetProfiles.length === 0 ? ( +
    + {translate( + 'auto.components.orca.profiles.management.93034915ab', + 'Create another profile before copying projects.' + )} +
    + ) : null} + setPendingConfirmation(null)} + onConfirm={() => { + void confirmTransfer() + }} + /> +
    +
    + ) +} diff --git a/src/renderer/src/components/orca-profiles/OrcaProfileOrgMemberRow.tsx b/src/renderer/src/components/orca-profiles/OrcaProfileOrgMemberRow.tsx new file mode 100644 index 000000000000..894e21c8481a --- /dev/null +++ b/src/renderer/src/components/orca-profiles/OrcaProfileOrgMemberRow.tsx @@ -0,0 +1,135 @@ +import { useState } from 'react' +import { Loader2, UserMinus } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue +} from '@/components/ui/select' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { translate } from '@/i18n/i18n' +import { cn } from '@/lib/utils' +import type { OrcaOrgMember, OrcaOrgRole } from '../../../../shared/orca-profiles' +import { + ORG_ROLE_OPTIONS, + orgMemberInitials, + orgRoleLabel +} from './orca-profile-org-members-labels' + +export function OrcaProfileOrgMemberRow({ + member, + canManage, + isSelf, + busy, + onChangeRole, + onRemove +}: { + member: OrcaOrgMember + canManage: boolean + isSelf: boolean + busy: boolean + onChangeRole: (role: OrcaOrgRole) => void + onRemove: () => void +}): React.JSX.Element { + const [confirmingRemove, setConfirmingRemove] = useState(false) + // Why: teammates provisioned server-side who never signed into Orca have no + // userId, so the API cannot target them for role/remove mutations. + const neverSignedIn = member.userId === null + const actionsDisabled = !canManage || isSelf || neverSignedIn || busy + const displayName = member.displayName?.trim() || member.email + + const roleControl = canManage ? ( + + ) : ( + {orgRoleLabel(member.role)} + ) + + return ( +
    + + {orgMemberInitials(member.displayName, member.email)} + +
    +
    {displayName}
    +
    {member.email}
    +
    + + {neverSignedIn && canManage ? ( + + + {roleControl} + + + {translate( + 'auto.components.orca.profiles.org.members.not.signed.in', + "They haven't signed in to Orca yet." + )} + + + ) : ( + roleControl + )} + + {canManage ? ( + confirmingRemove && !actionsDisabled ? ( +
    + + +
    + ) : ( + + ) + ) : null} +
    + ) +} diff --git a/src/renderer/src/components/orca-profiles/OrcaProfileOrgMembersDialog.test.tsx b/src/renderer/src/components/orca-profiles/OrcaProfileOrgMembersDialog.test.tsx new file mode 100644 index 000000000000..35e3a07ae903 --- /dev/null +++ b/src/renderer/src/components/orca-profiles/OrcaProfileOrgMembersDialog.test.tsx @@ -0,0 +1,151 @@ +// @vitest-environment happy-dom + +import type { ReactNode } from 'react' +import { render, screen, cleanup } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { OrcaOrgMembersRoster } from '../../../../shared/orca-profiles' +import { OrcaProfileOrgMembersDialog } from './OrcaProfileOrgMembersDialog' + +vi.mock('@/components/ui/dialog', () => ({ + Dialog: ({ children }: { children: ReactNode }) =>
    {children}
    , + DialogContent: ({ children }: { children: ReactNode }) =>
    {children}
    , + DialogHeader: ({ children }: { children: ReactNode }) =>
    {children}
    , + DialogTitle: ({ children }: { children: ReactNode }) =>
    {children}
    , + DialogDescription: ({ children }: { children: ReactNode }) =>
    {children}
    +})) + +vi.mock('@/components/ui/scroll-area', () => ({ + ScrollArea: ({ children }: { children: ReactNode }) =>
    {children}
    +})) + +vi.mock('@/components/ui/tooltip', () => ({ + Tooltip: ({ children }: { children: ReactNode }) => <>{children}, + TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}, + TooltipContent: ({ children }: { children: ReactNode }) => {children} +})) + +vi.mock('@/components/ui/button', () => ({ + Button: ({ + children, + disabled, + 'aria-label': ariaLabel, + type + }: { + children?: ReactNode + disabled?: boolean + 'aria-label'?: string + type?: 'button' | 'submit' + }) => ( + + ) +})) + +vi.mock('@/components/ui/input', () => ({ + Input: ({ placeholder, disabled }: { placeholder?: string; disabled?: boolean }) => ( + + ) +})) + +vi.mock('@/components/ui/select', () => ({ + Select: ({ children }: { children: ReactNode }) =>
    {children}
    , + SelectContent: ({ children }: { children: ReactNode }) =>
    {children}
    , + SelectItem: ({ children }: { children: ReactNode }) =>
    {children}
    , + SelectValue: () => null, + SelectTrigger: ({ + disabled, + 'aria-label': ariaLabel, + children + }: { + disabled?: boolean + 'aria-label'?: string + children?: ReactNode + }) => ( + + ) +})) + +const managerRoster: OrcaOrgMembersRoster = { + members: [ + { userId: 'user-viewer', email: 'me@example.com', displayName: 'Me', role: 'admin' }, + { userId: 'user-2', email: 'other@example.com', displayName: 'Other', role: 'member' }, + { userId: null, email: 'never@example.com', role: 'member' } + ], + pendingInvites: [{ email: 'pending@example.com', role: 'member', createdAt: 1 }], + viewerRole: 'owner', + canManageMembers: true +} + +const memberRoster: OrcaOrgMembersRoster = { + members: [ + { userId: 'user-1', email: 'boss@example.com', displayName: 'Boss', role: 'owner' }, + { userId: 'user-2', email: 'peer@example.com', displayName: 'Peer', role: 'member' } + ], + pendingInvites: [], + viewerRole: 'member', + canManageMembers: false +} + +function stubOrgMembersApi(roster: OrcaOrgMembersRoster): void { + ;(window as unknown as { api: unknown }).api = { + orcaProfiles: { + orgMembersList: vi.fn().mockResolvedValue({ status: 'ok', roster }) + } + } +} + +describe('OrcaProfileOrgMembersDialog', () => { + afterEach(() => { + cleanup() + vi.restoreAllMocks() + }) + + it('shows the invite form and a role select per member for managers', async () => { + stubOrgMembersApi(managerRoster) + render( + {}} + orgId="org-1" + orgName="Acme" + viewerUserId="user-viewer" + /> + ) + + expect(await screen.findByText('other@example.com')).toBeTruthy() + // Invite form present. + expect(screen.getByPlaceholderText('teammate@example.com')).toBeTruthy() + // Pending invite listed with a revoke action. + expect(screen.getByText('pending@example.com')).toBeTruthy() + // One role select per member. + expect(screen.getAllByLabelText('Role')).toHaveLength(3) + // Self and the never-signed-in row disable their remove action; the peer's stays enabled. + const removeButtons = screen.getAllByLabelText('Remove teammate') as HTMLButtonElement[] + expect(removeButtons).toHaveLength(3) + expect(removeButtons.filter((button) => button.disabled)).toHaveLength(2) + // Never-signed-in explanation is present. + expect(screen.getByText("They haven't signed in to Orca yet.")).toBeTruthy() + }) + + it('renders a read-only roster for non-managers', async () => { + stubOrgMembersApi(memberRoster) + render( + {}} + orgId="org-1" + viewerUserId="user-2" + /> + ) + + expect(await screen.findByText('boss@example.com')).toBeTruthy() + expect(screen.getByText('peer@example.com')).toBeTruthy() + // No management affordances. + expect(screen.queryByPlaceholderText('teammate@example.com')).toBeNull() + expect(screen.queryAllByLabelText('Role')).toHaveLength(0) + expect(screen.queryAllByLabelText('Remove teammate')).toHaveLength(0) + }) +}) diff --git a/src/renderer/src/components/orca-profiles/OrcaProfileOrgMembersDialog.tsx b/src/renderer/src/components/orca-profiles/OrcaProfileOrgMembersDialog.tsx new file mode 100644 index 000000000000..95c5344ebcb2 --- /dev/null +++ b/src/renderer/src/components/orca-profiles/OrcaProfileOrgMembersDialog.tsx @@ -0,0 +1,300 @@ +import { useCallback, useEffect, useState } from 'react' +import { Loader2, Mail, RefreshCw, Users } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import { ScrollArea } from '@/components/ui/scroll-area' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue +} from '@/components/ui/select' +import { translate } from '@/i18n/i18n' +import type { + OrcaOrgMember, + OrcaOrgMembersRoster, + OrcaOrgRole, + OrcaProfileOrgMemberMutationResult +} from '../../../../shared/orca-profiles' +import { OrcaProfileOrgMemberRow } from './OrcaProfileOrgMemberRow' +import { + describeOrgMutationError, + ORG_ROLE_OPTIONS, + orgRoleLabel +} from './orca-profile-org-members-labels' + +type DialogProps = { + open: boolean + onOpenChange: (open: boolean) => void + orgId: string + orgName?: string + viewerUserId?: string +} + +function isOk(result: OrcaProfileOrgMemberMutationResult): result is { status: 'ok' } { + return result.status === 'ok' +} + +export function OrcaProfileOrgMembersDialog({ + open, + onOpenChange, + orgId, + orgName, + viewerUserId +}: DialogProps): React.JSX.Element { + const [roster, setRoster] = useState(null) + const [loading, setLoading] = useState(false) + const [loadError, setLoadError] = useState(false) + const [actionError, setActionError] = useState(null) + const [pendingMemberId, setPendingMemberId] = useState(null) + const [pendingInviteEmail, setPendingInviteEmail] = useState(null) + const [inviteEmail, setInviteEmail] = useState('') + const [inviteRole, setInviteRole] = useState('member') + const [inviting, setInviting] = useState(false) + + const refresh = useCallback(async (): Promise => { + setLoading(true) + setLoadError(false) + setActionError(null) + const result = await window.api.orcaProfiles.orgMembersList({ orgId }) + if (result.status === 'ok') { + setRoster(result.roster) + } else { + setRoster(null) + setLoadError(true) + } + setLoading(false) + }, [orgId]) + + // Why: reload every time the dialog opens so a manager always acts on the + // current roster, and clear transient dialog state when it closes. + useEffect(() => { + if (open) { + void refresh() + } else { + setActionError(null) + setInviteEmail('') + setInviteRole('member') + } + }, [open, refresh]) + + const canManage = roster?.canManageMembers === true + + const runMutation = async ( + mutation: Promise + ): Promise => { + setActionError(null) + const result = await mutation + if (isOk(result)) { + await refresh() + return true + } + setActionError(describeOrgMutationError(result)) + return false + } + + const handleChangeRole = async (member: OrcaOrgMember, role: OrcaOrgRole): Promise => { + if (member.userId === null || role === member.role) { + return + } + setPendingMemberId(member.userId) + await runMutation( + window.api.orcaProfiles.orgMemberChangeRole({ orgId, userId: member.userId, role }) + ) + setPendingMemberId(null) + } + + const handleRemove = async (member: OrcaOrgMember): Promise => { + if (member.userId === null) { + return + } + setPendingMemberId(member.userId) + await runMutation(window.api.orcaProfiles.orgMemberRemove({ orgId, userId: member.userId })) + setPendingMemberId(null) + } + + const handleRevoke = async (email: string): Promise => { + setPendingInviteEmail(email) + await runMutation(window.api.orcaProfiles.orgInviteRevoke({ orgId, email })) + setPendingInviteEmail(null) + } + + const handleInvite = async (event: React.FormEvent): Promise => { + event.preventDefault() + const email = inviteEmail.trim() + if (!email || inviting) { + return + } + setInviting(true) + const ok = await runMutation( + window.api.orcaProfiles.orgMemberInvite({ orgId, email, role: inviteRole }) + ) + setInviting(false) + if (ok) { + setInviteEmail('') + setInviteRole('member') + } + } + + return ( + + + + + + {translate('auto.components.orca.profiles.org.members.title', 'Organization members')} + + + {orgName + ? translate( + 'auto.components.orca.profiles.org.members.subtitle.named', + 'People in {{orgName}} who can collaborate on Orca.', + { orgName } + ) + : translate( + 'auto.components.orca.profiles.org.members.subtitle.default', + 'People in your organization who can collaborate on Orca.' + )} + + + + {loading ? ( +
    + +
    + ) : loadError ? ( +
    +

    + {translate( + 'auto.components.orca.profiles.org.members.load.error', + "Couldn't load organization members." + )} +

    + +
    + ) : roster ? ( +
    + {actionError ? ( +

    + {actionError} +

    + ) : null} + + +
    + {roster.members.map((member) => ( + void handleChangeRole(member, role)} + onRemove={() => void handleRemove(member)} + /> + ))} +
    +
    + + {canManage && roster.pendingInvites.length > 0 ? ( +
    +

    + {translate( + 'auto.components.orca.profiles.org.members.pending.title', + 'Pending invites' + )} +

    + {roster.pendingInvites.map((invite) => ( +
    + + + {invite.email} + + + {orgRoleLabel(invite.role)} + + +
    + ))} +
    + ) : null} + + {canManage ? ( +
    void handleInvite(event)} className="flex items-end gap-2"> +
    + + setInviteEmail(event.target.value)} + disabled={inviting} + placeholder={translate( + 'auto.components.orca.profiles.org.members.invite.placeholder', + 'teammate@example.com' + )} + /> +
    + + +
    + ) : null} +
    + ) : null} +
    +
    + ) +} diff --git a/src/renderer/src/components/orca-profiles/OrcaProfileProjectTransferConfirmDialog.tsx b/src/renderer/src/components/orca-profiles/OrcaProfileProjectTransferConfirmDialog.tsx new file mode 100644 index 000000000000..4b5678e52b1c --- /dev/null +++ b/src/renderer/src/components/orca-profiles/OrcaProfileProjectTransferConfirmDialog.tsx @@ -0,0 +1,162 @@ +import { ArrowRightLeft, Loader2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { translate } from '@/i18n/i18n' +import type { + OrcaProfileSummary, + TransferOrcaProfileProjectMode +} from '../../../../shared/orca-profiles' +import type { Repo } from '../../../../shared/types' +import type { OrcaProfileSwitchLiveWorkSummary } from './orca-profile-switch-liveness' + +type PendingProjectTransfer = { + repo: Repo + targetProfile: OrcaProfileSummary + mode: TransferOrcaProfileProjectMode + liveWorkSummary: OrcaProfileSwitchLiveWorkSummary +} + +export type { PendingProjectTransfer } + +function liveWorkLines(summary: OrcaProfileSwitchLiveWorkSummary): string[] { + const lines: string[] = [] + if (summary.liveTerminalTabCount > 0) { + lines.push( + translate( + summary.liveTerminalTabCount === 1 + ? 'auto.components.orca.profiles.project.transfer.confirm.terminalSingular' + : 'auto.components.orca.profiles.project.transfer.confirm.terminalPlural', + summary.liveTerminalTabCount === 1 + ? '{{count}} live terminal tab' + : '{{count}} live terminal tabs', + { count: summary.liveTerminalTabCount } + ) + ) + } + if (summary.liveAgentCount > 0) { + lines.push( + translate( + summary.liveAgentCount === 1 + ? 'auto.components.orca.profiles.project.transfer.confirm.agentSingular' + : 'auto.components.orca.profiles.project.transfer.confirm.agentPlural', + summary.liveAgentCount === 1 ? '{{count}} active agent' : '{{count}} active agents', + { count: summary.liveAgentCount } + ) + ) + } + if (summary.browserWorkspaceCount > 0) { + lines.push( + translate( + summary.browserWorkspaceCount === 1 + ? 'auto.components.orca.profiles.project.transfer.confirm.browserSingular' + : 'auto.components.orca.profiles.project.transfer.confirm.browserPlural', + summary.browserWorkspaceCount === 1 + ? '{{count}} browser workspace' + : '{{count}} browser workspaces', + { count: summary.browserWorkspaceCount } + ) + ) + } + return lines +} + +export function OrcaProfileProjectTransferConfirmDialog({ + activeProfileName, + pendingTransfer, + pending, + onCancel, + onConfirm +}: { + activeProfileName: string + pendingTransfer: PendingProjectTransfer | null + pending: boolean + onCancel: () => void + onConfirm: () => void +}): React.JSX.Element { + const mode = pendingTransfer?.mode ?? 'copy' + const repoName = pendingTransfer?.repo.displayName ?? '' + const targetName = pendingTransfer?.targetProfile.name ?? '' + const lines = pendingTransfer ? liveWorkLines(pendingTransfer.liveWorkSummary) : [] + + return ( + { + if (!open && !pending) { + onCancel() + } + }} + > + + + + + {mode === 'move' + ? translate( + 'auto.components.orca.profiles.project.transfer.confirm.move.title', + 'Move project?' + ) + : translate( + 'auto.components.orca.profiles.project.transfer.confirm.copy.title', + 'Copy project?' + )} + + + {mode === 'move' + ? translate( + 'auto.components.orca.profiles.project.transfer.confirm.move.description', + 'Move {{repoName}} to {{targetName}}. Orca removes it from {{activeProfileName}}, keeps files in place, and relaunches into {{targetName}}.', + { activeProfileName, repoName, targetName } + ) + : translate( + 'auto.components.orca.profiles.project.transfer.confirm.copy.description', + 'Copy {{repoName}} to {{targetName}}. Both profiles will point at the same files with separate Orca metadata.', + { repoName, targetName } + )} + + + + {lines.length > 0 ? ( +
    +
    + {translate( + 'auto.components.orca.profiles.project.transfer.confirm.live.work', + 'Live work in this project' + )} +
    +
      + {lines.map((line) => ( +
    • {line}
    • + ))} +
    +
    + ) : null} + + + + + +
    +
    + ) +} diff --git a/src/renderer/src/components/orca-profiles/OrcaProfileSignOutConfirmDialog.tsx b/src/renderer/src/components/orca-profiles/OrcaProfileSignOutConfirmDialog.tsx new file mode 100644 index 000000000000..afa2b4707de4 --- /dev/null +++ b/src/renderer/src/components/orca-profiles/OrcaProfileSignOutConfirmDialog.tsx @@ -0,0 +1,60 @@ +import { AlertTriangle, Loader2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { translate } from '@/i18n/i18n' + +export function OrcaProfileSignOutConfirmDialog({ + open, + onOpenChange, + onConfirm, + profileName, + signingOut +}: { + open: boolean + onOpenChange: (open: boolean) => void + onConfirm: () => void + profileName: string + signingOut: boolean +}): React.JSX.Element { + return ( + + + + + + {translate('auto.components.orca.profiles.signout.confirm.title', 'Sign out?')} + + + {translate( + 'auto.components.orca.profiles.signout.confirm.description', + 'Sign out of {{profileName}} and keep its projects, worktrees, and local metadata on this device.', + { profileName } + )} + + + + + + + + + + ) +} diff --git a/src/renderer/src/components/orca-profiles/OrcaProfileSwitchConfirmDialog.tsx b/src/renderer/src/components/orca-profiles/OrcaProfileSwitchConfirmDialog.tsx new file mode 100644 index 000000000000..89c80e99aa6c --- /dev/null +++ b/src/renderer/src/components/orca-profiles/OrcaProfileSwitchConfirmDialog.tsx @@ -0,0 +1,129 @@ +import { AlertTriangle, Loader2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { translate } from '@/i18n/i18n' +import type { OrcaProfileSummary } from '../../../../shared/orca-profiles' +import type { OrcaProfileSwitchLiveWorkSummary } from './orca-profile-switch-liveness' + +function liveWorkLines(summary: OrcaProfileSwitchLiveWorkSummary): string[] { + const lines: string[] = [] + if (summary.liveTerminalTabCount > 0) { + lines.push( + translate( + summary.liveTerminalTabCount === 1 + ? 'auto.components.orca.profiles.switch.confirm.terminalSingular' + : 'auto.components.orca.profiles.switch.confirm.terminalPlural', + summary.liveTerminalTabCount === 1 + ? '{{count}} live terminal tab' + : '{{count}} live terminal tabs', + { count: summary.liveTerminalTabCount } + ) + ) + } + if (summary.liveAgentCount > 0) { + lines.push( + translate( + summary.liveAgentCount === 1 + ? 'auto.components.orca.profiles.switch.confirm.agentSingular' + : 'auto.components.orca.profiles.switch.confirm.agentPlural', + summary.liveAgentCount === 1 ? '{{count}} active agent' : '{{count}} active agents', + { count: summary.liveAgentCount } + ) + ) + } + if (summary.browserWorkspaceCount > 0) { + lines.push( + translate( + summary.browserWorkspaceCount === 1 + ? 'auto.components.orca.profiles.switch.confirm.browserSingular' + : 'auto.components.orca.profiles.switch.confirm.browserPlural', + summary.browserWorkspaceCount === 1 + ? '{{count}} browser workspace' + : '{{count}} browser workspaces', + { count: summary.browserWorkspaceCount } + ) + ) + } + return lines +} + +export function OrcaProfileSwitchConfirmDialog({ + open, + onOpenChange, + onConfirm, + activeProfileName, + targetProfile, + liveWorkSummary, + switching +}: { + open: boolean + onOpenChange: (open: boolean) => void + onConfirm: () => void + activeProfileName: string + targetProfile: OrcaProfileSummary | null + liveWorkSummary: OrcaProfileSwitchLiveWorkSummary + switching: boolean +}): React.JSX.Element { + const targetName = + targetProfile?.name ?? + translate('auto.components.orca.profiles.switch.confirm.target', 'the selected profile') + const lines = liveWorkLines(liveWorkSummary) + + return ( + + + + + + {translate('auto.components.orca.profiles.switch.confirm.title', 'Switch profiles?')} + + + {translate( + 'auto.components.orca.profiles.switch.confirm.description', + 'Switching to {{targetName}} will relaunch Orca and reload the workspace for {{activeProfileName}}.', + { activeProfileName, targetName } + )} + + + + {lines.length > 0 ? ( +
    +
    + {translate( + 'auto.components.orca.profiles.switch.confirm.live.work', + 'Live work in this profile' + )} +
    +
      + {lines.map((line) => ( +
    • {line}
    • + ))} +
    +
    + ) : null} + + + + + +
    +
    + ) +} diff --git a/src/renderer/src/components/orca-profiles/OrcaProfileSwitcher.test.tsx b/src/renderer/src/components/orca-profiles/OrcaProfileSwitcher.test.tsx new file mode 100644 index 000000000000..cc52a10c975f --- /dev/null +++ b/src/renderer/src/components/orca-profiles/OrcaProfileSwitcher.test.tsx @@ -0,0 +1,172 @@ +// @vitest-environment happy-dom + +import type { ReactNode } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AppState } from '@/store' +import type { OrcaProfileAuthStatus, OrcaProfileSummary } from '../../../../shared/orca-profiles' +import { OrcaProfileSwitcher } from './OrcaProfileSwitcher' + +const mocks = vi.hoisted(() => ({ + state: {} as Partial +})) + +vi.mock('@/store', () => ({ + useAppStore: (selector: (state: Partial) => unknown) => selector(mocks.state) +})) + +vi.mock('@/components/ui/dropdown-menu', () => ({ + DropdownMenu: ({ children }: { children: ReactNode }) => <>{children}, + DropdownMenuContent: ({ children }: { children: ReactNode }) => <>{children}, + DropdownMenuItem: ({ children }: { children: ReactNode }) =>
    {children}
    , + DropdownMenuLabel: ({ children }: { children: ReactNode }) =>
    {children}
    , + DropdownMenuSeparator: () =>
    , + DropdownMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}, + DropdownMenuSub: ({ children }: { children: ReactNode }) => <>{children}, + DropdownMenuSubContent: ({ children }: { children: ReactNode }) => <>{children}, + DropdownMenuSubTrigger: ({ children }: { children: ReactNode }) =>
    {children}
    +})) + +vi.mock('@/components/ui/tooltip', () => ({ + Tooltip: ({ children }: { children: ReactNode }) => <>{children}, + TooltipContent: ({ children }: { children: ReactNode }) => {children}, + TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children} +})) + +vi.mock('@/components/ui/button', () => ({ + Button: ({ + children, + 'aria-label': ariaLabel + }: { + children: ReactNode + 'aria-label'?: string + }) => +})) + +vi.mock('./OrcaProfileAvatar', () => ({ + OrcaProfileAvatar: () => +})) + +vi.mock('./OrcaProfileCreateDialog', () => ({ + OrcaProfileCreateDialog: () =>
    +})) + +vi.mock('./OrcaProfileManagementDialog', () => ({ + OrcaProfileManagementDialog: () =>
    +})) + +vi.mock('./OrcaProfileSwitchConfirmDialog', () => ({ + OrcaProfileSwitchConfirmDialog: () =>
    +})) + +vi.mock('./OrcaProfileSignOutConfirmDialog', () => ({ + OrcaProfileSignOutConfirmDialog: () =>
    +})) + +vi.mock('./orca-profile-switch-liveness', () => ({ + getOrcaProfileSwitchLiveWorkSummary: () => ({ hasLiveWork: false }) +})) + +const cloudProfile: OrcaProfileSummary = { + id: 'local-default', + name: 'Personal', + avatar: { kind: 'initials', initials: 'P', color: 'neutral' }, + kind: 'cloud-linked', + createdAt: 1, + updatedAt: 1, + lastOpenedAt: 1, + cloud: { + cloudProfileId: 'cloud-1', + userId: 'user-1', + email: 'nina@example.com', + activeOrgId: 'org-1', + activeOrgName: 'Acme', + linkedAt: 2 + } +} + +const connectedAuthStatus: OrcaProfileAuthStatus = { + activeProfileId: 'local-default', + configured: true, + state: 'connected', + persistence: 'encrypted', + cloud: cloudProfile.cloud, + organizations: [ + { orgId: 'org-1', name: 'Acme' }, + { orgId: 'org-2', name: 'Globex' } + ] +} + +const unconfiguredAuthStatus: OrcaProfileAuthStatus = { + activeProfileId: 'local-default', + configured: false, + state: 'unconfigured', + persistence: 'none' +} + +function baseState(overrides: Partial): Partial { + return { + orcaProfiles: [cloudProfile], + activeOrcaProfileId: 'local-default', + orcaProfilesLoading: false, + orcaProfileSwitching: false, + orcaProfileConnecting: false, + orcaProfileAuthStatus: connectedAuthStatus, + orcaProfilesMultiProfileUi: false, + fetchOrcaProfiles: vi.fn(), + createLocalOrcaProfile: vi.fn(), + createCloudLinkedOrcaProfile: vi.fn(), + connectCurrentOrcaProfile: vi.fn(), + signOutCurrentOrcaProfile: vi.fn(), + selectOrcaProfileOrg: vi.fn(), + switchOrcaProfile: vi.fn(), + ...overrides + } +} + +describe('OrcaProfileSwitcher', () => { + beforeEach(() => { + mocks.state = baseState({}) + }) + + it('renders an account menu without profile management when the flag is off and cloud is configured', () => { + mocks.state = baseState({ orcaProfilesMultiProfileUi: false }) + const html = renderToStaticMarkup() + + expect(html).toContain('aria-label="Account"') + // Cloud actions stay reachable in the downscoped account menu. + expect(html).toContain('Sign out') + // Profile management surfaces are gone. + expect(html).not.toContain('Manage profiles') + expect(html).not.toContain('New local profile') + expect(html).not.toContain('Create profile for org') + expect(html).not.toContain('data-testid="create-dialog"') + expect(html).not.toContain('data-testid="management-dialog"') + expect(html).not.toContain('data-testid="switch-confirm-dialog"') + // Sign-out remains mounted. + expect(html).toContain('data-testid="signout-confirm-dialog"') + }) + + it('renders nothing when the flag is off and cloud is unconfigured', () => { + mocks.state = baseState({ + orcaProfilesMultiProfileUi: false, + orcaProfileAuthStatus: unconfiguredAuthStatus + }) + const html = renderToStaticMarkup() + + expect(html).toBe('') + }) + + it('renders the full multi-profile menu when the flag is on', () => { + mocks.state = baseState({ orcaProfilesMultiProfileUi: true }) + const html = renderToStaticMarkup() + + expect(html).toContain('aria-label="Switch profile"') + expect(html).toContain('Manage profiles') + expect(html).toContain('New local profile') + expect(html).toContain('Create profile for org') + expect(html).toContain('data-testid="create-dialog"') + expect(html).toContain('data-testid="management-dialog"') + expect(html).toContain('data-testid="switch-confirm-dialog"') + }) +}) diff --git a/src/renderer/src/components/orca-profiles/OrcaProfileSwitcher.tsx b/src/renderer/src/components/orca-profiles/OrcaProfileSwitcher.tsx new file mode 100644 index 000000000000..f8a98da9d0a4 --- /dev/null +++ b/src/renderer/src/components/orca-profiles/OrcaProfileSwitcher.tsx @@ -0,0 +1,403 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { Check, ChevronDown, Cloud, Laptop, Loader2, Plus, Settings2, Users } from 'lucide-react' +import { useShallow } from 'zustand/react/shallow' +import { Button } from '@/components/ui/button' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { translate } from '@/i18n/i18n' +import { cn } from '@/lib/utils' +import { useAppStore } from '@/store' +import type { OrcaCloudOrgSummary, OrcaProfileSummary } from '../../../../shared/orca-profiles' +import { OrcaProfileAvatar } from './OrcaProfileAvatar' +import { OrcaProfileCloudMenuItems } from './OrcaProfileCloudMenuItems' +import { OrcaProfileCreateDialog } from './OrcaProfileCreateDialog' +import { OrcaProfileOrgMembersDialog } from './OrcaProfileOrgMembersDialog' +import { OrcaProfileManagementDialog } from './OrcaProfileManagementDialog' +import { OrcaProfileSignOutConfirmDialog } from './OrcaProfileSignOutConfirmDialog' +import { OrcaProfileSwitchConfirmDialog } from './OrcaProfileSwitchConfirmDialog' +import { getOrcaProfileSwitchLiveWorkSummary } from './orca-profile-switch-liveness' + +function isWebClient(): boolean { + return Boolean((window as unknown as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__) +} + +function getProfileSubtitle(profile: OrcaProfileSummary): string { + if (profile.cloud?.activeOrgName) { + return profile.cloud.activeOrgName + } + if (profile.cloud?.email) { + return profile.cloud.email + } + return translate('auto.components.orca.profiles.switcher.b4f9d1125d', 'Local') +} + +export function OrcaProfileSwitcher({ + placement = 'titlebar' +}: { + placement?: 'titlebar' | 'sidebar' +}): React.JSX.Element | null { + const profiles = useAppStore((s) => s.orcaProfiles) + const activeProfileId = useAppStore((s) => s.activeOrcaProfileId) + const loading = useAppStore((s) => s.orcaProfilesLoading) + const switching = useAppStore((s) => s.orcaProfileSwitching) + const connecting = useAppStore((s) => s.orcaProfileConnecting) + const authStatus = useAppStore((s) => s.orcaProfileAuthStatus) + const multiProfileUi = useAppStore((s) => s.orcaProfilesMultiProfileUi) + const fetchProfiles = useAppStore((s) => s.fetchOrcaProfiles) + const createLocalProfile = useAppStore((s) => s.createLocalOrcaProfile) + const createCloudLinkedProfile = useAppStore((s) => s.createCloudLinkedOrcaProfile) + const connectCurrentProfile = useAppStore((s) => s.connectCurrentOrcaProfile) + const signOutCurrentProfile = useAppStore((s) => s.signOutCurrentOrcaProfile) + const selectOrg = useAppStore((s) => s.selectOrcaProfileOrg) + const switchProfile = useAppStore((s) => s.switchOrcaProfile) + const liveWorkSummary = useAppStore(useShallow((s) => getOrcaProfileSwitchLiveWorkSummary(s))) + const [dialogOpen, setDialogOpen] = useState(false) + const [managementOpen, setManagementOpen] = useState(false) + const [newProfileName, setNewProfileName] = useState('') + const [creating, setCreating] = useState(false) + const [creatingCloudProfile, setCreatingCloudProfile] = useState(false) + const [signOutConfirmOpen, setSignOutConfirmOpen] = useState(false) + const [signingOut, setSigningOut] = useState(false) + const [orgMembersOpen, setOrgMembersOpen] = useState(false) + const [pendingSwitchProfileId, setPendingSwitchProfileId] = useState(null) + const activeProfile = useMemo( + () => profiles.find((profile) => profile.id === activeProfileId) ?? profiles[0] ?? null, + [activeProfileId, profiles] + ) + const pendingSwitchProfile = useMemo( + () => profiles.find((profile) => profile.id === pendingSwitchProfileId) ?? null, + [pendingSwitchProfileId, profiles] + ) + + // Why: one attempt per mount — retrying on every loading toggle would spin + // an unbounded IPC loop when the list call persistently fails. + const fetchAttemptedRef = useRef(false) + useEffect(() => { + if (profiles.length === 0 && !loading && !fetchAttemptedRef.current) { + fetchAttemptedRef.current = true + void fetchProfiles() + } + }, [fetchProfiles, loading, profiles.length]) + + // Why: the Orca Cloud account UX isn't ready for production users yet, so the + // trigger stays hidden in packaged builds. Dev builds still show it when + // cloud auth is configured, and a dev-only Settings > Dev Tools > Orca Cloud + // section mirrors it. import.meta.env.PROD is true only in packaged builds + // (false in dev and under vitest), so tests still exercise the render path. + if (import.meta.env.PROD) { + return null + } + + // Why: paired web/mobile clients only see the desktop stub's fabricated + // profile list; showing a switcher there would misreport the active profile + // and none of its actions can work remotely. + if (isWebClient() || !activeProfile) { + return null + } + + // Why: with multi-profile UI downscoped, local-only builds (no cloud + // configured) have nothing to offer in an account menu — show no trigger. + if (!multiProfileUi && authStatus?.configured !== true) { + return null + } + + const handleCreateProfile = async (event: React.FormEvent): Promise => { + event.preventDefault() + if (creating || switching) { + return + } + setCreating(true) + const profile = await createLocalProfile(newProfileName) + setCreating(false) + if (!profile) { + return + } + setNewProfileName('') + setDialogOpen(false) + if (liveWorkSummary.hasLiveWork) { + setPendingSwitchProfileId(profile.id) + return + } + await switchProfile(profile.id) + } + + const handleSwitchProfile = (profileId: string): void => { + if (profileId === activeProfileId || switching) { + return + } + if (liveWorkSummary.hasLiveWork) { + setPendingSwitchProfileId(profileId) + return + } + void switchProfile(profileId) + } + + const handleConfirmSwitchProfile = (): void => { + if (!pendingSwitchProfileId || switching) { + return + } + void switchProfile(pendingSwitchProfileId) + } + + const handleCreateCloudProfileForOrg = async ( + organization: OrcaCloudOrgSummary + ): Promise => { + if (creatingCloudProfile || switching) { + return + } + setCreatingCloudProfile(true) + const result = await createCloudLinkedProfile({ + orgId: organization.orgId, + name: organization.name + }) + setCreatingCloudProfile(false) + if (result?.status !== 'created') { + return + } + if (liveWorkSummary.hasLiveWork) { + setPendingSwitchProfileId(result.profile.id) + return + } + await switchProfile(result.profile.id) + } + + const handleConfirmSignOut = async (): Promise => { + if (signingOut) { + return + } + setSigningOut(true) + const result = await signOutCurrentProfile() + setSigningOut(false) + if (result) { + setSignOutConfirmOpen(false) + } + } + + const profileActionDisabled = + switching || creating || creatingCloudProfile || connecting || signingOut + // Why: teammate management needs a connected cloud profile scoped to an org; + // the server enforces role permissions, and the dialog adapts via + // canManageMembers, so cloud-linked + org + connected is enough to reveal it. + const activeOrgId = activeProfile.cloud?.activeOrgId + const showOrgMembers = + activeProfile.kind === 'cloud-linked' && + Boolean(activeOrgId) && + authStatus?.state === 'connected' + const sidebarPlacement = placement === 'sidebar' + const triggerLabel = multiProfileUi + ? translate('auto.components.orca.profiles.switcher.4815f7d163', 'Switch profile') + : translate('auto.components.orca.profiles.switcher.account', 'Account') + + return ( + <> + + + + + + + + + {triggerLabel} + + + + +
    + +
    +
    + {activeProfile.name} +
    +
    + {getProfileSubtitle(activeProfile)} +
    +
    +
    +
    + + {multiProfileUi + ? profiles.map((profile) => { + const active = profile.id === activeProfileId + return ( + handleSwitchProfile(profile.id)} + className="min-w-0" + > + + + {profile.name} + + {getProfileSubtitle(profile)} + + + {profile.kind === 'cloud-linked' ? : } + {active && } + + ) + }) + : null} + {showOrgMembers ? ( + <> + + setOrgMembersOpen(true)} + > + + {translate( + 'auto.components.orca.profiles.switcher.org.members', + 'Organization members' + )} + + + ) : null} + { + void connectCurrentProfile() + }} + onCreateProfileForOrg={(organization) => { + void handleCreateCloudProfileForOrg(organization) + }} + onSelectOrg={(orgId) => { + void selectOrg(orgId) + }} + onRequestSignOut={() => setSignOutConfirmOpen(true)} + /> + {multiProfileUi ? ( + <> + + { + setManagementOpen(true) + }} + > + + {translate('auto.components.orca.profiles.switcher.d00d853e2a', 'Manage profiles')} + + { + setDialogOpen(true) + }} + > + + {translate( + 'auto.components.orca.profiles.switcher.c106c674fe', + 'New local profile' + )} + + + ) : null} +
    +
    + + {multiProfileUi ? ( + <> + + + + ) : null} + {showOrgMembers && activeOrgId ? ( + + ) : null} + { + if (!signingOut) { + setSignOutConfirmOpen(open) + } + }} + onConfirm={() => { + void handleConfirmSignOut() + }} + profileName={activeProfile.name} + signingOut={signingOut} + /> + {multiProfileUi ? ( + { + if (!open && !switching) { + setPendingSwitchProfileId(null) + } + }} + onConfirm={handleConfirmSwitchProfile} + activeProfileName={activeProfile.name} + targetProfile={pendingSwitchProfile} + liveWorkSummary={liveWorkSummary} + switching={switching} + /> + ) : null} + + ) +} diff --git a/src/renderer/src/components/orca-profiles/orca-profile-org-members-labels.ts b/src/renderer/src/components/orca-profiles/orca-profile-org-members-labels.ts new file mode 100644 index 000000000000..9378d77cec11 --- /dev/null +++ b/src/renderer/src/components/orca-profiles/orca-profile-org-members-labels.ts @@ -0,0 +1,79 @@ +import { translate } from '@/i18n/i18n' +import type { + OrcaOrgRole, + OrcaProfileOrgMemberMutationResult +} from '../../../../shared/orca-profiles' + +export const ORG_ROLE_OPTIONS: readonly OrcaOrgRole[] = ['owner', 'admin', 'member'] + +export function orgRoleLabel(role: OrcaOrgRole): string { + switch (role) { + case 'owner': + return translate('auto.components.orca.profiles.org.members.role.owner', 'Owner') + case 'admin': + return translate('auto.components.orca.profiles.org.members.role.admin', 'Admin') + case 'member': + return translate('auto.components.orca.profiles.org.members.role.member', 'Member') + } +} + +export function orgMemberInitials(displayName: string | undefined, email: string): string { + const source = displayName?.trim() || email.trim() + if (!source) { + return '?' + } + const words = source.split(/\s+/).filter(Boolean) + if (words.length >= 2) { + return `${words[0][0]}${words[1][0]}`.toUpperCase() + } + return source.slice(0, 2).toUpperCase() +} + +// Why: the dialog maps every non-ok mutation status to a precise, translated +// message so managers see why an action was rejected instead of a raw code. +export function describeOrgMutationError( + result: Exclude +): string { + switch (result.status) { + case 'forbidden': + return translate( + 'auto.components.orca.profiles.org.members.error.forbidden', + "Your role can't do that." + ) + case 'conflict': + return translate( + 'auto.components.orca.profiles.org.members.error.conflict', + 'Already a member or invited.' + ) + case 'invalid': + return result.reason === 'cannot_remove_self' + ? translate( + 'auto.components.orca.profiles.org.members.error.remove.self', + "You can't remove yourself." + ) + : translate( + 'auto.components.orca.profiles.org.members.error.own.role', + "You can't change your own role." + ) + case 'not-found': + return translate( + 'auto.components.orca.profiles.org.members.error.not.found', + 'That teammate is no longer in this organization.' + ) + case 'reconnect-required': + return translate( + 'auto.components.orca.profiles.org.members.error.reconnect', + 'Reconnect your profile to manage members.' + ) + case 'unconfigured': + return translate( + 'auto.components.orca.profiles.org.members.error.unconfigured', + 'Organization management is unavailable in this build.' + ) + case 'failed': + return translate( + 'auto.components.orca.profiles.org.members.error.failed', + 'Something went wrong. Please try again.' + ) + } +} diff --git a/src/renderer/src/components/orca-profiles/orca-profile-switch-liveness.test.ts b/src/renderer/src/components/orca-profiles/orca-profile-switch-liveness.test.ts new file mode 100644 index 000000000000..1dfc08737274 --- /dev/null +++ b/src/renderer/src/components/orca-profiles/orca-profile-switch-liveness.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, it } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import type { BrowserWorkspace, TerminalTab } from '../../../../shared/types' +import { + getOrcaProfileProjectLiveWorkSummary, + getOrcaProfileSwitchLiveWorkSummary, + type OrcaProfileSwitchLiveWorkState +} from './orca-profile-switch-liveness' + +const NOW = 1_000_000 + +function makeState( + overrides: Partial = {} +): OrcaProfileSwitchLiveWorkState { + return { + agentStatusByPaneKey: {}, + browserTabsByWorktree: {}, + ptyIdsByTabId: {}, + runtimePaneTitlesByTabId: {}, + tabsByWorktree: {}, + ...overrides + } +} + +function makeTab( + overrides: Partial> & { + id: string + worktreeId?: string + } +): TerminalTab { + const { id, worktreeId = 'worktree-1', ...rest } = overrides + return { + id, + color: null, + createdAt: NOW, + customTitle: null, + ptyId: null, + sortOrder: 0, + title: 'zsh', + worktreeId, + ...rest + } +} + +function makeAgentEntry(overrides: Partial = {}): AgentStatusEntry { + return { + paneKey: 'tab-1:0', + prompt: '', + state: 'working', + stateHistory: [], + stateStartedAt: NOW, + updatedAt: NOW, + ...overrides + } +} + +function makeBrowserWorkspace(id: string): BrowserWorkspace { + return { + id, + activePageId: null, + canGoBack: false, + canGoForward: false, + createdAt: NOW, + faviconUrl: null, + label: 'Browser', + loadError: null, + loading: false, + pageIds: [], + title: 'Browser', + url: 'about:blank', + worktreeId: 'worktree-1' + } +} + +describe('getOrcaProfileSwitchLiveWorkSummary', () => { + it('reports quiet profiles as safe to switch without confirmation', () => { + expect(getOrcaProfileSwitchLiveWorkSummary(makeState(), NOW)).toEqual({ + browserWorkspaceCount: 0, + hasLiveWork: false, + liveAgentCount: 0, + livePtyCount: 0, + liveTerminalTabCount: 0 + }) + }) + + it('counts live PTYs as live terminal work', () => { + const summary = getOrcaProfileSwitchLiveWorkSummary( + makeState({ + ptyIdsByTabId: { + 'tab-1': ['pty-1', 'pty-2'], + 'tab-2': [] + } + }), + NOW + ) + + expect(summary).toMatchObject({ + hasLiveWork: true, + livePtyCount: 2, + liveTerminalTabCount: 1 + }) + }) + + it('counts fresh working explicit agent status', () => { + const summary = getOrcaProfileSwitchLiveWorkSummary( + makeState({ + agentStatusByPaneKey: { + 'tab-1:0': makeAgentEntry({ paneKey: 'tab-1:0', state: 'working' }), + 'tab-2:0': makeAgentEntry({ paneKey: 'tab-2:0', state: 'done' }), + 'tab-3:0': makeAgentEntry({ + paneKey: 'tab-3:0', + state: 'waiting', + updatedAt: -999_999_999 + }) + } + }), + NOW + ) + + expect(summary.liveAgentCount).toBe(1) + expect(summary.hasLiveWork).toBe(true) + }) + + it('counts title-detected agents only when the tab has a live PTY', () => { + const summary = getOrcaProfileSwitchLiveWorkSummary( + makeState({ + ptyIdsByTabId: { + 'tab-live': ['pty-1'] + }, + tabsByWorktree: { + 'worktree-1': [ + makeTab({ id: 'tab-live', title: 'Codex working' }), + makeTab({ id: 'tab-slept', title: 'Codex working' }) + ] + } + }), + NOW + ) + + expect(summary.liveAgentCount).toBe(1) + expect(summary.hasLiveWork).toBe(true) + }) + + it('counts browser workspaces as live browser work', () => { + const summary = getOrcaProfileSwitchLiveWorkSummary( + makeState({ + browserTabsByWorktree: { + 'worktree-1': [makeBrowserWorkspace('browser-1'), makeBrowserWorkspace('browser-2')] + } + }), + NOW + ) + + expect(summary).toMatchObject({ + browserWorkspaceCount: 2, + hasLiveWork: true + }) + }) + + it('filters live work to the selected project', () => { + const summary = getOrcaProfileProjectLiveWorkSummary( + makeState({ + agentStatusByPaneKey: { + 'other-tab:0': makeAgentEntry({ + paneKey: 'other-tab:0', + worktreeId: 'repo-other::/workspace/other' + }) + }, + browserTabsByWorktree: { + 'repo-1::/workspace/orca': [makeBrowserWorkspace('browser-1')], + 'repo-other::/workspace/other': [makeBrowserWorkspace('browser-2')] + }, + ptyIdsByTabId: { + 'tab-live': ['pty-1'], + 'other-tab': ['pty-2'] + }, + tabsByWorktree: { + 'repo-1::/workspace/orca': [makeTab({ id: 'tab-live', title: 'Codex working' })], + 'repo-other::/workspace/other': [makeTab({ id: 'other-tab', title: 'Codex working' })] + } + }), + 'repo-1', + NOW + ) + + expect(summary).toMatchObject({ + browserWorkspaceCount: 1, + hasLiveWork: true, + liveAgentCount: 1, + livePtyCount: 1, + liveTerminalTabCount: 1 + }) + }) +}) diff --git a/src/renderer/src/components/orca-profiles/orca-profile-switch-liveness.ts b/src/renderer/src/components/orca-profiles/orca-profile-switch-liveness.ts new file mode 100644 index 000000000000..c96a1812157d --- /dev/null +++ b/src/renderer/src/components/orca-profiles/orca-profile-switch-liveness.ts @@ -0,0 +1,180 @@ +import type { AppState } from '@/store/types' +import { + AGENT_STATUS_STALE_AFTER_MS, + type AgentStatusEntry +} from '../../../../shared/agent-status-types' +import type { TerminalTab } from '../../../../shared/types' +import { getRepoIdFromWorktreeId } from '../../../../shared/worktree-id' +import { detectAgentStatusFromTitle, isExplicitAgentStatusFresh } from '@/lib/agent-status' +import { tabHasLivePty } from '@/lib/tab-has-live-pty' + +export type OrcaProfileSwitchLiveWorkState = Pick< + AppState, + | 'agentStatusByPaneKey' + | 'browserTabsByWorktree' + | 'ptyIdsByTabId' + | 'runtimePaneTitlesByTabId' + | 'tabsByWorktree' +> + +export type OrcaProfileSwitchLiveWorkSummary = { + hasLiveWork: boolean + liveAgentCount: number + livePtyCount: number + liveTerminalTabCount: number + browserWorkspaceCount: number +} + +const LIVE_AGENT_STATES = new Set(['working', 'blocked', 'waiting']) + +export function getOrcaProfileSwitchLiveWorkSummary( + state: OrcaProfileSwitchLiveWorkState, + now = Date.now() +): OrcaProfileSwitchLiveWorkSummary { + const terminalSummary = getLiveTerminalSummary(state) + const liveAgentCount = getLiveAgentKeys(state, now).size + const browserWorkspaceCount = Object.values(state.browserTabsByWorktree).reduce( + (count, workspaces) => count + workspaces.length, + 0 + ) + + return { + hasLiveWork: + terminalSummary.livePtyCount > 0 || liveAgentCount > 0 || browserWorkspaceCount > 0, + liveAgentCount, + livePtyCount: terminalSummary.livePtyCount, + liveTerminalTabCount: terminalSummary.liveTerminalTabCount, + browserWorkspaceCount + } +} + +export function getOrcaProfileProjectLiveWorkSummary( + state: OrcaProfileSwitchLiveWorkState, + repoId: string, + now = Date.now() +): OrcaProfileSwitchLiveWorkSummary { + const tabsByWorktree = Object.fromEntries( + Object.entries(state.tabsByWorktree).filter(([worktreeId]) => + worktreeBelongsToRepo(worktreeId, repoId) + ) + ) + const tabIds = new Set(Object.values(tabsByWorktree).flatMap((tabs) => tabs.map((tab) => tab.id))) + const browserTabsByWorktree = Object.fromEntries( + Object.entries(state.browserTabsByWorktree).filter(([worktreeId]) => + worktreeBelongsToRepo(worktreeId, repoId) + ) + ) + const ptyIdsByTabId = Object.fromEntries( + Object.entries(state.ptyIdsByTabId).filter(([tabId]) => tabIds.has(tabId)) + ) + const runtimePaneTitlesByTabId = Object.fromEntries( + Object.entries(state.runtimePaneTitlesByTabId).filter(([tabId]) => tabIds.has(tabId)) + ) + const agentStatusByPaneKey = Object.fromEntries( + Object.entries(state.agentStatusByPaneKey).filter(([paneKey, entry]) => + agentEntryBelongsToProject(paneKey, entry, repoId, tabIds) + ) + ) + + return getOrcaProfileSwitchLiveWorkSummary( + { + agentStatusByPaneKey, + browserTabsByWorktree, + ptyIdsByTabId, + runtimePaneTitlesByTabId, + tabsByWorktree + }, + now + ) +} + +function getLiveTerminalSummary(state: OrcaProfileSwitchLiveWorkState): { + livePtyCount: number + liveTerminalTabCount: number +} { + const liveTabIds = new Set() + let livePtyCount = 0 + + for (const [tabId, ptyIds] of Object.entries(state.ptyIdsByTabId)) { + if (ptyIds.length === 0) { + continue + } + livePtyCount += ptyIds.length + liveTabIds.add(tabId) + } + + return { + livePtyCount, + liveTerminalTabCount: liveTabIds.size + } +} + +function getLiveAgentKeys(state: OrcaProfileSwitchLiveWorkState, now: number): Set { + const keys = new Set() + for (const entry of Object.values(state.agentStatusByPaneKey)) { + if ( + LIVE_AGENT_STATES.has(entry.state) && + isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS) + ) { + keys.add(entry.paneKey) + } + } + + for (const tabs of Object.values(state.tabsByWorktree)) { + for (const tab of tabs) { + addTitleDetectedLiveAgentKeys(keys, state, tab) + } + } + + return keys +} + +function addTitleDetectedLiveAgentKeys( + keys: Set, + state: OrcaProfileSwitchLiveWorkState, + tab: TerminalTab +): void { + if (!tabHasLivePty(state.ptyIdsByTabId, tab.id)) { + return + } + + const paneTitles = state.runtimePaneTitlesByTabId[tab.id] + if (paneTitles && Object.keys(paneTitles).length > 0) { + for (const [paneId, title] of Object.entries(paneTitles)) { + if (isLiveAgentTitle(title)) { + keys.add(`${tab.id}:${paneId}`) + } + } + return + } + + if (isLiveAgentTitle(tab.title)) { + keys.add(`${tab.id}:title`) + } +} + +function isLiveAgentTitle(title: string): boolean { + const status = detectAgentStatusFromTitle(title) + return status === 'working' || status === 'permission' +} + +function agentEntryBelongsToProject( + paneKey: string, + entry: AgentStatusEntry, + repoId: string, + tabIds: Set +): boolean { + if (entry.worktreeId && worktreeBelongsToRepo(entry.worktreeId, repoId)) { + return true + } + return tabIds.has(getPaneKeyTabId(paneKey)) +} + +function getPaneKeyTabId(paneKey: string): string { + const separatorIndex = paneKey.lastIndexOf(':') + return separatorIndex === -1 ? paneKey : paneKey.slice(0, separatorIndex) +} + +function worktreeBelongsToRepo(worktreeId: string, repoId: string): boolean { + return getRepoIdFromWorktreeId(worktreeId) === repoId +} diff --git a/src/renderer/src/components/ports/WorkspacePortScanner.test.tsx b/src/renderer/src/components/ports/WorkspacePortScanner.test.tsx index fa72745c3c34..35bf87d06ad0 100644 --- a/src/renderer/src/components/ports/WorkspacePortScanner.test.tsx +++ b/src/renderer/src/components/ports/WorkspacePortScanner.test.tsx @@ -14,11 +14,14 @@ import { clearRuntimeCompatibilityCache, markRuntimeEnvironmentCompatible } from '@/runtime/runtime-rpc-client' +import { getWorkspacePortsByWorktreeId } from '@/lib/workspace-port-groups' import { useAppStore } from '@/store' import { WorkspacePortScanner } from './WorkspacePortScanner' const localScan = vi.fn() const runtimeEnvironmentCall = vi.fn() +const remoteScanKey = 'environment:env-1:all' +const remoteWorktreeId = 'repo-1::/remote/repo' let container: HTMLDivElement | null = null let root: Root | null = null @@ -27,6 +30,99 @@ const emptyScan: WorkspacePortScanResult = { scannedAt: 1, ports: [] } +const liveScan: WorkspacePortScanResult = { + platform: 'linux', + scannedAt: 1, + ports: [ + { + id: 'tcp:3000', + bindHost: '127.0.0.1', + connectHost: '127.0.0.1', + port: 3000, + protocol: 'http', + kind: 'workspace', + owner: { + worktreeId: remoteWorktreeId, + repoId: 'repo-1', + displayName: 'main', + path: '/remote/repo', + confidence: 'cwd' + } + } + ] +} + +function addRemoteWorkspace(environmentId: string): void { + const state = useAppStore.getState() + const repoId = `repo-${environmentId}` + const path = `/remote/${environmentId}` + useAppStore.setState({ + repos: [ + ...state.repos, + { + id: repoId, + path, + displayName: environmentId, + connectionId: null, + executionHostId: toRuntimeExecutionHostId(environmentId) + } + ] as never, + worktreesByRepo: { + ...state.worktreesByRepo, + [repoId]: [ + { + id: `${repoId}::${path}`, + repoId, + path, + displayName: 'main' + } + ] + } as never + }) +} + +function removeRemoteWorkspaces(environmentIds: string[]): void { + const repoIds = new Set(environmentIds.map((environmentId) => `repo-${environmentId}`)) + const state = useAppStore.getState() + useAppStore.setState({ + repos: state.repos.filter((repo) => !repoIds.has(repo.id)) as never, + worktreesByRepo: Object.fromEntries( + Object.entries(state.worktreesByRepo).filter(([repoId]) => !repoIds.has(repoId)) + ) as never + }) +} + +function removeAllWorktrees(): void { + const state = useAppStore.getState() + useAppStore.setState({ + worktreesByRepo: Object.fromEntries( + Object.keys(state.worktreesByRepo).map((repoId) => [repoId, []]) + ) as never + }) +} + +function overrideDocumentVisibilityState( + getVisibilityState: () => DocumentVisibilityState +): () => void { + const descriptor = Object.getOwnPropertyDescriptor(document, 'visibilityState') + Object.defineProperty(document, 'visibilityState', { + configurable: true, + get: getVisibilityState + }) + return () => { + if (descriptor) { + Object.defineProperty(document, 'visibilityState', descriptor) + } else { + Reflect.deleteProperty(document, 'visibilityState') + } + } +} + +function getPublishedRemoteWorktreePorts() { + return getWorkspacePortsByWorktreeId(useAppStore.getState().workspacePortScan?.result).get( + remoteWorktreeId + ) +} const compatibleStatus = { runtimeId: 'env-1', @@ -40,11 +136,11 @@ async function flushPromises(): Promise { await Promise.resolve() } -function seedRemoteWorkspace(): void { +function seedRemoteWorkspace(environmentId = 'env-1'): void { useAppStore.setState({ settings: { ...getDefaultSettings('/tmp/orca-workspaces'), - activeRuntimeEnvironmentId: 'env-1' + activeRuntimeEnvironmentId: environmentId }, repos: [ { @@ -52,7 +148,7 @@ function seedRemoteWorkspace(): void { path: '/remote/repo', displayName: 'Remote Repo', connectionId: null, - executionHostId: toRuntimeExecutionHostId('env-1') + executionHostId: toRuntimeExecutionHostId(environmentId) } ] as never, worktreesByRepo: { @@ -164,4 +260,265 @@ describe('WorkspacePortScanner', () => { }) expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(2) }) + + it('scans a changed execution host immediately instead of applying the prior throttle', async () => { + await act(async () => { + root?.render() + await flushPromises() + }) + expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(1) + + markRuntimeEnvironmentCompatible('env-2') + await act(async () => { + seedRemoteWorkspace('env-2') + await flushPromises() + }) + + expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(2) + expect(runtimeEnvironmentCall).toHaveBeenLastCalledWith({ + selector: 'env-2', + method: 'workspacePorts.scan', + params: {}, + timeoutMs: 15_000 + }) + }) + + it('keeps an unchanged host scan when another execution host is added', async () => { + let env1Attempts = 0 + runtimeEnvironmentCall.mockImplementation(({ selector, method }) => { + if (method !== 'workspacePorts.scan') { + return Promise.resolve({ ok: false, error: { code: 'method_not_found', message: method } }) + } + if (selector !== 'env-1') { + return Promise.resolve({ ok: true, result: emptyScan }) + } + env1Attempts += 1 + return Promise.resolve({ ok: true, result: liveScan }) + }) + + await act(async () => { + root?.render() + await flushPromises() + }) + expect(useAppStore.getState().workspacePortScansByKey[remoteScanKey]).toBe(liveScan) + + markRuntimeEnvironmentCompatible('env-2') + await act(async () => { + addRemoteWorkspace('env-2') + await flushPromises() + }) + + expect(env1Attempts).toBe(1) + expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(2) + expect(runtimeEnvironmentCall).toHaveBeenLastCalledWith({ + selector: 'env-2', + method: 'workspacePorts.scan', + params: {}, + timeoutMs: 15_000 + }) + expect(getPublishedRemoteWorktreePorts()).toHaveLength(1) + }) + + it('scans only the added host when the window becomes visible', async () => { + let env1Attempts = 0 + runtimeEnvironmentCall.mockImplementation(({ selector, method }) => { + if (method !== 'workspacePorts.scan') { + return Promise.resolve({ ok: false, error: { code: 'method_not_found', message: method } }) + } + if (selector !== 'env-1') { + return Promise.resolve({ ok: true, result: emptyScan }) + } + env1Attempts += 1 + return Promise.resolve({ ok: true, result: liveScan }) + }) + let visibilityState: DocumentVisibilityState = 'visible' + const restoreVisibilityState = overrideDocumentVisibilityState(() => visibilityState) + try { + await act(async () => { + root?.render() + await flushPromises() + }) + expect(env1Attempts).toBe(1) + + visibilityState = 'hidden' + markRuntimeEnvironmentCompatible('env-2') + await act(async () => { + addRemoteWorkspace('env-2') + await flushPromises() + }) + expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(1) + + visibilityState = 'visible' + await act(async () => { + document.dispatchEvent(new Event('visibilitychange')) + await flushPromises() + }) + + expect(env1Attempts).toBe(1) + expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(2) + expect(runtimeEnvironmentCall).toHaveBeenLastCalledWith({ + selector: 'env-2', + method: 'workspacePorts.scan', + params: {}, + timeoutMs: 15_000 + }) + } finally { + restoreVisibilityState() + } + }) + + it('clears the refreshing state when a retained-host focus change supersedes a poll', async () => { + let env1Calls = 0 + let env2Calls = 0 + let resolveSecondPoll!: (result: { ok: true; result: WorkspacePortScanResult }) => void + const secondPoll = new Promise<{ ok: true; result: WorkspacePortScanResult }>((resolve) => { + resolveSecondPoll = resolve + }) + runtimeEnvironmentCall.mockImplementation(({ selector, method }) => { + if (method !== 'workspacePorts.scan') { + return Promise.resolve({ ok: false, error: { code: 'method_not_found', message: method } }) + } + if (selector === 'env-1') { + env1Calls += 1 + return env1Calls === 1 ? Promise.resolve({ ok: true, result: liveScan }) : secondPoll + } + env2Calls += 1 + return env2Calls === 1 ? Promise.resolve({ ok: true, result: emptyScan }) : secondPoll + }) + markRuntimeEnvironmentCompatible('env-2') + addRemoteWorkspace('env-2') + + await act(async () => { + root?.render() + await flushPromises() + }) + + await act(async () => { + vi.advanceTimersByTime(30_000) + await flushPromises() + }) + expect(useAppStore.getState().workspacePortScanRefreshing).toBe(true) + + await act(async () => { + useAppStore.setState({ + settings: { + ...getDefaultSettings('/tmp/orca-workspaces'), + activeRuntimeEnvironmentId: 'env-2' + } + }) + await flushPromises() + }) + expect(useAppStore.getState().workspacePortScanRefreshing).toBe(false) + + await act(async () => { + resolveSecondPoll({ ok: true, result: emptyScan }) + await flushPromises() + }) + }) + + it('removes multiple stale host scans in one map publication', async () => { + markRuntimeEnvironmentCompatible('env-2') + markRuntimeEnvironmentCompatible('env-3') + addRemoteWorkspace('env-2') + addRemoteWorkspace('env-3') + + await act(async () => { + root?.render() + await flushPromises() + }) + + let mapNotifications = 0 + const unsubscribe = useAppStore.subscribe((state, previousState) => { + if (state.workspacePortScansByKey !== previousState.workspacePortScansByKey) { + mapNotifications += 1 + } + }) + await act(async () => { + removeRemoteWorkspaces(['env-2', 'env-3']) + await flushPromises() + }) + unsubscribe() + + expect(mapNotifications).toBe(1) + expect(useAppStore.getState().workspacePortScansByKey['environment:env-2:all']).toBeUndefined() + expect(useAppStore.getState().workspacePortScansByKey['environment:env-3:all']).toBeUndefined() + }) + + it('clears ports immediately when the final worktree is removed', async () => { + runtimeEnvironmentCall.mockImplementation(({ method }) => { + if (method === 'workspacePorts.scan') { + return Promise.resolve({ ok: true, result: liveScan }) + } + return Promise.resolve({ ok: false, error: { code: 'method_not_found', message: method } }) + }) + + await act(async () => { + root?.render() + await flushPromises() + }) + expect(useAppStore.getState().workspacePortScan).not.toBeNull() + + await act(async () => { + removeAllWorktrees() + await flushPromises() + }) + + expect(useAppStore.getState().workspacePortScan).toBeNull() + expect(useAppStore.getState().workspacePortScansByKey).toEqual({}) + expect(useAppStore.getState().workspacePortScanRefreshing).toBe(false) + }) + + it('keeps the last reachable ports through one failed remote poll', async () => { + let scanAttempts = 0 + runtimeEnvironmentCall.mockImplementation(({ method }) => { + if (method !== 'workspacePorts.scan') { + return Promise.resolve({ ok: false, error: { code: 'method_not_found', message: method } }) + } + scanAttempts += 1 + if (scanAttempts === 1) { + return Promise.resolve({ ok: true, result: liveScan }) + } + return Promise.reject(new Error('temporary runtime failure')) + }) + + await act(async () => { + root?.render() + await flushPromises() + }) + expect(useAppStore.getState().workspacePortScansByKey[remoteScanKey]).toBe(liveScan) + expect(getPublishedRemoteWorktreePorts()).toHaveLength(1) + + let mapNotifications = 0 + let projectionNotifications = 0 + const firstProjection = useAppStore.getState().workspacePortScan + const unsubscribe = useAppStore.subscribe((state, previousState) => { + if (state.workspacePortScansByKey !== previousState.workspacePortScansByKey) { + mapNotifications += 1 + } + if (state.workspacePortScan !== previousState.workspacePortScan) { + projectionNotifications += 1 + } + }) + + await act(async () => { + vi.advanceTimersByTime(30_000) + await flushPromises() + }) + unsubscribe() + expect(useAppStore.getState().workspacePortScansByKey[remoteScanKey]).toBe(liveScan) + expect(getPublishedRemoteWorktreePorts()).toHaveLength(1) + expect(mapNotifications).toBe(0) + expect(useAppStore.getState().workspacePortScan).toBe(firstProjection) + expect(projectionNotifications).toBe(0) + + await act(async () => { + vi.advanceTimersByTime(30_000) + await flushPromises() + }) + expect(useAppStore.getState().workspacePortScansByKey[remoteScanKey]).toMatchObject({ + ports: [], + unavailableReason: 'temporary runtime failure' + }) + expect(getPublishedRemoteWorktreePorts()).toBeUndefined() + }) }) diff --git a/src/renderer/src/components/ports/WorkspacePortScanner.tsx b/src/renderer/src/components/ports/WorkspacePortScanner.tsx index be7fd9230446..f2805eb88a7a 100644 --- a/src/renderer/src/components/ports/WorkspacePortScanner.tsx +++ b/src/renderer/src/components/ports/WorkspacePortScanner.tsx @@ -9,6 +9,10 @@ import { workspacePortScanKeyForTarget } from '@/lib/workspace-port-actions' import { installWindowVisibilityInterval, isWindowVisible } from '@/lib/window-visibility-interval' +import { + reconcileTransientPortScanFailures, + type PortScanDebounceState +} from '@/lib/workspace-port-scan-debounce' import type { WorkspacePortScanResult } from '../../../../shared/workspace-ports' import { buildExecutionHostRegistry } from '../../../../shared/execution-host-registry' @@ -16,7 +20,10 @@ const WORKSPACE_PORT_SCAN_INTERVAL_MS = 30_000 const WORKSPACE_PORT_ADVERTISED_URL_SETTLE_MS = 1_000 type WorkspacePortScannerRefreshOptions = { force?: boolean + targets?: readonly RuntimeClientTarget[] } +// Why: keep live ports through one dropped SSH/IPC scan while reachable empty scans clear now. +const WORKSPACE_PORT_SCAN_FAILURE_THRESHOLD = 2 function makeUnavailableScan(reason: string): WorkspacePortScanResult { return { @@ -32,12 +39,16 @@ export function WorkspacePortScanner({ enabled = true }: { enabled?: boolean }): const repos = useAppStore((s) => s.repos) const hasWorktrees = useAppStore(getHasAnyWorktreesFromState) const setWorkspacePortScan = useAppStore((s) => s.setWorkspacePortScan) + const setWorkspacePortScanProjection = useAppStore((s) => s.setWorkspacePortScanProjection) + const replaceWorkspacePortScans = useAppStore((s) => s.replaceWorkspacePortScans) const setWorkspacePortScanForKey = useAppStore((s) => s.setWorkspacePortScanForKey) const setWorkspacePortScanRefreshing = useAppStore((s) => s.setWorkspacePortScanRefreshing) const inFlightRef = useRef | null>(null) const generationRef = useRef(0) - const lastRefreshStartedAtRef = useRef(Number.NEGATIVE_INFINITY) + const wasEnabledRef = useRef(false) + const lastRefreshStartedAtByKeyRef = useRef(new Map()) const scanTargetsRef = useRef([]) + const portScanDebounceRef = useRef(new Map()) const runtimeTarget = useMemo(() => getActiveRuntimeTarget(settings), [settings]) const scanKey = workspacePortScanKeyForTarget(runtimeTarget) @@ -60,25 +71,39 @@ export function WorkspacePortScanner({ enabled = true }: { enabled?: boolean }): const refresh = useCallback( (options: WorkspacePortScannerRefreshOptions = {}) => { - const targets = scanTargetsRef.current - if (!hasWorktrees || targets.length === 0) { + const allTargets = scanTargetsRef.current + if (!hasWorktrees || allTargets.length === 0) { + portScanDebounceRef.current.clear() + lastRefreshStartedAtByKeyRef.current.clear() setWorkspacePortScan(null) setWorkspacePortScanRefreshing(false) return Promise.resolve() } + const requestedTargets = options.targets ?? allTargets + if (requestedTargets.length === 0) { + return Promise.resolve() + } if (inFlightRef.current) { return inFlightRef.current } const now = Date.now() - // Why: host/runtime state can rerender this singleton without changing the - // desired poll cadence; remote scans must not restart on every such pass. - if ( - !options.force && - now - lastRefreshStartedAtRef.current < WORKSPACE_PORT_SCAN_INTERVAL_MS - ) { + const targets = options.force + ? requestedTargets + : requestedTargets.filter((target) => { + // Why: each host keeps its own cadence so a newly added runtime cannot restart + // healthy hosts' remote scans. + const key = workspacePortScanKeyForTarget(target) + const lastStartedAt = lastRefreshStartedAtByKeyRef.current.get(key) + return ( + lastStartedAt === undefined || now - lastStartedAt >= WORKSPACE_PORT_SCAN_INTERVAL_MS + ) + }) + if (targets.length === 0) { return Promise.resolve() } - lastRefreshStartedAtRef.current = now + for (const target of targets) { + lastRefreshStartedAtByKeyRef.current.set(workspacePortScanKeyForTarget(target), now) + } const generation = generationRef.current setWorkspacePortScanRefreshing(true) @@ -96,22 +121,45 @@ export function WorkspacePortScanner({ enabled = true }: { enabled?: boolean }): ) .then((results) => { if (generation === generationRef.current) { - const scansByKey = Object.fromEntries(results.map(({ key, result }) => [key, result])) - for (const { key, result } of results) { + const activeTargetKeys = new Set( + allTargets.map((target) => workspacePortScanKeyForTarget(target)) + ) + const reconciled = reconcileTransientPortScanFailures( + results, + useAppStore.getState().workspacePortScansByKey, + portScanDebounceRef.current, + WORKSPACE_PORT_SCAN_FAILURE_THRESHOLD, + activeTargetKeys + ) + const scansByKey = Object.fromEntries( + Object.entries(useAppStore.getState().workspacePortScansByKey).filter(([key]) => + activeTargetKeys.has(key) + ) + ) + let sourceChanged = false + for (const { key, result } of reconciled) { + sourceChanged ||= scansByKey[key] !== result + scansByKey[key] = result setWorkspacePortScanForKey(key, result) } const activeScan = scansByKey[scanKey] const merged = mergeWorkspacePortScans(scansByKey) const projectionKey = - results.length > 1 ? 'all-hosts:all' : activeScan ? scanKey : results[0].key - setWorkspacePortScan( - merged - ? { - key: projectionKey, - result: merged - } - : null - ) + allTargets.length > 1 + ? 'all-hosts:all' + : activeScan + ? scanKey + : workspacePortScanKeyForTarget(allTargets[0]) + if (sourceChanged || useAppStore.getState().workspacePortScan?.key !== projectionKey) { + setWorkspacePortScanProjection( + merged + ? { + key: projectionKey, + result: merged + } + : null + ) + } } }) .finally(() => { @@ -129,6 +177,7 @@ export function WorkspacePortScanner({ enabled = true }: { enabled?: boolean }): hasWorktrees, scanKey, setWorkspacePortScan, + setWorkspacePortScanProjection, setWorkspacePortScanForKey, setWorkspacePortScanRefreshing ] @@ -136,25 +185,93 @@ export function WorkspacePortScanner({ enabled = true }: { enabled?: boolean }): useEffect(() => { if (!enabled) { + wasEnabledRef.current = false + return + } + if (!hasWorktrees) { + wasEnabledRef.current = false + portScanDebounceRef.current.clear() + lastRefreshStartedAtByKeyRef.current.clear() + setWorkspacePortScan(null) + setWorkspacePortScanRefreshing(false) return } + const wasDisabled = !wasEnabledRef.current + wasEnabledRef.current = true generationRef.current += 1 - setWorkspacePortScan(null) + const targetKeys = new Set( + scanTargetsRef.current.map((target) => workspacePortScanKeyForTarget(target)) + ) + for (const key of lastRefreshStartedAtByKeyRef.current.keys()) { + if (!targetKeys.has(key)) { + lastRefreshStartedAtByKeyRef.current.delete(key) + } + } + const publishedScans = useAppStore.getState().workspacePortScansByKey + const retainedEntries = Object.entries(publishedScans).filter(([key]) => targetKeys.has(key)) + const retainedScans = + retainedEntries.length === Object.keys(publishedScans).length + ? publishedScans + : Object.fromEntries(retainedEntries) + const retainedProjection = mergeWorkspacePortScans(retainedScans) + const retainedProjectionKey = + targetKeys.size > 1 ? 'all-hosts:all' : Object.keys(retainedScans)[0] + // Why: unchanged hosts stay visible while the replacement RPC runs; removed + // hosts and the old synthetic aggregate are excluded immediately. + const nextProjection = + retainedProjection && retainedProjectionKey + ? { key: retainedProjectionKey, result: retainedProjection } + : null + if (retainedScans === publishedScans) { + setWorkspacePortScanProjection(nextProjection) + } else { + replaceWorkspacePortScans(retainedScans, nextProjection) + } + // Why: a scanner resumed after being disabled has no trustworthy cadence; a + // host-set change while it stays enabled only probes the new host. + const targetsToRefresh = wasDisabled + ? scanTargetsRef.current + : scanTargetsRef.current.filter( + (target) => !retainedScans[workspacePortScanKeyForTarget(target)] + ) + // Why: a visible target change should not restart retained hosts; a hidden + // addition still needs its targeted scan when the window becomes visible. + let shouldRefreshOnlyNewTargets = isWindowVisible() || targetsToRefresh.length > 0 // Why: workspace port scans can cross runtime IPC or shell out remotely. // Keep the timer stopped while no UI can display the result; visibility // changes run one immediate refresh on return. const stopVisibleInterval = installWindowVisibilityInterval({ run: () => void refresh(), + runOnVisible: () => { + if (shouldRefreshOnlyNewTargets) { + shouldRefreshOnlyNewTargets = false + if (targetsToRefresh.length > 0) { + void refresh({ force: true, targets: targetsToRefresh }) + } + return + } + void refresh({ force: true }) + }, intervalMs: WORKSPACE_PORT_SCAN_INTERVAL_MS }) return () => { generationRef.current += 1 inFlightRef.current = null + setWorkspacePortScanRefreshing(false) stopVisibleInterval() } - }, [enabled, refresh, scanTargetsSignature, setWorkspacePortScan]) + }, [ + enabled, + hasWorktrees, + refresh, + scanTargetsSignature, + setWorkspacePortScan, + setWorkspacePortScanProjection, + setWorkspacePortScanRefreshing, + replaceWorkspacePortScans + ]) useEffect(() => { if (!enabled) { @@ -182,7 +299,7 @@ export function WorkspacePortScanner({ enabled = true }: { enabled?: boolean }): if (!isWindowVisible()) { return } - void refresh({ force: true }).finally(() => { + void refresh({ force: true, targets: [runtimeTarget] }).finally(() => { if (disposed || sequence !== eventSequence || !isWindowVisible()) { return } @@ -192,7 +309,7 @@ export function WorkspacePortScanner({ enabled = true }: { enabled?: boolean }): if (disposed || sequence !== eventSequence || !isWindowVisible()) { return } - void refresh({ force: true }) + void refresh({ force: true, targets: [runtimeTarget] }) }, WORKSPACE_PORT_ADVERTISED_URL_SETTLE_MS) }) }) diff --git a/src/renderer/src/components/pull-request-page-host-boundary.test.ts b/src/renderer/src/components/pull-request-page-host-boundary.test.ts index 888225aa350d..89d0dc14f578 100644 --- a/src/renderer/src/components/pull-request-page-host-boundary.test.ts +++ b/src/renderer/src/components/pull-request-page-host-boundary.test.ts @@ -270,6 +270,9 @@ describe('PullRequestPage host boundaries', () => { expect(editHelperSection).toContain('sourceContext?: TaskSourceContext | null') expect(editHelperSection).toContain("args.sourceContext?.provider === 'github'") expect(editHelperSection).toContain('getTaskSourceRuntimeSettings(args.sourceContext)') + expect(editHelperSection).toContain( + 'getGitHubMutationRoutingSettings(useAppStore.getState(), args.repoId, args.sourceContext)' + ) expect(editHelperSection).toContain( "repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? '')" ) @@ -278,7 +281,7 @@ describe('PullRequestPage host boundaries', () => { expect(editSection).toContain('sourceContext,') }) - it('routes merge actions through the PR source context', () => { + it('routes merge actions through the repo owner host (#6957)', () => { const source = componentSource('PullRequestPage.tsx') const actionsSection = sourceBetween( source, @@ -286,7 +289,9 @@ describe('PullRequestPage host boundaries', () => { 'function CommentReactions' ) - expect(actionsSection).toContain('getTaskSourceRuntimeSettings(sourceContext)') + expect(actionsSection).toContain( + 'getGitHubMutationRoutingSettings(s, item.repoId ?? repoId ?? null, sourceContext)' + ) expect(actionsSection).toContain('getActiveRuntimeTarget(sourceSettings)') expect(actionsSection).toContain( 'const canMergeWithRepoContext = !!repoPath || mergeTarget.kind ===' diff --git a/src/renderer/src/components/quick-open-file-list.react.test.tsx b/src/renderer/src/components/quick-open-file-list.react.test.tsx index ff76e4305530..4a2305e06e38 100644 --- a/src/renderer/src/components/quick-open-file-list.react.test.tsx +++ b/src/renderer/src/components/quick-open-file-list.react.test.tsx @@ -10,9 +10,11 @@ import type { AppState } from '@/store/types' import { useRuntimeFileListForWorktree, type RuntimeFileListState } from './quick-open-file-list' const listRuntimeFilesMock = vi.hoisted(() => vi.fn()) +const cancelRuntimeFileListMock = vi.hoisted(() => vi.fn()) vi.mock('@/runtime/runtime-file-client', () => ({ - listRuntimeFiles: listRuntimeFilesMock + listRuntimeFiles: listRuntimeFilesMock, + cancelRuntimeFileList: cancelRuntimeFileListMock })) const initialAppState = useAppStore.getInitialState() @@ -104,6 +106,7 @@ async function renderProbe(args: { beforeEach(() => { useAppStore.setState(initialAppState, true) listRuntimeFilesMock.mockReset().mockResolvedValue(['packages/app/package.json']) + cancelRuntimeFileListMock.mockReset() }) afterEach(async () => { @@ -155,9 +158,37 @@ describe('useRuntimeFileListForWorktree', () => { }), { rootPath: '/srv/platform', - excludePaths: undefined + excludePaths: undefined, + requestToken: expect.any(String) } ) expect(states.at(-1)?.files).toEqual(['packages/app/package.json']) }) + + it('cancels the in-flight scan with the same request token on unmount (#7721)', async () => { + const workspaceKey = folderWorkspaceKey('folder-workspace-1') + + useAppStore.setState({ + folderWorkspaces: [makeFolderWorkspace({ connectionId: 'ssh-1' })], + projectGroups: [makeProjectGroup({ connectionId: 'ssh-1' })], + repos: [], + worktreesByRepo: {} + } as Partial) + + const root = await renderProbe({ + enabled: true, + onState: () => {}, + worktreeId: workspaceKey + }) + await waitForListRuntimeFilesCall() + + const [listContext, listRequest] = listRuntimeFilesMock.mock.calls[0] + expect(cancelRuntimeFileListMock).not.toHaveBeenCalled() + + await act(async () => { + root.unmount() + }) + + expect(cancelRuntimeFileListMock).toHaveBeenCalledWith(listContext, listRequest.requestToken) + }) }) diff --git a/src/renderer/src/components/quick-open-file-list.ts b/src/renderer/src/components/quick-open-file-list.ts index 9a7ffe8d5964..13e3738e2263 100644 --- a/src/renderer/src/components/quick-open-file-list.ts +++ b/src/renderer/src/components/quick-open-file-list.ts @@ -3,8 +3,9 @@ import { useEffect, useMemo, useRef, useState } from 'react' import type { Worktree } from '../../../shared/types' import { isWindowsAbsolutePathLike } from '../../../shared/cross-platform-path' import { getConnectionIdFromState } from '@/lib/connection-context' +import { createBrowserUuid } from '@/lib/browser-uuid' import { getSettingsForWorktreeRuntimeOwner } from '@/lib/worktree-runtime-owner' -import { listRuntimeFiles } from '@/runtime/runtime-file-client' +import { cancelRuntimeFileList, listRuntimeFiles } from '@/runtime/runtime-file-client' import { useAppStore } from '@/store' import { useWorktreesForRepo } from '@/store/selectors' @@ -152,21 +153,21 @@ export function useRuntimeFileListForWorktree({ setLoading(true) const excludePaths = excludeRequest.paths.length > 0 ? excludeRequest.paths : undefined + const requestToken = createBrowserUuid() + const requestContext = { + // Why: Quick Open lists files for the selected workspace. It must + // follow that workspace's owner host, not the globally focused host. + settings: getSettingsForWorktreeRuntimeOwner(useAppStore.getState(), worktreeId), + worktreeId, + worktreePath, + connectionId + } - void listRuntimeFiles( - { - // Why: Quick Open lists files for the selected workspace. It must - // follow that workspace's owner host, not the globally focused host. - settings: getSettingsForWorktreeRuntimeOwner(useAppStore.getState(), worktreeId), - worktreeId, - worktreePath, - connectionId - }, - { - rootPath: worktreePath, - excludePaths - } - ) + void listRuntimeFiles(requestContext, { + rootPath: worktreePath, + excludePaths, + requestToken + }) .then((result) => { if (!cancelled) { setFiles(result) @@ -186,6 +187,11 @@ export function useRuntimeFileListForWorktree({ return () => { cancelled = true + // Why #7721: switching workspaces (or closing the palette) must abort + // the previous full-tree scan host- and relay-side. Over SSH, abandoned + // scans otherwise stack up and starve fs.readDir/fs.stat past their + // 30s timeout ("Could not load files for this workspace"). + cancelRuntimeFileList(requestContext, requestToken) } }, [connectionId, enabled, excludeRequest, requestKey, target.canList, worktreeId, worktreePath]) diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx index 8442e73f54e5..202359730454 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx @@ -20,6 +20,12 @@ import { getRestorableAiVaultScope, normalizeAiVaultScopeForContext } from './ai-vault-scope-state' +import { + countAiVaultViewAdjustments, + DEFAULT_AI_VAULT_GROUP, + DEFAULT_AI_VAULT_HIDE_EMPTY_SESSIONS, + DEFAULT_AI_VAULT_SORT +} from './ai-vault-view-defaults' import { buildAiVaultProjectContext } from './ai-vault-session-projects' import { resolveAiVaultSessionResumeActions, @@ -28,7 +34,6 @@ import { import { useAiVaultSessionLaunchActions } from './ai-vault-session-launch-actions' import { useAiVaultSessionWorktreeMap } from './ai-vault-session-worktree' import { useAiVaultOriginalPaneActions } from './ai-vault-original-pane-actions' -import { getAiVaultResumeWorkspaceTargetStatus } from '@/lib/ai-vault-resume-target' import { AI_VAULT_AGENTS, type AiVaultAgent, @@ -41,7 +46,11 @@ import { translate } from '@/i18n/i18n' import { AiVaultPanelHeader } from './AiVaultPanelHeader' import { AiVaultSessionVirtualList } from './AiVaultSessionVirtualList' import { useAiVaultSessionRefresh } from './ai-vault-session-refresh' -import { useAiVaultExecutionHostScope } from './ai-vault-host-scope' +import { + buildAiVaultHostScopeOptions, + buildRuntimeAiVaultHostScopeOptions, + useAiVaultExecutionHostScope +} from './ai-vault-host-scope' export default function AiVaultPanel(): React.JSX.Element { const activeWorktreeId = useActiveWorktreeId() @@ -59,30 +68,42 @@ export default function AiVaultPanel(): React.JSX.Element { })) ) const settings = useAppStore((s) => s.settings) + const runtimeEnvironments = useAppStore((s) => s.runtimeEnvironments) const agentCmdOverrides = settings?.agentCmdOverrides - const { getOriginalPaneTarget, jumpToOriginalPane, jumpToWorktree } = + const { getOriginalPaneTarget, getSessionLiveState, jumpToOriginalPane, jumpToWorktree } = useAiVaultOriginalPaneActions() const [query, setQuery] = useState('') const [scope, setScope] = useState(DEFAULT_AI_VAULT_SCOPE) - const [sort, setSort] = useState('updated') - const [group, setGroup] = useState('project') - const [hideEmptySessions, setHideEmptySessions] = useState(true) + const [sort, setSort] = useState(DEFAULT_AI_VAULT_SORT) + const [group, setGroup] = useState(DEFAULT_AI_VAULT_GROUP) + const [hideEmptySessions, setHideEmptySessions] = useState(DEFAULT_AI_VAULT_HIDE_EMPTY_SESSIONS) const [agents, setAgents] = useState([...AI_VAULT_AGENTS]) const [collapsedGroups, setCollapsedGroups] = useState>(() => new Set()) const userChangedScopeRef = useRef(false) const preferredScopeRef = useRef(DEFAULT_AI_VAULT_SCOPE) - const isRuntimeWorktree = useMemo( - () => - getAiVaultResumeWorkspaceTargetStatus(resumeTargetState, activeWorktreeId ?? null) === - 'runtime', - [activeWorktreeId, resumeTargetState] + const runtimeHostOptions = useMemo( + () => buildRuntimeAiVaultHostScopeOptions(runtimeEnvironments), + [runtimeEnvironments] + ) + const availableExecutionHostScopes = useMemo( + () => runtimeHostOptions.map((option) => option.id), + [runtimeHostOptions] ) - const { executionHostScope, activeSshExecutionHostScope, onExecutionHostScopeChange } = + const { executionHostScope, activeExecutionHostScope, onExecutionHostScopeChange } = useAiVaultExecutionHostScope({ activeWorktreeId: activeWorktreeId ?? null, - resumeTargetState + resumeTargetState, + availableExecutionHostScopes }) + const hostScopeOptions = useMemo( + () => + buildAiVaultHostScopeOptions({ + activeExecutionHostScope, + runtimeHostOptions + }), + [activeExecutionHostScope, runtimeHostOptions] + ) const activeWorktreePath = activeWorktree?.path ?? null // Why: AI Vault ownership is cwd-based, so we must consider live worktrees across all repos. const activeWorktreePaths = useMemo( @@ -140,12 +161,12 @@ export default function AiVaultPanel(): React.JSX.Element { targetState: resumeTargetState, agentCmdOverrides }) - const hasAllAgentsSelected = agents.length === AI_VAULT_AGENTS.length - const viewAdjustmentCount = - (hasAllAgentsSelected ? 0 : 1) + - (sort === 'updated' ? 0 : 1) + - (group === 'project' ? 0 : 1) + - (hideEmptySessions ? 0 : 1) + const viewAdjustmentCount = countAiVaultViewAdjustments({ + agents, + sort, + group, + hideEmptySessions + }) // Workspace is the preferred default, but unavailable context still falls back to All. useEffect(() => { @@ -271,9 +292,9 @@ export default function AiVaultPanel(): React.JSX.Element { const resetViewOptions = useCallback(() => { setAgents([...AI_VAULT_AGENTS]) - setSort('updated') - setGroup('project') - setHideEmptySessions(true) + setSort(DEFAULT_AI_VAULT_SORT) + setGroup(DEFAULT_AI_VAULT_GROUP) + setHideEmptySessions(DEFAULT_AI_VAULT_HIDE_EMPTY_SESSIONS) }, []) const handleScopeChange = useCallback((nextScope: AiVaultScope) => { @@ -306,7 +327,7 @@ export default function AiVaultPanel(): React.JSX.Element { activeProjectKey={activeProjectKey} scope={scope} executionHostScope={executionHostScope} - activeSshExecutionHostScope={activeSshExecutionHostScope} + hostScopeOptions={hostScopeOptions} agents={agents} sort={sort} group={group} @@ -323,15 +344,6 @@ export default function AiVaultPanel(): React.JSX.Element { onRefresh={() => void refresh({ force: true })} /> - {isRuntimeWorktree ? ( -
    - {translate( - 'auto.components.right.sidebar.AiVaultPanel.runtimeBrowseLocalHistory', - 'Runtime-hosted workspaces can browse local history. Resume actions are available in local and SSH workspaces.' - )} -
    - ) : null} - {error ? (
    {error} @@ -360,6 +372,7 @@ export default function AiVaultPanel(): React.JSX.Element { getSessionResumeState={getSessionResumeState} getSessionResumeActions={getSessionResumeActions} getOriginalPaneTarget={getOriginalPaneTarget} + getSessionLiveState={getSessionLiveState} getWorktreeInfo={(session) => sessionWorktreeById.get(session.id) ?? null} onToggleGroup={toggleGroup} onJumpToOriginalPane={jumpToOriginalPane} diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx index 2b3cc2802b00..b64308b943e9 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx @@ -32,14 +32,10 @@ import { type AiVaultScope, type AiVaultSort } from '../../../../shared/ai-vault-types' -import { - ALL_EXECUTION_HOSTS_SCOPE, - getExecutionHostLabel, - LOCAL_EXECUTION_HOST_ID, - type ExecutionHostScope -} from '../../../../shared/execution-host' +import { getExecutionHostLabel, type ExecutionHostScope } from '../../../../shared/execution-host' import { agentLabel, type AiVaultSessionGroup } from './ai-vault-session-filters' import { translate } from '@/i18n/i18n' +import type { AiVaultHostScopeOption } from './ai-vault-host-scope' const VAULT_HEADER_CONTROL_CLASS = 'size-6 shrink-0' @@ -184,19 +180,15 @@ export function VaultScopeSwitch({ export function VaultHostScopeMenu({ executionHostScope, - activeSshExecutionHostScope, + hostOptions, onExecutionHostScopeChange }: { executionHostScope: ExecutionHostScope - activeSshExecutionHostScope: ExecutionHostScope | null + hostOptions: readonly AiVaultHostScopeOption[] onExecutionHostScopeChange: (scope: ExecutionHostScope) => void }): React.JSX.Element { - const hostOptions = [ - LOCAL_EXECUTION_HOST_ID, - ...(activeSshExecutionHostScope ? [activeSshExecutionHostScope] : []), - ALL_EXECUTION_HOSTS_SCOPE - ] as const - const label = getExecutionHostLabel(executionHostScope) + const selectedOption = hostOptions.find((option) => option.id === executionHostScope) + const label = selectedOption?.label ?? getExecutionHostLabel(executionHostScope) return ( @@ -224,9 +216,9 @@ export function VaultHostScopeMenu({ value={executionHostScope} onValueChange={(value) => onExecutionHostScopeChange(value as ExecutionHostScope)} > - {hostOptions.map((scope) => ( - - {getExecutionHostLabel(scope)} + {hostOptions.map((option) => ( + + {option.label} ))} diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx index b463e188a7e0..b3ec2ba36e36 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx @@ -9,6 +9,7 @@ import type { } from '../../../../shared/ai-vault-types' import type { ExecutionHostScope } from '../../../../shared/execution-host' import { VaultHostScopeMenu, VaultScopeSwitch, VaultViewMenu } from './AiVaultPanelControls' +import type { AiVaultHostScopeOption } from './ai-vault-host-scope' type AiVaultPanelHeaderProps = { query: string @@ -20,7 +21,7 @@ type AiVaultPanelHeaderProps = { activeProjectKey: string | null scope: AiVaultScope executionHostScope: ExecutionHostScope - activeSshExecutionHostScope: ExecutionHostScope | null + hostScopeOptions: readonly AiVaultHostScopeOption[] agents: readonly AiVaultAgent[] sort: AiVaultSort group: AiVaultGroup @@ -47,7 +48,7 @@ export function AiVaultPanelHeader({ activeProjectKey, scope, executionHostScope, - activeSshExecutionHostScope, + hostScopeOptions, agents, sort, group, @@ -108,7 +109,7 @@ export function AiVaultPanelHeader({
    void showJumpToWorktree: boolean onJumpToWorktree?: () => void - onCopyResume: () => void + // Absent for zero-turn sessions: copying a resume command that lands in an + // empty conversation would contradict the "not saved" state. + onCopyResume?: () => void onCopyId: () => void onCopyPath: () => void onOpenLog?: () => void @@ -60,13 +62,15 @@ export function SessionActionMenuItems({ {resumeLabel} - - - {translate( - 'auto.components.right.sidebar.AiVaultSessionRow.copyResumeCommand', - 'Copy Resume Command' - )} - + {onCopyResume ? ( + + + {translate( + 'auto.components.right.sidebar.AiVaultSessionRow.copyResumeCommand', + 'Copy Resume Command' + )} + + ) : null} {hasLocalPathActions ? ( <> diff --git a/src/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsx b/src/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsx index 85f5b2a57597..d9ea283a0a53 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsx @@ -3,9 +3,15 @@ import { FileJson, FolderGit2, MessageSquare, Play } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' -import type { AiVaultScope, AiVaultSession } from '../../../../shared/ai-vault-types' +import { + isAiVaultSessionResumableContent, + type AiVaultScope, + type AiVaultSession +} from '../../../../shared/ai-vault-types' import { translate } from '@/i18n/i18n' import { sessionDetailConversationTurns } from './ai-vault-session-display' +import { SessionSubagentsSection } from './AiVaultSessionSubagents' +import { SessionUnsavedConversationNotice } from './AiVaultSessionUnsavedNotice' import { aiVaultWorktreeCompactPath, aiVaultWorktreeStatusLabel, @@ -36,8 +42,13 @@ export function SessionInlineDetails({ onResumeInNewTab: () => void onOpenLog?: () => void }): React.JSX.Element { - const showResumeInWorktree = Boolean(resumeActions.worktree.worktreeId) - const showResumeInNewTab = !showResumeInWorktree || Boolean(resumeActions.newTab.worktreeId) + // A zero-turn transcript would resume into an empty conversation, so the plain + // resume affordances are withheld and a distinct "not saved" state is shown. + const hasResumableContent = isAiVaultSessionResumableContent(session) + const showResumeInWorktree = hasResumableContent && Boolean(resumeActions.worktree.worktreeId) + const showResumeInNewTab = + hasResumableContent && + (!resumeActions.worktree.worktreeId || Boolean(resumeActions.newTab.worktreeId)) const detailTurns = sessionDetailConversationTurns(session, 3) const worktreeDisplay = worktreeInfo @@ -54,34 +65,44 @@ export function SessionInlineDetails({ }} >
    - } - label={translate( - 'auto.components.right.sidebar.AiVaultSessionDetails.latestTurns', - 'Latest turns' - )} - > - {detailTurns.length > 0 ? ( -
    - {detailTurns.map((turn, index) => ( - - ))} -
    - ) : ( - - )} -
    + {hasResumableContent ? ( + } + label={translate( + 'auto.components.right.sidebar.AiVaultSessionDetails.latestTurns', + 'Latest turns' + )} + > + {detailTurns.length > 0 ? ( +
    + {detailTurns.map((turn, index) => ( + + ))} +
    + ) : ( + + )} +
    + ) : ( + // An unsaved session has no turns to show; the notice replaces the + // preview section instead of stacking a second empty state under it. + + )} - {shouldShowAiVaultSessionWorktreeLine(worktreeDisplay, { vaultScope }) ? ( + + + {shouldShowAiVaultSessionWorktreeLine(worktreeDisplay, { + vaultScope + }) ? ( } label={translate( @@ -94,64 +115,66 @@ export function SessionInlineDetails({ ) : null}
    -
    - {showResumeInWorktree ? ( - - ) : null} - {showResumeInNewTab ? ( - - ) : null} - {onOpenLog ? ( - - ) : null} -
    + {showResumeInWorktree || showResumeInNewTab || onOpenLog ? ( +
    + {showResumeInWorktree ? ( + + ) : null} + {showResumeInNewTab ? ( + + ) : null} + {onOpenLog ? ( + + ) : null} +
    + ) : null}
    ) } @@ -219,7 +242,9 @@ function WorktreeMetadataLines({ return (
    - {shouldShowAiVaultWorktreeStatusBadge(worktreeInfo.status, { vaultScope }) ? ( + {shouldShowAiVaultWorktreeStatusBadge(worktreeInfo.status, { + vaultScope + }) ? ( <> {aiVaultWorktreeStatusLabel(worktreeInfo.status)} diff --git a/src/renderer/src/components/right-sidebar/AiVaultSessionRow.tsx b/src/renderer/src/components/right-sidebar/AiVaultSessionRow.tsx index b0d880163277..448be77c1228 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultSessionRow.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultSessionRow.tsx @@ -25,9 +25,11 @@ import { SessionMetadata, SessionWorktreeLine } from './ai-vault-session-row-display' +import type { AgentStatusState } from '../../../../shared/agent-status-types' export function VaultSessionRow({ session, + liveState, resumeStartup, worktreeInfo, vaultScope, @@ -50,6 +52,7 @@ export function VaultSessionRow({ onOpenCwd }: { session: AiVaultSession + liveState: AgentStatusState | null resumeStartup: AiVaultResumeStartup worktreeInfo: AiVaultSessionWorktreeInfo | null vaultScope: AiVaultScope @@ -64,7 +67,7 @@ export function VaultSessionRow({ resumeActions: AiVaultSessionResumeActions onResumeInWorktree: () => void onResumeInNewTab: () => void - onCopyResume: () => void + onCopyResume?: () => void onCopyId: () => void onCopyPath: () => void onOpenLog?: () => void @@ -178,6 +181,7 @@ export function VaultSessionRow({
    Promise>() + +beforeEach(() => { + listSubagentSessions.mockReset() + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- test-only window.api shim + ;(window as any).api = { + aiVault: { listSubagentSessions }, + shell: { openFilePath: vi.fn() } + } +}) + +afterEach(() => { + document.body.replaceChildren() +}) + +function makeSession(overrides: Partial = {}): AiVaultSession { + return { + id: 'local:claude:parent-session:/tmp/parent-session.jsonl', + executionHostId: 'local', + agent: 'claude', + sessionId: 'parent-session', + title: 'Parent session', + cwd: '/repo', + branch: null, + model: null, + filePath: '/tmp/parent-session.jsonl', + codexHome: null, + createdAt: null, + updatedAt: null, + modifiedAt: '2026-07-05T10:00:00.000Z', + messageCount: 3, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 1, + resumeCommand: 'claude --resume parent-session', + subagent: null, + ...overrides + } +} + +function makeSubagent(title: string): AiVaultSession { + return makeSession({ + id: `local:claude:parent-session:/tmp/parent-session/subagents/agent-${title}.jsonl`, + title, + filePath: `/tmp/parent-session/subagents/agent-${title}.jsonl`, + subagent: { parentSessionId: 'parent-session', agentType: null, status: 'running' }, + subagentTranscriptCount: 0 + }) +} + +describe('SessionSubagentsSection', () => { + it('keeps the loaded list visible while a rescan-triggered refetch is in flight', async () => { + listSubagentSessions.mockResolvedValueOnce({ + sessions: [makeSubagent('First pass')], + issues: [] + }) + const { rerender, queryByText } = render() + await act(async () => {}) + expect(queryByText('First pass')).not.toBeNull() + + // Second fetch stays pending: the previous rows must remain visible + // instead of flickering back to the hidden loading state. + let resolveSecond: (result: AiVaultSubagentListResult) => void = () => {} + listSubagentSessions.mockImplementationOnce( + () => new Promise((resolve) => (resolveSecond = resolve)) + ) + rerender( + + ) + await act(async () => {}) + expect(listSubagentSessions).toHaveBeenCalledTimes(2) + expect(queryByText('First pass')).not.toBeNull() + + await act(async () => { + resolveSecond({ sessions: [makeSubagent('Second pass')], issues: [] }) + }) + expect(queryByText('Second pass')).not.toBeNull() + expect(queryByText('First pass')).toBeNull() + }) + + it('does not fetch for remote sessions even when the scan counted transcripts', async () => { + const { container } = render( + + ) + await act(async () => {}) + expect(listSubagentSessions).not.toHaveBeenCalled() + expect(container.firstChild).toBeNull() + }) +}) diff --git a/src/renderer/src/components/right-sidebar/AiVaultSessionSubagents.tsx b/src/renderer/src/components/right-sidebar/AiVaultSessionSubagents.tsx new file mode 100644 index 000000000000..aa84e4bebe3a --- /dev/null +++ b/src/renderer/src/components/right-sidebar/AiVaultSessionSubagents.tsx @@ -0,0 +1,165 @@ +import { useEffect, useState } from 'react' +import type React from 'react' +import { Bot, FileJson } from 'lucide-react' +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { AgentStateDot, agentStateLabel, type AgentDotState } from '@/components/AgentStateDot' +import type { AiVaultSession, AiVaultSubagentRunStatus } from '../../../../shared/ai-vault-types' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' +import { translate } from '@/i18n/i18n' + +type SubagentListState = { status: 'loading' } | { status: 'loaded'; sessions: AiVaultSession[] } + +/** + * Lists the Task subagent transcripts spawned by one session, fetched on + * demand when the parent's details expand. Subagents share the parent's + * sessionId and aren't independently resumable, so rows are view-only. + */ +export function SessionSubagentsSection({ + session +}: { + session: AiVaultSession +}): React.JSX.Element | null { + const subagents = useSubagentSessions(session) + + if (subagents.status !== 'loaded' || subagents.sessions.length === 0) { + return null + } + + return ( +
    +
    + + + + + {translate( + 'auto.components.right.sidebar.AiVaultSessionSubagents.subagentsCount', + 'Subagents ({{value0}})', + { value0: subagents.sessions.length } + )} + +
    +
    + {subagents.sessions.map((subagentSession) => ( + + ))} +
    +
    + ) +} + +function useSubagentSessions(session: AiVaultSession): SubagentListState { + const [state, setState] = useState({ status: 'loading' }) + + useEffect(() => { + // The scan already counted the transcripts; skip the IPC round-trip when + // there is nothing to list. Remote sessions can carry a count (from the + // remote walk listing), but their transcripts aren't local files to list. + if ( + session.subagentTranscriptCount === 0 || + session.executionHostId !== LOCAL_EXECUTION_HOST_ID + ) { + setState({ status: 'loaded', sessions: [] }) + return + } + let cancelled = false + // Why: rescans re-run this effect (modifiedAt changes); resetting to + // loading would unmount the section until IPC returns and flicker on + // every active-session rescan. Keep prior rows visible while refetching. + setState((prev) => (prev.status === 'loaded' ? prev : { status: 'loading' })) + window.api.aiVault + .listSubagentSessions({ + agent: session.agent, + parentFilePath: session.filePath, + executionHostId: session.executionHostId + }) + .then((result) => { + if (!cancelled) { + setState({ status: 'loaded', sessions: result.sessions }) + } + }) + .catch(() => { + // A failed listing degrades to "no subagents" — the section stays hidden. + if (!cancelled) { + setState({ status: 'loaded', sessions: [] }) + } + }) + return () => { + cancelled = true + } + // Why: modifiedAt changes exactly when the parent transcript is rewritten, + // so re-listing on it refreshes a subagent's status (e.g. running -> done). + }, [ + session.agent, + session.filePath, + session.executionHostId, + session.subagentTranscriptCount, + session.modifiedAt + ]) + + return state +} + +// AI Vault run statuses map onto the shared dot vocabulary: a completed Task +// is an outcome ('done'), stopped/killed reads as an interruption. +const SUBAGENT_DOT_STATES: Record = { + running: 'working', + completed: 'done', + failed: 'failed', + stopped: 'interrupted' +} + +function SubagentSessionLine({ session }: { session: AiVaultSession }): React.JSX.Element { + const dotState = session.subagent?.status ? SUBAGENT_DOT_STATES[session.subagent.status] : null + + return ( +
    + {dotState ? ( + // Why: a plain inline span would baseline-align the dot; flex keeps it + // vertically centered with the row text. + + + + ) : null} + + {session.title} + + {session.subagent?.agentType ? ( + + {session.subagent.agentType} + + ) : null} + + {translate( + 'auto.components.right.sidebar.AiVaultSessionSubagents.messageCount', + '{{value0}} msgs', + { value0: session.messageCount } + )} + + +
    + ) +} diff --git a/src/renderer/src/components/right-sidebar/AiVaultSessionUnsavedNotice.tsx b/src/renderer/src/components/right-sidebar/AiVaultSessionUnsavedNotice.tsx new file mode 100644 index 000000000000..56a3e951c7d6 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/AiVaultSessionUnsavedNotice.tsx @@ -0,0 +1,91 @@ +import type React from 'react' +import { Archive } from 'lucide-react' +import { + aiVaultSessionRecoverableSignalCount, + isAiVaultSessionRecoverableEmpty, + type AiVaultSession +} from '../../../../shared/ai-vault-types' +import { translate } from '@/i18n/i18n' + +// Distinct state for a zero-turn transcript: the conversation was not persisted, +// but queued prompts and/or subagent transcripts may still be recoverable. +export function SessionUnsavedConversationNotice({ + session, + logAvailable +}: { + session: AiVaultSession + // Whether an open-log affordance exists nearby; remote (SSH) sessions have + // none, so the "open the log" hint would point at nothing. + logAvailable: boolean +}): React.JSX.Element { + const recoverable = isAiVaultSessionRecoverableEmpty(session) + + return ( +
    +
    + + + {translate( + 'auto.components.right.sidebar.AiVaultSessionDetails.conversationNotSaved', + 'Conversation not saved' + )} + +
    +
    + {recoverable + ? translate( + 'auto.components.right.sidebar.AiVaultSessionDetails.recoverableEmptyDetail', + 'This session has no saved conversation, but {{value0}} recoverable item(s) survive.', + { value0: aiVaultSessionRecoverableSignalCount(session) } + ) + : translate( + 'auto.components.right.sidebar.AiVaultSessionDetails.emptyConversationDetail', + 'This session has no saved conversation and cannot be resumed.' + )} + {recoverable && logAvailable + ? ` ${translate( + 'auto.components.right.sidebar.AiVaultSessionDetails.recoverableEmptyOpenLogHint', + 'Open the log to recover them.' + )}` + : null} + {recoverable ? ( + + ) : null} +
    +
    + ) +} + +function SessionRecoverableSignalLines({ + queuedMessageCount, + subagentTranscriptCount +}: { + queuedMessageCount: number + subagentTranscriptCount: number +}): React.JSX.Element { + return ( +
      + {queuedMessageCount > 0 ? ( +
    • + {translate( + 'auto.components.right.sidebar.AiVaultSessionDetails.queuedMessages', + '{{value0}} queued message(s)', + { value0: queuedMessageCount } + )} +
    • + ) : null} + {subagentTranscriptCount > 0 ? ( +
    • + {translate( + 'auto.components.right.sidebar.AiVaultSessionDetails.subagentTranscripts', + '{{value0}} subagent transcript(s)', + { value0: subagentTranscriptCount } + )} +
    • + ) : null} +
    + ) +} diff --git a/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.tsx b/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.tsx index 545b40955445..ce9416ac73aa 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.tsx @@ -1,5 +1,6 @@ import { useVirtualizer } from '@tanstack/react-virtual' import { useCallback, useMemo, useRef, useState } from 'react' +import type { AgentStatusState } from '../../../../shared/agent-status-types' import type { AiVaultScope, AiVaultSession } from '../../../../shared/ai-vault-types' import type { AiVaultResumeStartup } from '@/lib/ai-vault-resume-command' import { cn } from '@/lib/utils' @@ -11,6 +12,7 @@ import type { AiVaultSessionGroup } from './ai-vault-session-filters' import type { AiVaultOriginalPaneTarget } from './ai-vault-original-pane' import { aiVaultSessionResumeLabel, + aiVaultSessionRowResumeGating, type AiVaultSessionResumeActions, type AiVaultSessionResumeState } from './ai-vault-session-resume' @@ -44,6 +46,7 @@ export function AiVaultSessionVirtualList({ vaultScope, buildResumeStartup, getOriginalPaneTarget, + getSessionLiveState, getWorktreeInfo, getSessionResumeState, getSessionResumeActions, @@ -67,6 +70,7 @@ export function AiVaultSessionVirtualList({ vaultScope: AiVaultScope buildResumeStartup: (session: AiVaultSession, worktreeId?: string | null) => AiVaultResumeStartup getOriginalPaneTarget: (session: AiVaultSession) => AiVaultOriginalPaneTarget | null + getSessionLiveState: (session: AiVaultSession) => AgentStatusState | null getWorktreeInfo: (session: AiVaultSession) => AiVaultSessionWorktreeInfo | null getSessionResumeState: (session: AiVaultSession) => AiVaultSessionResumeState getSessionResumeActions: (session: AiVaultSession) => AiVaultSessionResumeActions @@ -193,6 +197,7 @@ export function AiVaultSessionVirtualList({ vaultScope={vaultScope} buildResumeStartup={buildResumeStartup} getOriginalPaneTarget={getOriginalPaneTarget} + getSessionLiveState={getSessionLiveState} getWorktreeInfo={getWorktreeInfo} getSessionResumeState={getSessionResumeState} getSessionResumeActions={getSessionResumeActions} @@ -226,6 +231,7 @@ function AiVaultVirtualRow({ vaultScope, buildResumeStartup, getOriginalPaneTarget, + getSessionLiveState, getWorktreeInfo, getSessionResumeState, getSessionResumeActions, @@ -251,6 +257,7 @@ function AiVaultVirtualRow({ vaultScope: AiVaultScope buildResumeStartup: (session: AiVaultSession, worktreeId?: string | null) => AiVaultResumeStartup getOriginalPaneTarget: (session: AiVaultSession) => AiVaultOriginalPaneTarget | null + getSessionLiveState: (session: AiVaultSession) => AgentStatusState | null getWorktreeInfo: (session: AiVaultSession) => AiVaultSessionWorktreeInfo | null getSessionResumeState: (session: AiVaultSession) => AiVaultSessionResumeState getSessionResumeActions: (session: AiVaultSession) => AiVaultSessionResumeActions @@ -282,6 +289,12 @@ function AiVaultVirtualRow({ : null const resumeState = row.type === 'session' ? getSessionResumeState(row.session) : null const resumeActions = row.type === 'session' ? getSessionResumeActions(row.session) : null + // Gate resume on real content: a zero-turn transcript would resume into an + // empty conversation, so it is never offered as normally resumable. + const resumeGating = + row.type === 'session' + ? aiVaultSessionRowResumeGating(row.session, resumeState) + : { resumeDisabled: true, canCopyResumeCommand: false } const resumeLabel = resumeState ? aiVaultSessionResumeLabel(resumeState) : '' const canOpenLocalSessionPaths = row.type === 'session' && canUseLocalAiVaultSessionPathActions(row.session.executionHostId) @@ -305,11 +318,12 @@ function AiVaultVirtualRow({ ) : ( onCopyResume(row.session, resumeState?.worktreeId)} + onCopyResume={ + resumeGating.canCopyResumeCommand + ? () => onCopyResume(row.session, resumeState?.worktreeId) + : undefined + } onCopyId={() => onCopyId(row.session)} onCopyPath={() => onCopyPath(row.session)} onOpenLog={canOpenLocalSessionPaths ? () => onOpenLog(row.session) : undefined} diff --git a/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx index 4501df7ff63d..25c898721f02 100644 --- a/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx +++ b/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx @@ -33,9 +33,11 @@ function baseProps(overrides: Partial = {}) { commitMessage: 'feat: add commit area', commitError: null as string | null, commitFailureRecoveryPrompt: null as string | null, + pushRecovery: null, remoteActionError: null as string | null, isCommitting: inputs.isCommitting, isFixingCommitFailureWithAI: false, + isFixingPushFailureWithAI: false, sourceControlAiActionsVisible: true, aiEnabled: false, aiAgentConfigured: false, @@ -52,6 +54,7 @@ function baseProps(overrides: Partial = {}) { onGenerate: vi.fn(), onCancelGenerate: vi.fn(), onFixCommitFailureWithAI: vi.fn(), + onFixPushFailureWithAI: vi.fn(), onPrimaryAction: vi.fn(), onDropdownAction: vi.fn() as (kind: DropdownActionKind) => void } diff --git a/src/renderer/src/components/right-sidebar/CommitArea.generate.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.generate.test.tsx index 7e0471ff3925..137c4c3116ee 100644 --- a/src/renderer/src/components/right-sidebar/CommitArea.generate.test.tsx +++ b/src/renderer/src/components/right-sidebar/CommitArea.generate.test.tsx @@ -33,9 +33,11 @@ function baseProps(overrides: Partial = {}) { commitMessage: 'feat: add commit area', commitError: null as string | null, commitFailureRecoveryPrompt: null as string | null, + pushRecovery: null, remoteActionError: null as string | null, isCommitting: inputs.isCommitting, isFixingCommitFailureWithAI: false, + isFixingPushFailureWithAI: false, showComposer: true, sourceControlAiActionsVisible: true, aiEnabled: false, @@ -53,6 +55,7 @@ function baseProps(overrides: Partial = {}) { onGenerate: vi.fn(), onCancelGenerate: vi.fn(), onFixCommitFailureWithAI: vi.fn(), + onFixPushFailureWithAI: vi.fn(), onPrimaryAction: vi.fn(), onDropdownAction: vi.fn() as (kind: DropdownActionKind) => void } diff --git a/src/renderer/src/components/right-sidebar/CommitArea.primary-icons.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.primary-icons.test.tsx index 20764fe73bc1..4c8d9de1e0e4 100644 --- a/src/renderer/src/components/right-sidebar/CommitArea.primary-icons.test.tsx +++ b/src/renderer/src/components/right-sidebar/CommitArea.primary-icons.test.tsx @@ -33,9 +33,11 @@ function baseProps(overrides: Partial = {}) { commitMessage: 'feat: add commit area', commitError: null as string | null, commitFailureRecoveryPrompt: null as string | null, + pushRecovery: null, remoteActionError: null as string | null, isCommitting: inputs.isCommitting, isFixingCommitFailureWithAI: false, + isFixingPushFailureWithAI: false, sourceControlAiActionsVisible: true, aiEnabled: false, aiAgentConfigured: false, @@ -52,6 +54,7 @@ function baseProps(overrides: Partial = {}) { onGenerate: vi.fn(), onCancelGenerate: vi.fn(), onFixCommitFailureWithAI: vi.fn(), + onFixPushFailureWithAI: vi.fn(), onPrimaryAction: vi.fn(), onDropdownAction: vi.fn() as (kind: DropdownActionKind) => void } diff --git a/src/renderer/src/components/right-sidebar/CommitArea.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.test.tsx index 297d441b28ac..b360795e6622 100644 --- a/src/renderer/src/components/right-sidebar/CommitArea.test.tsx +++ b/src/renderer/src/components/right-sidebar/CommitArea.test.tsx @@ -7,6 +7,7 @@ import { } from './source-control-primary-action' import { resolveDropdownItems, type DropdownActionKind } from './source-control-dropdown-items' import { TooltipProvider } from '@/components/ui/tooltip' +import { deriveSourceControlPushRecovery } from './source-control-push-recovery' function buildInputs(overrides: Partial = {}): PrimaryActionInputs { return { @@ -31,9 +32,11 @@ function baseProps(overrides: Partial = {}) { commitMessage: 'feat: add commit area', commitError: null as string | null, commitFailureRecoveryPrompt: null as string | null, + pushRecovery: null as ReturnType, remoteActionError: null as string | null, isCommitting: inputs.isCommitting, isFixingCommitFailureWithAI: false, + isFixingPushFailureWithAI: false, sourceControlAiActionsVisible: true, aiEnabled: false, aiAgentConfigured: false, @@ -50,11 +53,35 @@ function baseProps(overrides: Partial = {}) { onGenerate: vi.fn(), onCancelGenerate: vi.fn(), onFixCommitFailureWithAI: vi.fn(), + onFixPushFailureWithAI: vi.fn(), onPrimaryAction: vi.fn(), onDropdownAction: vi.fn() as (kind: DropdownActionKind) => void } } +function buildPushRecovery( + rawError: string +): NonNullable> { + const recovery = deriveSourceControlPushRecovery({ + actionError: { + kind: 'push', + message: 'Push blocked', + rawError, + branchName: 'main', + worktreePath: '/repo', + entriesSnapshot: [], + entriesSnapshotTotalCount: 0, + sequence: 1 + }, + currentBranchName: 'main', + currentSequence: 1 + }) + if (!recovery) { + throw new Error('push recovery was not derived') + } + return recovery +} + function renderCommitArea(props: Parameters[0]): string { return renderToStaticMarkup( @@ -242,6 +269,33 @@ describe('CommitArea', () => { expect(markup).toContain('commit-area-remote-error') }) + it('shows a compact push hook summary and AI fix action when push fails on a hook', () => { + const raw = + "error: failed to push some refs to 'origin'\nhusky - pre-push hook exited with code 1\neslint found 2 errors" + const markup = renderCommitArea({ + ...baseProps(), + pushRecovery: buildPushRecovery(raw) + }) + + expect(markup).toContain('id="commit-area-push-error"') + expect(markup).toContain('Push blocked') + expect(markup).toContain('Lint failed during push.') + expect(markup).not.toContain('eslint found 2 errors') + expect(markup).toContain('aria-label="Fix push failure with AI"') + expect(markup).toContain('Details') + }) + + it('hides push failure AI actions when Source Control AI actions are hidden', () => { + const markup = renderCommitArea({ + ...baseProps(), + pushRecovery: buildPushRecovery('husky - pre-push hook failed'), + sourceControlAiActionsVisible: false + }) + + expect(markup).not.toContain('Fix push failure with AI') + expect(markup).toContain('Push blocked') + }) + it('formats pull policy errors with command options', () => { const markup = renderCommitArea({ ...baseProps(), diff --git a/src/renderer/src/components/right-sidebar/SessionRowTrailingActions.tsx b/src/renderer/src/components/right-sidebar/SessionRowTrailingActions.tsx index 10167da346be..dbb5cfaf7dd5 100644 --- a/src/renderer/src/components/right-sidebar/SessionRowTrailingActions.tsx +++ b/src/renderer/src/components/right-sidebar/SessionRowTrailingActions.tsx @@ -64,7 +64,7 @@ export function SessionRowTrailingActions({ showJumpToWorktree: boolean onJumpToWorktree?: () => void onResume: () => void - onCopyResume: () => void + onCopyResume?: () => void onCopyId: () => void onCopyPath: () => void onOpenLog?: () => void diff --git a/src/renderer/src/components/right-sidebar/SourceControl.commit-failure-recovery.test.ts b/src/renderer/src/components/right-sidebar/SourceControl.commit-failure-recovery.test.ts index 7bafffbbb308..02aeaa1911af 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.commit-failure-recovery.test.ts +++ b/src/renderer/src/components/right-sidebar/SourceControl.commit-failure-recovery.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest' import { appendCommitFailureCustomInstruction, - buildCommitFailureAgentCommandInput, buildFixCommitFailurePrompt -} from './SourceControl' +} from '../../../../shared/source-control-commit-failure' +import { buildCommitFailureAgentCommandInput } from '../../../../shared/source-control-commit-failure-agent-command' describe('SourceControl commit failure recovery prompt', () => { it('builds a provider-neutral AI prompt for fixing a failed commit hook', () => { diff --git a/src/renderer/src/components/right-sidebar/SourceControl.push-failure-recovery.test.ts b/src/renderer/src/components/right-sidebar/SourceControl.push-failure-recovery.test.ts new file mode 100644 index 000000000000..2ec8633d61c0 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/SourceControl.push-failure-recovery.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import { + appendPushFailureCustomInstruction, + buildFixPushFailurePrompt +} from '../../../../shared/source-control-push-failure' +import { buildPushFailureAgentCommandInput } from '../../../../shared/source-control-push-failure-agent-command' + +describe('SourceControl push failure recovery prompt', () => { + it('leaves blank launch templates blank so the launcher can reject them', () => { + expect( + buildPushFailureAgentCommandInput({ + commandInputTemplate: ' ', + basePrompt: 'Fix this push failure.' + }) + ).toBe('') + }) + + it('falls back to the base push-failure prompt when no launch template is saved', () => { + expect( + buildPushFailureAgentCommandInput({ + commandInputTemplate: undefined, + basePrompt: 'Fix this push failure.' + }) + ).toBe('Fix this push failure.') + }) + + it('adds one-time custom instructions before the response contract', () => { + const prompt = buildFixPushFailurePrompt({ + summary: 'Pre-push hook failed.', + error: 'lint failed', + branchName: 'main', + worktreePath: null, + entries: [], + customInstruction: 'Only change TypeScript files.' + }) + + expect(prompt).toContain('Additional user instruction for this fix:') + expect(prompt).toContain('Only change TypeScript files.') + expect(prompt.trim().endsWith('anything left for the user.')).toBe(true) + }) + + it('leaves the base prompt unchanged for empty custom instructions', () => { + const prompt = 'Fix the failed push.' + expect(appendPushFailureCustomInstruction(prompt, ' ')).toBe(prompt) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/SourceControl.remote-action-errors.test.ts b/src/renderer/src/components/right-sidebar/SourceControl.remote-action-errors.test.ts index 71f709de6586..b04fd1bea157 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.remote-action-errors.test.ts +++ b/src/renderer/src/components/right-sidebar/SourceControl.remote-action-errors.test.ts @@ -4,7 +4,11 @@ import { clearRemoteActionErrorsForCompletedConflictOperations } from './SourceC describe('SourceControl remote action error reconciliation', () => { it('clears a rebase failure after git status observes the rebase completed', () => { const errors = { - 'wt-1': { kind: 'rebase' as const, message: 'Rebase failed. Could not apply abc123' } + 'wt-1': { + kind: 'rebase' as const, + message: 'Rebase failed. Could not apply abc123', + rawError: 'Rebase failed. Could not apply abc123' + } } expect( @@ -18,7 +22,11 @@ describe('SourceControl remote action error reconciliation', () => { it('keeps a rebase failure while the rebase is still in progress', () => { const errors = { - 'wt-1': { kind: 'rebase' as const, message: 'Rebase failed. Could not apply abc123' } + 'wt-1': { + kind: 'rebase' as const, + message: 'Rebase failed. Could not apply abc123', + rawError: 'Rebase failed. Could not apply abc123' + } } expect( @@ -32,7 +40,11 @@ describe('SourceControl remote action error reconciliation', () => { it('keeps immediate rebase failures that never entered a rebase operation', () => { const errors = { - 'wt-1': { kind: 'rebase' as const, message: 'Rebase blocked - commit first.' } + 'wt-1': { + kind: 'rebase' as const, + message: 'Rebase blocked - commit first.', + rawError: 'Rebase blocked - commit first.' + } } expect( @@ -46,9 +58,21 @@ describe('SourceControl remote action error reconciliation', () => { it('clears pull and sync conflict errors after their merge operation completes', () => { const errors = { - 'wt-pull': { kind: 'pull' as const, message: 'Pull stopped with merge conflicts.' }, - 'wt-sync': { kind: 'sync' as const, message: 'Sync stopped with merge conflicts.' }, - 'wt-fetch': { kind: 'fetch' as const, message: 'Fetch failed. network timeout' } + 'wt-pull': { + kind: 'pull' as const, + message: 'Pull stopped with merge conflicts.', + rawError: 'Pull stopped with merge conflicts.' + }, + 'wt-sync': { + kind: 'sync' as const, + message: 'Sync stopped with merge conflicts.', + rawError: 'Sync stopped with merge conflicts.' + }, + 'wt-fetch': { + kind: 'fetch' as const, + message: 'Fetch failed. network timeout', + rawError: 'Fetch failed. network timeout' + } } expect( diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index b097fab1358b..6a863e9a36db 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -11,9 +11,7 @@ import { Loader2, RefreshCw, Settings2, - Sparkle, Sparkles, - SlidersHorizontal, Square, Undo2, Check, @@ -32,7 +30,10 @@ import { type LucideIcon } from 'lucide-react' import { useAppStore } from '@/store' -import { resolveRemoteOperationErrorMessage } from '@/lib/source-control-remote-error' +import { + isSyncPushStageError, + resolveRemoteOperationErrorMessage +} from '@/lib/source-control-remote-error' import { useActiveWorktree, useRepoById, useWorktreeMap } from '@/store/selectors' import { getHostedReviewCacheKey } from '@/store/slices/hosted-review' import { getGitHubPRCacheKey } from '@/store/slices/github-cache-key' @@ -108,6 +109,7 @@ import { type SourceControlEntryGroups, type SourceControlSectionArea } from './source-control-section-order' +import { SourceControlVirtualFileList } from './source-control-virtual-file-list' import { buildActiveOpenFileSignature, buildActiveOpenRowKeys @@ -131,7 +133,6 @@ import { toast } from 'sonner' import { SourceControlEntryContextMenu } from './source-control-entry-context-menu' import { Dialog, - DialogClose, DialogContent, DialogDescription, DialogFooter, @@ -219,12 +220,6 @@ import { loadSessionCommitDrafts, saveSessionCommitDrafts } from '@/lib/source-control-commit-draft-session' -import { - getCommitFailureDialogWorktreeKey, - shouldShowCommitFailureDialog, - syncCommitFailureDialogState, - type CommitFailureDialogState -} from './commit-failure-dialog-state' import { hasExpandedCommitFailureDetails, summarizeCommitFailure } from './commit-failure-summary' import { isSourceControlSplitOpenModifier, @@ -303,11 +298,25 @@ import { type PullRequestGenerationContext, type PullRequestGenerationFields } from '@/store/slices/pull-request-generation' +import { + captureSourceControlRecoveryEntrySnapshot, + type SourceControlActionError, + type SourceControlRecoveryStatusEntry +} from './source-control-action-error' +import { + deriveSourceControlPushRecovery, + getSourceControlRecoveryFailureKindLabel, + type SourceControlPushRecovery +} from './source-control-push-recovery' +import { SourceControlRecoveryNotice } from './source-control-recovery-notice' export { appendCommitFailureCustomInstruction, + appendPushFailureCustomInstruction, buildCommitFailureAgentCommandInput, buildFixCommitFailurePrompt, + buildFixPushFailurePrompt, + buildPushFailureAgentCommandInput, buildResolveConflictsPrompt, buildResolvePullRequestConflictsPrompt } from './source-control-ai-prompts' @@ -317,11 +326,6 @@ export { } from './source-control-text-generation-defaults' type AbortConflictOperation = Extract -type AbortActionErrorKind = 'abort_merge' | 'abort_rebase' -export type SourceControlActionError = { - kind: RemoteOpKind | AbortActionErrorKind - message: string -} type SourceControlOperationTarget = RuntimeGitContext & { worktreeId: string pushTarget?: GitPushTarget @@ -725,6 +729,7 @@ function resolveRemoteActionError(kind: RemoteOpKind, error: unknown): string { isPush: kind === 'push', isForcePush: kind === 'force_push', isSync: kind === 'sync', + isSyncPushStage: kind === 'sync' && isSyncPushStageError(error), isFetch: kind === 'fetch', isFastForward: kind === 'fast_forward', isRebase: kind === 'rebase' @@ -795,6 +800,10 @@ export function clearRemoteActionErrorsForCompletedConflictOperations({ function SourceControlInner(): React.JSX.Element { const sourceControlRef = useRef(null) + // Why: the changed-file sections virtualize against the panel's shared + // scroller rather than owning a nested scroll container. State (not a ref) + // so the lists re-render and start observing once the element attaches. + const [fileListScrollElement, setFileListScrollElement] = useState(null) const isMac = useMemo(() => navigator.userAgent.includes('Mac'), []) const pendingCommentEditorRevealFrameIdsRef = useRef([]) // Why: React setState is async, so a rapid double-click on the Commit @@ -1034,6 +1043,7 @@ function SourceControlInner(): React.JSX.Element { const [remoteActionErrors, setRemoteActionErrors] = useState< Record >({}) + const remoteActionErrorSequenceByWorktreeRef = useRef>({}) const previousConflictOperationsRef = useRef>({}) // Why: keep commit-in-flight state per-worktree. A single boolean would be // cleared when the user switched worktrees, letting them double-click Commit @@ -1134,6 +1144,9 @@ function SourceControlInner(): React.JSX.Element { const commitMessage = readCommitDraftForWorktree(commitDrafts, activeWorktreeId) const commitError = commitErrors[activeWorktreeId ?? ''] ?? null const remoteActionError = remoteActionErrors[activeWorktreeId ?? ''] ?? null + const activeRemoteActionSequence = activeWorktreeId + ? (remoteActionErrorSequenceByWorktreeRef.current[activeWorktreeId] ?? null) + : null const [gitHistoryByWorktree, setGitHistoryByWorktree] = useState< Record >({}) @@ -1887,6 +1900,15 @@ function SourceControlInner(): React.JSX.Element { })), [unresolvedConflicts] ) + const pushRecovery = useMemo( + () => + deriveSourceControlPushRecovery({ + actionError: remoteActionError, + currentBranchName: branchName || null, + currentSequence: activeRemoteActionSequence + }), + [activeRemoteActionSequence, branchName, remoteActionError] + ) const { sourceControlAiDiscoveryHostKey, sourceControlAiActionsVisible, @@ -1901,12 +1923,14 @@ function SourceControlInner(): React.JSX.Element { openCommitGenerationDialog, openPullRequestGenerationDialog, isLaunchingCommitFailureAgent, + isLaunchingPushFailureAgent, resolveConflictsPrompt, commitFailureRecoveryPrompt, getLaunchActionRecipe, saveLaunchActionDefault, handleResolveConflictsWithAI, handleFixCommitFailureWithAI, + handleFixPushFailureWithAI, handleSaveCommitMessageGenerationDefaults, handleSavePullRequestGenerationDefaults, openSourceControlAiSettings @@ -1923,6 +1947,7 @@ function SourceControlInner(): React.JSX.Element { worktreePath, commitMessage, commitError, + pushRecoveryPrompt: pushRecovery?.prompt ?? null, updateSettings, updateRepo, openSettingsTarget, @@ -1978,6 +2003,11 @@ function SourceControlInner(): React.JSX.Element { delete commitInFlightRef.current[key] } } + for (const key of Object.keys(remoteActionErrorSequenceByWorktreeRef.current)) { + if (!worktreeMap.has(key)) { + delete remoteActionErrorSequenceByWorktreeRef.current[key] + } + } for (const key of Object.keys(generateInFlightRef.current)) { if (!worktreeMap.has(key)) { delete generateInFlightRef.current[key] @@ -2429,7 +2459,6 @@ function SourceControlInner(): React.JSX.Element { | 'rebase', options?: { target?: SourceControlOperationTarget - remoteStatus?: GitUpstreamStatus baseRef?: string | null } ): Promise => { @@ -2447,6 +2476,19 @@ function SourceControlInner(): React.JSX.Element { if (!target) { return false } + const sequence = (remoteActionErrorSequenceByWorktreeRef.current[target.worktreeId] ?? 0) + 1 + remoteActionErrorSequenceByWorktreeRef.current[target.worktreeId] = sequence + const targetIsActiveWorktree = target.worktreeId === activeWorktreeId + const recoveryEntrySnapshot = captureSourceControlRecoveryEntrySnapshot( + targetIsActiveWorktree + ? ([ + ...grouped.staged, + ...grouped.unstaged, + ...grouped.untracked + ] satisfies SourceControlRecoveryStatusEntry[]) + : [] + ) + const failureBranchName = targetIsActiveWorktree ? branchName || null : null setRemoteActionErrors((prev) => ({ ...prev, [target.worktreeId]: null })) try { if (kind === 'publish') { @@ -2461,18 +2503,17 @@ function SourceControlInner(): React.JSX.Element { return true } if (kind === 'push') { - const forceWithLease = shouldForcePushWithLeaseForUpstream( - options?.remoteStatus ?? remoteStatus - ) + // Why: kind 'push' must stay a regular push. Force-with-lease is only + // for kind 'force_push' (and callers that choose it). Auto-upgrading + // here made the always-enabled dropdown Push row silently force-push + // while its tooltip claimed a normal push might merely fail. await pushBranch( target.worktreeId, target.worktreePath, false, target.connectionId, target.pushTarget, - forceWithLease - ? { forceWithLease: true, runtimeTargetSettings: target.settings } - : { runtimeTargetSettings: target.settings } + { runtimeTargetSettings: target.settings } ) return true } @@ -2545,18 +2586,30 @@ function SourceControlInner(): React.JSX.Element { runtimeTargetSettings: target.settings } ) - setRemoteActionErrors((prev) => ({ ...prev, [target.worktreeId]: null })) + if (remoteActionErrorSequenceByWorktreeRef.current[target.worktreeId] === sequence) { + setRemoteActionErrors((prev) => ({ ...prev, [target.worktreeId]: null })) + } return true } catch (error) { // Why: remote action failures are surfaced by editor-slice actions to keep // one consistent toast path and avoid duplicate notifications in the UI. // Keep the latest failure inline too: dropdown-only actions like Fetch can // otherwise look like nothing happened once the menu closes. + if (remoteActionErrorSequenceByWorktreeRef.current[target.worktreeId] !== sequence) { + return false + } setRemoteActionErrors((prev) => ({ ...prev, [target.worktreeId]: { kind, - message: resolveRemoteActionError(kind, error) + message: resolveRemoteActionError(kind, error), + rawError: error instanceof Error ? error.message : String(error), + syncPushStage: kind === 'sync' ? isSyncPushStageError(error) : false, + branchName: failureBranchName, + worktreePath: target.worktreePath, + entriesSnapshot: recoveryEntrySnapshot.entries, + entriesSnapshotTotalCount: recoveryEntrySnapshot.totalCount, + sequence } })) return false @@ -2574,14 +2627,17 @@ function SourceControlInner(): React.JSX.Element { activeRepoSettings, activeWorktree?.pushTarget, activeWorktreeId, + branchName, fetchBranch, fastForwardBranch, effectiveBaseRef, + grouped.staged, + grouped.unstaged, + grouped.untracked, pullBranch, pushBranch, rebaseFromBase, refreshActiveGitStatusAfterMutation, - remoteStatus, syncBranch, worktreePath ] @@ -2639,7 +2695,11 @@ function SourceControlInner(): React.JSX.Element { ) setRemoteActionErrors((prev) => ({ ...prev, - [activeWorktreeId]: { kind: isRebase ? 'abort_rebase' : 'abort_merge', message } + [activeWorktreeId]: { + kind: isRebase ? 'abort_rebase' : 'abort_merge', + message, + rawError: message + } })) } finally { setAbortOperationInFlightByWorktree((prev) => ({ ...prev, [activeWorktreeId]: false })) @@ -2695,9 +2755,20 @@ function SourceControlInner(): React.JSX.Element { if (!ok) { return } + // Why: "Commit & Force Push" still invokes remoteKind 'push' from the + // dropdown kind map. Route to force_push when the upstream shape requires + // lease force so compound commit does not silently fall back to a regular + // push after we stopped auto-upgrading kind 'push'. + if ( + remoteKind === 'push' && + shouldForcePushWithLeaseForUpstream(remoteStatusForActions ?? remoteStatus) + ) { + await runRemoteAction('force_push') + return + } await runRemoteAction(remoteKind) }, - [handleCommit, runRemoteAction] + [handleCommit, remoteStatus, remoteStatusForActions, runRemoteAction] ) const handlePullRequestCreated = useCallback( @@ -3951,7 +4022,6 @@ function SourceControlInner(): React.JSX.Element { }) const remoteOk = await runRemoteAction(remoteStep, { target: operationTarget, - remoteStatus: latestUpstreamStatus, baseRef: token.baseRef }) if (abortIfStale()) { @@ -4642,8 +4712,17 @@ function SourceControlInner(): React.JSX.Element { case 'stage': void handleStageAllPrimary() return - case 'commit': case 'push': + // Why: primary labels "Force Push" while keeping kind 'push'. Invoke the + // explicit force path when lease force is required so regular push stays + // non-force for the dropdown. + handleActionInvoke( + shouldForcePushWithLeaseForUpstream(remoteStatusForActions ?? remoteStatus) + ? 'force_push' + : 'push' + ) + return + case 'commit': case 'pull': case 'sync': case 'publish': @@ -4653,7 +4732,14 @@ function SourceControlInner(): React.JSX.Element { case 'create_pr_intent': void runCreatePrIntent() } - }, [handleActionInvoke, handleStageAllPrimary, primaryAction.kind, runCreatePrIntent]) + }, [ + handleActionInvoke, + handleStageAllPrimary, + primaryAction.kind, + remoteStatus, + remoteStatusForActions, + runCreatePrIntent + ]) const handleCreatePrHeaderClick = useCallback((): void => { if (!createPrHeaderAction || createPrHeaderAction.disabled) { @@ -5627,6 +5713,7 @@ function SourceControlInner(): React.JSX.Element { )}
    0 ? 50 : undefined }} > @@ -5772,10 +5859,12 @@ function SourceControlInner(): React.JSX.Element { commitMessage={commitMessage} commitError={commitError} commitFailureRecoveryPrompt={commitFailureRecoveryPrompt} - remoteActionError={remoteActionError?.message ?? null} + pushRecovery={pushRecovery} + remoteActionError={pushRecovery ? null : (remoteActionError?.message ?? null)} createPrIntentNotice={createPrIntentNotice} isCommitting={isCommitting} isFixingCommitFailureWithAI={isLaunchingCommitFailureAgent} + isFixingPushFailureWithAI={isLaunchingPushFailureAgent} isCreatingPr={isCreatingPr || isCreatePrIntentInFlight} isCreatePrIntentInFlight={isCreatePrIntentInFlight} groupId={activeGroupId ?? activeWorktreeId} @@ -5793,6 +5882,7 @@ function SourceControlInner(): React.JSX.Element { primaryAction={primaryAction} dropdownItems={dropdownItems} fixCommitFailureRecipe={getLaunchActionRecipe('fixCommitFailure')} + fixPushFailureRecipe={getLaunchActionRecipe('fixPushFailure')} onCommitMessageChange={(value) => { if (!activeWorktreeId) { return @@ -5806,6 +5896,7 @@ function SourceControlInner(): React.JSX.Element { onSaveLaunchActionDefault={saveLaunchActionDefault} onOpenSourceControlAiSettings={openSourceControlAiSettings} onFixCommitFailureWithAI={handleFixCommitFailureWithAI} + onFixPushFailureWithAI={handleFixPushFailureWithAI} onPrimaryAction={handlePrimaryClick} onDropdownAction={handleActionInvoke} /> @@ -5957,8 +6048,12 @@ function SourceControlInner(): React.JSX.Element { } /> {!isCollapsed && - (sourceControlViewMode === 'tree' - ? (visibleTreeRowsBySection[id] ?? []).map((node) => { + (sourceControlViewMode === 'tree' ? ( + node.key} + renderRow={(node) => { if (node.type === 'submodule-placeholder') { return ( ) - }) - : (visibleListRowsBySection[id] ?? []).map((row) => { + }} + /> + ) : ( + + row.type === 'submodule-placeholder' + ? row.key + : `${row.entry.area}::${row.entry.path}` + } + renderRow={(row) => { if (row.type === 'submodule-placeholder') { return ( ) - }))} + }} + /> + ))}
    ) })} @@ -6117,8 +6224,12 @@ function SourceControlInner(): React.JSX.Element { } /> {!collapsedSections.has('branch') && - (sourceControlViewMode === 'tree' - ? visibleBranchTreeRows.map((node) => { + (sourceControlViewMode === 'tree' ? ( + node.key} + renderRow={(node) => { if (node.type === 'directory') { return ( ) - }) - : filteredBranchEntries.map((entry) => ( + }} + /> + ) : ( + `branch:${entry.path}`} + renderRow={(entry) => ( openCommittedDiff(entry, event)} commentCount={diffCommentCountByPath.get(entry.path) ?? 0} /> - )))} + )} + /> + ))}
    )} @@ -6365,173 +6484,6 @@ function SourceControlInner(): React.JSX.Element { const SourceControl = React.memo(SourceControlInner) export default SourceControl -type CommitFailureFixSplitButtonProps = { - label: string - worktreeId: string | null - groupId: string | null - connectionId?: string | null - repoId?: string | null - launchPlatform?: NodeJS.Platform - prompt: string | null - isLaunching: boolean - variant: React.ComponentProps['variant'] - size: React.ComponentProps['size'] - iconClassName: string - primaryClassName?: string - chevronClassName?: string - savedAgentId?: TuiAgent | null - savedCommandInputTemplate?: string | null - savedAgentArgs?: string | null - onSaveAgentDefault?: ( - target: SourceControlAiWriteTarget, - actionId: SourceControlLaunchActionId, - recipe: SourceControlActionRecipe - ) => void | Promise - onOpenSettings?: () => void - onFixWithDefaultAgent: (promptOverride?: string) => Promise | boolean - onPromptDelivered: () => void -} - -function CommitFailureFixSplitButton({ - label, - worktreeId, - groupId, - connectionId, - repoId, - launchPlatform, - prompt, - isLaunching, - variant, - size, - iconClassName, - primaryClassName, - chevronClassName, - savedAgentId, - savedCommandInputTemplate, - savedAgentArgs, - onSaveAgentDefault, - onOpenSettings, - onFixWithDefaultAgent, - onPromptDelivered -}: CommitFailureFixSplitButtonProps): React.JSX.Element { - const [composerOpen, setComposerOpen] = useState(false) - const canLaunch = Boolean(worktreeId && groupId && prompt) - const dividerClass = variant === 'default' ? 'border-primary-foreground/20' : 'border-border' - - return ( - <> - -
    - - - - -
    - - {worktreeId && groupId && prompt ? ( - setComposerOpen(true)} - className="gap-2 rounded-[7px] px-2 py-1.5 text-[12px] leading-5 font-medium" - > - - {translate( - 'auto.components.right.sidebar.SourceControl.f0a2dc9e46', - 'Customize launch...' - )} - - ) : ( - - {translate( - 'auto.components.right.sidebar.SourceControl.9e5ccd00aa', - 'Commit failure context unavailable' - )} - - )} - -
    - {worktreeId && groupId && prompt ? ( - - ) : null} - - ) -} - -function getCommitFailureKindLabel(summary: string): string | null { - if (/\blint\b/i.test(summary)) { - return 'Lint' - } - - if (/\bhook\b|\bpre-commit\b/i.test(summary)) { - return 'Hook' - } - - return null -} - type CommitAreaProps = { worktreeId: string | null groupId: string | null @@ -6541,10 +6493,12 @@ type CommitAreaProps = { commitMessage: string commitError: string | null commitFailureRecoveryPrompt: string | null + pushRecovery: SourceControlPushRecovery | null remoteActionError: string | null createPrIntentNotice?: CreatePrIntentNotice | null isCommitting: boolean isFixingCommitFailureWithAI: boolean + isFixingPushFailureWithAI: boolean isCreatingPr?: boolean isCreatePrIntentInFlight?: boolean showComposer?: boolean @@ -6561,6 +6515,7 @@ type CommitAreaProps = { primaryAction: PrimaryAction dropdownItems: DropdownEntry[] fixCommitFailureRecipe?: SourceControlActionRecipe + fixPushFailureRecipe?: SourceControlActionRecipe onCommitMessageChange: (message: string) => void onGenerate: () => void onCancelGenerate: () => void @@ -6571,6 +6526,7 @@ type CommitAreaProps = { ) => void | Promise onOpenSourceControlAiSettings?: () => void onFixCommitFailureWithAI: (promptOverride?: string) => Promise | boolean + onFixPushFailureWithAI: (promptOverride?: string) => Promise | boolean onPrimaryAction: () => void onDropdownAction: (kind: DropdownActionKind) => void } @@ -6584,10 +6540,12 @@ export function CommitArea({ commitMessage, commitError, commitFailureRecoveryPrompt, + pushRecovery, remoteActionError, createPrIntentNotice, isCommitting, isFixingCommitFailureWithAI, + isFixingPushFailureWithAI, isCreatingPr = false, isCreatePrIntentInFlight = false, showComposer = true, @@ -6604,12 +6562,14 @@ export function CommitArea({ primaryAction, dropdownItems, fixCommitFailureRecipe, + fixPushFailureRecipe, onCommitMessageChange, onGenerate, onCancelGenerate, onSaveLaunchActionDefault, onOpenSourceControlAiSettings, onFixCommitFailureWithAI, + onFixPushFailureWithAI, onPrimaryAction, onDropdownAction }: CommitAreaProps): React.JSX.Element { @@ -6649,7 +6609,8 @@ export function CommitArea({ [commitError] ) const commitFailureKindLabel = useMemo( - () => (commitFailureSummary ? getCommitFailureKindLabel(commitFailureSummary) : null), + () => + commitFailureSummary ? getSourceControlRecoveryFailureKindLabel(commitFailureSummary) : null, [commitFailureSummary] ) const hasCommitFailureDetails = useMemo( @@ -6659,45 +6620,6 @@ export function CommitArea({ : false, [commitError, commitFailureSummary] ) - // Why: the details dialog is scoped to the worktree, not the exact stderr - // text, so a retried commit can refresh an open dialog with newer output. - const commitFailureWorktreeKey = getCommitFailureDialogWorktreeKey(worktreeId) - const [commitFailureDialogState, setCommitFailureDialogState] = - useState({ - worktreeKey: commitFailureWorktreeKey, - open: false - }) - const isCommitFailureDialogOpen = shouldShowCommitFailureDialog( - commitFailureDialogState, - commitFailureWorktreeKey, - hasCommitFailureDetails - ) - const setCommitFailureDialogOpen = useCallback( - (open: boolean) => { - setCommitFailureDialogState({ worktreeKey: commitFailureWorktreeKey, open }) - }, - [commitFailureWorktreeKey] - ) - const handleFixCommitFailureWithAI = useCallback( - async (promptOverride?: string): Promise => { - const launched = await onFixCommitFailureWithAI(promptOverride) - if (launched) { - setCommitFailureDialogOpen(false) - } - return launched - }, - [onFixCommitFailureWithAI, setCommitFailureDialogOpen] - ) - const handleCommitFailureAgentPromptDelivered = useCallback(() => { - setCommitFailureDialogOpen(false) - }, [setCommitFailureDialogOpen]) - - useEffect(() => { - setCommitFailureDialogState((current) => - syncCommitFailureDialogState(current, commitFailureWorktreeKey, hasCommitFailureDetails) - ) - }, [commitFailureWorktreeKey, hasCommitFailureDetails]) - // Why: most primary-kind labels are anchored by a directional icon so // the affirmative Commit (✓) reads distinctly from the remote-state // labels sharing this slot — Push (↑), Sync (↕), Publish (☁︎↑). Pull is @@ -6718,6 +6640,7 @@ export function CommitArea({ }) const describedBy = [ commitError ? 'commit-area-error' : null, + pushRecovery ? 'commit-area-push-error' : null, remoteActionError ? 'commit-area-remote-error' : null, createPrIntentNotice ? 'commit-area-create-pr-intent' : null, generateError ? 'commit-area-generate-error' : null @@ -6977,138 +6900,66 @@ export function CommitArea({
    - {commitError && ( - // Why: role="alert" + aria-live="polite" lets screen readers announce - // commit failures; the id ties the message to the textarea via - // aria-describedby so assistive tech associates the two. -